From 6ac017b35b07c79d85da0e6decd86dd6bee61c57 Mon Sep 17 00:00:00 2001 From: devtools-ci-cd Date: Tue, 25 Mar 2025 15:18:41 +0100 Subject: [PATCH 01/24] chore: fix linter configuration --- .golangci.yml | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index bd8283bf58..4c34a7da60 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -2,6 +2,15 @@ # Golang CI pipeline configuration # # To execute linters in local the ./scripts/lint.sh script can be used. +version: 2 + +formatters: + enable: + - gci # Gci controls golang package import order and makes it always deterministic. [fast: true, auto-fix: false] + - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true] + - gofumpt # Gofumpt checks whether code was gofumpt-ed. [fast: true, auto-fix: true] + - goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt. [fast: true, auto-fix: true] + - golines linters: # Run golangci-lint linters to see the list of all linters @@ -20,21 +29,16 @@ linters: - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted. [fast: false, auto-fix: false] - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. [fast: false, auto-fix: false] - exptostd # Detects functions from golang.org/x/exp/ that can be replaced by std functions. [auto-fix] - - gci # Gci controls golang package import order and makes it always deterministic. [fast: true, auto-fix: false] - gocheckcompilerdirectives # Checks that go compiler directive comments (//go:) are valid. [fast: true, auto-fix: false] - gochecksumtype # Run exhaustiveness checks on Go "sum types" [fast: false, auto-fix: false] - goconst # Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false] - gocritic # Provides diagnostics that check for bugs, performance and style issues. [fast: false, auto-fix: false] - gocyclo # Computes and checks the cyclomatic complexity of functions [fast: true, auto-fix: false] - - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true] - - gofumpt # Gofumpt checks whether code was gofumpt-ed. [fast: true, auto-fix: true] - goheader # Checks is file header matches to pattern [fast: true, auto-fix: false] - - goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt. [fast: true, auto-fix: true] - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. [fast: true, auto-fix: false] - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. [fast: true, auto-fix: false] - goprintffuncname # Checks that printf-like functions are named with `f` at the end [fast: true, auto-fix: false] - gosec #(gas): Inspects source code for security problems [fast: false, auto-fix: false] - - gosimple #(megacheck): Linter for Go source code that specializes in simplifying a code [fast: false, auto-fix: false] - govet #(vet, vetshadow): Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string [fast: false, auto-fix: false] - grouper # An analyzer to analyze expression groups. [fast: true, auto-fix: false] - importas # Enforces consistent import aliases [fast: false, auto-fix: false] @@ -60,13 +64,11 @@ linters: - rowserrcheck # checks whether Err of rows is checked successfully [fast: false, auto-fix: false] - sloglint # ensure consistent code style when using log/slog [fast: false, auto-fix: false] - staticcheck - - stylecheck # Stylecheck is a replacement for golint [fast: false, auto-fix: false] - tagalign # check that struct tags are well aligned [fast: true, auto-fix: true] - testifylint # Checks usage of github.com/stretchr/testify. [fast: false, auto-fix: false] - testpackage # linter that makes you use a separate _test package [fast: true, auto-fix: false] - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers [fast: false, auto-fix: false] - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes [fast: false, auto-fix: false] - - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code [fast: false, auto-fix: false] - unconvert # Remove unnecessary type conversions [fast: false, auto-fix: false] - unparam # Reports unused function parameters [fast: false, auto-fix: false] - unused #(megacheck): Checks Go code for unused constants, variables, functions and types [fast: false, auto-fix: false] From a17ac34d9961357dea14722b85710f84d56f93ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20L=C3=A9one?= Date: Thu, 27 Mar 2025 17:33:30 +0100 Subject: [PATCH 02/24] FIx linters --- .DS_Store | Bin 0 -> 8196 bytes .golangci.yml | 32 +- cmd/.DS_Store | Bin 0 -> 6148 bytes cmd/scw/.DS_Store | Bin 0 -> 6148 bytes cmd/scw/main.go | 4 +- core/arg_file_content.go | 5 +- core/arg_specs.go | 8 +- core/autocomplete.go | 38 +- core/autocomplete_test.go | 496 ++++++++-- core/autocomplete_utils.go | 7 +- core/bootstrap.go | 21 +- core/build_info.go | 4 +- core/build_info_test.go | 22 +- core/cobra_builder.go | 11 +- core/cobra_usage_builder.go | 7 +- core/cobra_usage_builder_test.go | 13 +- core/cobra_utils.go | 56 +- core/cobra_utils_test.go | 8 +- core/command.go | 11 +- core/command_interceptor.go | 22 +- core/context.go | 6 +- core/default_test.go | 20 +- core/errors.go | 12 +- core/errors_cmp.go | 3 +- core/example.go | 8 +- core/human/marshal.go | 14 +- core/human/marshal_func.go | 217 +++-- core/printer.go | 18 +- core/reflect.go | 13 +- core/reflect_test.go | 15 +- core/result_test.go | 2 +- core/shell.go | 15 +- core/shell_test.go | 8 +- core/testing.go | 78 +- core/testing_recorder.go | 36 +- core/validate.go | 95 +- core/validate_test.go | 39 +- internal/.DS_Store | Bin 0 -> 6148 bytes internal/args/args_test.go | 6 +- internal/args/errors.go | 22 +- internal/args/unmarshal.go | 3 +- internal/docgen/docgen.go | 5 +- internal/e2e/human_test.go | 18 +- internal/editor/editor.go | 18 +- internal/editor/editor_test.go | 16 +- internal/editor/reflect.go | 7 +- internal/editor/reflect_test.go | 18 +- internal/gofields/gofields.go | 57 +- internal/gofields/gofields_test.go | 10 +- internal/gotty/client.go | 12 +- internal/interactive/prompt.go | 16 +- internal/interactive/utils.go | 3 +- internal/namespaces/account/v3/account_cli.go | 10 +- .../applesilicon/v1alpha1/applesilicon_cli.go | 38 +- .../applesilicon/v1alpha1/custom.go | 10 +- .../applesilicon/v1alpha1/custom_server.go | 53 +- .../v1alpha1/custom_server_ssh_test.go | 10 +- .../v1alpha1/custom_server_types.go | 33 +- .../audit_trail/v1alpha1/audit_trail_cli.go | 28 +- .../audit_trail/v1alpha1/custom_event.go | 18 +- .../namespaces/autocomplete/autocomplete.go | 24 +- internal/namespaces/autocomplete/errors.go | 8 +- .../namespaces/baremetal/v1/baremetal_cli.go | 339 +++++-- internal/namespaces/baremetal/v1/custom.go | 10 +- .../namespaces/baremetal/v1/custom_offer.go | 9 +- .../namespaces/baremetal/v1/custom_server.go | 24 +- .../baremetal/v1/custom_server_create_test.go | 18 +- .../baremetal/v1/custom_server_fip_prompt.go | 5 +- .../baremetal/v1/custome_server_delete.go | 16 +- .../namespaces/baremetal/v1/helpers_test.go | 14 +- .../namespaces/baremetal/v3/baremetal_cli.go | 52 +- .../namespaces/billing/v2beta1/billing_cli.go | 74 +- internal/namespaces/billing/v2beta1/custom.go | 10 +- .../v2beta1/custom_invoice_download.go | 15 +- .../billing/v2beta1/custom_invoice_export.go | 13 +- .../namespaces/block/v1alpha1/block_cli.go | 186 +++- internal/namespaces/block/v1alpha1/custom.go | 15 +- .../block/v1alpha1/custom_snapshot.go | 15 +- .../block/v1alpha1/custom_snapshot_test.go | 19 +- .../block/v1alpha1/custom_volume_test.go | 5 +- internal/namespaces/cockpit/v1/cockpit_cli.go | 111 ++- internal/namespaces/config/commands.go | 32 +- internal/namespaces/config/commands_test.go | 12 +- .../container/v1beta1/container_cli.go | 110 ++- .../namespaces/container/v1beta1/custom.go | 15 +- .../container/v1beta1/custom_container.go | 32 +- .../v1beta1/custom_container_test.go | 5 +- .../container/v1beta1/custom_deploy.go | 123 ++- .../v1beta1/custom_deploy_helpers.go | 14 +- .../container/v1beta1/custom_deploy_test.go | 36 +- .../v1beta1/getorcreate/getorcreate.go | 22 +- internal/namespaces/dedibox/v1/dedibox_cli.go | 268 ++++-- .../namespaces/documentdb/v1beta1/custom.go | 60 +- .../documentdb/v1beta1/custom_engine.go | 36 +- .../documentdb/v1beta1/documentdb_cli.go | 178 ++-- internal/namespaces/domain/v2beta1/custom.go | 31 +- .../domain/v2beta1/custom_record_set.go | 9 +- .../namespaces/domain/v2beta1/domain_cli.go | 184 +++- .../v1alpha1/edge_services_cli.go | 54 +- internal/namespaces/feedback/custom_test.go | 12 +- .../namespaces/flexibleip/v1alpha1/custom.go | 10 +- .../flexibleip/v1alpha1/flexibleip_cli.go | 133 ++- .../namespaces/function/v1beta1/custom.go | 15 +- .../function/v1beta1/custom_deploy.go | 55 +- .../function/v1beta1/custom_deploy_test.go | 6 +- .../function/v1beta1/function_cli.go | 202 +++- internal/namespaces/iam/v1alpha1/custom.go | 8 +- .../namespaces/iam/v1alpha1/custom_policy.go | 40 +- .../iam/v1alpha1/custom_policy_test.go | 10 +- .../iam/v1alpha1/custom_rule_test.go | 26 +- internal/namespaces/iam/v1alpha1/iam_cli.go | 164 +++- .../namespaces/inference/v1beta1/custom.go | 5 +- .../inference/v1beta1/custom_deployment.go | 11 +- .../inference/v1beta1/custom_endpoint.go | 4 +- .../inference/v1beta1/inference_cli.go | 45 +- internal/namespaces/info/custom.go | 31 +- internal/namespaces/init/init.go | 33 +- internal/namespaces/init/init_test.go | 23 +- internal/namespaces/init/prompt.go | 20 +- internal/namespaces/instance/v1/custom.go | 55 +- .../namespaces/instance/v1/custom_image.go | 166 ++-- .../instance/v1/custom_image_test.go | 61 +- internal/namespaces/instance/v1/custom_ip.go | 49 +- .../namespaces/instance/v1/custom_ip_test.go | 28 +- .../instance/v1/custom_placement_group.go | 54 +- .../v1/custom_placement_group_test.go | 9 +- .../instance/v1/custom_security_group.go | 131 +-- .../namespaces/instance/v1/custom_server.go | 51 +- .../instance/v1/custom_server_action.go | 63 +- .../instance/v1/custom_server_action_test.go | 91 +- .../instance/v1/custom_server_create.go | 104 +- .../v1/custom_server_create_builder.go | 81 +- .../instance/v1/custom_server_create_test.go | 180 +++- .../instance/v1/custom_server_delete.go | 6 +- .../instance/v1/custom_server_rdp.go | 32 +- .../instance/v1/custom_server_rdp_test.go | 20 +- .../instance/v1/custom_server_ssh.go | 16 +- .../instance/v1/custom_server_test.go | 207 ++-- .../instance/v1/custom_server_type.go | 27 +- .../namespaces/instance/v1/custom_snapshot.go | 80 +- .../instance/v1/custom_snapshot_test.go | 10 +- .../instance/v1/custom_ssh_config.go | 48 +- .../instance/v1/custom_ssh_key_test.go | 18 +- .../instance/v1/custom_user_data.go | 76 +- .../instance/v1/custom_user_data_test.go | 12 +- .../namespaces/instance/v1/custom_volume.go | 57 +- .../instance/v1/custom_volume_type.go | 40 +- .../namespaces/instance/v1/helpers_test.go | 80 +- .../namespaces/instance/v1/helpers_types.go | 13 +- .../namespaces/instance/v1/instance_cli.go | 905 +++++++++++++++--- .../instance/v1/instance_cli_test.go | 157 +-- .../namespaces/interlink/v1beta1/custom.go | 10 +- .../interlink/v1beta1/interlink_cli.go | 97 +- internal/namespaces/iot/v1/custom.go | 10 +- internal/namespaces/iot/v1/custom_device.go | 15 +- internal/namespaces/iot/v1/iot_cli.go | 105 +- internal/namespaces/ipam/v1/ipam_cli.go | 75 +- internal/namespaces/jobs/v1alpha1/custom.go | 5 +- internal/namespaces/jobs/v1alpha1/jobs_cli.go | 54 +- internal/namespaces/k8s/v1/custom.go | 13 +- internal/namespaces/k8s/v1/custom_cluster.go | 53 +- .../k8s/v1/custom_execcredentials.go | 9 +- .../k8s/v1/custom_kubeconfig_get_test.go | 11 +- .../k8s/v1/custom_kubeconfig_install.go | 6 +- .../k8s/v1/custom_kubeconfig_install_test.go | 71 +- .../k8s/v1/custom_kubeconfig_uninstall.go | 6 +- .../v1/custom_kubeconfig_uninstall_test.go | 63 +- internal/namespaces/k8s/v1/custom_pool.go | 4 +- internal/namespaces/k8s/v1/custom_version.go | 18 +- internal/namespaces/k8s/v1/helpers_test.go | 77 +- internal/namespaces/k8s/v1/k8s_cli.go | 220 ++++- internal/namespaces/k8s/v1/types/types.go | 6 +- .../key_manager/v1alpha1/key_manager_cli.go | 47 +- internal/namespaces/lb/v1/custom.go | 15 +- internal/namespaces/lb/v1/custom_backend.go | 137 ++- .../namespaces/lb/v1/custom_certificate.go | 14 +- internal/namespaces/lb/v1/custom_lb.go | 3 +- internal/namespaces/lb/v1/helper_test.go | 24 +- internal/namespaces/lb/v1/lb_cli.go | 761 +++++++++++++-- .../login/webcallback/webcallback.go | 6 +- .../marketplace/v2/marketplace_cli.go | 26 +- internal/namespaces/mnq/v1beta1/custom.go | 5 +- .../namespaces/mnq/v1beta1/custom_nats.go | 14 +- .../mnq/v1beta1/custom_nats_helpers.go | 25 +- .../mnq/v1beta1/custom_nats_prompt.go | 14 +- .../mnq/v1beta1/custom_nats_test.go | 42 +- internal/namespaces/mnq/v1beta1/custom_sns.go | 12 +- internal/namespaces/mnq/v1beta1/custom_sqs.go | 12 +- internal/namespaces/mnq/v1beta1/mnq_cli.go | 85 +- .../namespaces/mongodb/v1alpha1/custom.go | 15 +- .../mongodb/v1alpha1/custom_instance.go | 46 +- .../mongodb/v1alpha1/custom_nodetype.go | 15 +- .../mongodb/v1alpha1/custom_snapshot.go | 27 +- .../mongodb/v1alpha1/mongodb_cli.go | 55 +- .../namespaces/object/v1/custom_bucket.go | 17 +- .../object/v1/custom_bucket_test.go | 10 +- .../object/v1/custom_config_install_test.go | 7 +- internal/namespaces/rdb/v1/custom.go | 25 +- internal/namespaces/rdb/v1/custom_acl_test.go | 87 +- internal/namespaces/rdb/v1/custom_backup.go | 103 +- internal/namespaces/rdb/v1/custom_endpoint.go | 11 +- .../namespaces/rdb/v1/custom_endpoint_test.go | 42 +- internal/namespaces/rdb/v1/custom_engine.go | 36 +- internal/namespaces/rdb/v1/custom_instance.go | 100 +- .../namespaces/rdb/v1/custom_instance_test.go | 168 +++- internal/namespaces/rdb/v1/custom_log.go | 11 +- .../namespaces/rdb/v1/custom_node_type.go | 17 +- internal/namespaces/rdb/v1/custom_url.go | 12 +- internal/namespaces/rdb/v1/custom_url_test.go | 49 +- internal/namespaces/rdb/v1/custom_user.go | 3 +- .../namespaces/rdb/v1/custom_user_test.go | 74 +- internal/namespaces/rdb/v1/helper_test.go | 8 +- internal/namespaces/rdb/v1/rdb_cli.go | 208 ++-- .../namespaces/redis/v1/custom_cluster.go | 57 +- .../redis/v1/custom_cluster_test.go | 32 +- internal/namespaces/redis/v1/redis_cli.go | 259 ++++- internal/namespaces/registry/v1/custom.go | 15 +- .../registry/v1/custom_docker_helper.go | 19 +- .../registry/v1/custom_docker_helper_test.go | 12 +- .../namespaces/registry/v1/custom_image.go | 13 +- .../registry/v1/custom_image_test.go | 25 +- .../registry/v1/custom_login_test.go | 12 +- .../namespaces/registry/v1/registry_cli.go | 55 +- .../namespaces/secret/v1beta1/secret_cli.go | 85 +- .../serverless_sqldb/v1alpha1/custom.go | 54 +- .../v1alpha1/serverless_sqldb_cli.go | 21 +- internal/namespaces/tem/v1alpha1/custom.go | 5 +- internal/namespaces/tem/v1alpha1/tem_cli.go | 130 ++- internal/namespaces/test/v1/test_cli.go | 50 +- .../vpc/v2/custom_private_network.go | 21 +- internal/namespaces/vpc/v2/vpc_cli.go | 67 +- internal/namespaces/vpcgw/v1/custom.go | 10 +- .../vpcgw/v1/custom_gateway_network.go | 3 +- .../vpcgw/v1/custom_gateway_type.go | 18 +- internal/namespaces/vpcgw/v1/vpcgw_cli.go | 555 +++++++++-- internal/namespaces/webhosting/v1/custom.go | 15 +- .../webhosting/v1/webhosting_cli.go | 127 ++- .../passwordgenerator/password_generator.go | 4 +- internal/pkg/shlex/shlex.go | 68 +- internal/pkg/shlex/shlex_test.go | 56 +- internal/platform/terminal/terminal_client.go | 33 +- internal/qa/argspec.go | 10 +- internal/qa/qa.go | 69 +- internal/sentry/sentry.go | 6 +- internal/tabwriter/tabwriter.go | 14 +- internal/tabwriter/tabwriter_test.go | 82 +- internal/tasks/logger.go | 6 +- internal/tasks/tasks.go | 18 +- internal/tasks/tasks_test.go | 188 ++-- 249 files changed, 10087 insertions(+), 3201 deletions(-) create mode 100644 .DS_Store create mode 100644 cmd/.DS_Store create mode 100644 cmd/scw/.DS_Store create mode 100644 internal/.DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..8f95adcb51e2ed5771ae21cc3c4726ccb0825f81 GIT binary patch literal 8196 zcmeHMJ%|%Q6n?WwxD8i$;?D)I*+K+S#E4*}#3TMy2gbriFh9rLX*L^^I}fW%<8hKg zZIpEOA}AIj3U;Da7GfoOjg5jRdX0tn%}3srj%RGn*p{{`6?5w9 zL6}rwN(`aX;rC=XY|hx0wmO}JPA6fIg{e@4LPwsb!b#+`wWC$QDiBpb*6uFtL)BiS z3a{VGfnR6gkr+S7=S$U~B=h%X_M~r~cz!f)EG`xt(2n?oWt>*o3{UWsyGbH z!<85w#rcr9A^D`hXHMOnVu*`4xEl6y9v>!7?ry(SJXk*G5FZhPpP&-(YaH8IP8|Za z@o?O+wbG7Tj}>+rI-*FUND1)!RFP-RM(=a4h(4Zy8gy=kkZIf1xERji^UCGUqUI2pi?ca>Zlb$4B5@&J`tVCCUJd;{ zt-Jpzb-fKfJs;+Nq4x7_gxR2wGpFOoSe$PC2 zCYP@}&L6_vB4KeKu*+y3Z=nWkk*fSYI8QFTjf>$t9>4h7-3yVqIG;boabC_x_56)c z6KXWTt`2r#Rp`hBSPevQPE(yq^1+gMAB5)NjD|;XK16o_hWoP!b(-XJecS_=o^c=N z;Qi|K_l3#j=y86I>t1{U?r&zLrgcD=Fa`JnpifO1E& zm4!U6?)v=G!)IpQ*7bbV&Jn3@o?l-MPy4HWcKJhgbKg6)xde?y1*iZOpaN9jUn_u~ ztyY~ma-{-PfC_vlpx=iKS1f^@qkTHC*a!gB-*_`T+bjXh8UU8S&Jht5}YboD(;vm{5}4j(E0mNyU*X6`%sg3XFU^(f)r8|7QL_CUHjvsKB36 zAdTy$p5c|Ew+>!Tdu@i_!ru+GR*uD5G0<8uHrk3WdUaW!kuQOrqtOvJI*>mCstb(@ H{DuN=-H0pe literal 0 HcmV?d00001 diff --git a/cmd/scw/.DS_Store b/cmd/scw/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..439e4a7457d537f7e2b039f43217e23abb54bc34 GIT binary patch literal 6148 zcmeHKJ5B>J5S@V(E73%vq4X8@21~SDAS+Rmun3Ao8!13qAA*JpA#n-BDX4k#A!3CK z8W2J=lKsY>kG)S?+e1V=yX$MBDG^m@f-FiwWV&cNaOVk-HAhbix~0YHy6y^z{^FGE zy~3WaXp8>S{x661MmK!?@=)?w4{f_#4NI}To!>w1o}W(3e*L%nHaB&*UvvJ7R3X7Y zFc1s`1Hr(LFn~K-q&hN;J{SlFf`L5)ay}$9!NxHg>d}EtO8}reqg9|wEg><= gives no suggestion for now // eg: scw test flower create name=p -o=jso -func AutoComplete(ctx context.Context, leftWords []string, wordToComplete string, rightWords []string) *AutocompleteResponse { +func AutoComplete( + ctx context.Context, + leftWords []string, + wordToComplete string, + rightWords []string, +) *AutocompleteResponse { commands := ExtractCommands(ctx) // Create AutoComplete Tree @@ -310,7 +319,13 @@ func AutoComplete(ctx context.Context, leftWords []string, wordToComplete string // We try to complete the value of an unknown arg return &AutocompleteResponse{} } - suggestions := AutoCompleteArgValue(ctx, argNode.Command, argNode.ArgSpec, argValuePrefix, completedArgs) + suggestions := AutoCompleteArgValue( + ctx, + argNode.Command, + argNode.ArgSpec, + argValuePrefix, + completedArgs, + ) // We need to prefix suggestions with the argName to enable the arg value auto-completion. for k, s := range suggestions { @@ -368,12 +383,22 @@ func AutoComplete(ctx context.Context, leftWords []string, wordToComplete string // AutoCompleteArgValue returns suggestions for a (argument name, argument value prefix) pair. // Priority is given to the AutoCompleteFunc from the ArgSpec, if it is set. // Otherwise, we use EnumValues from the ArgSpec. -func AutoCompleteArgValue(ctx context.Context, cmd *Command, argSpec *ArgSpec, argValuePrefix string, completedArgs map[string]string) []string { +func AutoCompleteArgValue( + ctx context.Context, + cmd *Command, + argSpec *ArgSpec, + argValuePrefix string, + completedArgs map[string]string, +) []string { if argSpec == nil { return nil } if argSpec.AutoCompleteFunc != nil { - return argSpec.AutoCompleteFunc(ctx, argValuePrefix, requestFromCompletedArgs(cmd, completedArgs)) + return argSpec.AutoCompleteFunc( + ctx, + argValuePrefix, + requestFromCompletedArgs(cmd, completedArgs), + ) } possibleValues := []string(nil) @@ -475,7 +500,8 @@ func keySuggestion(key string, completedArg map[string]string, wordToComplete st if i >= len(splitWordToComplete) { continue } - if k != splitWordToComplete[i] && (k == sliceSchema || k == mapSchema) && splitWordToComplete[i] != "" { + if k != splitWordToComplete[i] && (k == sliceSchema || k == mapSchema) && + splitWordToComplete[i] != "" { splitKey[i] = splitWordToComplete[i] } } diff --git a/core/autocomplete_test.go b/core/autocomplete_test.go index 9dd2fefbbd..bdbb6567a8 100644 --- a/core/autocomplete_test.go +++ b/core/autocomplete_test.go @@ -127,72 +127,424 @@ func TestAutocomplete(t *testing.T) { t.Run("scw ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"test"}})) t.Run("scw te", run(&testCase{Suggestions: core.AutocompleteSuggestions{"test"}})) t.Run("scw test", run(&testCase{Suggestions: core.AutocompleteSuggestions{"test"}})) - t.Run("scw flower create name=plop", run(&testCase{WordToCompleteIndex: 1, Suggestions: core.AutocompleteSuggestions{"test"}})) - t.Run("scw te flower create name=plop", run(&testCase{WordToCompleteIndex: 1, Suggestions: core.AutocompleteSuggestions{"test"}})) + t.Run( + "scw flower create name=plop", + run(&testCase{WordToCompleteIndex: 1, Suggestions: core.AutocompleteSuggestions{"test"}}), + ) + t.Run( + "scw te flower create name=plop", + run(&testCase{WordToCompleteIndex: 1, Suggestions: core.AutocompleteSuggestions{"test"}}), + ) t.Run("scw test ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"flower"}})) t.Run("scw test fl", run(&testCase{Suggestions: core.AutocompleteSuggestions{"flower"}})) - t.Run("scw test flower ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"create", "delete"}})) + t.Run( + "scw test flower ", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"create", "delete"}}), + ) t.Run("scw test flower cr", run(&testCase{Suggestions: core.AutocompleteSuggestions{"create"}})) t.Run("scw test flower d", run(&testCase{Suggestions: core.AutocompleteSuggestions{"delete"}})) - t.Run("scw test flower create ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0=", "leaves.", "name=", "size=", "species="}})) - t.Run("scw test flower create n", run(&testCase{Suggestions: core.AutocompleteSuggestions{"name="}})) - t.Run("scw test flower create name", run(&testCase{Suggestions: core.AutocompleteSuggestions{"name="}})) + t.Run( + "scw test flower create ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "colours.0=", + "leaves.", + "name=", + "size=", + "species=", + }, + }, + ), + ) + t.Run( + "scw test flower create n", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"name="}}), + ) + t.Run( + "scw test flower create name", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"name="}}), + ) t.Run("scw test flower create name=", run(&testCase{Suggestions: nil})) - t.Run("scw test flower create name n", run(&testCase{Suggestions: core.AutocompleteSuggestions{"name="}})) + t.Run( + "scw test flower create name n", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"name="}}), + ) t.Run("scw test flower create name=p", run(&testCase{Suggestions: nil})) - t.Run("scw test flower create name=p ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0=", "leaves.", "size=", "species="}})) + t.Run( + "scw test flower create name=p ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "colours.0=", + "leaves.", + "size=", + "species=", + }, + }, + ), + ) t.Run("scw test flower create name=plop n", run(&testCase{Suggestions: nil})) - t.Run("scw test flower create n name=plop", run(&testCase{WordToCompleteIndex: 4, Suggestions: nil})) - t.Run("scw test flower create s", run(&testCase{Suggestions: core.AutocompleteSuggestions{"size=", "species="}})) - t.Run("scw test flower create species=", run(&testCase{Suggestions: core.AutocompleteSuggestions{"species=petunia", "species=rose", "species=violet", "species=virginia bluebell"}})) - t.Run("scw test flower create species=v", run(&testCase{Suggestions: core.AutocompleteSuggestions{"species=violet", "species=virginia bluebell"}})) - t.Run("scw test flower create size=a1b2c", run(&testCase{Suggestions: core.AutocompleteSuggestions{"size=12"}})) - t.Run("scw test flower create colo", run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0="}})) - t.Run("scw test flower create colours.0", run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0="}})) - t.Run("scw test flower create colours.0=", run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0=blue", "colours.0=pink", "colours.0=red"}})) - t.Run("scw test flower create colours.0=r", run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0=red"}})) - t.Run("scw test flower create colo colours.1=red", run(&testCase{WordToCompleteIndex: 4, Suggestions: core.AutocompleteSuggestions{"colours.0="}})) - t.Run("scw test flower create colo colours.0=blue colours.1=red", run(&testCase{WordToCompleteIndex: 4, Suggestions: core.AutocompleteSuggestions{"colours.2="}})) - t.Run("scw test flower create colours.0=blue colours.1=r", run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.1=red"}})) - t.Run("scw test flower create leaves.", run(&testCase{Suggestions: core.AutocompleteSuggestions{"leaves."}})) - t.Run("scw test flower create leaves.0", run(&testCase{Suggestions: core.AutocompleteSuggestions{"leaves.0.size="}})) - t.Run("scw test flower create leaves.0.", run(&testCase{Suggestions: core.AutocompleteSuggestions{"leaves.0.size="}})) - t.Run("scw test flower create leaves.0.size=M", run(&testCase{Suggestions: core.AutocompleteSuggestions{"leaves.0.size=M"}})) - t.Run("scw test flower create leaves.0.size=M leaves", run(&testCase{Suggestions: core.AutocompleteSuggestions{"leaves."}})) - t.Run("scw test flower create leaves.0.size=M leaves leaves.1.size=M", run(&testCase{WordToCompleteIndex: 5, Suggestions: core.AutocompleteSuggestions{"leaves."}})) - t.Run("scw test flower delete ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"anemone", "hibiscus", "with-leaves="}})) - t.Run("scw test flower delete w", run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves="}})) - t.Run("scw test flower delete h", run(&testCase{Suggestions: core.AutocompleteSuggestions{"hibiscus"}})) - t.Run("scw test flower delete with-leaves=true ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"anemone", "hibiscus"}})) // invalid notation + t.Run( + "scw test flower create n name=plop", + run(&testCase{WordToCompleteIndex: 4, Suggestions: nil}), + ) + t.Run( + "scw test flower create s", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"size=", "species="}}), + ) + t.Run( + "scw test flower create species=", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "species=petunia", + "species=rose", + "species=violet", + "species=virginia bluebell", + }, + }, + ), + ) + t.Run( + "scw test flower create species=v", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "species=violet", + "species=virginia bluebell", + }, + }, + ), + ) + t.Run( + "scw test flower create size=a1b2c", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"size=12"}}), + ) + t.Run( + "scw test flower create colo", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0="}}), + ) + t.Run( + "scw test flower create colours.0", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0="}}), + ) + t.Run( + "scw test flower create colours.0=", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "colours.0=blue", + "colours.0=pink", + "colours.0=red", + }, + }, + ), + ) + t.Run( + "scw test flower create colours.0=r", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0=red"}}), + ) + t.Run( + "scw test flower create colo colours.1=red", + run( + &testCase{ + WordToCompleteIndex: 4, + Suggestions: core.AutocompleteSuggestions{"colours.0="}, + }, + ), + ) + t.Run( + "scw test flower create colo colours.0=blue colours.1=red", + run( + &testCase{ + WordToCompleteIndex: 4, + Suggestions: core.AutocompleteSuggestions{"colours.2="}, + }, + ), + ) + t.Run( + "scw test flower create colours.0=blue colours.1=r", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.1=red"}}), + ) + t.Run( + "scw test flower create leaves.", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"leaves."}}), + ) + t.Run( + "scw test flower create leaves.0", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"leaves.0.size="}}), + ) + t.Run( + "scw test flower create leaves.0.", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"leaves.0.size="}}), + ) + t.Run( + "scw test flower create leaves.0.size=M", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"leaves.0.size=M"}}), + ) + t.Run( + "scw test flower create leaves.0.size=M leaves", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"leaves."}}), + ) + t.Run( + "scw test flower create leaves.0.size=M leaves leaves.1.size=M", + run( + &testCase{WordToCompleteIndex: 5, Suggestions: core.AutocompleteSuggestions{"leaves."}}, + ), + ) + t.Run( + "scw test flower delete ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{"anemone", "hibiscus", "with-leaves="}, + }, + ), + ) + t.Run( + "scw test flower delete w", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves="}}), + ) + t.Run( + "scw test flower delete h", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"hibiscus"}}), + ) + t.Run( + "scw test flower delete with-leaves=true ", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"anemone", "hibiscus"}}), + ) // invalid notation t.Run("scw test flower delete hibiscus n", run(&testCase{Suggestions: nil})) - t.Run("scw test flower delete hibiscus w", run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves="}})) - t.Run("scw test flower delete hibiscus with-leaves=true", run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves=true"}})) - t.Run("scw test flower delete hibiscus with-leaves=true ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"anemone"}})) - t.Run("scw test flower delete hibiscus with-leaves=", run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves=false", "with-leaves=true"}})) - t.Run("scw test flower delete hibiscus with-leaves=tr", run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves=true"}})) + t.Run( + "scw test flower delete hibiscus w", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves="}}), + ) + t.Run( + "scw test flower delete hibiscus with-leaves=true", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves=true"}}), + ) + t.Run( + "scw test flower delete hibiscus with-leaves=true ", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"anemone"}}), + ) + t.Run( + "scw test flower delete hibiscus with-leaves=", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{"with-leaves=false", "with-leaves=true"}, + }, + ), + ) + t.Run( + "scw test flower delete hibiscus with-leaves=tr", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves=true"}}), + ) t.Run("scw test flower delete hibiscus with-leaves=yes", run(&testCase{Suggestions: nil})) - t.Run("scw test flower create leaves.0.size=", run(&testCase{Suggestions: core.AutocompleteSuggestions{"leaves.0.size=L", "leaves.0.size=M", "leaves.0.size=S", "leaves.0.size=XL", "leaves.0.size=XXL"}})) - t.Run("scw -", run(&testCase{Suggestions: core.AutocompleteSuggestions{"--config", "--debug", "--help", "--output", "--profile", "-D", "-c", "-h", "-o", "-p"}})) + t.Run( + "scw test flower create leaves.0.size=", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "leaves.0.size=L", + "leaves.0.size=M", + "leaves.0.size=S", + "leaves.0.size=XL", + "leaves.0.size=XXL", + }, + }, + ), + ) + t.Run( + "scw -", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "--config", + "--debug", + "--help", + "--output", + "--profile", + "-D", + "-c", + "-h", + "-o", + "-p", + }, + }, + ), + ) t.Run("scw test -o j", run(&testCase{Suggestions: core.AutocompleteSuggestions{"json"}})) - t.Run("scw test flower -o ", run(&testCase{Suggestions: core.AutocompleteSuggestions{core.PrinterTypeHuman.String(), core.PrinterTypeJSON.String(), core.PrinterTypeTemplate.String(), core.PrinterTypeYAML.String()}})) - t.Run("scw test flower -o json create -", run(&testCase{Suggestions: core.AutocompleteSuggestions{"--config", "--debug", "--help", "--output", "--profile", "--wait", "-D", "-c", "-h", "-p", "-w"}})) - t.Run("scw test flower create name=p -o j", run(&testCase{Suggestions: core.AutocompleteSuggestions{"json"}})) - t.Run("scw test flower create name=p -o json ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0=", "leaves.", "size=", "species="}})) - t.Run("scw test flower create name=p -o=json ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0=", "leaves.", "size=", "species="}})) - t.Run("scw test flower create name=p -o=jso", run(&testCase{Suggestions: nil})) // TODO: make this work - t.Run("scw test flower create name=p -o", run(&testCase{Suggestions: core.AutocompleteSuggestions{"-o"}})) - t.Run("scw test -o json flower create ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0=", "leaves.", "name=", "size=", "species="}})) - t.Run("scw test flower create name=p --profile xxxx ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0=", "leaves.", "size=", "species="}})) - t.Run("scw test --profile xxxx flower create name=p ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"colours.0=", "leaves.", "size=", "species="}})) + t.Run( + "scw test flower -o ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + core.PrinterTypeHuman.String(), + core.PrinterTypeJSON.String(), + core.PrinterTypeTemplate.String(), + core.PrinterTypeYAML.String(), + }, + }, + ), + ) + t.Run( + "scw test flower -o json create -", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "--config", + "--debug", + "--help", + "--output", + "--profile", + "--wait", + "-D", + "-c", + "-h", + "-p", + "-w", + }, + }, + ), + ) + t.Run( + "scw test flower create name=p -o j", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"json"}}), + ) + t.Run( + "scw test flower create name=p -o json ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "colours.0=", + "leaves.", + "size=", + "species=", + }, + }, + ), + ) + t.Run( + "scw test flower create name=p -o=json ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "colours.0=", + "leaves.", + "size=", + "species=", + }, + }, + ), + ) + t.Run( + "scw test flower create name=p -o=jso", + run(&testCase{Suggestions: nil}), + ) // TODO: make this work + t.Run( + "scw test flower create name=p -o", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"-o"}}), + ) + t.Run( + "scw test -o json flower create ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "colours.0=", + "leaves.", + "name=", + "size=", + "species=", + }, + }, + ), + ) + t.Run( + "scw test flower create name=p --profile xxxx ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "colours.0=", + "leaves.", + "size=", + "species=", + }, + }, + ), + ) + t.Run( + "scw test --profile xxxx flower create name=p ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "colours.0=", + "leaves.", + "size=", + "species=", + }, + }, + ), + ) t.Run("scw test flower create name=p --profile xxxx", run(&testCase{Suggestions: nil})) - t.Run("scw test flower -o json delete -", run(&testCase{Suggestions: core.AutocompleteSuggestions{"--config", "--debug", "--help", "--output", "--profile", "-D", "-c", "-h", "-p"}})) - t.Run("scw test flower delete -o ", run(&testCase{Suggestions: core.AutocompleteSuggestions{core.PrinterTypeHuman.String(), core.PrinterTypeJSON.String(), core.PrinterTypeTemplate.String(), core.PrinterTypeYAML.String()}})) - t.Run("scw test flower delete -o j", run(&testCase{Suggestions: core.AutocompleteSuggestions{"json"}})) - t.Run("scw test flower delete -o json ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"anemone", "hibiscus", "with-leaves="}})) - t.Run("scw test flower delete -o=json ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"anemone", "hibiscus", "with-leaves="}})) - t.Run("scw test flower delete -o json hibiscus w", run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves="}})) - t.Run("scw test flower delete -o=json hibiscus w", run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves="}})) + t.Run( + "scw test flower -o json delete -", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "--config", + "--debug", + "--help", + "--output", + "--profile", + "-D", + "-c", + "-h", + "-p", + }, + }, + ), + ) + t.Run( + "scw test flower delete -o ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + core.PrinterTypeHuman.String(), + core.PrinterTypeJSON.String(), + core.PrinterTypeTemplate.String(), + core.PrinterTypeYAML.String(), + }, + }, + ), + ) + t.Run( + "scw test flower delete -o j", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"json"}}), + ) + t.Run( + "scw test flower delete -o json ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{"anemone", "hibiscus", "with-leaves="}, + }, + ), + ) + t.Run( + "scw test flower delete -o=json ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{"anemone", "hibiscus", "with-leaves="}, + }, + ), + ) + t.Run( + "scw test flower delete -o json hibiscus w", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves="}}), + ) + t.Run( + "scw test flower delete -o=json hibiscus w", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"with-leaves="}}), + ) } func TestAutocompleteArgs(t *testing.T) { @@ -264,10 +616,33 @@ func TestAutocompleteArgs(t *testing.T) { return runAutocompleteTest(ctx, tc) } - t.Run("scw test flower get ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"flower1", "flower2", "material-name="}})) - t.Run("scw test flower get material-name=", run(&testCase{Suggestions: core.AutocompleteSuggestions{"material-name=material1", "material-name=material2"}})) - t.Run("scw test flower get material-name=mat ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"flower1", "flower2"}})) - t.Run("scw test flower create name=", run(&testCase{Suggestions: core.AutocompleteSuggestions(nil)})) + t.Run( + "scw test flower get ", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{"flower1", "flower2", "material-name="}, + }, + ), + ) + t.Run( + "scw test flower get material-name=", + run( + &testCase{ + Suggestions: core.AutocompleteSuggestions{ + "material-name=material1", + "material-name=material2", + }, + }, + ), + ) + t.Run( + "scw test flower get material-name=mat ", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"flower1", "flower2"}}), + ) + t.Run( + "scw test flower create name=", + run(&testCase{Suggestions: core.AutocompleteSuggestions(nil)}), + ) } func TestAutocompleteProfiles(t *testing.T) { @@ -296,7 +671,10 @@ func TestAutocompleteProfiles(t *testing.T) { t.Run("scw -p ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"p1", "p2"}})) t.Run("scw test -p ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"p1", "p2"}})) - t.Run("scw test flower --profile ", run(&testCase{Suggestions: core.AutocompleteSuggestions{"p1", "p2"}})) + t.Run( + "scw test flower --profile ", + run(&testCase{Suggestions: core.AutocompleteSuggestions{"p1", "p2"}}), + ) } func TestAutocompleteDeprecatedCommand(t *testing.T) { diff --git a/core/autocomplete_utils.go b/core/autocomplete_utils.go index 9cdf85ed1a..eecb346cb0 100644 --- a/core/autocomplete_utils.go +++ b/core/autocomplete_utils.go @@ -88,7 +88,12 @@ var autocompleteResourceToNamespace = map[string]string{ // AutocompleteGetArg tries to complete an argument by using the list verb if it exists for the same resource // It will search for the same field in the response of the list // Field name will be stripped of the resource name (ex: cluster-id -> id) -func AutocompleteGetArg(ctx context.Context, cmd *Command, argSpec *ArgSpec, completedArgs map[string]string) []string { +func AutocompleteGetArg( + ctx context.Context, + cmd *Command, + argSpec *ArgSpec, + completedArgs map[string]string, +) []string { commands := ExtractCommands(ctx) // The argument we want to find (ex: server-id) diff --git a/core/bootstrap.go b/core/bootstrap.go index ed6cdab5c9..6e911dc31d 100644 --- a/core/bootstrap.go +++ b/core/bootstrap.go @@ -87,7 +87,13 @@ func Bootstrap(config *BootstrapConfig) (exitCode int, result interface{}, err e flags := pflag.NewFlagSet(config.Args[0], pflag.ContinueOnError) flags.StringVarP(&profileFlag, "profile", "p", "", "The config profile to use") flags.StringVarP(&configPathFlag, "config", "c", "", "The path to the config file") - flags.StringVarP(&outputFlag, "output", "o", cliConfig.DefaultOutput, "Output format: json or human") + flags.StringVarP( + &outputFlag, + "output", + "o", + cliConfig.DefaultOutput, + "Output format: json or human", + ) flags.BoolVarP(&debug, "debug", "D", os.Getenv("SCW_DEBUG") == "true", "Enable debug mode") // Ignore unknown flag flags.ParseErrorsWhitelist.UnknownFlags = true @@ -135,7 +141,9 @@ func Bootstrap(config *BootstrapConfig) (exitCode int, result interface{}, err e return 1, nil, err } - interactive.SetOutputWriter(config.Stderr) // set printer for interactive function (always stderr). + interactive.SetOutputWriter( + config.Stderr, + ) // set printer for interactive function (always stderr). httpClient := config.HTTPClient if httpClient == nil { @@ -259,9 +267,12 @@ func Bootstrap(config *BootstrapConfig) (exitCode int, result interface{}, err e // These flag are already handle at the beginning of this function but we keep this // declaration in order for them to be shown in the cobra usage documentation. - rootCmd.PersistentFlags().StringVarP(&profileFlag, "profile", "p", "", "The config profile to use") - rootCmd.PersistentFlags().StringVarP(&configPathFlag, "config", "c", "", "The path to the config file") - rootCmd.PersistentFlags().StringVarP(&outputFlag, "output", "o", cliConfig.DefaultOutput, "Output format: json or human, see 'scw help output' for more info") + rootCmd.PersistentFlags(). + StringVarP(&profileFlag, "profile", "p", "", "The config profile to use") + rootCmd.PersistentFlags(). + StringVarP(&configPathFlag, "config", "c", "", "The path to the config file") + rootCmd.PersistentFlags(). + StringVarP(&outputFlag, "output", "o", cliConfig.DefaultOutput, "Output format: json or human, see 'scw help output' for more info") rootCmd.PersistentFlags().BoolVarP(&debug, "debug", "D", false, "Enable debug mode") rootCmd.SetArgs(args) rootCmd.SetHelpCommand(&cobra.Command{Hidden: true}) diff --git a/core/build_info.go b/core/build_info.go index d6b93ba4d1..ffe0dfddb5 100644 --- a/core/build_info.go +++ b/core/build_info.go @@ -80,7 +80,9 @@ func (b *BuildInfo) checkVersion(ctx context.Context) { } if b.Version.LessThan(latestVersion) { - ExtractLogger(ctx).Warningf("A new version of scw is available (%s), beware that you are currently running %s\n", latestVersion, b.Version) + ExtractLogger( + ctx, + ).Warningf("A new version of scw is available (%s), beware that you are currently running %s\n", latestVersion, b.Version) } else { ExtractLogger(ctx).Debugf("version is up to date (%s)\n", b.Version) } diff --git a/core/build_info_test.go b/core/build_info_test.go index ce6c5ff856..505d338bbd 100644 --- a/core/build_info_test.go +++ b/core/build_info_test.go @@ -35,7 +35,11 @@ func Test_CheckVersion(t *testing.T) { Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - assert.Equal(t, "A new version of scw is available (2.5.4), beware that you are currently running 1.20.0\n", ctx.LogBuffer) + assert.Equal( + t, + "A new version of scw is available (2.5.4), beware that you are currently running 1.20.0\n", + ctx.LogBuffer, + ) }, ), TmpHomeDir: true, @@ -62,13 +66,19 @@ func Test_CheckVersion(t *testing.T) { Version: version.Must(version.NewSemver("v1.0")), }, BeforeFunc: func(ctx *core.BeforeFuncCtx) error { - return core.CreateAndCloseFile(core.GetLatestVersionUpdateFilePath(ctx.OverrideEnv[scw.ScwCacheDirEnv])) + return core.CreateAndCloseFile( + core.GetLatestVersionUpdateFilePath(ctx.OverrideEnv[scw.ScwCacheDirEnv]), + ) }, Cmd: "scw plop -D", Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - assert.Contains(t, ctx.LogBuffer, "version was already checked during past 24 hours\n") + assert.Contains( + t, + ctx.LogBuffer, + "version was already checked during past 24 hours\n", + ) }, ), TmpHomeDir: true, @@ -91,7 +101,11 @@ func Test_CheckVersion(t *testing.T) { Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - assert.Contains(t, ctx.LogBuffer, "A new version of scw is available (2.5.4), beware that you are currently running 1.0.0\n") + assert.Contains( + t, + ctx.LogBuffer, + "A new version of scw is available (2.5.4), beware that you are currently running 1.0.0\n", + ) }, ), TmpHomeDir: true, diff --git a/core/cobra_builder.go b/core/cobra_builder.go index e931ace71b..02a93898a5 100644 --- a/core/cobra_builder.go +++ b/core/cobra_builder.go @@ -80,7 +80,10 @@ func (b *cobraBuilder) build() *cobra.Command { } // Same as namespace but with verbs. - verbKey := strings.Join([]string{cmd.Namespace, cmd.Resource, cmd.Verb}, indexCommandSeparator) + verbKey := strings.Join( + []string{cmd.Namespace, cmd.Resource, cmd.Verb}, + indexCommandSeparator, + ) if _, verbExist := index[verbKey]; !verbExist { cobraCmd := &cobra.Command{Use: cmd.Verb} index[verbKey] = cobraCmd @@ -101,7 +104,11 @@ func (b *cobraBuilder) build() *cobra.Command { // hydrateCobra hydrates a cobra command from a *Command. // Field like Short, Long will be copied over. // More complex field like PreRun or Run will also be generated if needed. -func (b *cobraBuilder) hydrateCobra(cobraCmd *cobra.Command, cmd *Command, groups map[string]*cobra.Group) { +func (b *cobraBuilder) hydrateCobra( + cobraCmd *cobra.Command, + cmd *Command, + groups map[string]*cobra.Group, +) { cobraCmd.Short = cmd.Short cobraCmd.Long = cmd.Long cobraCmd.Hidden = cmd.Hidden diff --git a/core/cobra_usage_builder.go b/core/cobra_usage_builder.go index ca2424e1ba..6b18c9b53c 100644 --- a/core/cobra_usage_builder.go +++ b/core/cobra_usage_builder.go @@ -30,7 +30,12 @@ func buildUsageAliases(ctx context.Context, cmd *Command) string { aliasCfg := ExtractAliases(ctx) for _, aliasName := range aliases { - _, _ = fmt.Fprintf(tw, " %s\t%s\n", aliasName, strings.Join(aliasCfg.GetAlias(aliasName), " ")) + _, _ = fmt.Fprintf( + tw, + " %s\t%s\n", + aliasName, + strings.Join(aliasCfg.GetAlias(aliasName), " "), + ) } tw.Flush() diff --git a/core/cobra_usage_builder_test.go b/core/cobra_usage_builder_test.go index c45929bb39..f369c2a763 100644 --- a/core/cobra_usage_builder_test.go +++ b/core/cobra_usage_builder_test.go @@ -58,10 +58,15 @@ func Test_buildUsageArgs(t *testing.T) { Default: core.DefaultValueSetter("1"), }, { - Name: "color", - Short: "Filter by color", - Default: core.DefaultValueSetter(ServerColorRed), - EnumValues: []string{ServerColorBlue, ServerColorRed, ServerColorPink, ServerColorGreen}, + Name: "color", + Short: "Filter by color", + Default: core.DefaultValueSetter(ServerColorRed), + EnumValues: []string{ + ServerColorBlue, + ServerColorRed, + ServerColorPink, + ServerColorGreen, + }, }, { Name: "multi-word-arg", diff --git a/core/cobra_utils.go b/core/cobra_utils.go index 153098ca0d..8b401c5c55 100644 --- a/core/cobra_utils.go +++ b/core/cobra_utils.go @@ -24,7 +24,11 @@ func cobraRun(ctx context.Context, cmd *Command) func(*cobra.Command, []string) // If command requires authentication and the client was not directly provided in the bootstrap config, we create a new client and overwrite the existing one if !cmd.AllowAnonymousClient && !meta.isClientFromBootstrapConfig { - client, err := meta.Platform.CreateClient(meta.httpClient, ExtractConfigPath(ctx), ExtractProfileName(ctx)) + client, err := meta.Platform.CreateClient( + meta.httpClient, + ExtractConfigPath(ctx), + ExtractProfileName(ctx), + ) if err != nil { return createClientError(err) } @@ -61,16 +65,28 @@ func cobraRun(ctx context.Context, cmd *Command) func(*cobra.Command, []string) otherArgs := rawArgs.Remove(positionalArgSpec.Name) return &CliError{ - Err: errors.New("a positional argument is required for this command"), - Hint: positionalArgHint(meta.BinaryName, cmd, value, otherArgs, len(positionalArgs) > 0), + Err: errors.New("a positional argument is required for this command"), + Hint: positionalArgHint( + meta.BinaryName, + cmd, + value, + otherArgs, + len(positionalArgs) > 0, + ), } } // If no positional arguments were provided, return an error if len(positionalArgs) == 0 { return &CliError{ - Err: errors.New("a positional argument is required for this command"), - Hint: positionalArgHint(meta.BinaryName, cmd, "<"+positionalArgSpec.Name+">", rawArgs, false), + Err: errors.New("a positional argument is required for this command"), + Hint: positionalArgHint( + meta.BinaryName, + cmd, + "<"+positionalArgSpec.Name+">", + rawArgs, + false, + ), } } @@ -82,7 +98,10 @@ func cobraRun(ctx context.Context, cmd *Command) func(*cobra.Command, []string) rawArgsWithPositional := rawArgs.Add(argNameWithIndex, positionalArgs[0]) for i := 1; i < len(positionalArgs); i++ { argNameWithIndex = fmt.Sprintf("%s.%d", positionalArgSpec.Name, i) - rawArgsWithPositional = rawArgsWithPositional.Add(argNameWithIndex, positionalArgs[i]) + rawArgsWithPositional = rawArgsWithPositional.Add( + argNameWithIndex, + positionalArgs[i], + ) } result, err := run(ctx, cobraCmd, cmd, rawArgsWithPositional) @@ -115,7 +134,12 @@ func cobraRun(ctx context.Context, cmd *Command) func(*cobra.Command, []string) } } -func run(ctx context.Context, cobraCmd *cobra.Command, cmd *Command, rawArgs []string) (interface{}, error) { +func run( + ctx context.Context, + cobraCmd *cobra.Command, + cmd *Command, + rawArgs []string, +) (interface{}, error) { var err error // create a new Args interface{} @@ -172,9 +196,13 @@ func run(ctx context.Context, cobraCmd *cobra.Command, cmd *Command, rawArgs []s cmd.Interceptor, ) - data, err := interceptor(ctx, cmdArgs, func(ctx context.Context, argsI interface{}) (i interface{}, err error) { - return cmd.Run(ctx, argsI) - }) + data, err := interceptor( + ctx, + cmdArgs, + func(ctx context.Context, argsI interface{}) (i interface{}, err error) { + return cmd.Run(ctx, argsI) + }, + ) if err != nil { return nil, err } @@ -190,7 +218,13 @@ func run(ctx context.Context, cobraCmd *cobra.Command, cmd *Command, rawArgs []s } // positionalArgHint formats the positional argument error hint. -func positionalArgHint(binaryName string, cmd *Command, hintValue string, otherArgs []string, positionalArgumentFound bool) string { +func positionalArgHint( + binaryName string, + cmd *Command, + hintValue string, + otherArgs []string, + positionalArgumentFound bool, +) string { suggestedArgs := []string{} // If no positional argument exists, suggest one. diff --git a/core/cobra_utils_test.go b/core/cobra_utils_test.go index da9abd6f4e..cbd5dc81c1 100644 --- a/core/cobra_utils_test.go +++ b/core/cobra_utils_test.go @@ -117,7 +117,9 @@ func Test_handleUnmarshalErrors(t *testing.T) { Check: core.TestCheckCombine( core.TestCheckExitCode(1), core.TestCheckError(&core.CliError{ - Err: errors.New("invalid argument 'name_id': arg name must only contain lowercase letters, numbers or dashes"), + Err: errors.New( + "invalid argument 'name_id': arg name must only contain lowercase letters, numbers or dashes", + ), Hint: "Valid arguments are: name-id", }), ), @@ -129,7 +131,9 @@ func Test_handleUnmarshalErrors(t *testing.T) { Check: core.TestCheckCombine( core.TestCheckExitCode(1), core.TestCheckError(&core.CliError{ - Err: errors.New("invalid argument 'ubuntu_focal': arg name must only contain lowercase letters, numbers or dashes"), + Err: errors.New( + "invalid argument 'ubuntu_focal': arg name must only contain lowercase letters, numbers or dashes", + ), Hint: "Valid arguments are: name-id", }), ), diff --git a/core/command.go b/core/command.go index 86d806a36c..dcfa18e9d8 100644 --- a/core/command.go +++ b/core/command.go @@ -138,7 +138,10 @@ func (c *Command) getPath() string { } func (c *Command) GetCommandLine(binaryName string) string { - return strings.Trim(binaryName+" "+strings.ReplaceAll(c.getPath(), indexCommandSeparator, " "), " ") + return strings.Trim( + binaryName+" "+strings.ReplaceAll(c.getPath(), indexCommandSeparator, " "), + " ", + ) } func (c *Command) GetUsage(binaryName string, commands *Commands) string { @@ -268,7 +271,8 @@ func (c *Commands) Remove(namespace, verb string) { func (c *Commands) RemoveResource(namespace, resource string) { for i := range c.commands { - if c.commands[i].Namespace == namespace && c.commands[i].Resource == resource && c.commands[i].Verb == "" { + if c.commands[i].Namespace == namespace && c.commands[i].Resource == resource && + c.commands[i].Verb == "" { c.commands = append(c.commands[:i], c.commands[i+1:]...) return @@ -326,7 +330,8 @@ func (c *Commands) HasSubCommands(cmd *Command) bool { if cmd.Resource == "" && cmd.Namespace == command.Namespace { return true } - if cmd.Verb == "" && cmd.Namespace == command.Namespace && cmd.Resource == command.Resource { + if cmd.Verb == "" && cmd.Namespace == command.Namespace && + cmd.Resource == command.Resource { return true } } diff --git a/core/command_interceptor.go b/core/command_interceptor.go index d8b4323199..4c28c99847 100644 --- a/core/command_interceptor.go +++ b/core/command_interceptor.go @@ -27,9 +27,13 @@ func CombineCommandInterceptor(interceptors ...CommandInterceptor) CommandInterc previousInterceptor := combinedInterceptors combinedInterceptors = func(ctx context.Context, args interface{}, runner CommandRunner) (interface{}, error) { - return previousInterceptor(ctx, args, func(ctx context.Context, _ interface{}) (interface{}, error) { - return localInterceptor(ctx, args, runner) - }) + return previousInterceptor( + ctx, + args, + func(ctx context.Context, _ interface{}) (interface{}, error) { + return localInterceptor(ctx, args, runner) + }, + ) } } @@ -37,7 +41,11 @@ func CombineCommandInterceptor(interceptors ...CommandInterceptor) CommandInterc } // sdkStdErrorInterceptor is a command interceptor that will catch sdk standard error and return more friendly CLI error. -func sdkStdErrorInterceptor(ctx context.Context, args interface{}, runner CommandRunner) (interface{}, error) { +func sdkStdErrorInterceptor( + ctx context.Context, + args interface{}, + runner CommandRunner, +) (interface{}, error) { res, err := runner(ctx, args) switch sdkError := err.(type) { case *scw.ResourceNotFoundError: @@ -120,7 +128,11 @@ func sdkStdErrorInterceptor(ctx context.Context, args interface{}, runner Comman } // sdkStdErrorInterceptor is a command interceptor that will catch sdk standard error and return more friendly CLI error. -func sdkStdTypeInterceptor(ctx context.Context, args interface{}, runner CommandRunner) (interface{}, error) { +func sdkStdTypeInterceptor( + ctx context.Context, + args interface{}, + runner CommandRunner, +) (interface{}, error) { res, err := runner(ctx, args) if err != nil { return res, err diff --git a/core/context.go b/core/context.go index ac8f2040fa..a79255e68c 100644 --- a/core/context.go +++ b/core/context.go @@ -200,7 +200,11 @@ func ExtractCliConfigPath(ctx context.Context) string { func ReloadClient(ctx context.Context) error { var err error meta := extractMeta(ctx) - meta.Client, err = meta.Platform.CreateClient(meta.httpClient, ExtractConfigPath(ctx), ExtractProfileName(ctx)) + meta.Client, err = meta.Platform.CreateClient( + meta.httpClient, + ExtractConfigPath(ctx), + ExtractProfileName(ctx), + ) return err } diff --git a/core/default_test.go b/core/default_test.go index d7908a5cad..f3a9fa1bb8 100644 --- a/core/default_test.go +++ b/core/default_test.go @@ -48,8 +48,14 @@ func Test_ApplyDefaultValues(t *testing.T) { {Name: "friends.{index}.name", Default: core.DefaultValueSetter("bob")}, {Name: "friends.{index}.age", Default: core.DefaultValueSetter("42")}, }, - rawArgs: args.RawArgs{"name=paul", "friends.0.name=bob", "friends.1.name=alice"}, - expected: args.RawArgs{"name=paul", "friends.0.name=bob", "friends.1.name=alice", "friends.0.age=42", "friends.1.age=42"}, + rawArgs: args.RawArgs{"name=paul", "friends.0.name=bob", "friends.1.name=alice"}, + expected: args.RawArgs{ + "name=paul", + "friends.0.name=bob", + "friends.1.name=alice", + "friends.0.age=42", + "friends.1.age=42", + }, })) t.Run("Map", run(&testCase{ @@ -58,8 +64,14 @@ func Test_ApplyDefaultValues(t *testing.T) { {Name: "friends.{key}.age", Default: core.DefaultValueSetter("42")}, {Name: "friends.{key}.weight", Default: core.DefaultValueSetter("80")}, }, - rawArgs: args.RawArgs{"name=paul", "friends.bob.weight=75", "friends.alice.age=21"}, - expected: args.RawArgs{"name=paul", "friends.bob.weight=75", "friends.alice.age=21", "friends.bob.age=42", "friends.alice.weight=80"}, + rawArgs: args.RawArgs{"name=paul", "friends.bob.weight=75", "friends.alice.age=21"}, + expected: args.RawArgs{ + "name=paul", + "friends.bob.weight=75", + "friends.alice.age=21", + "friends.bob.age=42", + "friends.alice.weight=80", + }, })) t.Run("Map of slice", run(&testCase{ diff --git a/core/errors.go b/core/errors.go index 54cb862ac0..c5e7dfe133 100644 --- a/core/errors.go +++ b/core/errors.go @@ -11,7 +11,11 @@ func MissingRequiredArgumentError(argumentName string) *CliError { } } -func InvalidValueForEnumError(argSpecName string, argSpecEnumValues []string, value string) *CliError { +func InvalidValueForEnumError( + argSpecName string, + argSpecEnumValues []string, + value string, +) *CliError { return &CliError{ Err: fmt.Errorf("invalid value '%v' for arg '%v'", value, argSpecName), Hint: fmt.Sprintf("Accepted values for '%v' are %v", argSpecName, argSpecEnumValues), @@ -69,7 +73,11 @@ func InvalidAPIURLError(value string) *CliError { func ArgumentConflictError(arg1 string, arg2 string) *CliError { return &CliError{ - Err: fmt.Errorf("only one of those two arguments '%s' and '%s' can be specified in the same time", arg1, arg2), + Err: fmt.Errorf( + "only one of those two arguments '%s' and '%s' can be specified in the same time", + arg1, + arg2, + ), } } diff --git a/core/errors_cmp.go b/core/errors_cmp.go index af8a7f2c7a..51fb50fac3 100644 --- a/core/errors_cmp.go +++ b/core/errors_cmp.go @@ -11,5 +11,6 @@ func IsNotFoundError(err error) bool { notFoundError := &scw.ResourceNotFoundError{} responseError := &scw.ResponseError{} - return errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) + return errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || + errors.As(err, ¬FoundError) } diff --git a/core/example.go b/core/example.go index 278bb16b57..8fb79219d1 100644 --- a/core/example.go +++ b/core/example.go @@ -66,6 +66,12 @@ func (e *Example) GetCommandLine(binaryName string, cmd *Command) string { return strings.Join(commandParts, " ") default: - panic(fmt.Errorf("in command '%s' invalid example '%s', it should either have a ArgsJSON or a Raw", cmd.getPath(), cmd.Short)) + panic( + fmt.Errorf( + "in command '%s' invalid example '%s', it should either have a ArgsJSON or a Raw", + cmd.getPath(), + cmd.Short, + ), + ) } } diff --git a/core/human/marshal.go b/core/human/marshal.go index 02244f8d11..f3c4b02145 100644 --- a/core/human/marshal.go +++ b/core/human/marshal.go @@ -134,7 +134,9 @@ func marshalStruct(value reflect.Value, opt *MarshalOpt) (string, error) { // If data is a stringers case rType.Implements(reflect.TypeOf((*fmt.Stringer)(nil)).Elem()): - return [][]string{{strings.Join(keys, "."), value.Interface().(fmt.Stringer).String()}}, nil + return [][]string{ + {strings.Join(keys, "."), value.Interface().(fmt.Stringer).String()}, + }, nil case rType.Kind() == reflect.Ptr: // If type is a pointer we Marshal pointer.Elem() @@ -182,7 +184,10 @@ func marshalStruct(value reflect.Value, opt *MarshalOpt) (string, error) { // We loop through all struct field data := [][]string(nil) for _, fieldIndex := range GetStructFieldsIndex(value.Type()) { - subData, err := marshal(value.FieldByIndex(fieldIndex), append(keys, value.Type().FieldByIndex(fieldIndex).Name)) + subData, err := marshal( + value.FieldByIndex(fieldIndex), + append(keys, value.Type().FieldByIndex(fieldIndex).Name), + ) if err != nil { return nil, err } @@ -317,7 +322,10 @@ func marshalSlice(slice reflect.Value, opt *MarshalOpt) (string, error) { for _, fieldSpec := range opt.Fields { v, err := gofields.GetValue(item.Interface(), fieldSpec.FieldName) if err != nil { - logger.Debugf("invalid getFieldValue(): '%v' might not be exported", fieldSpec.FieldName) + logger.Debugf( + "invalid getFieldValue(): '%v' might not be exported", + fieldSpec.FieldName, + ) row = append(row, "") continue diff --git a/core/human/marshal_func.go b/core/human/marshal_func.go index 9419c6a36d..7b401e3aee 100644 --- a/core/human/marshal_func.go +++ b/core/human/marshal_func.go @@ -28,109 +28,142 @@ func init() { marshalerFuncs.Store(reflect.TypeOf(uint32(0)), defaultMarshalerFunc) marshalerFuncs.Store(reflect.TypeOf(uint64(0)), defaultMarshalerFunc) marshalerFuncs.Store(reflect.TypeOf(string("")), defaultMarshalerFunc) - marshalerFuncs.Store(reflect.TypeOf(bool(false)), func(i interface{}, _ *MarshalOpt) (string, error) { - v := i.(bool) - if v { - return terminal.Style("true", color.FgGreen), nil - } + marshalerFuncs.Store( + reflect.TypeOf(bool(false)), + func(i interface{}, _ *MarshalOpt) (string, error) { + v := i.(bool) + if v { + return terminal.Style("true", color.FgGreen), nil + } - return terminal.Style("false", color.FgRed), nil - }) - marshalerFuncs.Store(reflect.TypeOf(time.Time{}), func(i interface{}, _ *MarshalOpt) (string, error) { - return humanize.Time(i.(time.Time)), nil - }) - marshalerFuncs.Store(reflect.TypeOf(&time.Time{}), func(i interface{}, _ *MarshalOpt) (string, error) { - t := i.(*time.Time) - if t == nil { - return Marshal(nil, nil) - } + return terminal.Style("false", color.FgRed), nil + }, + ) + marshalerFuncs.Store( + reflect.TypeOf(time.Time{}), + func(i interface{}, _ *MarshalOpt) (string, error) { + return humanize.Time(i.(time.Time)), nil + }, + ) + marshalerFuncs.Store( + reflect.TypeOf(&time.Time{}), + func(i interface{}, _ *MarshalOpt) (string, error) { + t := i.(*time.Time) + if t == nil { + return Marshal(nil, nil) + } - return Marshal(*t, nil) - }) - marshalerFuncs.Store(reflect.TypeOf(scw.Size(0)), func(i interface{}, _ *MarshalOpt) (string, error) { - size := uint64(i.(scw.Size)) + return Marshal(*t, nil) + }, + ) + marshalerFuncs.Store( + reflect.TypeOf(scw.Size(0)), + func(i interface{}, _ *MarshalOpt) (string, error) { + size := uint64(i.(scw.Size)) - if isIECNotation := size%1024 == 0 && size%1000 != 0; isIECNotation { - return humanize.IBytes(size), nil - } + if isIECNotation := size%1024 == 0 && size%1000 != 0; isIECNotation { + return humanize.IBytes(size), nil + } - return humanize.Bytes(size), nil - }) - marshalerFuncs.Store(reflect.TypeOf(scw.SizePtr(0)), func(i interface{}, _ *MarshalOpt) (string, error) { - size := uint64(*i.(*scw.Size)) + return humanize.Bytes(size), nil + }, + ) + marshalerFuncs.Store( + reflect.TypeOf(scw.SizePtr(0)), + func(i interface{}, _ *MarshalOpt) (string, error) { + size := uint64(*i.(*scw.Size)) - if isIECNotation := size%1024 == 0 && size%1000 != 0; isIECNotation { - return humanize.IBytes(size), nil - } + if isIECNotation := size%1024 == 0 && size%1000 != 0; isIECNotation { + return humanize.IBytes(size), nil + } - return humanize.Bytes(size), nil - }) - marshalerFuncs.Store(reflect.TypeOf([]scw.Size{}), func(i interface{}, _ *MarshalOpt) (string, error) { - sizes := i.([]scw.Size) - strs := []string(nil) - for _, size := range sizes { - s, err := Marshal(size, nil) - if err != nil { - return "", err + return humanize.Bytes(size), nil + }, + ) + marshalerFuncs.Store( + reflect.TypeOf([]scw.Size{}), + func(i interface{}, _ *MarshalOpt) (string, error) { + sizes := i.([]scw.Size) + strs := []string(nil) + for _, size := range sizes { + s, err := Marshal(size, nil) + if err != nil { + return "", err + } + strs = append(strs, s) } - strs = append(strs, s) - } - return strings.Join(strs, ", "), nil - }) - marshalerFuncs.Store(reflect.TypeOf(net.IP{}), func(i interface{}, _ *MarshalOpt) (string, error) { - return fmt.Sprintf("%v", i.(net.IP)), nil - }) - marshalerFuncs.Store(reflect.TypeOf([]net.IP{}), func(i interface{}, _ *MarshalOpt) (string, error) { - return fmt.Sprintf("%v", i), nil - }) - marshalerFuncs.Store(reflect.TypeOf(scw.IPNet{}), func(i interface{}, _ *MarshalOpt) (string, error) { - v := i.(scw.IPNet) - str := v.String() - if str == "" { - return "-", nil - } + return strings.Join(strs, ", "), nil + }, + ) + marshalerFuncs.Store( + reflect.TypeOf(net.IP{}), + func(i interface{}, _ *MarshalOpt) (string, error) { + return fmt.Sprintf("%v", i.(net.IP)), nil + }, + ) + marshalerFuncs.Store( + reflect.TypeOf([]net.IP{}), + func(i interface{}, _ *MarshalOpt) (string, error) { + return fmt.Sprintf("%v", i), nil + }, + ) + marshalerFuncs.Store( + reflect.TypeOf(scw.IPNet{}), + func(i interface{}, _ *MarshalOpt) (string, error) { + v := i.(scw.IPNet) + str := v.String() + if str == "" { + return "-", nil + } - return str, nil - }) - marshalerFuncs.Store(reflect.TypeOf(version.Version{}), func(i interface{}, _ *MarshalOpt) (string, error) { - v := i.(version.Version) + return str, nil + }, + ) + marshalerFuncs.Store( + reflect.TypeOf(version.Version{}), + func(i interface{}, _ *MarshalOpt) (string, error) { + v := i.(version.Version) - return v.String(), nil - }) - marshalerFuncs.Store(reflect.TypeOf(scw.Duration{}), func(i interface{}, _ *MarshalOpt) (string, error) { - v := i.(scw.Duration) - const ( - minutes = int64(60) - hours = 60 * minutes - days = 24 * hours - ) - d := v.Seconds / days - h := (v.Seconds - d*days) / hours - m := (v.Seconds - (d*days + h*hours)) / minutes - s := v.Seconds % 60 - res := []string(nil) - if d != 0 { - res = append(res, fmt.Sprintf("%d days", d)) - } - if h != 0 { - res = append(res, fmt.Sprintf("%d hours", h)) - } - if m != 0 { - res = append(res, fmt.Sprintf("%d minutes", m)) - } - if s != 0 { - res = append(res, fmt.Sprintf("%d seconds", s)) - } - if v.Nanos != 0 { - res = append(res, fmt.Sprintf("%d nanoseconds", v.Nanos)) - } - if len(res) == 0 { - return "0 seconds", nil - } + return v.String(), nil + }, + ) + marshalerFuncs.Store( + reflect.TypeOf(scw.Duration{}), + func(i interface{}, _ *MarshalOpt) (string, error) { + v := i.(scw.Duration) + const ( + minutes = int64(60) + hours = 60 * minutes + days = 24 * hours + ) + d := v.Seconds / days + h := (v.Seconds - d*days) / hours + m := (v.Seconds - (d*days + h*hours)) / minutes + s := v.Seconds % 60 + res := []string(nil) + if d != 0 { + res = append(res, fmt.Sprintf("%d days", d)) + } + if h != 0 { + res = append(res, fmt.Sprintf("%d hours", h)) + } + if m != 0 { + res = append(res, fmt.Sprintf("%d minutes", m)) + } + if s != 0 { + res = append(res, fmt.Sprintf("%d seconds", s)) + } + if v.Nanos != 0 { + res = append(res, fmt.Sprintf("%d nanoseconds", v.Nanos)) + } + if len(res) == 0 { + return "0 seconds", nil + } - return strings.Join(res, " "), nil - }) + return strings.Join(res, " "), nil + }, + ) registerMarshaler(func(i scw.JSONObject, _ *MarshalOpt) (string, error) { data, err := json.Marshal(i) if err != nil { diff --git a/core/printer.go b/core/printer.go index f128599d35..dd90731fb8 100644 --- a/core/printer.go +++ b/core/printer.go @@ -95,7 +95,11 @@ func setupJSONPrinter(printer *Printer, opts string) error { printer.jsonPretty = true case "": default: - return fmt.Errorf("invalid option %s for json outout. Valid options are: %s", opts, PrinterOptJSONPretty) + return fmt.Errorf( + "invalid option %s for json outout. Valid options are: %s", + opts, + PrinterOptJSONPretty, + ) } return nil @@ -190,7 +194,12 @@ func (p *Printer) printHuman(data interface{}, opt *human.MarshalOpt) error { } if len(p.humanFields) > 0 && reflect.TypeOf(data).Kind() != reflect.Slice { - return p.printHuman(errors.New("list of fields for human output is only supported for commands that return a list"), nil) + return p.printHuman( + errors.New( + "list of fields for human output is only supported for commands that return a list", + ), + nil, + ) } if len(p.humanFields) > 0 { @@ -307,7 +316,10 @@ func (p *Printer) printTemplate(data interface{}) error { return p.printHuman(&CliError{ Err: err, Message: "templating error", - Hint: "Acceptable values are:\n - " + strings.Join(gofields.ListFields(elemValue.Type()), "\n - "), + Hint: "Acceptable values are:\n - " + strings.Join( + gofields.ListFields(elemValue.Type()), + "\n - ", + ), }, nil) } _, err = writer.Write([]byte{'\n'}) diff --git a/core/reflect.go b/core/reflect.go index 043d188c07..dd53cd3258 100644 --- a/core/reflect.go +++ b/core/reflect.go @@ -24,7 +24,13 @@ func newObjectWithForcedJSONTags(t reflect.Type) interface{} { } for i := range anonymousType.NumField() { fieldCopy := anonymousType.Field(i) - fieldCopy.Tag = reflect.StructTag(`json:"` + strings.ReplaceAll(strcase.ToBashArg(fieldCopy.Name), "-", "_") + `"`) + fieldCopy.Tag = reflect.StructTag( + `json:"` + strings.ReplaceAll( + strcase.ToBashArg(fieldCopy.Name), + "-", + "_", + ) + `"`, + ) structFieldsCopy = append(structFieldsCopy, fieldCopy) } } else { @@ -38,7 +44,10 @@ func newObjectWithForcedJSONTags(t reflect.Type) interface{} { // GetValuesForFieldByName recursively search for fields in a cmdArgs' value and returns its values if they exist. // The search is based on the name of the field. -func GetValuesForFieldByName(value reflect.Value, parts []string) (values []reflect.Value, err error) { +func GetValuesForFieldByName( + value reflect.Value, + parts []string, +) (values []reflect.Value, err error) { if len(parts) == 0 { return []reflect.Value{value}, nil } diff --git a/core/reflect_test.go b/core/reflect_test.go index a015a41cb7..54b9cd07bf 100644 --- a/core/reflect_test.go +++ b/core/reflect_test.go @@ -88,7 +88,10 @@ func Test_getValuesForFieldByName(t *testing.T) { }, testFunc: func(t *testing.T, tc TestCase) { t.Helper() - values, err := core.GetValuesForFieldByName(reflect.ValueOf(tc.cmdArgs), strings.Split(tc.fieldName, ".")) + values, err := core.GetValuesForFieldByName( + reflect.ValueOf(tc.cmdArgs), + strings.Split(tc.fieldName, "."), + ) if err != nil { assert.Equal(t, tc.expectedError, err.Error()) } else if tc.expectedValues != nil && !reflect.DeepEqual(tc.expectedValues[0].Interface(), values[0].Interface()) { @@ -117,7 +120,10 @@ func Test_getValuesForFieldByName(t *testing.T) { }, testFunc: func(t *testing.T, tc TestCase) { t.Helper() - values, err := core.GetValuesForFieldByName(reflect.ValueOf(tc.cmdArgs), strings.Split(tc.fieldName, ".")) + values, err := core.GetValuesForFieldByName( + reflect.ValueOf(tc.cmdArgs), + strings.Split(tc.fieldName, "."), + ) if err != nil { assert.Equal(t, tc.expectedError, err.Error()) } else if tc.expectedValues != nil && !reflect.DeepEqual(tc.expectedValues[0].Interface(), values[0].Interface()) { @@ -159,7 +165,10 @@ func Test_getValuesForFieldByName(t *testing.T) { }, testFunc: func(t *testing.T, tc TestCase) { t.Helper() - values, err := core.GetValuesForFieldByName(reflect.ValueOf(tc.cmdArgs), strings.Split(tc.fieldName, ".")) + values, err := core.GetValuesForFieldByName( + reflect.ValueOf(tc.cmdArgs), + strings.Split(tc.fieldName, "."), + ) if err != nil { assert.Nil(t, err.Error()) } else if tc.expectedValues != nil && !reflect.DeepEqual(tc.expectedValues[0].Interface(), values[0].Interface()) { diff --git a/core/result_test.go b/core/result_test.go index 446912ca7e..7ed2b04c45 100644 --- a/core/result_test.go +++ b/core/result_test.go @@ -19,7 +19,7 @@ func TestResult(t *testing.T) { humanOutput, err := result.MarshalHuman() require.NoError(t, err) - assert.Equal(t, "", humanOutput) + assert.Empty(t, humanOutput) jsonOutput, err := result.MarshalJSON() require.NoError(t, err) assert.JSONEq(t, "{}", string(jsonOutput)) diff --git a/core/shell.go b/core/shell.go index 8af5a4228f..969d2f36d3 100644 --- a/core/shell.go +++ b/core/shell.go @@ -202,7 +202,8 @@ func sortOptions(meta *Meta, args []string, toSuggest string, suggestions []stri } sort.Slice(argSpecs, func(i, j int) bool { - if argSpecs[i].Arg != nil && argSpecs[j].Arg != nil && argSpecs[i].Arg.Required != argSpecs[j].Arg.Required { + if argSpecs[i].Arg != nil && argSpecs[j].Arg != nil && + argSpecs[i].Arg.Required != argSpecs[j].Arg.Required { return argSpecs[i].Arg.Required } @@ -227,7 +228,9 @@ func (c *Completer) Complete(d prompt.Document) []prompt.Suggest { meta := extractMeta(c.ctx) - argsBeforeCursor := meta.CliConfig.Alias.ResolveAliases(strings.Split(d.TextBeforeCursor(), " ")) + argsBeforeCursor := meta.CliConfig.Alias.ResolveAliases( + strings.Split(d.TextBeforeCursor(), " "), + ) argsAfterCursor := meta.CliConfig.Alias.ResolveAliases(strings.Split(d.TextAfterCursor(), " ")) currentArg := lastArg(argsBeforeCursor) + firstArg(argsAfterCursor) @@ -316,7 +319,13 @@ func getShellCommand(rootCmd *cobra.Command) *cobra.Command { } // RunShell will run an interactive shell that runs cobra commands -func RunShell(ctx context.Context, printer *Printer, meta *Meta, rootCmd *cobra.Command, args []string) { +func RunShell( + ctx context.Context, + printer *Printer, + meta *Meta, + rootCmd *cobra.Command, + args []string, +) { autoCompleteCache = cache.New() completer := NewShellCompleter(ctx) diff --git a/core/shell_test.go b/core/shell_test.go index 2e53510940..8952654b3b 100644 --- a/core/shell_test.go +++ b/core/shell_test.go @@ -45,6 +45,12 @@ func TestShell_isOption(t *testing.T) { }, } for _, test := range tt { - assert.Equal(t, core.ArgIsOption(test.Arg), test.IsOption, "%s option value is wrong", test.Arg) + assert.Equal( + t, + core.ArgIsOption(test.Arg), + test.IsOption, + "%s option value is wrong", + test.Arg, + ) } } diff --git a/core/testing.go b/core/testing.go index 25d03b786a..3f9cc6619b 100644 --- a/core/testing.go +++ b/core/testing.go @@ -39,10 +39,18 @@ const TestBucketNamePrefix = "cli-test-bucket" // You can create a binary of each test using "go test -c -o myBinary" var ( // UpdateGoldens will update all the golden files of a given test - UpdateGoldens = flag.Bool("goldens", os.Getenv("CLI_UPDATE_GOLDENS") == "true", "Record goldens") + UpdateGoldens = flag.Bool( + "goldens", + os.Getenv("CLI_UPDATE_GOLDENS") == "true", + "Record goldens", + ) // UpdateCassettes will update all cassettes of a given test - UpdateCassettes = flag.Bool("cassettes", os.Getenv("CLI_UPDATE_CASSETTES") == "true", "Record Cassettes") + UpdateCassettes = flag.Bool( + "cassettes", + os.Getenv("CLI_UPDATE_CASSETTES") == "true", + "Record Cassettes", + ) // Debug set the log level to LogLevelDebug Debug = flag.Bool("debug", os.Getenv("SCW_DEBUG") == "true", "Enable Debug Mode") @@ -82,7 +90,10 @@ type CheckFuncCtx struct { var testRenderHelpers = map[string]any{ "randint": func() string { - return strconv.FormatUint(rand.Uint64(), 10) //nolint:gosec // Use weak random for a non-important use + return strconv.FormatUint( + rand.Uint64(), + 10, + ) }, } @@ -93,7 +104,11 @@ type TestMetadata map[string]interface{} func (meta TestMetadata) Render(strTpl string) string { t := meta["t"].(*testing.T) buf := &bytes.Buffer{} - require.NoError(t, template.Must(template.New("tpl").Funcs(testRenderHelpers).Parse(strTpl)).Execute(buf, meta)) + require.NoError( + t, + template.Must(template.New("tpl").Funcs(testRenderHelpers).Parse(strTpl)). + Execute(buf, meta), + ) return buf.String() } @@ -224,7 +239,11 @@ func getTestFilePath(t *testing.T, suffix string) string { return filepath.Join(".", "testdata", fileName) } -func createTestClient(t *testing.T, testConfig *TestConfig, httpClient *http.Client) (client *scw.Client) { +func createTestClient( + t *testing.T, + testConfig *TestConfig, + httpClient *http.Client, +) (client *scw.Client) { t.Helper() var err error @@ -274,7 +293,8 @@ func createTestClient(t *testing.T, testConfig *TestConfig, httpClient *http.Cli res, err := test.NewAPI(client).Register(&test.RegisterRequest{Username: "sidi"}) require.NoError(t, err) - client, err = scw.NewClient(append(clientOpts, scw.WithAuth(res.AccessKey, res.SecretKey))...) + client, err = scw.NewClient( + append(clientOpts, scw.WithAuth(res.AccessKey, res.SecretKey))...) require.NoError(t, err) } @@ -308,9 +328,12 @@ func Test(config *TestConfig) func(t *testing.T) { // Because human marshal of date is relative (e.g 3 minutes ago) we must make sure it stay consistent for golden to works. // Here we return a constant string. We may need to find a better place to put this. - human.RegisterMarshalerFunc(time.Time{}, func(_ interface{}, _ *human.MarshalOpt) (string, error) { - return "few seconds ago", nil - }) + human.RegisterMarshalerFunc( + time.Time{}, + func(_ interface{}, _ *human.MarshalOpt) (string, error) { + return "few seconds ago", nil + }, + ) if !*UpdateCassettes { tmp := 0 * time.Second @@ -402,7 +425,14 @@ func Test(config *TestConfig) func(t *testing.T) { HTTPClient: httpClient, Platform: terminal.NewPlatform(buildInfo.GetUserAgent()), }) - require.NoError(t, err, "error executing cmd (%s)\nstdout: %s\nstderr: %s", args, stdoutBuffer.String(), stderrBuffer.String()) + require.NoError( + t, + err, + "error executing cmd (%s)\nstdout: %s\nstderr: %s", + args, + stdoutBuffer.String(), + stderrBuffer.String(), + ) return result } @@ -716,7 +746,10 @@ func TestCheckS3Golden() TestCheck { // In order to avoid diff in goldens we set all timestamp to the same date if *UpdateGoldens { require.NoError(t, os.MkdirAll(path.Dir(goldenPath), 0o755)) - require.NoError(t, os.WriteFile(goldenPath, []byte(normalizedActual), 0o644)) //nolint:gosec + require.NoError( + t, + os.WriteFile(goldenPath, []byte(normalizedActual), 0o644), + ) } expected, err := os.ReadFile(goldenPath) @@ -809,25 +842,38 @@ func marshalGolden(t *testing.T, ctx *CheckFuncCtx) string { } buffer := bytes.Buffer{} - buffer.WriteString(fmt.Sprintf("\U0001F3B2\U0001F3B2\U0001F3B2 EXIT CODE: %d \U0001F3B2\U0001F3B2\U0001F3B2\n", ctx.ExitCode)) + buffer.WriteString( + fmt.Sprintf( + "\U0001F3B2\U0001F3B2\U0001F3B2 EXIT CODE: %d \U0001F3B2\U0001F3B2\U0001F3B2\n", + ctx.ExitCode, + ), + ) if len(ctx.Stdout) > 0 { - buffer.WriteString("\U0001F7E9\U0001F7E9\U0001F7E9 STDOUT️ \U0001F7E9\U0001F7E9\U0001F7E9️\n") + buffer.WriteString( + "\U0001F7E9\U0001F7E9\U0001F7E9 STDOUT️ \U0001F7E9\U0001F7E9\U0001F7E9️\n", + ) buffer.Write(ctx.Stdout) } if len(ctx.Stderr) > 0 { - buffer.WriteString("\U0001F7E5\U0001F7E5\U0001F7E5 STDERR️️ \U0001F7E5\U0001F7E5\U0001F7E5️\n") + buffer.WriteString( + "\U0001F7E5\U0001F7E5\U0001F7E5 STDERR️️ \U0001F7E5\U0001F7E5\U0001F7E5️\n", + ) buffer.Write(ctx.Stderr) } if jsonStdout.Len() > 0 { - buffer.WriteString("\U0001F7E9\U0001F7E9\U0001F7E9 JSON STDOUT \U0001F7E9\U0001F7E9\U0001F7E9\n") + buffer.WriteString( + "\U0001F7E9\U0001F7E9\U0001F7E9 JSON STDOUT \U0001F7E9\U0001F7E9\U0001F7E9\n", + ) buffer.Write(jsonStdout.Bytes()) } if jsonStderr.Len() > 0 { - buffer.WriteString("\U0001F7E5\U0001F7E5\U0001F7E5 JSON STDERR \U0001F7E5\U0001F7E5\U0001F7E5\n") + buffer.WriteString( + "\U0001F7E5\U0001F7E5\U0001F7E5 JSON STDERR \U0001F7E5\U0001F7E5\U0001F7E5\n", + ) buffer.Write(jsonStderr.Bytes()) } diff --git a/core/testing_recorder.go b/core/testing_recorder.go index dee1fcfff9..e2a7dc7ac6 100644 --- a/core/testing_recorder.go +++ b/core/testing_recorder.go @@ -18,22 +18,30 @@ import ( func cassetteRequestFilter(i *cassette.Interaction) error { delete(i.Request.Headers, "x-auth-token") delete(i.Request.Headers, "X-Auth-Token") - i.Request.URL = regexp.MustCompile("organization_id=[0-9a-f-]{36}").ReplaceAllString(i.Request.URL, "organization_id=11111111-1111-1111-1111-111111111111") - i.Request.URL = regexp.MustCompile(`api\.scaleway\.com/account/v1/tokens/[0-9a-f-]{36}`).ReplaceAllString(i.Request.URL, "api.scaleway.com/account/v1/tokens/11111111-1111-1111-1111-111111111111") - i.Request.URL = regexp.MustCompile(`^api\.scaleway\.com/iam/v1alpha1/api-keys/SCW[0-9A-Z]{17}`).ReplaceAllString(i.Request.URL, "api.scaleway.com/iam/v1alpha1/api-keys/SCWXXXXXXXXXXXXXXXXX") + i.URL = regexp.MustCompile("organization_id=[0-9a-f-]{36}"). + ReplaceAllString(i.URL, "organization_id=11111111-1111-1111-1111-111111111111") + i.URL = regexp.MustCompile(`api\.scaleway\.com/account/v1/tokens/[0-9a-f-]{36}`). + ReplaceAllString(i.URL, "api.scaleway.com/account/v1/tokens/11111111-1111-1111-1111-111111111111") + i.URL = regexp.MustCompile(`^api\.scaleway\.com/iam/v1alpha1/api-keys/SCW[0-9A-Z]{17}`). + ReplaceAllString(i.URL, "api.scaleway.com/iam/v1alpha1/api-keys/SCWXXXXXXXXXXXXXXXXX") return nil } func cassetteResponseFilter(i *cassette.Interaction) error { - i.Response.Body = regexp.MustCompile(`"secret_key":"[0-9a-f-]{36}"`).ReplaceAllString(i.Response.Body, `"secret_key":"11111111-1111-1111-1111-111111111111"`) + i.Response.Body = regexp.MustCompile(`"secret_key":"[0-9a-f-]{36}"`). + ReplaceAllString(i.Response.Body, `"secret_key":"11111111-1111-1111-1111-111111111111"`) // Buildpacks - i.Request.URL = regexp.MustCompile(`pack\.local%2Fbuilder%2F[0-9a-f]{20}`).ReplaceAllString(i.Request.URL, "pack.local%2Fbuilder%2F11111111111111111111") - i.Request.URL = regexp.MustCompile(`pack\.local/builder/[0-9a-f]{20}`).ReplaceAllString(i.Request.URL, "pack.local/builder/11111111111111111111") + i.URL = regexp.MustCompile(`pack\.local%2Fbuilder%2F[0-9a-f]{20}`). + ReplaceAllString(i.URL, "pack.local%2Fbuilder%2F11111111111111111111") + i.URL = regexp.MustCompile(`pack\.local/builder/[0-9a-f]{20}`). + ReplaceAllString(i.URL, "pack.local/builder/11111111111111111111") - i.Request.Body = regexp.MustCompile(`pack\.local/builder/[0-9a-f]{20}`).ReplaceAllString(i.Response.Body, "pack.local/builder/11111111111111111111") - i.Response.Body = regexp.MustCompile(`pack\.local/builder/[0-9a-f]{20}`).ReplaceAllString(i.Response.Body, "pack.local/builder/11111111111111111111") + i.Request.Body = regexp.MustCompile(`pack\.local/builder/[0-9a-f]{20}`). + ReplaceAllString(i.Response.Body, "pack.local/builder/11111111111111111111") + i.Response.Body = regexp.MustCompile(`pack\.local/builder/[0-9a-f]{20}`). + ReplaceAllString(i.Response.Body, "pack.local/builder/11111111111111111111") return nil } @@ -49,8 +57,10 @@ func cassetteMatcher(r *http.Request, i cassette.Request) bool { r.URL.Host = unixDockerEngine } - r.URL.RawQuery = regexp.MustCompile(`pack\.local%2Fbuilder%2F[0-9a-f]{20}`).ReplaceAllString(r.URL.RawQuery, "pack.local%2Fbuilder%2F11111111111111111111") - r.URL.Path = regexp.MustCompile(`pack\.local/builder/[0-9a-f]{20}`).ReplaceAllString(r.URL.Path, "pack.local/builder/11111111111111111111") + r.URL.RawQuery = regexp.MustCompile(`pack\.local%2Fbuilder%2F[0-9a-f]{20}`). + ReplaceAllString(r.URL.RawQuery, "pack.local%2Fbuilder%2F11111111111111111111") + r.URL.Path = regexp.MustCompile(`pack\.local/builder/[0-9a-f]{20}`). + ReplaceAllString(r.URL.Path, "pack.local/builder/11111111111111111111") // Read body if r.Body != nil && r.Body != http.NoBody { @@ -121,7 +131,11 @@ func getHTTPRecoder(t *testing.T, update bool) (client *http.Client, cleanup fun } // Setup recorder and scw client - r, err := recorder.NewAsMode(getTestFilePath(t, ".cassette"), recorderMode, &SocketPassthroughTransport{}) + r, err := recorder.NewAsMode( + getTestFilePath(t, ".cassette"), + recorderMode, + &SocketPassthroughTransport{}, + ) if err != nil { return nil, nil, err } diff --git a/core/validate.go b/core/validate.go index 1f7665b903..d062e154a9 100644 --- a/core/validate.go +++ b/core/validate.go @@ -51,9 +51,17 @@ func DefaultCommandValidateFunc() CommandValidateFunc { func validateArgValues(cmd *Command, cmdArgs interface{}) error { for _, argSpec := range cmd.ArgSpecs { fieldName := strcase.ToPublicGoName(argSpec.Name) - fieldValues, err := GetValuesForFieldByName(reflect.ValueOf(cmdArgs), strings.Split(fieldName, ".")) + fieldValues, err := GetValuesForFieldByName( + reflect.ValueOf(cmdArgs), + strings.Split(fieldName, "."), + ) if err != nil { - logger.Infof("could not validate arg value for '%v': invalid fieldName: %v: %v", argSpec.Name, fieldName, err.Error()) + logger.Infof( + "could not validate arg value for '%v': invalid fieldName: %v: %v", + argSpec.Name, + fieldName, + err.Error(), + ) continue } @@ -83,9 +91,17 @@ func validateRequiredArgs(cmd *Command, cmdArgs interface{}, rawArgs args.RawArg } fieldName := strcase.ToPublicGoName(arg.Name) - fieldValues, err := GetValuesForFieldByName(reflect.ValueOf(cmdArgs), strings.Split(fieldName, ".")) + fieldValues, err := GetValuesForFieldByName( + reflect.ValueOf(cmdArgs), + strings.Split(fieldName, "."), + ) if err != nil { - validationErr := fmt.Errorf("could not validate arg value for '%v': invalid field name '%v': %v", arg.Name, fieldName, err.Error()) + validationErr := fmt.Errorf( + "could not validate arg value for '%v': invalid field name '%v': %v", + arg.Name, + fieldName, + err.Error(), + ) if !arg.Required { logger.Infof(validationErr.Error()) @@ -100,7 +116,9 @@ func validateRequiredArgs(cmd *Command, cmdArgs interface{}, rawArgs args.RawArg // TODO handle required maps for i := range fieldValues { if !rawArgs.ExistsArgByName(strings.Replace(arg.Name, "{index}", strconv.Itoa(i), 1)) { - return MissingRequiredArgumentError(strings.Replace(arg.Name, "{index}", strconv.Itoa(i), 1)) + return MissingRequiredArgumentError( + strings.Replace(arg.Name, "{index}", strconv.Itoa(i), 1), + ) } } } @@ -139,13 +157,26 @@ func ValidateNoConflict(cmd *Command, rawArgs args.RawArgs) error { } // validateDeprecated print a warning message if a deprecated argument is used -func validateDeprecated(ctx context.Context, cmd *Command, cmdArgs interface{}, rawArgs args.RawArgs) { +func validateDeprecated( + ctx context.Context, + cmd *Command, + cmdArgs interface{}, + rawArgs args.RawArgs, +) { deprecatedArgs := cmd.ArgSpecs.GetDeprecated(true) for _, arg := range deprecatedArgs { fieldName := strcase.ToPublicGoName(arg.Name) - fieldValues, err := GetValuesForFieldByName(reflect.ValueOf(cmdArgs), strings.Split(fieldName, ".")) + fieldValues, err := GetValuesForFieldByName( + reflect.ValueOf(cmdArgs), + strings.Split(fieldName, "."), + ) if err != nil { - validationErr := fmt.Errorf("could not validate arg value for '%v': invalid field name '%v': %v", arg.Name, fieldName, err.Error()) + validationErr := fmt.Errorf( + "could not validate arg value for '%v': invalid field name '%v': %v", + arg.Name, + fieldName, + err.Error(), + ) if !arg.Required { logger.Infof(validationErr.Error()) @@ -157,7 +188,9 @@ func validateDeprecated(ctx context.Context, cmd *Command, cmdArgs interface{}, for i := range fieldValues { if rawArgs.ExistsArgByName(strings.Replace(arg.Name, "{index}", strconv.Itoa(i), 1)) { helpCmd := cmd.GetCommandLine(extractMeta(ctx).BinaryName) + " --help" - ExtractLogger(ctx).Warningf("The argument '%s' is deprecated, more info with: %s\n", arg.Name, helpCmd) + ExtractLogger( + ctx, + ).Warningf("The argument '%s' is deprecated, more info with: %s\n", arg.Name, helpCmd) } } } @@ -301,14 +334,25 @@ func NewOneOfGroupManager(cmd *Command) *OneOfGroupManager { return manager } -func (m *OneOfGroupManager) ValidateUniqueOneOfGroups(rawArgs args.RawArgs, cmdArgs interface{}) error { +func (m *OneOfGroupManager) ValidateUniqueOneOfGroups( + rawArgs args.RawArgs, + cmdArgs interface{}, +) error { for groupName, groupArgs := range m.Groups { existingArg := "" for _, argName := range groupArgs { fieldName := strcase.ToPublicGoName(argName) - fieldValues, err := GetValuesForFieldByName(reflect.ValueOf(cmdArgs), strings.Split(fieldName, ".")) + fieldValues, err := GetValuesForFieldByName( + reflect.ValueOf(cmdArgs), + strings.Split(fieldName, "."), + ) if err != nil { - validationErr := fmt.Errorf("could not validate arg value for '%v': invalid field name '%v': %v", argName, fieldName, err.Error()) + validationErr := fmt.Errorf( + "could not validate arg value for '%v': invalid field name '%v': %v", + argName, + fieldName, + err.Error(), + ) if m.RequiredGroups[groupName] { logger.Infof(validationErr.Error()) @@ -320,7 +364,11 @@ func (m *OneOfGroupManager) ValidateUniqueOneOfGroups(rawArgs args.RawArgs, cmdA argNameWithIndex := strings.Replace(argName, "{index}", strconv.Itoa(i), 1) if rawArgs.ExistsArgByName(argNameWithIndex) { if existingArg != "" { - return fmt.Errorf("arguments '%s' and '%s' are mutually exclusive", existingArg, argNameWithIndex) + return fmt.Errorf( + "arguments '%s' and '%s' are mutually exclusive", + existingArg, + argNameWithIndex, + ) } existingArg = argNameWithIndex } @@ -331,19 +379,32 @@ func (m *OneOfGroupManager) ValidateUniqueOneOfGroups(rawArgs args.RawArgs, cmdA return nil } -func (m *OneOfGroupManager) ValidateRequiredOneOfGroups(rawArgs args.RawArgs, cmdArgs interface{}) error { +func (m *OneOfGroupManager) ValidateRequiredOneOfGroups( + rawArgs args.RawArgs, + cmdArgs interface{}, +) error { for group, required := range m.RequiredGroups { if required { found := false for _, argName := range m.Groups[group] { fieldName := strcase.ToPublicGoName(argName) - fieldValues, err := GetValuesForFieldByName(reflect.ValueOf(cmdArgs), strings.Split(fieldName, ".")) + fieldValues, err := GetValuesForFieldByName( + reflect.ValueOf(cmdArgs), + strings.Split(fieldName, "."), + ) if err != nil { - validationErr := fmt.Errorf("could not validate arg value for '%v': invalid field name '%v': %v", argName, fieldName, err.Error()) + validationErr := fmt.Errorf( + "could not validate arg value for '%v': invalid field name '%v': %v", + argName, + fieldName, + err.Error(), + ) panic(validationErr) } for i := range fieldValues { - if rawArgs.ExistsArgByName(strings.Replace(argName, "{index}", strconv.Itoa(i), 1)) { + if rawArgs.ExistsArgByName( + strings.Replace(argName, "{index}", strconv.Itoa(i), 1), + ) { found = true break diff --git a/core/validate_test.go b/core/validate_test.go index c41f2fddc5..61b86c5621 100644 --- a/core/validate_test.go +++ b/core/validate_test.go @@ -40,7 +40,12 @@ func Test_DefaultCommandValidateFunc(t *testing.T) { run := func(testCase TestCase) func(t *testing.T) { return func(t *testing.T) { t.Helper() - err := core.DefaultCommandValidateFunc()(t.Context(), testCase.command, testCase.parsedArguments, testCase.rawArgs) + err := core.DefaultCommandValidateFunc()( + t.Context(), + testCase.command, + testCase.parsedArguments, + testCase.rawArgs, + ) assert.Equal(t, errors.New("arg validation called"), err) } } @@ -198,7 +203,12 @@ func Test_DefaultCommandRequiredFunc(t *testing.T) { runOK := func(testCase TestCase) func(t *testing.T) { return func(t *testing.T) { t.Helper() - err := core.DefaultCommandValidateFunc()(t.Context(), testCase.command, testCase.parsedArguments, testCase.rawArgs) + err := core.DefaultCommandValidateFunc()( + t.Context(), + testCase.command, + testCase.parsedArguments, + testCase.rawArgs, + ) assert.NoError(t, err) } } @@ -206,7 +216,12 @@ func Test_DefaultCommandRequiredFunc(t *testing.T) { runErr := func(testCase TestCase, argName string) func(t *testing.T) { return func(t *testing.T) { t.Helper() - err := core.DefaultCommandValidateFunc()(t.Context(), testCase.command, testCase.parsedArguments, testCase.rawArgs) + err := core.DefaultCommandValidateFunc()( + t.Context(), + testCase.command, + testCase.parsedArguments, + testCase.rawArgs, + ) assert.Equal(t, core.MissingRequiredArgumentError(argName), err) } } @@ -371,7 +386,11 @@ func Test_ValidateDeprecated(t *testing.T) { Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - assert.Equal(t, "The argument 'a' is deprecated, more info with: scw plop --help\n", ctx.LogBuffer) + assert.Equal( + t, + "The argument 'a' is deprecated, more info with: scw plop --help\n", + ctx.LogBuffer, + ) }, ), })) @@ -780,7 +799,9 @@ func Test_ValidateOneOf(t *testing.T) { Cmd: "scw oneof c=yo", Check: core.TestCheckCombine( core.TestCheckExitCode(1), - core.TestCheckError(errors.New("at least one argument from the 'group1' group is required")), + core.TestCheckError( + errors.New("at least one argument from the 'group1' group is required"), + ), ), })(t) }) @@ -878,7 +899,9 @@ func Test_ValidateOneOf(t *testing.T) { Cmd: "scw oneof all-ssh-keys=true ssh-key.0=11111111-1111-1111-1111-111111111111", Check: core.TestCheckCombine( core.TestCheckExitCode(1), - core.TestCheckError(errors.New("arguments 'ssh-key.0' and 'all-ssh-keys' are mutually exclusive")), + core.TestCheckError( + errors.New("arguments 'ssh-key.0' and 'all-ssh-keys' are mutually exclusive"), + ), ), })(t) }) @@ -1009,7 +1032,9 @@ func Test_ValidateOneOf(t *testing.T) { Cmd: "scw oneof arg=true", Check: core.TestCheckCombine( core.TestCheckExitCode(1), - core.TestCheckError(errors.New("at least one argument from the 'ssh' group is required")), + core.TestCheckError( + errors.New("at least one argument from the 'ssh' group is required"), + ), ), })(t) }) diff --git a/internal/.DS_Store b/internal/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..231a824050ff5f8cbcb18925f80e362087e4d82c GIT binary patch literal 6148 zcmeHKJ5B>J5S^Js&?0wSO9wOq|?Pf|eA)*RRkVP2~nI1Ha+<6RS&9S47mb9h|+6^T7i&L`q zW4gw!8{PGO|J%#yeBCykY#!@iqu`*v5K)_++b zWk@g(3_I5vP=J literal 0 HcmV?d00001 diff --git a/internal/args/args_test.go b/internal/args/args_test.go index 5386f9fc97..03c49a9411 100644 --- a/internal/args/args_test.go +++ b/internal/args/args_test.go @@ -160,7 +160,11 @@ func TestRawArgs_GetAll(t *testing.T) { "countries.FR.cities.nice.street.promenade=anglais", "countries.RU.cities.moscow.street.kremelin=rouge", } - assert.Equal(t, []string{"pouet", "tati", "anglais", "rouge"}, a.GetAll("countries.{key}.cities.{key}.street.{key}")) + assert.Equal( + t, + []string{"pouet", "tati", "anglais", "rouge"}, + a.GetAll("countries.{key}.cities.{key}.street.{key}"), + ) }) } diff --git a/internal/args/errors.go b/internal/args/errors.go index 81c910811f..d2371fd6cd 100644 --- a/internal/args/errors.go +++ b/internal/args/errors.go @@ -116,11 +116,19 @@ type MissingIndicesInArrayError struct { } func (e *MissingIndicesInArrayError) Error() string { - switch { - case e.IndexToInsert-e.CurrentLength == 1: - return fmt.Sprintf("missing index %d, all indices prior to %d must be set as well", e.CurrentLength, e.IndexToInsert) + switch e.IndexToInsert - e.CurrentLength { + case 1: + return fmt.Sprintf( + "missing index %d, all indices prior to %d must be set as well", + e.CurrentLength, + e.IndexToInsert, + ) default: - return fmt.Sprintf("missing indices, %s all indices prior to %d must be set as well", missingIndices(e.IndexToInsert, e.CurrentLength), e.IndexToInsert) + return fmt.Sprintf( + "missing indices, %s all indices prior to %d must be set as well", + missingIndices(e.IndexToInsert, e.CurrentLength), + e.IndexToInsert, + ) } } @@ -163,7 +171,11 @@ type ConflictArgError struct { } func (e *ConflictArgError) Error() string { - return fmt.Sprintf("arguments '%s' and '%s' cannot be used simultaneously", e.ArgName1, e.ArgName2) + return fmt.Sprintf( + "arguments '%s' and '%s' cannot be used simultaneously", + e.ArgName1, + e.ArgName2, + ) } // missingIndices returns a string of all the missing indices between index and length. diff --git a/internal/args/unmarshal.go b/internal/args/unmarshal.go index 061b6a68fa..bf9b4fd291 100644 --- a/internal/args/unmarshal.go +++ b/internal/args/unmarshal.go @@ -271,7 +271,8 @@ func set(dest reflect.Value, argNameWords []string, value string) error { // - value == none // slice ptr was allocated // we allocate the empty slice and return - if dest.Elem().Kind() == reflect.Slice && len(argNameWords) == 0 && value == emptySliceValue { + if dest.Elem().Kind() == reflect.Slice && len(argNameWords) == 0 && + value == emptySliceValue { sliceDest := dest.Elem() sliceDest.Set(reflect.MakeSlice(sliceDest.Type(), 0, 0)) diff --git a/internal/docgen/docgen.go b/internal/docgen/docgen.go index 3f37800b05..b187445462 100644 --- a/internal/docgen/docgen.go +++ b/internal/docgen/docgen.go @@ -141,7 +141,10 @@ func newTemplate() *template.Template { parts = append(parts, fmt.Sprintf("Default: `%s`", doc)) } if len(arg.EnumValues) > 0 { - parts = append(parts, fmt.Sprintf("One of: `%s`", strings.Join(arg.EnumValues, "`, `"))) + parts = append( + parts, + fmt.Sprintf("One of: `%s`", strings.Join(arg.EnumValues, "`, `")), + ) } return strings.Join(parts, "
") diff --git a/internal/e2e/human_test.go b/internal/e2e/human_test.go index db9c4f654e..353b6c3460 100644 --- a/internal/e2e/human_test.go +++ b/internal/e2e/human_test.go @@ -113,8 +113,10 @@ func TestHumanUpdate(t *testing.T) { Commands: test.GetCommands(), UseE2EClient: true, DisableParallel: true, // because e2e client is used - BeforeFunc: core.ExecBeforeCmd("scw test human create height=170.5 shoe-size=35.1 altitude-in-meter=-12 altitude-in-millimeter=-12050 fingers-count=21 hair-count=9223372036854775808 is-happy=true eyes-color=amber organization-id=b3ba839a-dcf2-4b0a-ac81-fc32370052a0"), - Cmd: "scw test human update 0194fdc2-fa2f-fcc0-41d3-ff12045b73c8 is-happy=false", + BeforeFunc: core.ExecBeforeCmd( + "scw test human create height=170.5 shoe-size=35.1 altitude-in-meter=-12 altitude-in-millimeter=-12050 fingers-count=21 hair-count=9223372036854775808 is-happy=true eyes-color=amber organization-id=b3ba839a-dcf2-4b0a-ac81-fc32370052a0", + ), + Cmd: "scw test human update 0194fdc2-fa2f-fcc0-41d3-ff12045b73c8 is-happy=false", Check: core.TestCheckCombine( core.TestCheckExitCode(0), core.TestCheckGolden(), @@ -150,8 +152,10 @@ func TestHumanGet(t *testing.T) { Commands: test.GetCommands(), UseE2EClient: true, DisableParallel: true, // because e2e client is used - BeforeFunc: core.ExecBeforeCmd("scw test human create height=155.666 shoe-size=36.0 altitude-in-meter=2147483647 altitude-in-millimeter=2147483647285 fingers-count=20 hair-count=9223372036854775809 is-happy=true eyes-color=blue organization-id=b3ba839a-dcf2-4b0a-ac81-fc32370052a0"), - Cmd: "scw test human get 0194fdc2-fa2f-fcc0-41d3-ff12045b73c8", + BeforeFunc: core.ExecBeforeCmd( + "scw test human create height=155.666 shoe-size=36.0 altitude-in-meter=2147483647 altitude-in-millimeter=2147483647285 fingers-count=20 hair-count=9223372036854775809 is-happy=true eyes-color=blue organization-id=b3ba839a-dcf2-4b0a-ac81-fc32370052a0", + ), + Cmd: "scw test human get 0194fdc2-fa2f-fcc0-41d3-ff12045b73c8", Check: core.TestCheckCombine( core.TestCheckExitCode(0), core.TestCheckGolden(), @@ -197,8 +201,10 @@ func TestHumanDelete(t *testing.T) { Commands: test.GetCommands(), UseE2EClient: true, DisableParallel: true, // because e2e client is used - BeforeFunc: core.ExecBeforeCmd("scw test human create height=155.666 shoe-size=36.0 altitude-in-meter=2147483647 altitude-in-millimeter=2147483647285 fingers-count=20 hair-count=9223372036854775809 is-happy=true eyes-color=blue organization-id=b3ba839a-dcf2-4b0a-ac81-fc32370052a0"), - Cmd: "scw test human delete 0194fdc2-fa2f-fcc0-41d3-ff12045b73c8", + BeforeFunc: core.ExecBeforeCmd( + "scw test human create height=155.666 shoe-size=36.0 altitude-in-meter=2147483647 altitude-in-millimeter=2147483647285 fingers-count=20 hair-count=9223372036854775809 is-happy=true eyes-color=blue organization-id=b3ba839a-dcf2-4b0a-ac81-fc32370052a0", + ), + Cmd: "scw test human delete 0194fdc2-fa2f-fcc0-41d3-ff12045b73c8", Check: core.TestCheckCombine( core.TestCheckExitCode(0), core.TestCheckGolden(), diff --git a/internal/editor/editor.go b/internal/editor/editor.go index fae7768ff9..1297121cfc 100644 --- a/internal/editor/editor.go +++ b/internal/editor/editor.go @@ -83,7 +83,11 @@ func edit(content []byte) ([]byte, error) { // updateResourceEditor takes a complete resource and a partial updateRequest // will return a copy of updateRequest that has been edited -func updateResourceEditor(resource interface{}, updateRequest interface{}, cfg *Config) (interface{}, error) { +func updateResourceEditor( + resource interface{}, + updateRequest interface{}, + cfg *Config, +) (interface{}, error) { // Create a copy of updateRequest completed with resource content completeUpdateRequest := copyAndCompleteUpdateRequest(updateRequest, resource) @@ -98,7 +102,11 @@ func updateResourceEditor(resource interface{}, updateRequest interface{}, cfg * } if len(cfg.IgnoreFields) > 0 { - updateRequestMarshaled, err = removeFields(updateRequestMarshaled, cfg.MarshalMode, cfg.IgnoreFields) + updateRequestMarshaled, err = removeFields( + updateRequestMarshaled, + cfg.MarshalMode, + cfg.IgnoreFields, + ) if err != nil { return nil, fmt.Errorf("failed to remove ignored fields: %w", err) } @@ -143,6 +151,10 @@ func updateResourceEditor(resource interface{}, updateRequest interface{}, cfg * // will return a copy of updateRequest that has been edited // Only edited fields will be present in returned updateRequest // If putRequest is true, all fields will be present, edited or not -func UpdateResourceEditor(resource interface{}, updateRequest interface{}, cfg *Config) (interface{}, error) { +func UpdateResourceEditor( + resource interface{}, + updateRequest interface{}, + cfg *Config, +) (interface{}, error) { return updateResourceEditor(resource, updateRequest, cfg) } diff --git a/internal/editor/editor_test.go b/internal/editor/editor_test.go index a72b8c739b..6666c626a6 100644 --- a/internal/editor/editor_test.go +++ b/internal/editor/editor_test.go @@ -50,7 +50,11 @@ func Test_updateResourceEditor_pointers(t *testing.T) { nil, } - editedUpdateRequestI, err := editor.UpdateResourceEditor(resource, updateRequest, &editor.Config{}) + editedUpdateRequestI, err := editor.UpdateResourceEditor( + resource, + updateRequest, + &editor.Config{}, + ) require.NoError(t, err) editedUpdateRequest := editedUpdateRequestI.(*UpdateRequest) @@ -80,12 +84,16 @@ func Test_updateResourceEditor_map(t *testing.T) { nil, } - editedUpdateRequestI, err := editor.UpdateResourceEditor(resource, updateRequest, &editor.Config{ - EditedResource: ` + editedUpdateRequestI, err := editor.UpdateResourceEditor( + resource, + updateRequest, + &editor.Config{ + EditedResource: ` id: uuid env: {} `, - }) + }, + ) require.NoError(t, err) editedUpdateRequest := editedUpdateRequestI.(*UpdateRequest) assert.NotNil(t, editedUpdateRequest.Env) diff --git a/internal/editor/reflect.go b/internal/editor/reflect.go index 5a2bc69ce4..053d206d50 100644 --- a/internal/editor/reflect.go +++ b/internal/editor/reflect.go @@ -43,7 +43,12 @@ func hasTag(tags []string, actualTag string) bool { return false } -func valueMapperWithoutOpt(dest reflect.Value, src reflect.Value, includeFields []string, excludeFields []string) { +func valueMapperWithoutOpt( + dest reflect.Value, + src reflect.Value, + includeFields []string, + excludeFields []string, +) { switch dest.Kind() { case reflect.Struct: for i := range dest.NumField() { diff --git a/internal/editor/reflect_test.go b/internal/editor/reflect_test.go index a626ab538a..ea74898024 100644 --- a/internal/editor/reflect_test.go +++ b/internal/editor/reflect_test.go @@ -53,7 +53,7 @@ func Test_valueMapperDifferentFields(t *testing.T) { }{} editor.ValueMapper(reflect.ValueOf(&dest), reflect.ValueOf(&src)) - assert.Zero(t, dest.Arg3) + assert.Empty(t, dest.Arg3) assert.Zero(t, dest.Arg4) } @@ -69,9 +69,9 @@ func Test_valueMapperPointers(t *testing.T) { editor.ValueMapper(reflect.ValueOf(&dest), reflect.ValueOf(&src)) assert.NotNil(t, dest.Arg1) - assert.EqualValues(t, src.Arg1, *dest.Arg1) + assert.Equal(t, src.Arg1, *dest.Arg1) assert.NotNil(t, dest.Arg2) - assert.EqualValues(t, src.Arg2, *dest.Arg2) + assert.Equal(t, src.Arg2, *dest.Arg2) } func Test_valueMapperPointersWithPointers(t *testing.T) { @@ -86,9 +86,9 @@ func Test_valueMapperPointersWithPointers(t *testing.T) { editor.ValueMapper(reflect.ValueOf(&dest), reflect.ValueOf(&src)) assert.NotNil(t, dest.Arg1) - assert.EqualValues(t, src.Arg1, dest.Arg1) + assert.Equal(t, src.Arg1, dest.Arg1) assert.NotNil(t, dest.Arg2) - assert.EqualValues(t, src.Arg2, dest.Arg2) + assert.Equal(t, src.Arg2, dest.Arg2) } func Test_valueMapperSlice(t *testing.T) { @@ -106,9 +106,9 @@ func Test_valueMapperSlice(t *testing.T) { editor.ValueMapper(reflect.ValueOf(&dest), reflect.ValueOf(&src)) assert.NotNil(t, dest.Arg1) - assert.EqualValues(t, src.Arg1, dest.Arg1) + assert.Equal(t, src.Arg1, dest.Arg1) assert.NotNil(t, dest.Arg2) - assert.EqualValues(t, src.Arg2, dest.Arg2) + assert.Equal(t, src.Arg2, dest.Arg2) } func Test_valueMapperSliceOfPointers(t *testing.T) { @@ -126,14 +126,14 @@ func Test_valueMapperSliceOfPointers(t *testing.T) { editor.ValueMapper(reflect.ValueOf(&dest), reflect.ValueOf(&src)) assert.NotNil(t, dest.Arg1) - assert.Equal(t, len(src.Arg1), len(dest.Arg1)) + assert.Len(t, dest.Arg1, len(src.Arg1)) for i := range src.Arg1 { assert.NotNil(t, dest.Arg1[i]) assert.Equal(t, src.Arg1[i], *dest.Arg1[i]) } assert.NotNil(t, dest.Arg2) - assert.Equal(t, len(src.Arg2), len(dest.Arg2)) + assert.Len(t, dest.Arg2, len(src.Arg2)) for i := range src.Arg2 { assert.NotNil(t, dest.Arg2[i]) assert.Equal(t, src.Arg2[i], *dest.Arg2[i]) diff --git a/internal/gofields/gofields.go b/internal/gofields/gofields.go index d77e1e0c7b..be208ecad2 100644 --- a/internal/gofields/gofields.go +++ b/internal/gofields/gofields.go @@ -48,33 +48,57 @@ func getValue(value reflect.Value, parents []string, path []string) (reflect.Val case reflect.Slice: idx, err := strconv.Atoi(path[0]) if err != nil { - return reflect.Value{}, fmt.Errorf("trying to access array %s but %s is not a numerical index", strings.Join(parents, "."), path[0]) + return reflect.Value{}, fmt.Errorf( + "trying to access array %s but %s is not a numerical index", + strings.Join(parents, "."), + path[0], + ) } if idx >= value.Len() { - return reflect.Value{}, fmt.Errorf("trying to access array %s but %d is out of range", strings.Join(parents, "."), idx) + return reflect.Value{}, fmt.Errorf( + "trying to access array %s but %d is out of range", + strings.Join(parents, "."), + idx, + ) } return getValue(value.Index(idx), append(parents, path[0]), path[1:]) case reflect.Map: v := value.MapIndex(reflect.ValueOf(path[0])) if !v.IsValid() { - return reflect.Value{}, fmt.Errorf("trying to access map %s but %s key does not exist", strings.Join(parents, "."), path[0]) + return reflect.Value{}, fmt.Errorf( + "trying to access map %s but %s key does not exist", + strings.Join(parents, "."), + path[0], + ) } return getValue(v, append(parents, path[0]), path[1:]) case reflect.Struct: f, exist := value.Type().FieldByName(path[0]) if !exist { - return reflect.Value{}, fmt.Errorf("field %s does not exist in %s", path[0], strings.Join(parents, ".")) + return reflect.Value{}, fmt.Errorf( + "field %s does not exist in %s", + path[0], + strings.Join(parents, "."), + ) } if !isFieldPublic(f) { - return reflect.Value{}, fmt.Errorf("field %s is private in %s", path[0], strings.Join(parents, ".")) + return reflect.Value{}, fmt.Errorf( + "field %s is private in %s", + path[0], + strings.Join(parents, "."), + ) } v := value.FieldByIndex(f.Index) return getValue(v, append(parents, path[0]), path[1:]) default: - return reflect.Value{}, fmt.Errorf("cannot get %s in field %s", strings.Join(path, "."), strings.Join(parents, ".")) + return reflect.Value{}, fmt.Errorf( + "cannot get %s in field %s", + strings.Join(path, "."), + strings.Join(parents, "."), + ) } } @@ -97,7 +121,11 @@ func getType(t reflect.Type, parents []string, path []string) (reflect.Type, err case reflect.Slice: _, err := strconv.Atoi(path[0]) if err != nil { - return nil, fmt.Errorf("trying to access array %s but %s is not a numerical index", strings.Join(parents, "."), path[0]) + return nil, fmt.Errorf( + "trying to access array %s but %s is not a numerical index", + strings.Join(parents, "."), + path[0], + ) } return getType(t.Elem(), append(parents, path[0]), path[1:]) @@ -106,7 +134,11 @@ func getType(t reflect.Type, parents []string, path []string) (reflect.Type, err case reflect.Struct: field, exist := t.FieldByName(path[0]) if !exist { - return nil, fmt.Errorf("field %s does not exist in %s", path[0], strings.Join(parents, ".")) + return nil, fmt.Errorf( + "field %s does not exist in %s", + path[0], + strings.Join(parents, "."), + ) } if !isFieldPublic(field) { return nil, fmt.Errorf("field %s is private in %s", path[0], strings.Join(parents, ".")) @@ -114,7 +146,11 @@ func getType(t reflect.Type, parents []string, path []string) (reflect.Type, err return getType(field.Type, append(parents, path[0]), path[1:]) default: - return nil, fmt.Errorf("cannot get %s in field %s", strings.Join(path, "."), strings.Join(parents, ".")) + return nil, fmt.Errorf( + "cannot get %s in field %s", + strings.Join(path, "."), + strings.Join(parents, "."), + ) } } @@ -170,7 +206,8 @@ func listFields(t reflect.Type, parents []string, filter ListFieldFilter) []stri // IsNil test if a given value is nil. It is saf to call the mthod with non nillable value like scalar types func IsNil(value reflect.Value) bool { - return (value.Kind() == reflect.Ptr || value.Kind() == reflect.Slice || value.Kind() == reflect.Map) && value.IsNil() + return (value.Kind() == reflect.Ptr || value.Kind() == reflect.Slice || value.Kind() == reflect.Map) && + value.IsNil() } // isFieldPublic returns true if the given field is public (Name starts with an uppercase) diff --git a/internal/gofields/gofields_test.go b/internal/gofields/gofields_test.go index 19a79a7d34..2bd5d8fd2b 100644 --- a/internal/gofields/gofields_test.go +++ b/internal/gofields/gofields_test.go @@ -238,8 +238,14 @@ func TestListFields(t *testing.T) { } t.Run("Simple", run(&TestCase{ - Data: reflect.TypeOf(&User{}), - Expected: []string{"Name", "Address.Zip", "Friends..Name", "Pets..Species", "Pets..Name"}, + Data: reflect.TypeOf(&User{}), + Expected: []string{ + "Name", + "Address.Zip", + "Friends..Name", + "Pets..Species", + "Pets..Name", + }, })) } diff --git a/internal/gotty/client.go b/internal/gotty/client.go index 4418ae47a4..291adc0a30 100644 --- a/internal/gotty/client.go +++ b/internal/gotty/client.go @@ -49,7 +49,10 @@ func (c *Client) Connect() error { defer func() { // Websocket protocol require the server to close the connection. // This sent a close request. - conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) //nolint:errcheck + conn.WriteMessage( + websocket.CloseMessage, + websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), + ) }() // This is how scaleway implement gotty authentication @@ -91,7 +94,12 @@ func (c *Client) Connect() error { if err != nil { return err } - message := fmt.Sprintf(`%c{"columns":%d,"rows":%d}`, resizeTerminalCode, size.Width, size.Height) + message := fmt.Sprintf( + `%c{"columns":%d,"rows":%d}`, + resizeTerminalCode, + size.Width, + size.Height, + ) err = conn.WriteMessage(websocket.TextMessage, []byte(message)) if err != nil { return fmt.Errorf("failed to write message on websocket: %w", err) diff --git a/internal/interactive/prompt.go b/internal/interactive/prompt.go index 42868b6557..a0ffbe4c4d 100644 --- a/internal/interactive/prompt.go +++ b/internal/interactive/prompt.go @@ -134,13 +134,15 @@ func Readline(config *ReadlineConfig) (string, error) { ctx: config.Ctx, defaultReader: os.Stdin, }, - Listener: readline.FuncListener(func(line []rune, _ int, _ rune) (newLine []rune, newPos int, ok bool) { - value := string(line) - promptHandler.SetPrompt(promptFunc(value)) - promptHandler.rl.Refresh() - - return nil, 0, false - }), + Listener: readline.FuncListener( + func(line []rune, _ int, _ rune) (newLine []rune, newPos int, ok bool) { + value := string(line) + promptHandler.SetPrompt(promptFunc(value)) + promptHandler.rl.Refresh() + + return nil, 0, false + }, + ), }) if err != nil { return "", err diff --git a/internal/interactive/utils.go b/internal/interactive/utils.go index 7448897356..eb7ff7997b 100644 --- a/internal/interactive/utils.go +++ b/internal/interactive/utils.go @@ -38,7 +38,8 @@ func SetOutputWriter(w io.Writer) { // we should expect both Stdin and Stderr to enable interactive mode func isInteractive() bool { return isatty.IsTerminal(os.Stdin.Fd()) && isatty.IsTerminal(os.Stderr.Fd()) || - isatty.IsCygwinTerminal(os.Stdin.Fd()) && isatty.IsCygwinTerminal(os.Stderr.Fd()) // windows cygwin terminal + isatty.IsCygwinTerminal(os.Stdin.Fd()) && + isatty.IsCygwinTerminal(os.Stderr.Fd()) // windows cygwin terminal } func ValidateOrganizationID() ValidateFunc { diff --git a/internal/namespaces/account/v3/account_cli.go b/internal/namespaces/account/v3/account_cli.go index 1f1c086962..92b9663417 100644 --- a/internal/namespaces/account/v3/account_cli.go +++ b/internal/namespaces/account/v3/account_cli.go @@ -28,6 +28,7 @@ func GetGeneratedCommands() *core.Commands { accountProjectUpdate(), ) } + func accountRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Scaleway Projects`, @@ -77,8 +78,8 @@ func accountProjectCreate() *core.Command { client := core.ExtractClient(ctx) api := account.NewProjectAPI(client) - return api.CreateProject(request) + return api.CreateProject(request) }, } } @@ -127,8 +128,8 @@ func accountProjectList() *core.Command { if err != nil { return nil, err } - return resp.Projects, nil + return resp.Projects, nil }, } } @@ -150,8 +151,8 @@ func accountProjectGet() *core.Command { client := core.ExtractClient(ctx) api := account.NewProjectAPI(client) - return api.GetProject(request) + return api.GetProject(request) }, } } @@ -177,6 +178,7 @@ func accountProjectDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "project", Verb: "delete", @@ -216,8 +218,8 @@ func accountProjectUpdate() *core.Command { client := core.ExtractClient(ctx) api := account.NewProjectAPI(client) - return api.UpdateProject(request) + return api.UpdateProject(request) }, } } diff --git a/internal/namespaces/applesilicon/v1alpha1/applesilicon_cli.go b/internal/namespaces/applesilicon/v1alpha1/applesilicon_cli.go index 30d108fd8d..57d609f31f 100644 --- a/internal/namespaces/applesilicon/v1alpha1/applesilicon_cli.go +++ b/internal/namespaces/applesilicon/v1alpha1/applesilicon_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/applesilicon/v1alpha1" + applesilicon "github.com/scaleway/scaleway-sdk-go/api/applesilicon/v1alpha1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -41,6 +41,7 @@ func GetGeneratedCommands() *core.Commands { appleSiliconPrivateNetworkDelete(), ) } + func appleSiliconRoot() *core.Command { return &core.Command{ Short: `Apple silicon API`, @@ -107,8 +108,8 @@ func appleSiliconServerTypeList() *core.Command { client := core.ExtractClient(ctx) api := applesilicon.NewAPI(client) - return api.ListServerTypes(request) + return api.ListServerTypes(request) }, } } @@ -137,8 +138,8 @@ func appleSiliconServerTypeGet() *core.Command { client := core.ExtractClient(ctx) api := applesilicon.NewAPI(client) - return api.GetServerType(request) + return api.GetServerType(request) }, } } @@ -198,8 +199,8 @@ func appleSiliconServerCreate() *core.Command { client := core.ExtractClient(ctx) api := applesilicon.NewAPI(client) - return api.CreateServer(request) + return api.CreateServer(request) }, } } @@ -252,8 +253,8 @@ func appleSiliconServerList() *core.Command { if err != nil { return nil, err } - return resp.Servers, nil + return resp.Servers, nil }, } } @@ -298,8 +299,8 @@ func appleSiliconOsList() *core.Command { if err != nil { return nil, err } - return resp.Os, nil + return resp.Os, nil }, } } @@ -328,8 +329,8 @@ func appleSiliconOsGet() *core.Command { client := core.ExtractClient(ctx) api := applesilicon.NewAPI(client) - return api.GetOS(request) + return api.GetOS(request) }, } } @@ -358,8 +359,8 @@ func appleSiliconServerGet() *core.Command { client := core.ExtractClient(ctx) api := applesilicon.NewAPI(client) - return api.GetServer(request) + return api.GetServer(request) }, } } @@ -416,8 +417,8 @@ func appleSiliconServerUpdate() *core.Command { client := core.ExtractClient(ctx) api := applesilicon.NewAPI(client) - return api.UpdateServer(request) + return api.UpdateServer(request) }, } } @@ -450,6 +451,7 @@ func appleSiliconServerDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "server", Verb: "delete", @@ -482,8 +484,8 @@ func appleSiliconServerReboot() *core.Command { client := core.ExtractClient(ctx) api := applesilicon.NewAPI(client) - return api.RebootServer(request) + return api.RebootServer(request) }, } } @@ -519,8 +521,8 @@ func appleSiliconServerReinstall() *core.Command { client := core.ExtractClient(ctx) api := applesilicon.NewAPI(client) - return api.ReinstallServer(request) + return api.ReinstallServer(request) }, } } @@ -563,8 +565,8 @@ func appleSiliconPrivateNetworkAdd() *core.Command { client := core.ExtractClient(ctx) api := applesilicon.NewPrivateNetworkAPI(client) - return api.AddServerPrivateNetwork(request) + return api.AddServerPrivateNetwork(request) }, } } @@ -600,8 +602,8 @@ func appleSiliconPrivateNetworkSet() *core.Command { client := core.ExtractClient(ctx) api := applesilicon.NewPrivateNetworkAPI(client) - return api.SetServerPrivateNetworks(request) + return api.SetServerPrivateNetworks(request) }, } } @@ -622,7 +624,12 @@ func appleSiliconPrivateNetworkList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + }, }, { Name: "server-id", @@ -675,8 +682,8 @@ func appleSiliconPrivateNetworkList() *core.Command { if err != nil { return nil, err } - return resp.ServerPrivateNetworks, nil + return resp.ServerPrivateNetworks, nil }, } } @@ -716,6 +723,7 @@ func appleSiliconPrivateNetworkDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "private-network", Verb: "delete", diff --git a/internal/namespaces/applesilicon/v1alpha1/custom.go b/internal/namespaces/applesilicon/v1alpha1/custom.go index f3f08a8e72..8af1e66a59 100644 --- a/internal/namespaces/applesilicon/v1alpha1/custom.go +++ b/internal/namespaces/applesilicon/v1alpha1/custom.go @@ -19,8 +19,14 @@ func GetCommands() *core.Commands { human.RegisterMarshalerFunc(applesilicon.ServerTypeMemory{}, memoryMarshalerFunc) human.RegisterMarshalerFunc(applesilicon.OS{}, OSMarshalerFunc) - human.RegisterMarshalerFunc(applesilicon.ServerStatus(""), human.EnumMarshalFunc(serverStatusMarshalSpecs)) - human.RegisterMarshalerFunc(applesilicon.ServerTypeStock(""), human.EnumMarshalFunc(serverTypeStockMarshalSpecs)) + human.RegisterMarshalerFunc( + applesilicon.ServerStatus(""), + human.EnumMarshalFunc(serverStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + applesilicon.ServerTypeStock(""), + human.EnumMarshalFunc(serverTypeStockMarshalSpecs), + ) cmds.MustFind("apple-silicon", "server", "create").Override(serverCreateBuilder) cmds.MustFind("apple-silicon", "server", "reboot").Override(serverRebootBuilder) diff --git a/internal/namespaces/applesilicon/v1alpha1/custom_server.go b/internal/namespaces/applesilicon/v1alpha1/custom_server.go index f0ae750840..d0c194010f 100644 --- a/internal/namespaces/applesilicon/v1alpha1/custom_server.go +++ b/internal/namespaces/applesilicon/v1alpha1/custom_server.go @@ -27,11 +27,26 @@ const ( ) var serverStatusMarshalSpecs = human.EnumMarshalSpecs{ - applesilicon.ServerStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "error"}, - applesilicon.ServerStatusReady: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "ready"}, - applesilicon.ServerStatusRebooting: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "rebooting"}, - applesilicon.ServerStatusStarting: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "starting"}, - applesilicon.ServerStatusUpdating: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "updating"}, + applesilicon.ServerStatusError: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "error", + }, + applesilicon.ServerStatusReady: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "ready", + }, + applesilicon.ServerStatusRebooting: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "rebooting", + }, + applesilicon.ServerStatusStarting: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "starting", + }, + applesilicon.ServerStatusUpdating: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "updating", + }, } func serverCreateBuilder(c *core.Command) *core.Command { @@ -55,12 +70,13 @@ func serverRebootBuilder(c *core.Command) *core.Command { func waitForServerFunc(action int) core.WaitFunc { return func(ctx context.Context, _, respI interface{}) (interface{}, error) { - server, err := applesilicon.NewAPI(core.ExtractClient(ctx)).WaitForServer(&applesilicon.WaitForServerRequest{ - Zone: respI.(*applesilicon.Server).Zone, - ServerID: respI.(*applesilicon.Server).ID, - Timeout: scw.TimeDurationPtr(serverActionTimeout), - RetryInterval: core.DefaultRetryInterval, - }) + server, err := applesilicon.NewAPI(core.ExtractClient(ctx)). + WaitForServer(&applesilicon.WaitForServerRequest{ + Zone: respI.(*applesilicon.Server).Zone, + ServerID: respI.(*applesilicon.Server).ID, + Timeout: scw.TimeDurationPtr(serverActionTimeout), + RetryInterval: core.DefaultRetryInterval, + }) switch action { case serverActionCreate: @@ -72,8 +88,13 @@ func waitForServerFunc(action int) core.WaitFunc { // if we get a 404 here, it means the resource was successfully deleted notFoundError := &scw.ResourceNotFoundError{} responseError := &scw.ResponseError{} - if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) { - return fmt.Sprintf("Server %s successfully deleted.", respI.(*applesilicon.Server).ID), nil + if errors.As(err, &responseError) && + responseError.StatusCode == http.StatusNotFound || + errors.As(err, ¬FoundError) { + return fmt.Sprintf( + "Server %s successfully deleted.", + respI.(*applesilicon.Server).ID, + ), nil } } } @@ -132,7 +153,11 @@ func serverWaitCommand() *core.Command { var completeListTypeServerCache *applesilicon.ListServerTypesResponse -func autocompleteServerType(ctx context.Context, prefix string, _ any) core.AutocompleteSuggestions { +func autocompleteServerType( + ctx context.Context, + prefix string, + _ any, +) core.AutocompleteSuggestions { suggestions := core.AutocompleteSuggestions(nil) client := core.ExtractClient(ctx) diff --git a/internal/namespaces/applesilicon/v1alpha1/custom_server_ssh_test.go b/internal/namespaces/applesilicon/v1alpha1/custom_server_ssh_test.go index 440283646e..6a02f46f0a 100644 --- a/internal/namespaces/applesilicon/v1alpha1/custom_server_ssh_test.go +++ b/internal/namespaces/applesilicon/v1alpha1/custom_server_ssh_test.go @@ -12,7 +12,10 @@ func Test_ServerSSH(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ Commands: applesilicon.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Server", "scw apple-silicon server create server-type=M2-M --wait"), + core.ExecStoreBeforeCmd( + "Server", + "scw apple-silicon server create server-type=M2-M --wait", + ), ), Cmd: "scw apple-silicon server ssh {{ .Server.ID }}", OverrideExec: core.OverrideExecSimple( @@ -32,7 +35,10 @@ func Test_ServerSSH(t *testing.T) { t.Run("With-Exit-Code", core.Test(&core.TestConfig{ Commands: applesilicon.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Server", "scw apple-silicon server create server-type=M2-M --wait"), + core.ExecStoreBeforeCmd( + "Server", + "scw apple-silicon server create server-type=M2-M --wait", + ), ), Cmd: "scw apple-silicon server ssh {{ .Server.ID }}", OverrideExec: core.OverrideExecSimple( diff --git a/internal/namespaces/applesilicon/v1alpha1/custom_server_types.go b/internal/namespaces/applesilicon/v1alpha1/custom_server_types.go index 68d9e7781e..4c7ce0071a 100644 --- a/internal/namespaces/applesilicon/v1alpha1/custom_server_types.go +++ b/internal/namespaces/applesilicon/v1alpha1/custom_server_types.go @@ -11,9 +11,18 @@ import ( ) var serverTypeStockMarshalSpecs = human.EnumMarshalSpecs{ - applesilicon.ServerTypeStockLowStock: &human.EnumMarshalSpec{Attribute: color.FgYellow, Value: "low stock"}, - applesilicon.ServerTypeStockNoStock: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "no stock"}, - applesilicon.ServerTypeStockHighStock: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "high stock"}, + applesilicon.ServerTypeStockLowStock: &human.EnumMarshalSpec{ + Attribute: color.FgYellow, + Value: "low stock", + }, + applesilicon.ServerTypeStockNoStock: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "no stock", + }, + applesilicon.ServerTypeStockHighStock: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "high stock", + }, } func cpuMarshalerFunc(i interface{}, _ *human.MarshalOpt) (string, error) { @@ -72,16 +81,18 @@ func serverTypeBuilder(c *core.Command) *core.Command { }, } - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { - originalRes, err := runner(ctx, argsI) - if err != nil { - return nil, err - } + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + originalRes, err := runner(ctx, argsI) + if err != nil { + return nil, err + } - versionsResponse := originalRes.(*applesilicon.ListServerTypesResponse) + versionsResponse := originalRes.(*applesilicon.ListServerTypesResponse) - return versionsResponse.ServerTypes, nil - }) + return versionsResponse.ServerTypes, nil + }, + ) return c } diff --git a/internal/namespaces/audit_trail/v1alpha1/audit_trail_cli.go b/internal/namespaces/audit_trail/v1alpha1/audit_trail_cli.go index 266b39f5cc..0603edefe0 100644 --- a/internal/namespaces/audit_trail/v1alpha1/audit_trail_cli.go +++ b/internal/namespaces/audit_trail/v1alpha1/audit_trail_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/audit_trail/v1alpha1" + audit_trail "github.com/scaleway/scaleway-sdk-go/api/audit_trail/v1alpha1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -26,6 +26,7 @@ func GetGeneratedCommands() *core.Commands { auditTrailProductList(), ) } + func auditTrailRoot() *core.Command { return &core.Command{ Short: `This API allows you to ensure accountability and security by recording events and changes performed within your Scaleway Organization.`, @@ -75,7 +76,26 @@ func auditTrailEventList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_type", "secm_secret", "secm_secret_version", "kube_cluster", "kube_pool", "kube_node", "kube_acl", "keym_key", "iam_user", "iam_application", "iam_group", "iam_policy", "iam_api_key", "iam_ssh_key", "iam_rule", "secret_manager_secret", "secret_manager_version", "key_manager_key"}, + EnumValues: []string{ + "unknown_type", + "secm_secret", + "secm_secret_version", + "kube_cluster", + "kube_pool", + "kube_node", + "kube_acl", + "keym_key", + "iam_user", + "iam_application", + "iam_group", + "iam_policy", + "iam_api_key", + "iam_ssh_key", + "iam_rule", + "secret_manager_secret", + "secret_manager_version", + "key_manager_key", + }, }, { Name: "method-name", @@ -146,8 +166,8 @@ func auditTrailEventList() *core.Command { client := core.ExtractClient(ctx) api := audit_trail.NewAPI(client) - return api.ListEvents(request) + return api.ListEvents(request) }, } } @@ -170,8 +190,8 @@ func auditTrailProductList() *core.Command { client := core.ExtractClient(ctx) api := audit_trail.NewAPI(client) - return api.ListProducts(request) + return api.ListProducts(request) }, } } diff --git a/internal/namespaces/audit_trail/v1alpha1/custom_event.go b/internal/namespaces/audit_trail/v1alpha1/custom_event.go index 7012532338..939418479a 100644 --- a/internal/namespaces/audit_trail/v1alpha1/custom_event.go +++ b/internal/namespaces/audit_trail/v1alpha1/custom_event.go @@ -81,16 +81,18 @@ func eventListBuilder(c *core.Command) *core.Command { }, } - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { - originalRes, err := runner(ctx, argsI) - if err != nil { - return nil, err - } + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + originalRes, err := runner(ctx, argsI) + if err != nil { + return nil, err + } - eventsResponse := originalRes.(*audit_trail.ListEventsResponse) + eventsResponse := originalRes.(*audit_trail.ListEventsResponse) - return eventsResponse.Events, nil - }) + return eventsResponse.Events, nil + }, + ) return c } diff --git a/internal/namespaces/autocomplete/autocomplete.go b/internal/namespaces/autocomplete/autocomplete.go index eb709f8237..875928dd6c 100644 --- a/internal/namespaces/autocomplete/autocomplete.go +++ b/internal/namespaces/autocomplete/autocomplete.go @@ -167,7 +167,9 @@ func autocompleteInstallCommand() *core.Command { func InstallCommandRun(ctx context.Context, argsI interface{}) (i interface{}, e error) { // Warning - _, _ = interactive.Println("To enable autocomplete, scw needs to update your shell configuration.") + _, _ = interactive.Println( + "To enable autocomplete, scw needs to update your shell configuration.", + ) // If `shell=` is empty, ask for a value for `shell=`. shellArg := argsI.(*InstallArgs).Shell @@ -210,7 +212,11 @@ func InstallCommandRun(ctx context.Context, argsI interface{}) (i interface{}, e defer f.Close() } if err != nil { - return nil, installationNotFound(shellName, shellConfigurationFilePath, script.CompleteScript) + return nil, installationNotFound( + shellName, + shellConfigurationFilePath, + script.CompleteScript, + ) } // Early exit if eval line is already present in the shell configuration. @@ -220,7 +226,9 @@ func InstallCommandRun(ctx context.Context, argsI interface{}) (i interface{}, e } if strings.Contains(string(shellConfigurationFileContent), script.CompleteScript) { _, _ = interactive.Println() - _, _ = interactive.Println("Autocomplete looks already installed. If it does not work properly, try to open a new shell.") + _, _ = interactive.Println( + "Autocomplete looks already installed. If it does not work properly, try to open a new shell.", + ) return "", nil } @@ -230,7 +238,9 @@ func InstallCommandRun(ctx context.Context, argsI interface{}) (i interface{}, e // Warning _, _ = interactive.Println() - _, _ = interactive.PrintlnWithoutIndent("To enable autocomplete we need to append to " + shellConfigurationFilePath + " the following lines:") + _, _ = interactive.PrintlnWithoutIndent( + "To enable autocomplete we need to append to " + shellConfigurationFilePath + " the following lines:", + ) _, _ = interactive.Println(strings.ReplaceAll(autoCompleteScript, "\n", "\n\t")) // Early exit if user disagrees @@ -255,7 +265,11 @@ func InstallCommandRun(ctx context.Context, argsI interface{}) (i interface{}, e // Ack return &core.SuccessResult{ - Message: fmt.Sprintf("Autocomplete has been successfully installed for your %v shell.\nUpdated %v.", shellName, shellConfigurationFilePath), + Message: fmt.Sprintf( + "Autocomplete has been successfully installed for your %v shell.\nUpdated %v.", + shellName, + shellConfigurationFilePath, + ), }, nil } diff --git a/internal/namespaces/autocomplete/errors.go b/internal/namespaces/autocomplete/errors.go index 47a668e259..2e911d57fe 100644 --- a/internal/namespaces/autocomplete/errors.go +++ b/internal/namespaces/autocomplete/errors.go @@ -28,7 +28,11 @@ func installationCancelledError(shellName string, script string) *core.CliError func installationNotFound(shellName string, location string, script string) *core.CliError { return &core.CliError{ - Err: fmt.Errorf("cannot find where to install autocomplete script (tried %s)", location), - Hint: fmt.Sprintf("You can add this line: `%s` in your %s configuration file", script, shellName), + Err: fmt.Errorf("cannot find where to install autocomplete script (tried %s)", location), + Hint: fmt.Sprintf( + "You can add this line: `%s` in your %s configuration file", + script, + shellName, + ), } } diff --git a/internal/namespaces/baremetal/v1/baremetal_cli.go b/internal/namespaces/baremetal/v1/baremetal_cli.go index 3d0f18fbcd..10db1dfac8 100644 --- a/internal/namespaces/baremetal/v1/baremetal_cli.go +++ b/internal/namespaces/baremetal/v1/baremetal_cli.go @@ -59,6 +59,7 @@ func GetGeneratedCommands() *core.Commands { baremetalPrivateNetworkDelete(), ) } + func baremetalRoot() *core.Command { return &core.Command{ Short: `Elastic Metal API`, @@ -211,7 +212,15 @@ func baremetalServerList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.ListServersRequest) @@ -227,8 +236,8 @@ func baremetalServerList() *core.Command { if err != nil { return nil, err } - return resp.Servers, nil + return resp.Servers, nil }, Examples: []*core.Example{ { @@ -256,15 +265,22 @@ func baremetalServerGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.GetServerRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.GetServer(request) + return api.GetServer(request) }, Examples: []*core.Example{ { @@ -374,7 +390,18 @@ func baremetalServerCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_partition_label", "uefi", "legacy", "root", "boot", "swap", "data", "home", "raid", "zfs"}, + EnumValues: []string{ + "unknown_partition_label", + "uefi", + "legacy", + "root", + "boot", + "swap", + "data", + "home", + "raid", + "zfs", + }, }, { Name: "install.partitioning-schema.disks.{index}.partitions.{index}.number", @@ -405,7 +432,14 @@ func baremetalServerCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_raid_level", "raid_level_0", "raid_level_1", "raid_level_5", "raid_level_6", "raid_level_10"}, + EnumValues: []string{ + "unknown_raid_level", + "raid_level_0", + "raid_level_1", + "raid_level_5", + "raid_level_6", + "raid_level_10", + }, }, { Name: "install.partitioning-schema.raids.{index}.devices.{index}", @@ -471,15 +505,22 @@ func baremetalServerCreate() *core.Command { Positional: false, }, core.OrganizationIDArgSpec(), - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.CreateServerRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.CreateServer(request) + return api.CreateServer(request) }, Examples: []*core.Example{ { @@ -528,15 +569,22 @@ func baremetalServerUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.UpdateServerRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.UpdateServer(request) + return api.UpdateServer(request) }, } } @@ -618,7 +666,18 @@ func baremetalServerInstall() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_partition_label", "uefi", "legacy", "root", "boot", "swap", "data", "home", "raid", "zfs"}, + EnumValues: []string{ + "unknown_partition_label", + "uefi", + "legacy", + "root", + "boot", + "swap", + "data", + "home", + "raid", + "zfs", + }, }, { Name: "partitioning-schema.disks.{index}.partitions.{index}.number", @@ -649,7 +708,14 @@ func baremetalServerInstall() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_raid_level", "raid_level_0", "raid_level_1", "raid_level_5", "raid_level_6", "raid_level_10"}, + EnumValues: []string{ + "unknown_raid_level", + "raid_level_0", + "raid_level_1", + "raid_level_5", + "raid_level_6", + "raid_level_10", + }, }, { Name: "partitioning-schema.raids.{index}.devices.{index}", @@ -707,15 +773,22 @@ func baremetalServerInstall() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.InstallServerRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.InstallServer(request) + return api.InstallServer(request) }, Examples: []*core.Example{ { @@ -757,15 +830,22 @@ func baremetalServerGetMetrics() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.GetServerMetricsRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.GetServerMetrics(request) + return api.GetServerMetrics(request) }, } } @@ -787,15 +867,22 @@ func baremetalServerDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.DeleteServerRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.DeleteServer(request) + return api.DeleteServer(request) }, Examples: []*core.Example{ { @@ -831,15 +918,22 @@ func baremetalServerReboot() *core.Command { Positional: false, EnumValues: []string{"unknown_boot_type", "normal", "rescue"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.RebootServerRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.RebootServer(request) + return api.RebootServer(request) }, Examples: []*core.Example{ { @@ -879,15 +973,22 @@ func baremetalServerStart() *core.Command { Positional: false, EnumValues: []string{"unknown_boot_type", "normal", "rescue"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.StartServerRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.StartServer(request) + return api.StartServer(request) }, Examples: []*core.Example{ { @@ -919,15 +1020,22 @@ func baremetalServerStop() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.StopServerRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.StopServer(request) + return api.StopServer(request) }, Examples: []*core.Example{ { @@ -963,7 +1071,15 @@ func baremetalServerListEvents() *core.Command { Positional: false, EnumValues: []string{"created_at_asc", "created_at_desc"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.ListServerEventsRequest) @@ -979,8 +1095,8 @@ func baremetalServerListEvents() *core.Command { if err != nil { return nil, err } - return resp.Events, nil + return resp.Events, nil }, } } @@ -1012,15 +1128,22 @@ After adding the BMC option, you need to Get Remote Access to get the login/pass Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.StartBMCAccessRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.StartBMCAccess(request) + return api.StartBMCAccess(request) }, } } @@ -1042,15 +1165,22 @@ func baremetalBmcGet() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.GetBMCAccessRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.GetBMCAccess(request) + return api.GetBMCAccess(request) }, } } @@ -1072,7 +1202,14 @@ func baremetalBmcStop() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.StopBMCAccessRequest) @@ -1083,6 +1220,7 @@ func baremetalBmcStop() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "bmc", Verb: "stop", @@ -1122,15 +1260,22 @@ func baremetalServerUpdateIP() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.UpdateIPRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.UpdateIP(request) + return api.UpdateIP(request) }, } } @@ -1166,15 +1311,22 @@ func baremetalOptionsAdd() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.AddOptionServerRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.AddOptionServer(request) + return api.AddOptionServer(request) }, Examples: []*core.Example{ { @@ -1209,15 +1361,22 @@ func baremetalOptionsDelete() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.DeleteOptionServerRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.DeleteOptionServer(request) + return api.DeleteOptionServer(request) }, Examples: []*core.Example{ { @@ -1253,7 +1412,15 @@ func baremetalOfferList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.ListOffersRequest) @@ -1269,8 +1436,8 @@ func baremetalOfferList() *core.Command { if err != nil { return nil, err } - return resp.Offers, nil + return resp.Offers, nil }, Examples: []*core.Example{ { @@ -1302,15 +1469,22 @@ func baremetalOfferGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.GetOfferRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.GetOffer(request) + return api.GetOffer(request) }, Examples: []*core.Example{ { @@ -1338,15 +1512,22 @@ func baremetalOptionsGet() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.GetOptionRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.GetOption(request) + return api.GetOption(request) }, Examples: []*core.Example{ { @@ -1381,7 +1562,15 @@ func baremetalOptionsList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.ListOptionsRequest) @@ -1397,8 +1586,8 @@ func baremetalOptionsList() *core.Command { if err != nil { return nil, err } - return resp.Options, nil + return resp.Options, nil }, Examples: []*core.Example{ { @@ -1438,7 +1627,15 @@ func baremetalSettingsList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.ListSettingsRequest) @@ -1454,8 +1651,8 @@ func baremetalSettingsList() *core.Command { if err != nil { return nil, err } - return resp.Settings, nil + return resp.Settings, nil }, } } @@ -1484,15 +1681,22 @@ func baremetalSettingsUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.UpdateSettingRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.UpdateSetting(request) + return api.UpdateSetting(request) }, } } @@ -1514,7 +1718,15 @@ func baremetalOsList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.ListOSRequest) @@ -1530,8 +1742,8 @@ func baremetalOsList() *core.Command { if err != nil { return nil, err } - return resp.Os, nil + return resp.Os, nil }, } } @@ -1553,15 +1765,22 @@ func baremetalOsGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.GetOSRequest) client := core.ExtractClient(ctx) api := baremetal.NewAPI(client) - return api.GetOS(request) + return api.GetOS(request) }, Examples: []*core.Example{ { @@ -1603,8 +1822,8 @@ func baremetalPrivateNetworkAdd() *core.Command { client := core.ExtractClient(ctx) api := baremetal.NewPrivateNetworkAPI(client) - return api.AddServerPrivateNetwork(request) + return api.AddServerPrivateNetwork(request) }, } } @@ -1640,8 +1859,8 @@ func baremetalPrivateNetworkSet() *core.Command { client := core.ExtractClient(ctx) api := baremetal.NewPrivateNetworkAPI(client) - return api.SetServerPrivateNetworks(request) + return api.SetServerPrivateNetworks(request) }, } } @@ -1662,7 +1881,12 @@ func baremetalPrivateNetworkList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + }, }, { Name: "server-id", @@ -1708,8 +1932,8 @@ func baremetalPrivateNetworkList() *core.Command { if err != nil { return nil, err } - return resp.ServerPrivateNetworks, nil + return resp.ServerPrivateNetworks, nil }, } } @@ -1749,6 +1973,7 @@ func baremetalPrivateNetworkDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "private-network", Verb: "delete", diff --git a/internal/namespaces/baremetal/v1/custom.go b/internal/namespaces/baremetal/v1/custom.go index f88ad29fd7..a35dee7d4d 100644 --- a/internal/namespaces/baremetal/v1/custom.go +++ b/internal/namespaces/baremetal/v1/custom.go @@ -14,8 +14,14 @@ func GetCommands() *core.Commands { serverAddFlexibleIP(), )) - human.RegisterMarshalerFunc(baremetal.ServerPingStatus(""), human.EnumMarshalFunc(serverPingStatusMarshalSpecs)) - human.RegisterMarshalerFunc(baremetal.OfferStock(""), human.EnumMarshalFunc(offerAvailabilityMarshalSpecs)) + human.RegisterMarshalerFunc( + baremetal.ServerPingStatus(""), + human.EnumMarshalFunc(serverPingStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + baremetal.OfferStock(""), + human.EnumMarshalFunc(offerAvailabilityMarshalSpecs), + ) human.RegisterMarshalerFunc(baremetal.Server{}, serverMarshalerFunc) human.RegisterMarshalerFunc(baremetal.Offer{}, listOfferMarshalerFunc) diff --git a/internal/namespaces/baremetal/v1/custom_offer.go b/internal/namespaces/baremetal/v1/custom_offer.go index 2693dee5b8..49a5f7ee37 100644 --- a/internal/namespaces/baremetal/v1/custom_offer.go +++ b/internal/namespaces/baremetal/v1/custom_offer.go @@ -7,9 +7,12 @@ import ( ) var offerAvailabilityMarshalSpecs = human.EnumMarshalSpecs{ - baremetal.OfferStockEmpty: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "empty"}, - baremetal.OfferStockLow: &human.EnumMarshalSpec{Attribute: color.FgYellow, Value: "low"}, - baremetal.OfferStockAvailable: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "available"}, + baremetal.OfferStockEmpty: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "empty"}, + baremetal.OfferStockLow: &human.EnumMarshalSpec{Attribute: color.FgYellow, Value: "low"}, + baremetal.OfferStockAvailable: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "available", + }, } func listOfferMarshalerFunc(i interface{}, opt *human.MarshalOpt) (string, error) { diff --git a/internal/namespaces/baremetal/v1/custom_server.go b/internal/namespaces/baremetal/v1/custom_server.go index b656ffee9f..6fdd7aafa1 100644 --- a/internal/namespaces/baremetal/v1/custom_server.go +++ b/internal/namespaces/baremetal/v1/custom_server.go @@ -20,9 +20,18 @@ const ( ) var serverPingStatusMarshalSpecs = human.EnumMarshalSpecs{ - baremetal.ServerPingStatusPingStatusDown: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "down"}, - baremetal.ServerPingStatusPingStatusUp: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "up"}, - baremetal.ServerPingStatusPingStatusUnknown: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "unknown"}, + baremetal.ServerPingStatusPingStatusDown: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "down", + }, + baremetal.ServerPingStatusPingStatusUp: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "up", + }, + baremetal.ServerPingStatusPingStatusUnknown: &human.EnumMarshalSpec{ + Attribute: color.Faint, + Value: "unknown", + }, } func serverWaitCommand() *core.Command { @@ -64,7 +73,9 @@ func serverWaitCommand() *core.Command { return server, nil } - logger.Debugf("server reached a stable delivery status. Will now starting to wait for server to reach a stable installation status") + logger.Debugf( + "server reached a stable delivery status. Will now starting to wait for server to reach a stable installation status", + ) server, err = api.WaitForServerInstall(&baremetal.WaitForServerInstallRequest{ ServerID: args.ServerID, Zone: args.Zone, @@ -76,7 +87,10 @@ func serverWaitCommand() *core.Command { } if server.Install.Status != baremetal.ServerInstallStatusCompleted { return nil, &core.CliError{ - Err: fmt.Errorf("server %s did not reach a stable installation status", server.ID), + Err: fmt.Errorf( + "server %s did not reach a stable installation status", + server.ID, + ), Details: fmt.Sprintf("server %s is in %s status", server.ID, server.Status), } } diff --git a/internal/namespaces/baremetal/v1/custom_server_create_test.go b/internal/namespaces/baremetal/v1/custom_server_create_test.go index 071e7d9e4d..203fa3d243 100644 --- a/internal/namespaces/baremetal/v1/custom_server_create_test.go +++ b/internal/namespaces/baremetal/v1/custom_server_create_test.go @@ -33,7 +33,9 @@ func Test_CreateServer(t *testing.T) { core.TestCheckGolden(), core.TestCheckExitCode(0), ), - AfterFunc: core.ExecAfterCmd("scw baremetal server delete {{ .CmdResult.ID }} zone=" + region), + AfterFunc: core.ExecAfterCmd( + "scw baremetal server delete {{ .CmdResult.ID }} zone=" + region, + ), }, )) @@ -55,11 +57,17 @@ func Test_CreateServer(t *testing.T) { Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - assert.Equal(t, "test-create-server-with-name", ctx.Result.(*baremetalSDK.Server).Name) + assert.Equal( + t, + "test-create-server-with-name", + ctx.Result.(*baremetalSDK.Server).Name, + ) }, core.TestCheckExitCode(0), ), - AfterFunc: core.ExecAfterCmd("scw baremetal server delete {{ .CmdResult.ID }} zone=" + region), + AfterFunc: core.ExecAfterCmd( + "scw baremetal server delete {{ .CmdResult.ID }} zone=" + region, + ), })) t.Run("Tags", core.Test(&core.TestConfig{ @@ -85,7 +93,9 @@ func Test_CreateServer(t *testing.T) { }, core.TestCheckExitCode(0), ), - AfterFunc: core.ExecAfterCmd("scw baremetal server delete {{ .CmdResult.ID }} zone=" + region), + AfterFunc: core.ExecAfterCmd( + "scw baremetal server delete {{ .CmdResult.ID }} zone=" + region, + ), })) }) } diff --git a/internal/namespaces/baremetal/v1/custom_server_fip_prompt.go b/internal/namespaces/baremetal/v1/custom_server_fip_prompt.go index db00b4a611..8ac6654dc4 100644 --- a/internal/namespaces/baremetal/v1/custom_server_fip_prompt.go +++ b/internal/namespaces/baremetal/v1/custom_server_fip_prompt.go @@ -13,7 +13,10 @@ import ( var ipTypeOption = []string{"IPv4", "IPv6"} -func promptIPFlexibleServer(ctx context.Context, req *serverAddFlexibleIPRequest) (*serverAddFlexibleIPRequest, error) { +func promptIPFlexibleServer( + ctx context.Context, + req *serverAddFlexibleIPRequest, +) (*serverAddFlexibleIPRequest, error) { if !interactive.IsInteractive { return nil, &core.CliError{ Err: errors.New("failed to create and attach a new flexible IP"), diff --git a/internal/namespaces/baremetal/v1/custome_server_delete.go b/internal/namespaces/baremetal/v1/custome_server_delete.go index df1557b0d9..78c53e0a20 100644 --- a/internal/namespaces/baremetal/v1/custome_server_delete.go +++ b/internal/namespaces/baremetal/v1/custome_server_delete.go @@ -12,16 +12,18 @@ import ( func serverDeleteBuilder(c *core.Command) *core.Command { c.WaitFunc = func(ctx context.Context, argsI, _ interface{}) (interface{}, error) { - server, err := baremetal.NewAPI(core.ExtractClient(ctx)).WaitForServer(&baremetal.WaitForServerRequest{ - ServerID: argsI.(*baremetal.DeleteServerRequest).ServerID, - Zone: argsI.(*baremetal.DeleteServerRequest).Zone, - Timeout: scw.TimeDurationPtr(ServerActionTimeout), - RetryInterval: core.DefaultRetryInterval, - }) + server, err := baremetal.NewAPI(core.ExtractClient(ctx)). + WaitForServer(&baremetal.WaitForServerRequest{ + ServerID: argsI.(*baremetal.DeleteServerRequest).ServerID, + Zone: argsI.(*baremetal.DeleteServerRequest).Zone, + Timeout: scw.TimeDurationPtr(ServerActionTimeout), + RetryInterval: core.DefaultRetryInterval, + }) if err != nil { notFoundError := &scw.ResourceNotFoundError{} responseError := &scw.ResponseError{} - if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) { + if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || + errors.As(err, ¬FoundError) { return server, nil } diff --git a/internal/namespaces/baremetal/v1/helpers_test.go b/internal/namespaces/baremetal/v1/helpers_test.go index 0ae136a895..c5e36c3b12 100644 --- a/internal/namespaces/baremetal/v1/helpers_test.go +++ b/internal/namespaces/baremetal/v1/helpers_test.go @@ -9,7 +9,10 @@ import ( // createServerAndWait creates a baremetal instance // register it in the context Meta at metaKey. func createServerAndWait(metaKey string) core.BeforeFunc { - return core.ExecStoreBeforeCmd(metaKey, "scw baremetal server create zone="+region+" type="+offerName+" -w") + return core.ExecStoreBeforeCmd( + metaKey, + "scw baremetal server create zone="+region+" type="+offerName+" -w", + ) } func createServerAndWaitDefault(metaKey string) core.BeforeFunc { @@ -17,7 +20,10 @@ func createServerAndWaitDefault(metaKey string) core.BeforeFunc { } func createServer(metaKey string, offerType string) core.BeforeFunc { - return core.ExecStoreBeforeCmd(metaKey, "scw baremetal server create zone="+region+" type="+offerType) + return core.ExecStoreBeforeCmd( + metaKey, + "scw baremetal server create zone="+region+" type="+offerType, + ) } // deleteServer deletes a server @@ -25,7 +31,9 @@ func createServer(metaKey string, offerType string) core.BeforeFunc { // //nolint:unparam func deleteServer(metaKey string) core.AfterFunc { - return core.ExecAfterCmd(fmt.Sprintf("scw baremetal server delete zone="+region+" {{ .%s.ID }}", metaKey)) + return core.ExecAfterCmd( + fmt.Sprintf("scw baremetal server delete zone="+region+" {{ .%s.ID }}", metaKey), + ) } func deleteServerDefault(metaKey string) core.AfterFunc { diff --git a/internal/namespaces/baremetal/v3/baremetal_cli.go b/internal/namespaces/baremetal/v3/baremetal_cli.go index 1322663d8d..02132af7ec 100644 --- a/internal/namespaces/baremetal/v3/baremetal_cli.go +++ b/internal/namespaces/baremetal/v3/baremetal_cli.go @@ -27,6 +27,7 @@ func GetGeneratedCommands() *core.Commands { baremetalPrivateNetworkDelete(), ) } + func baremetalRoot() *core.Command { return &core.Command{ Short: `Elastic Metal - Private Networks API`, @@ -82,15 +83,22 @@ func baremetalPrivateNetworkAdd() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.PrivateNetworkAPIAddServerPrivateNetworkRequest) client := core.ExtractClient(ctx) api := baremetal.NewPrivateNetworkAPI(client) - return api.AddServerPrivateNetwork(request) + return api.AddServerPrivateNetwork(request) }, } } @@ -119,15 +127,22 @@ func baremetalPrivateNetworkSet() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.PrivateNetworkAPISetServerPrivateNetworksRequest) client := core.ExtractClient(ctx) api := baremetal.NewPrivateNetworkAPI(client) - return api.SetServerPrivateNetworks(request) + return api.SetServerPrivateNetworks(request) }, } } @@ -148,7 +163,12 @@ func baremetalPrivateNetworkList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + }, }, { Name: "server-id", @@ -185,7 +205,15 @@ func baremetalPrivateNetworkList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.PrivateNetworkAPIListServerPrivateNetworksRequest) @@ -201,8 +229,8 @@ func baremetalPrivateNetworkList() *core.Command { if err != nil { return nil, err } - return resp.ServerPrivateNetworks, nil + return resp.ServerPrivateNetworks, nil }, } } @@ -231,7 +259,14 @@ func baremetalPrivateNetworkDelete() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*baremetal.PrivateNetworkAPIDeleteServerPrivateNetworkRequest) @@ -242,6 +277,7 @@ func baremetalPrivateNetworkDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "private-network", Verb: "delete", diff --git a/internal/namespaces/billing/v2beta1/billing_cli.go b/internal/namespaces/billing/v2beta1/billing_cli.go index d8631c3740..9054e8dd1b 100644 --- a/internal/namespaces/billing/v2beta1/billing_cli.go +++ b/internal/namespaces/billing/v2beta1/billing_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/billing/v2beta1" + billing "github.com/scaleway/scaleway-sdk-go/api/billing/v2beta1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -32,6 +32,7 @@ func GetGeneratedCommands() *core.Commands { billingDiscountList(), ) } + func billingRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage and query your Scaleway billing and consumption`, @@ -83,7 +84,12 @@ func billingConsumptionList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"updated_at_desc", "updated_at_asc", "category_name_desc", "category_name_asc"}, + EnumValues: []string{ + "updated_at_desc", + "updated_at_asc", + "category_name_desc", + "category_name_asc", + }, }, core.ProjectIDArgSpec(), { @@ -112,8 +118,8 @@ func billingConsumptionList() *core.Command { if err != nil { return nil, err } - return resp.Consumptions, nil + return resp.Consumptions, nil }, } } @@ -134,7 +140,12 @@ func billingConsumptionListTaxes() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"updated_at_desc", "updated_at_asc", "category_name_desc", "category_name_asc"}, + EnumValues: []string{ + "updated_at_desc", + "updated_at_asc", + "category_name_desc", + "category_name_asc", + }, }, { Name: "billing-period", @@ -155,8 +166,8 @@ func billingConsumptionListTaxes() *core.Command { if err != nil { return nil, err } - return resp.Taxes, nil + return resp.Taxes, nil }, } } @@ -199,7 +210,22 @@ func billingInvoiceList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"invoice_number_desc", "invoice_number_asc", "start_date_desc", "start_date_asc", "issued_date_desc", "issued_date_asc", "due_date_desc", "due_date_asc", "total_untaxed_desc", "total_untaxed_asc", "total_taxed_desc", "total_taxed_asc", "invoice_type_desc", "invoice_type_asc"}, + EnumValues: []string{ + "invoice_number_desc", + "invoice_number_asc", + "start_date_desc", + "start_date_asc", + "issued_date_desc", + "issued_date_asc", + "due_date_desc", + "due_date_asc", + "total_untaxed_desc", + "total_untaxed_asc", + "total_taxed_desc", + "total_taxed_asc", + "invoice_type_desc", + "invoice_type_asc", + }, }, { Name: "organization-id", @@ -219,8 +245,8 @@ func billingInvoiceList() *core.Command { if err != nil { return nil, err } - return resp.Invoices, nil + return resp.Invoices, nil }, } } @@ -278,7 +304,22 @@ func billingInvoiceExport() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"invoice_number_desc", "invoice_number_asc", "start_date_desc", "start_date_asc", "issued_date_desc", "issued_date_asc", "due_date_desc", "due_date_asc", "total_untaxed_desc", "total_untaxed_asc", "total_taxed_desc", "total_taxed_asc", "invoice_type_desc", "invoice_type_asc"}, + EnumValues: []string{ + "invoice_number_desc", + "invoice_number_asc", + "start_date_desc", + "start_date_asc", + "issued_date_desc", + "issued_date_asc", + "due_date_desc", + "due_date_asc", + "total_untaxed_desc", + "total_untaxed_asc", + "total_taxed_desc", + "total_taxed_asc", + "invoice_type_desc", + "invoice_type_asc", + }, }, { Name: "file-type", @@ -302,8 +343,8 @@ func billingInvoiceExport() *core.Command { client := core.ExtractClient(ctx) api := billing.NewAPI(client) - return api.ExportInvoices(request) + return api.ExportInvoices(request) }, } } @@ -331,8 +372,8 @@ func billingInvoiceGet() *core.Command { client := core.ExtractClient(ctx) api := billing.NewAPI(client) - return api.GetInvoice(request) + return api.GetInvoice(request) }, } } @@ -368,8 +409,8 @@ func billingInvoiceDownload() *core.Command { client := core.ExtractClient(ctx) api := billing.NewAPI(client) - return api.DownloadInvoice(request) + return api.DownloadInvoice(request) }, } } @@ -393,7 +434,14 @@ func billingDiscountList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"creation_date_desc", "creation_date_asc", "start_date_desc", "start_date_asc", "stop_date_desc", "stop_date_asc"}, + EnumValues: []string{ + "creation_date_desc", + "creation_date_asc", + "start_date_desc", + "start_date_asc", + "stop_date_desc", + "stop_date_asc", + }, }, { Name: "organization-id", @@ -413,8 +461,8 @@ func billingDiscountList() *core.Command { if err != nil { return nil, err } - return resp.Discounts, nil + return resp.Discounts, nil }, } } diff --git a/internal/namespaces/billing/v2beta1/custom.go b/internal/namespaces/billing/v2beta1/custom.go index 446e617576..4e3626fcc0 100644 --- a/internal/namespaces/billing/v2beta1/custom.go +++ b/internal/namespaces/billing/v2beta1/custom.go @@ -8,13 +8,19 @@ import ( ) var invoiceTypeMarshalSpecs = human.EnumMarshalSpecs{ - billing.DownloadInvoiceRequestFileTypePdf: &human.EnumMarshalSpec{Attribute: color.FgHiBlue, Value: "pdf"}, + billing.DownloadInvoiceRequestFileTypePdf: &human.EnumMarshalSpec{ + Attribute: color.FgHiBlue, + Value: "pdf", + }, } func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(billing.DownloadInvoiceRequestFileType("pdf"), human.EnumMarshalFunc(invoiceTypeMarshalSpecs)) + human.RegisterMarshalerFunc( + billing.DownloadInvoiceRequestFileType("pdf"), + human.EnumMarshalFunc(invoiceTypeMarshalSpecs), + ) cmds.MustFind("billing", "invoice", "download").Override(invoiceDownloadBuilder) cmds.MustFind("billing", "invoice", "export").Override(invoiceExportBuilder) diff --git a/internal/namespaces/billing/v2beta1/custom_invoice_download.go b/internal/namespaces/billing/v2beta1/custom_invoice_download.go index 9218a45d44..4f07422839 100644 --- a/internal/namespaces/billing/v2beta1/custom_invoice_download.go +++ b/internal/namespaces/billing/v2beta1/custom_invoice_download.go @@ -98,7 +98,13 @@ func invoiceDownloadBuilder(command *core.Command) *core.Command { } // check default name - defaultFileName := fmt.Sprintf("%s-%s-%s.%s", invoiceDefaultPrefix, date, args.InvoiceID, args.FileType) + defaultFileName := fmt.Sprintf( + "%s-%s-%s.%s", + invoiceDefaultPrefix, + date, + args.InvoiceID, + args.FileType, + ) // read only in the parent path for _, e := range entries { if e.IsDir() { @@ -175,7 +181,12 @@ func billingDownloadRun(ctx context.Context, argsI interface{}) (interface{}, er return nil, errors.New("parse date on file name") } - defaultFileName := fmt.Sprintf("%s-%s-%s", invoiceDefaultPrefix, date, argsDownload.InvoiceID) + defaultFileName := fmt.Sprintf( + "%s-%s-%s", + invoiceDefaultPrefix, + date, + argsDownload.InvoiceID, + ) pathAbs, err := filepath.Abs(argsDownload.FilePath) if err != nil { return nil, err diff --git a/internal/namespaces/billing/v2beta1/custom_invoice_export.go b/internal/namespaces/billing/v2beta1/custom_invoice_export.go index 69a4a20a6b..b349677859 100644 --- a/internal/namespaces/billing/v2beta1/custom_invoice_export.go +++ b/internal/namespaces/billing/v2beta1/custom_invoice_export.go @@ -94,7 +94,12 @@ func invoiceExportBuilder(command *core.Command) *core.Command { return nil } - defaultFileName := fmt.Sprintf("%s-%s.%s", invoiceDefaultPrefix, time.Now().Format("2006-01"), args.FileType) + defaultFileName := fmt.Sprintf( + "%s-%s.%s", + invoiceDefaultPrefix, + time.Now().Format("2006-01"), + args.FileType, + ) // read only in the parent path for _, e := range entries { if e.IsDir() { @@ -157,7 +162,11 @@ func billingExportRun(ctx context.Context, argsI interface{}) (interface{}, erro if err == nil { if fInfo.IsDir() { // case when filepath is a directory: join default name with custom path - defaultFileName := fmt.Sprintf("%s-%s", invoiceDefaultPrefix, time.Now().Format("2006-01")) + defaultFileName := fmt.Sprintf( + "%s-%s", + invoiceDefaultPrefix, + time.Now().Format("2006-01"), + ) pathAbs, err := filepath.Abs(argsExport.FilePath) if err != nil { return nil, err diff --git a/internal/namespaces/block/v1alpha1/block_cli.go b/internal/namespaces/block/v1alpha1/block_cli.go index 11989e1c7b..c3baa40441 100644 --- a/internal/namespaces/block/v1alpha1/block_cli.go +++ b/internal/namespaces/block/v1alpha1/block_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/block/v1alpha1" + block "github.com/scaleway/scaleway-sdk-go/api/block/v1alpha1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -38,6 +38,7 @@ func GetGeneratedCommands() *core.Commands { blockSnapshotUpdate(), ) } + func blockRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Block Storage volumes`, @@ -83,7 +84,18 @@ func blockVolumeTypeList() *core.Command { // Deprecated: false, ArgsType: reflect.TypeOf(block.ListVolumeTypesRequest{}), ArgSpecs: core.ArgSpecs{ - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.ListVolumeTypesRequest) @@ -99,8 +111,8 @@ func blockVolumeTypeList() *core.Command { if err != nil { return nil, err } - return resp.VolumeTypes, nil + return resp.VolumeTypes, nil }, } } @@ -158,7 +170,18 @@ func blockVolumeList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.ListVolumesRequest) @@ -174,8 +197,8 @@ func blockVolumeList() *core.Command { if err != nil { return nil, err } - return resp.Volumes, nil + return resp.Volumes, nil }, } } @@ -235,15 +258,25 @@ To create a volume from an existing snapshot, specify ` + "`" + `from_snapshot` Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.CreateVolumeRequest) client := core.ExtractClient(ctx) api := block.NewAPI(client) - return api.CreateVolume(request) + return api.CreateVolume(request) }, } } @@ -265,15 +298,25 @@ func blockVolumeGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.GetVolumeRequest) client := core.ExtractClient(ctx) api := block.NewAPI(client) - return api.GetVolume(request) + return api.GetVolume(request) }, } } @@ -295,7 +338,17 @@ func blockVolumeDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.DeleteVolumeRequest) @@ -306,6 +359,7 @@ func blockVolumeDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "volume", Verb: "delete", @@ -360,15 +414,25 @@ You can only resize a volume to a larger size. It is currently not possible to c Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.UpdateVolumeRequest) client := core.ExtractClient(ctx) api := block.NewAPI(client) - return api.UpdateVolume(request) + return api.UpdateVolume(request) }, } } @@ -426,7 +490,18 @@ func blockSnapshotList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.ListSnapshotsRequest) @@ -442,8 +517,8 @@ func blockSnapshotList() *core.Command { if err != nil { return nil, err } - return resp.Snapshots, nil + return resp.Snapshots, nil }, } } @@ -465,15 +540,25 @@ func blockSnapshotGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.GetSnapshotRequest) client := core.ExtractClient(ctx) api := block.NewAPI(client) - return api.GetSnapshot(request) + return api.GetSnapshot(request) }, } } @@ -512,15 +597,25 @@ If your volume is in a transient state, you need to wait until the end of the cu Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.CreateSnapshotRequest) client := core.ExtractClient(ctx) api := block.NewAPI(client) - return api.CreateSnapshot(request) + return api.CreateSnapshot(request) }, } } @@ -572,15 +667,25 @@ The bucket can be imported into any Availability Zone as long as it is in the sa Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.ImportSnapshotFromObjectStorageRequest) client := core.ExtractClient(ctx) api := block.NewAPI(client) - return api.ImportSnapshotFromObjectStorage(request) + return api.ImportSnapshotFromObjectStorage(request) }, } } @@ -617,15 +722,25 @@ The snapshot must not be in transient state.`, Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.ExportSnapshotToObjectStorageRequest) client := core.ExtractClient(ctx) api := block.NewAPI(client) - return api.ExportSnapshotToObjectStorage(request) + return api.ExportSnapshotToObjectStorage(request) }, } } @@ -647,7 +762,17 @@ func blockSnapshotDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.DeleteSnapshotRequest) @@ -658,6 +783,7 @@ func blockSnapshotDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "snapshot", Verb: "delete", @@ -697,15 +823,25 @@ func blockSnapshotUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*block.UpdateSnapshotRequest) client := core.ExtractClient(ctx) api := block.NewAPI(client) - return api.UpdateSnapshot(request) + return api.UpdateSnapshot(request) }, } } diff --git a/internal/namespaces/block/v1alpha1/custom.go b/internal/namespaces/block/v1alpha1/custom.go index 8fbcbff142..644bacb99c 100644 --- a/internal/namespaces/block/v1alpha1/custom.go +++ b/internal/namespaces/block/v1alpha1/custom.go @@ -51,9 +51,18 @@ func GetCommands() *core.Commands { cmds.MustFind("block", "snapshot", "create").Override(blockSnapshotCreateBuilder) cmds.MustFind("block", "volume", "create").Override(blockVolumeCreateBuilder) - human.RegisterMarshalerFunc(block.VolumeStatus(""), human.EnumMarshalFunc(volumeStatusMarshalSpecs)) - human.RegisterMarshalerFunc(block.SnapshotStatus(""), human.EnumMarshalFunc(snapshotStatusMarshalSpecs)) - human.RegisterMarshalerFunc(block.ReferenceStatus(""), human.EnumMarshalFunc(referenceStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + block.VolumeStatus(""), + human.EnumMarshalFunc(volumeStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + block.SnapshotStatus(""), + human.EnumMarshalFunc(snapshotStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + block.ReferenceStatus(""), + human.EnumMarshalFunc(referenceStatusMarshalSpecs), + ) return cmds } diff --git a/internal/namespaces/block/v1alpha1/custom_snapshot.go b/internal/namespaces/block/v1alpha1/custom_snapshot.go index 8c2391f7a6..65440f11d9 100644 --- a/internal/namespaces/block/v1alpha1/custom_snapshot.go +++ b/internal/namespaces/block/v1alpha1/custom_snapshot.go @@ -41,14 +41,15 @@ func snapshotWaitCommand() *core.Command { Run: func(ctx context.Context, argsI interface{}) (i interface{}, err error) { args := argsI.(*snapshotWaitRequest) - return block.NewAPI(core.ExtractClient(ctx)).WaitForSnapshot(&block.WaitForSnapshotRequest{ - Zone: args.Zone, - SnapshotID: args.SnapshotID, - Timeout: scw.TimeDurationPtr(args.Timeout), - RetryInterval: core.DefaultRetryInterval, + return block.NewAPI(core.ExtractClient(ctx)). + WaitForSnapshot(&block.WaitForSnapshotRequest{ + Zone: args.Zone, + SnapshotID: args.SnapshotID, + Timeout: scw.TimeDurationPtr(args.Timeout), + RetryInterval: core.DefaultRetryInterval, - TerminalStatus: args.TerminalStatus, - }) + TerminalStatus: args.TerminalStatus, + }) }, ArgSpecs: core.ArgSpecs{ core.WaitTimeoutArgSpec(snapshotActionTimeout), diff --git a/internal/namespaces/block/v1alpha1/custom_snapshot_test.go b/internal/namespaces/block/v1alpha1/custom_snapshot_test.go index 4f54291360..4775c42317 100644 --- a/internal/namespaces/block/v1alpha1/custom_snapshot_test.go +++ b/internal/namespaces/block/v1alpha1/custom_snapshot_test.go @@ -14,8 +14,14 @@ func Test_SnapshotWait(t *testing.T) { t.Run("Wait command", core.Test(&core.TestConfig{ Commands: block.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Volume", "scw block volume create perf-iops=5000 from-empty.size=20GB -w"), - core.ExecStoreBeforeCmd("Snapshot", "scw block snapshot create volume-id={{ .Volume.ID }}"), + core.ExecStoreBeforeCmd( + "Volume", + "scw block volume create perf-iops=5000 from-empty.size=20GB -w", + ), + core.ExecStoreBeforeCmd( + "Snapshot", + "scw block snapshot create volume-id={{ .Volume.ID }}", + ), ), Cmd: "scw block snapshot wait {{ .Snapshot.ID }}", Check: core.TestCheckCombine( @@ -29,9 +35,12 @@ func Test_SnapshotWait(t *testing.T) { })) t.Run("Wait flag", core.Test(&core.TestConfig{ - Commands: block.GetCommands(), - BeforeFunc: core.ExecStoreBeforeCmd("Volume", "scw block volume create perf-iops=5000 from-empty.size=20GB -w"), - Cmd: "scw block snapshot create volume-id={{ .Volume.ID }} -w", + Commands: block.GetCommands(), + BeforeFunc: core.ExecStoreBeforeCmd( + "Volume", + "scw block volume create perf-iops=5000 from-empty.size=20GB -w", + ), + Cmd: "scw block snapshot create volume-id={{ .Volume.ID }} -w", Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() diff --git a/internal/namespaces/block/v1alpha1/custom_volume_test.go b/internal/namespaces/block/v1alpha1/custom_volume_test.go index 89f786a3d9..ce78116445 100644 --- a/internal/namespaces/block/v1alpha1/custom_volume_test.go +++ b/internal/namespaces/block/v1alpha1/custom_volume_test.go @@ -14,7 +14,10 @@ func Test_VolumeWait(t *testing.T) { t.Run("Wait command", core.Test(&core.TestConfig{ Commands: block.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Volume", "scw block volume create perf-iops=5000 from-empty.size=20GB"), + core.ExecStoreBeforeCmd( + "Volume", + "scw block volume create perf-iops=5000 from-empty.size=20GB", + ), ), Cmd: "scw block volume wait {{ .Volume.ID }}", Check: core.TestCheckCombine( diff --git a/internal/namespaces/cockpit/v1/cockpit_cli.go b/internal/namespaces/cockpit/v1/cockpit_cli.go index 5dc021bfc3..27d3ed416a 100644 --- a/internal/namespaces/cockpit/v1/cockpit_cli.go +++ b/internal/namespaces/cockpit/v1/cockpit_cli.go @@ -63,6 +63,7 @@ func GetGeneratedCommands() *core.Commands { cockpitTestAlertTrigger(), ) } + func cockpitRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Scaleway Cockpit, for storing and visualizing metrics and logs`, @@ -188,8 +189,8 @@ The output returned displays the URL to access your Cockpit's Grafana.`, client := core.ExtractClient(ctx) api := cockpit.NewGlobalAPI(client) - return api.GetGrafana(request) + return api.GetGrafana(request) }, } } @@ -215,6 +216,7 @@ func cockpitGrafanaSyncDataSources() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "grafana", Verb: "sync-data-sources", @@ -256,8 +258,8 @@ Each Grafana user is associated with a role: viewer or editor. A viewer can only client := core.ExtractClient(ctx) api := cockpit.NewGlobalAPI(client) - return api.CreateGrafanaUser(request) + return api.CreateGrafanaUser(request) }, } } @@ -292,8 +294,8 @@ func cockpitGrafanaUserList() *core.Command { if err != nil { return nil, err } - return resp.GrafanaUsers, nil + return resp.GrafanaUsers, nil }, } } @@ -326,6 +328,7 @@ func cockpitGrafanaUserDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "grafana-user", Verb: "delete", @@ -359,8 +362,8 @@ A new password regenerates and only displays once. Make sure that you save it.`, client := core.ExtractClient(ctx) api := cockpit.NewGlobalAPI(client) - return api.ResetGrafanaUserPassword(request) + return api.ResetGrafanaUserPassword(request) }, } } @@ -394,8 +397,8 @@ func cockpitProductDashboardsList() *core.Command { if err != nil { return nil, err } - return resp.Dashboards, nil + return resp.Dashboards, nil }, } } @@ -424,8 +427,8 @@ func cockpitProductDashboardsGet() *core.Command { client := core.ExtractClient(ctx) api := cockpit.NewGlobalAPI(client) - return api.GetGrafanaProductDashboard(request) + return api.GetGrafanaProductDashboard(request) }, } } @@ -459,8 +462,8 @@ Deprecated, retention is now managed at the data source level.`, if err != nil { return nil, err } - return resp.Plans, nil + return resp.Plans, nil }, } } @@ -491,8 +494,8 @@ Deprecated, retention is now managed at the data source level.`, client := core.ExtractClient(ctx) api := cockpit.NewGlobalAPI(client) - return api.SelectPlan(request) + return api.SelectPlan(request) }, } } @@ -515,8 +518,8 @@ Deprecated, retention is now managed at the data source level.`, client := core.ExtractClient(ctx) api := cockpit.NewGlobalAPI(client) - return api.GetCurrentPlan(request) + return api.GetCurrentPlan(request) }, } } @@ -565,8 +568,8 @@ The name of the data source will then be used as reference to name the associate client := core.ExtractClient(ctx) api := cockpit.NewRegionalAPI(client) - return api.CreateDataSource(request) + return api.CreateDataSource(request) }, } } @@ -595,8 +598,8 @@ func cockpitDataSourceGet() *core.Command { client := core.ExtractClient(ctx) api := cockpit.NewRegionalAPI(client) - return api.GetDataSource(request) + return api.GetDataSource(request) }, } } @@ -629,6 +632,7 @@ func cockpitDataSourceDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "data-source", Verb: "delete", @@ -654,7 +658,14 @@ You can list data sources by Project, type and origin.`, Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "type_asc", "type_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + "type_asc", + "type_desc", + }, }, core.ProjectIDArgSpec(), { @@ -673,7 +684,12 @@ You can list data sources by Project, type and origin.`, Positional: false, EnumValues: []string{"unknown_type", "metrics", "logs", "traces"}, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*cockpit.RegionalAPIListDataSourcesRequest) @@ -689,8 +705,8 @@ You can list data sources by Project, type and origin.`, if err != nil { return nil, err } - return resp.DataSources, nil + return resp.DataSources, nil }, } } @@ -733,8 +749,8 @@ func cockpitDataSourceUpdate() *core.Command { client := core.ExtractClient(ctx) api := cockpit.NewRegionalAPI(client) - return api.UpdateDataSource(request) + return api.UpdateDataSource(request) }, } } @@ -763,8 +779,8 @@ func cockpitUsageOverviewGet() *core.Command { client := core.ExtractClient(ctx) api := cockpit.NewRegionalAPI(client) - return api.GetUsageOverview(request) + return api.GetUsageOverview(request) }, } } @@ -794,7 +810,18 @@ Upon creation, your token's secret key display only once. Make sure that you sav Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_scope", "read_only_metrics", "write_only_metrics", "full_access_metrics_rules", "read_only_logs", "write_only_logs", "full_access_logs_rules", "full_access_alert_manager", "read_only_traces", "write_only_traces"}, + EnumValues: []string{ + "unknown_scope", + "read_only_metrics", + "write_only_metrics", + "full_access_metrics_rules", + "read_only_logs", + "write_only_logs", + "full_access_logs_rules", + "full_access_alert_manager", + "read_only_traces", + "write_only_traces", + }, }, core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw), }, @@ -803,8 +830,8 @@ Upon creation, your token's secret key display only once. Make sure that you sav client := core.ExtractClient(ctx) api := cockpit.NewRegionalAPI(client) - return api.CreateToken(request) + return api.CreateToken(request) }, } } @@ -835,9 +862,25 @@ You can filter tokens by Project ID and token scopes.`, Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_scope", "read_only_metrics", "write_only_metrics", "full_access_metrics_rules", "read_only_logs", "write_only_logs", "full_access_logs_rules", "full_access_alert_manager", "read_only_traces", "write_only_traces"}, + EnumValues: []string{ + "unknown_scope", + "read_only_metrics", + "write_only_metrics", + "full_access_metrics_rules", + "read_only_logs", + "write_only_logs", + "full_access_logs_rules", + "full_access_alert_manager", + "read_only_traces", + "write_only_traces", + }, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*cockpit.RegionalAPIListTokensRequest) @@ -853,8 +896,8 @@ You can filter tokens by Project ID and token scopes.`, if err != nil { return nil, err } - return resp.Tokens, nil + return resp.Tokens, nil }, } } @@ -883,8 +926,8 @@ func cockpitTokenGet() *core.Command { client := core.ExtractClient(ctx) api := cockpit.NewRegionalAPI(client) - return api.GetToken(request) + return api.GetToken(request) }, } } @@ -917,6 +960,7 @@ func cockpitTokenDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "token", Verb: "delete", @@ -944,8 +988,8 @@ The output returned displays a URL to access the Alert manager, and whether the client := core.ExtractClient(ctx) api := cockpit.NewRegionalAPI(client) - return api.GetAlertManager(request) + return api.GetAlertManager(request) }, } } @@ -968,8 +1012,8 @@ func cockpitAlertManagerEnable() *core.Command { client := core.ExtractClient(ctx) api := cockpit.NewRegionalAPI(client) - return api.EnableAlertManager(request) + return api.EnableAlertManager(request) }, } } @@ -992,8 +1036,8 @@ func cockpitAlertManagerDisable() *core.Command { client := core.ExtractClient(ctx) api := cockpit.NewRegionalAPI(client) - return api.DisableAlertManager(request) + return api.DisableAlertManager(request) }, } } @@ -1031,8 +1075,8 @@ If you need to receive alerts for other receivers, you can create additional con client := core.ExtractClient(ctx) api := cockpit.NewRegionalAPI(client) - return api.CreateContactPoint(request) + return api.CreateContactPoint(request) }, } } @@ -1048,7 +1092,12 @@ func cockpitContactPointList() *core.Command { ArgsType: reflect.TypeOf(cockpit.RegionalAPIListContactPointsRequest{}), ArgSpecs: core.ArgSpecs{ core.ProjectIDArgSpec(), - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*cockpit.RegionalAPIListContactPointsRequest) @@ -1064,8 +1113,8 @@ func cockpitContactPointList() *core.Command { if err != nil { return nil, err } - return resp.ContactPoints, nil + return resp.ContactPoints, nil }, } } @@ -1098,6 +1147,7 @@ func cockpitContactPointDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "contact-point", Verb: "delete", @@ -1124,8 +1174,8 @@ func cockpitManagedAlertsEnable() *core.Command { client := core.ExtractClient(ctx) api := cockpit.NewRegionalAPI(client) - return api.EnableManagedAlerts(request) + return api.EnableManagedAlerts(request) }, } } @@ -1148,8 +1198,8 @@ func cockpitManagedAlertsDisable() *core.Command { client := core.ExtractClient(ctx) api := cockpit.NewRegionalAPI(client) - return api.DisableManagedAlerts(request) + return api.DisableManagedAlerts(request) }, } } @@ -1176,6 +1226,7 @@ func cockpitTestAlertTrigger() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "test-alert", Verb: "trigger", diff --git a/internal/namespaces/config/commands.go b/internal/namespaces/config/commands.go index 7a6c7a9a84..967effef9f 100644 --- a/internal/namespaces/config/commands.go +++ b/internal/namespaces/config/commands.go @@ -54,7 +54,15 @@ func configRoot() *core.Command { {"|", scw.ScwInsecureEnv, "|", "Set this to true to enable the insecure mode", "|"}, {"|", scw.ScwActiveProfileEnv, "|", "Set the config profile to use", "|"}, } { - fmt.Fprintf(w, " %s%s%s%s%s\n", envVar[0], terminal.Style(envVar[1], color.Bold, color.FgBlue), envVar[2], envVar[3], envVar[4]) + fmt.Fprintf( + w, + " %s%s%s%s%s\n", + envVar[0], + terminal.Style(envVar[1], color.Bold, color.FgBlue), + envVar[2], + envVar[3], + envVar[4], + ) } w.Flush() @@ -184,7 +192,8 @@ The only allowed attributes are access_key, secret_key, default_organization_id, Name: "access-key", Short: "A Scaleway access key", ValidateFunc: func(_ *core.ArgSpec, value interface{}) error { - if !reflect.ValueOf(value).IsNil() && !validation.IsAccessKey(*value.(*string)) { + if !reflect.ValueOf(value).IsNil() && + !validation.IsAccessKey(*value.(*string)) { return core.InvalidAccessKeyError(*value.(*string)) } @@ -195,7 +204,8 @@ The only allowed attributes are access_key, secret_key, default_organization_id, Name: "secret-key", Short: "A Scaleway secret key", ValidateFunc: func(_ *core.ArgSpec, value interface{}) error { - if !reflect.ValueOf(value).IsNil() && !validation.IsSecretKey(*value.(*string)) { + if !reflect.ValueOf(value).IsNil() && + !validation.IsSecretKey(*value.(*string)) { return core.InvalidSecretKeyError(*value.(*string)) } @@ -221,7 +231,8 @@ The only allowed attributes are access_key, secret_key, default_organization_id, Name: "default-organization-id", Short: "A default Scaleway organization id", ValidateFunc: func(_ *core.ArgSpec, value interface{}) error { - if !reflect.ValueOf(value).IsNil() && !validation.IsOrganizationID(*value.(*string)) { + if !reflect.ValueOf(value).IsNil() && + !validation.IsOrganizationID(*value.(*string)) { return core.InvalidOrganizationIDError(*value.(*string)) } @@ -232,7 +243,8 @@ The only allowed attributes are access_key, secret_key, default_organization_id, Name: "default-project-id", Short: "A default Scaleway project id", ValidateFunc: func(_ *core.ArgSpec, value interface{}) error { - if !reflect.ValueOf(value).IsNil() && !validation.IsProjectID(*value.(*string)) { + if !reflect.ValueOf(value).IsNil() && + !validation.IsProjectID(*value.(*string)) { return core.InvalidProjectIDError(*value.(*string)) } @@ -623,7 +635,10 @@ func configInfoCommand() *core.Command { } if len(overridedVariables) > 0 { - msg := "Some variables are overridden by the environment: " + strings.Join(overridedVariables, ", ") + msg := "Some variables are overridden by the environment: " + strings.Join( + overridedVariables, + ", ", + ) fmt.Println(terminal.Style(msg, color.FgRed)) } @@ -688,7 +703,10 @@ func configImportCommand() *core.Command { for profileName, profile := range importedConfig.Profiles { existingProfile, exists := currentConfig.Profiles[profileName] if exists { - currentConfig.Profiles[profileName] = scw.MergeProfiles(existingProfile, profile) + currentConfig.Profiles[profileName] = scw.MergeProfiles( + existingProfile, + profile, + ) } else { currentConfig.Profiles[profileName] = profile } diff --git a/internal/namespaces/config/commands_test.go b/internal/namespaces/config/commands_test.go index 754c6fe06f..2547449e6b 100644 --- a/internal/namespaces/config/commands_test.go +++ b/internal/namespaces/config/commands_test.go @@ -335,10 +335,18 @@ func Test_ConfigImportCommand(t *testing.T) { assert.Equal(t, "22222222-2222-2222-2222-222222222222", *config.SecretKey) assert.Equal(t, "nl-ams", *config.DefaultRegion) // modified p1 - assert.Equal(t, "99999999-9999-9999-9999-999999999999", *config.Profiles["p1"].SecretKey) + assert.Equal( + t, + "99999999-9999-9999-9999-999999999999", + *config.Profiles["p1"].SecretKey, + ) assert.Equal(t, "nl-ams", *config.Profiles["p1"].DefaultRegion) // new p3 - assert.Equal(t, "33333333-3333-3333-3333-333333333333", *config.Profiles["p3"].SecretKey) + assert.Equal( + t, + "33333333-3333-3333-3333-333333333333", + *config.Profiles["p3"].SecretKey, + ) assert.Equal(t, "fr-par", *config.Profiles["p3"].DefaultRegion) }), ), diff --git a/internal/namespaces/container/v1beta1/container_cli.go b/internal/namespaces/container/v1beta1/container_cli.go index 4b23c8735c..87727952bb 100644 --- a/internal/namespaces/container/v1beta1/container_cli.go +++ b/internal/namespaces/container/v1beta1/container_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/container/v1beta1" + container "github.com/scaleway/scaleway-sdk-go/api/container/v1beta1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -57,6 +57,7 @@ func GetGeneratedCommands() *core.Commands { containerTriggerDelete(), ) } + func containerRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Serverless Containers`, @@ -158,7 +159,12 @@ func containerNamespaceList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*container.ListNamespacesRequest) @@ -174,8 +180,8 @@ func containerNamespaceList() *core.Command { if err != nil { return nil, err } - return resp.Namespaces, nil + return resp.Namespaces, nil }, } } @@ -204,8 +210,8 @@ func containerNamespaceGet() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.GetNamespace(request) + return api.GetNamespace(request) }, } } @@ -269,8 +275,8 @@ func containerNamespaceCreate() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.CreateNamespace(request) + return api.CreateNamespace(request) }, } } @@ -332,8 +338,8 @@ func containerNamespaceUpdate() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.UpdateNamespace(request) + return api.UpdateNamespace(request) }, } } @@ -362,8 +368,8 @@ func containerNamespaceDelete() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.DeleteNamespace(request) + return api.DeleteNamespace(request) }, } } @@ -414,7 +420,12 @@ func containerContainerList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*container.ListContainersRequest) @@ -430,8 +441,8 @@ func containerContainerList() *core.Command { if err != nil { return nil, err } - return resp.Containers, nil + return resp.Containers, nil }, } } @@ -460,8 +471,8 @@ func containerContainerGet() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.GetContainer(request) + return api.GetContainer(request) }, } } @@ -658,8 +669,8 @@ func containerContainerCreate() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.CreateContainer(request) + return api.CreateContainer(request) }, } } @@ -853,8 +864,8 @@ func containerContainerUpdate() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.UpdateContainer(request) + return api.UpdateContainer(request) }, } } @@ -883,8 +894,8 @@ func containerContainerDelete() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.DeleteContainer(request) + return api.DeleteContainer(request) }, } } @@ -913,8 +924,8 @@ func containerContainerDeploy() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.DeployContainer(request) + return api.DeployContainer(request) }, } } @@ -944,7 +955,12 @@ func containerCronList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*container.ListCronsRequest) @@ -960,8 +976,8 @@ func containerCronList() *core.Command { if err != nil { return nil, err } - return resp.Crons, nil + return resp.Crons, nil }, } } @@ -990,8 +1006,8 @@ func containerCronGet() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.GetCron(request) + return api.GetCron(request) }, } } @@ -1041,8 +1057,8 @@ func containerCronCreate() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.CreateCron(request) + return api.CreateCron(request) }, } } @@ -1099,8 +1115,8 @@ func containerCronUpdate() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.UpdateCron(request) + return api.UpdateCron(request) }, } } @@ -1129,8 +1145,8 @@ func containerCronDelete() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.DeleteCron(request) + return api.DeleteCron(request) }, } } @@ -1151,7 +1167,12 @@ func containerDomainList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "hostname_asc", "hostname_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "hostname_asc", + "hostname_desc", + }, }, { Name: "container-id", @@ -1160,7 +1181,12 @@ func containerDomainList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*container.ListDomainsRequest) @@ -1176,8 +1202,8 @@ func containerDomainList() *core.Command { if err != nil { return nil, err } - return resp.Domains, nil + return resp.Domains, nil }, } } @@ -1206,8 +1232,8 @@ func containerDomainGet() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.GetDomain(request) + return api.GetDomain(request) }, } } @@ -1243,8 +1269,8 @@ func containerDomainCreate() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.CreateDomain(request) + return api.CreateDomain(request) }, } } @@ -1273,8 +1299,8 @@ func containerDomainDelete() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.DeleteDomain(request) + return api.DeleteDomain(request) }, } } @@ -1324,8 +1350,8 @@ func containerTokenCreate() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.CreateToken(request) + return api.CreateToken(request) }, } } @@ -1354,8 +1380,8 @@ func containerTokenGet() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.GetToken(request) + return api.GetToken(request) }, } } @@ -1392,7 +1418,12 @@ func containerTokenList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*container.ListTokensRequest) @@ -1408,8 +1439,8 @@ func containerTokenList() *core.Command { if err != nil { return nil, err } - return resp.Tokens, nil + return resp.Tokens, nil }, } } @@ -1438,8 +1469,8 @@ func containerTokenDelete() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.DeleteToken(request) + return api.DeleteToken(request) }, } } @@ -1531,8 +1562,8 @@ func containerTriggerCreate() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.CreateTrigger(request) + return api.CreateTrigger(request) }, } } @@ -1561,8 +1592,8 @@ func containerTriggerGet() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.GetTrigger(request) + return api.GetTrigger(request) }, } } @@ -1600,7 +1631,12 @@ func containerTriggerList() *core.Command { Positional: false, }, core.ProjectIDArgSpec(), - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*container.ListTriggersRequest) @@ -1616,8 +1652,8 @@ func containerTriggerList() *core.Command { if err != nil { return nil, err } - return resp.Triggers, nil + return resp.Triggers, nil }, } } @@ -1660,8 +1696,8 @@ func containerTriggerUpdate() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.UpdateTrigger(request) + return api.UpdateTrigger(request) }, } } @@ -1690,8 +1726,8 @@ func containerTriggerDelete() *core.Command { client := core.ExtractClient(ctx) api := container.NewAPI(client) - return api.DeleteTrigger(request) + return api.DeleteTrigger(request) }, } } diff --git a/internal/namespaces/container/v1beta1/custom.go b/internal/namespaces/container/v1beta1/custom.go index 90454fd590..dc20eee773 100644 --- a/internal/namespaces/container/v1beta1/custom.go +++ b/internal/namespaces/container/v1beta1/custom.go @@ -9,9 +9,18 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(container.NamespaceStatus(""), human.EnumMarshalFunc(namespaceStatusMarshalSpecs)) - human.RegisterMarshalerFunc(container.ContainerStatus(""), human.EnumMarshalFunc(containerStatusMarshalSpecs)) - human.RegisterMarshalerFunc(container.CronStatus(""), human.EnumMarshalFunc(cronStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + container.NamespaceStatus(""), + human.EnumMarshalFunc(namespaceStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + container.ContainerStatus(""), + human.EnumMarshalFunc(containerStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + container.CronStatus(""), + human.EnumMarshalFunc(cronStatusMarshalSpecs), + ) cmds.MustFind("container", "container", "deploy").Override(containerContainerDeployBuilder) cmds.MustFind("container", "container", "create").Override(containerContainerCreateBuilder) diff --git a/internal/namespaces/container/v1beta1/custom_container.go b/internal/namespaces/container/v1beta1/custom_container.go index 294b0b3d62..1a830d2d1a 100644 --- a/internal/namespaces/container/v1beta1/custom_container.go +++ b/internal/namespaces/container/v1beta1/custom_container.go @@ -63,21 +63,23 @@ func containerContainerCreateBuilder(command *core.Command) *core.Command { command.ArgsType = reflect.TypeOf(CustomCreateContainerRequest{}) - command.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { - args := argsI.(*CustomCreateContainerRequest) - resI, err := runner(ctx, args.CreateContainerRequest) - if err != nil { - return resI, err - } - - c := resI.(*container.Container) - containerAPI := container.NewAPI(core.ExtractClient(ctx)) - - return containerAPI.DeployContainer(&container.DeployContainerRequest{ - Region: c.Region, - ContainerID: c.ID, - }, scw.WithContext(ctx)) - }) + command.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + args := argsI.(*CustomCreateContainerRequest) + resI, err := runner(ctx, args.CreateContainerRequest) + if err != nil { + return resI, err + } + + c := resI.(*container.Container) + containerAPI := container.NewAPI(core.ExtractClient(ctx)) + + return containerAPI.DeployContainer(&container.DeployContainerRequest{ + Region: c.Region, + ContainerID: c.ID, + }, scw.WithContext(ctx)) + }, + ) command.WaitFunc = waitForContainer diff --git a/internal/namespaces/container/v1beta1/custom_container_test.go b/internal/namespaces/container/v1beta1/custom_container_test.go index 1fe6b669ad..1e647d1086 100644 --- a/internal/namespaces/container/v1beta1/custom_container_test.go +++ b/internal/namespaces/container/v1beta1/custom_container_test.go @@ -28,7 +28,10 @@ func Test_Create(t *testing.T) { BeforeFunc: core.BeforeFuncCombine( createNamespace("Namespace"), ), - Cmd: fmt.Sprintf("scw container container create namespace-id={{ .Namespace.ID }} name=%s deploy=true", core.GetRandomName("test")), + Cmd: fmt.Sprintf( + "scw container container create namespace-id={{ .Namespace.ID }} name=%s deploy=true", + core.GetRandomName("test"), + ), Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() diff --git a/internal/namespaces/container/v1beta1/custom_deploy.go b/internal/namespaces/container/v1beta1/custom_deploy.go index ebd7ccb680..3b96dd6fe2 100644 --- a/internal/namespaces/container/v1beta1/custom_deploy.go +++ b/internal/namespaces/container/v1beta1/custom_deploy.go @@ -101,7 +101,12 @@ func containerDeployCommand() *core.Command { Name: "namespace-id", Short: "Container Namespace ID to deploy to", }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: containerDeployRun, } @@ -118,7 +123,9 @@ func containerDeployRun(ctx context.Context, argsI interface{}) (i interface{}, if args.Name == "" { args.Name = filepath.Base(args.BuildSource) if args.Name == "." { - return nil, errors.New("unable to determine application name, please specify it with name=") + return nil, errors.New( + "unable to determine application name, please specify it with name=", + ) } args.Name = "app-" + args.Name @@ -164,7 +171,10 @@ func containerDeployRun(ctx context.Context, argsI interface{}) (i interface{}, container := result.(*DeployStepDeployContainerResponse).Container - return fmt.Sprintln(terminal.Style("Your application is now available at", color.FgGreen), terminal.Style("https://"+container.DomainName, color.FgGreen, color.Bold)), nil + return fmt.Sprintln( + terminal.Style("Your application is now available at", color.FgGreen), + terminal.Style("https://"+container.DomainName, color.FgGreen, color.Bold), + ), nil } type DeployStepData struct { @@ -178,7 +188,10 @@ type DeployStepCreateNamespaceResponse struct { Namespace *container.Namespace } -func DeployStepFetchNamespace(t *tasks.Task, data *DeployStepData) (*DeployStepCreateNamespaceResponse, error) { +func DeployStepFetchNamespace( + t *tasks.Task, + data *DeployStepData, +) (*DeployStepCreateNamespaceResponse, error) { namespace, err := data.API.GetNamespace(&container.GetNamespaceRequest{ Region: data.Args.Region, NamespaceID: *data.Args.NamespaceID, @@ -193,7 +206,10 @@ func DeployStepFetchNamespace(t *tasks.Task, data *DeployStepData) (*DeployStepC }, nil } -func DeployStepCreateNamespace(t *tasks.Task, data *DeployStepData) (*DeployStepCreateNamespaceResponse, error) { +func DeployStepCreateNamespace( + t *tasks.Task, + data *DeployStepData, +) (*DeployStepCreateNamespaceResponse, error) { namespace, err := getorcreate.Namespace(t.Ctx, data.API, data.Args.Region, data.Args.Name) if err != nil { return nil, err @@ -211,11 +227,19 @@ type DeployStepFetchOrCreateResponse struct { RegistryEndpoint string } -func DeployStepFetchOrCreateRegistry(t *tasks.Task, data *DeployStepCreateNamespaceResponse) (*DeployStepFetchOrCreateResponse, error) { +func DeployStepFetchOrCreateRegistry( + t *tasks.Task, + data *DeployStepCreateNamespaceResponse, +) (*DeployStepFetchOrCreateResponse, error) { registryEndpoint := data.Namespace.RegistryEndpoint if registryEndpoint == "" { registryAPI := registry.NewAPI(data.Client) - registryNamespace, err := getorcreate.Registry(t.Ctx, registryAPI, data.Args.Region, data.Namespace.Name) + registryNamespace, err := getorcreate.Registry( + t.Ctx, + registryAPI, + data.Args.Region, + data.Namespace.Name, + ) if err != nil { return nil, err } @@ -237,7 +261,10 @@ type DeployStepPackImageResponse struct { Tar io.Reader } -func DeployStepDockerPackImage(_ *tasks.Task, data *DeployStepFetchOrCreateResponse) (*DeployStepPackImageResponse, error) { +func DeployStepDockerPackImage( + _ *tasks.Task, + data *DeployStepFetchOrCreateResponse, +) (*DeployStepPackImageResponse, error) { tar, err := archive.TarWithOptions(data.Args.BuildSource, &archive.TarOptions{}) if err != nil { return nil, fmt.Errorf("could not create tar: %w", err) @@ -258,27 +285,44 @@ type DeployStepBuildImageResponse struct { DockerClient DockerClient } -func DeployStepDockerBuildImage(t *tasks.Task, data *DeployStepPackImageResponse) (*DeployStepBuildImageResponse, error) { +func DeployStepDockerBuildImage( + t *tasks.Task, + data *DeployStepPackImageResponse, +) (*DeployStepBuildImageResponse, error) { tag := data.RegistryEndpoint + "/" + data.Args.Name + ":latest" httpClient := core.ExtractHTTPClient(t.Ctx) - dockerClient, err := docker.NewClientWithOpts(docker.FromEnv, docker.WithAPIVersionNegotiation(), docker.WithHTTPClient(httpClient)) + dockerClient, err := docker.NewClientWithOpts( + docker.FromEnv, + docker.WithAPIVersionNegotiation(), + docker.WithHTTPClient(httpClient), + ) if err != nil { return nil, fmt.Errorf("could not connect to Docker: %w", err) } - imageBuildResponse, err := dockerClient.ImageBuild(t.Ctx, data.Tar, dockertypes.ImageBuildOptions{ - Dockerfile: data.Args.Dockerfile, - Tags: []string{tag}, - NoCache: !data.Args.Cache, - BuildArgs: data.Args.BuildArgs, - }) + imageBuildResponse, err := dockerClient.ImageBuild( + t.Ctx, + data.Tar, + dockertypes.ImageBuildOptions{ + Dockerfile: data.Args.Dockerfile, + Tags: []string{tag}, + NoCache: !data.Args.Cache, + BuildArgs: data.Args.BuildArgs, + }, + ) if err != nil { return nil, fmt.Errorf("could not build image: %w", errors.Unwrap(err)) } defer imageBuildResponse.Body.Close() - err = jsonmessage.DisplayJSONMessagesStream(imageBuildResponse.Body, t.Logs, t.Logs.Fd(), true, nil) + err = jsonmessage.DisplayJSONMessagesStream( + imageBuildResponse.Body, + t.Logs, + t.Logs.Fd(), + true, + nil, + ) if err != nil { if jerr, ok := err.(*jsonmessage.JSONError); ok { // If no error code is set, default to 1 @@ -286,7 +330,11 @@ func DeployStepDockerBuildImage(t *tasks.Task, data *DeployStepPackImageResponse jerr.Code = 1 } - return nil, fmt.Errorf("docker build failed with error code %d: %s", jerr.Code, jerr.Message) + return nil, fmt.Errorf( + "docker build failed with error code %d: %s", + jerr.Code, + jerr.Message, + ) } return nil, err @@ -300,7 +348,10 @@ func DeployStepDockerBuildImage(t *tasks.Task, data *DeployStepPackImageResponse }, nil } -func DeployStepBuildpackBuildImage(t *tasks.Task, data *DeployStepFetchOrCreateResponse) (*DeployStepBuildImageResponse, error) { +func DeployStepBuildpackBuildImage( + t *tasks.Task, + data *DeployStepFetchOrCreateResponse, +) (*DeployStepBuildImageResponse, error) { tag := data.RegistryEndpoint + "/" + data.Args.Name + ":latest" httpClient := core.ExtractHTTPClient(t.Ctx) @@ -309,7 +360,10 @@ func DeployStepBuildpackBuildImage(t *tasks.Task, data *DeployStepFetchOrCreateR return nil, err } - packClient, err := pack.NewClient(pack.WithDockerClient(dockerClient), pack.WithLogger(logging.NewLogWithWriters(t.Logs, t.Logs))) + packClient, err := pack.NewClient( + pack.WithDockerClient(dockerClient), + pack.WithLogger(logging.NewLogWithWriters(t.Logs, t.Logs)), + ) if err != nil { return nil, fmt.Errorf("could not create pack client: %w", err) } @@ -339,7 +393,10 @@ type DeployStepPushImageResponse struct { Tag string } -func DeployStepPushImage(t *tasks.Task, data *DeployStepBuildImageResponse) (*DeployStepPushImageResponse, error) { +func DeployStepPushImage( + t *tasks.Task, + data *DeployStepBuildImageResponse, +) (*DeployStepPushImageResponse, error) { accessKey, _ := data.Client.GetAccessKey() secretKey, _ := data.Client.GetSecretKey() authConfig := dockerregistry.AuthConfig{ @@ -371,7 +428,11 @@ func DeployStepPushImage(t *tasks.Task, data *DeployStepBuildImageResponse) (*De jerr.Code = 1 } - return nil, fmt.Errorf("docker build failed with error code %d: %s", jerr.Code, jerr.Message) + return nil, fmt.Errorf( + "docker build failed with error code %d: %s", + jerr.Code, + jerr.Message, + ) } return nil, err @@ -389,8 +450,17 @@ type DeployStepCreateContainerResponse struct { Container *container.Container } -func DeployStepCreateContainer(t *tasks.Task, data *DeployStepPushImageResponse) (*DeployStepCreateContainerResponse, error) { - targetContainer, err := getorcreate.Container(t.Ctx, data.API, data.Args.Region, data.Namespace.ID, data.Args.Name) +func DeployStepCreateContainer( + t *tasks.Task, + data *DeployStepPushImageResponse, +) (*DeployStepCreateContainerResponse, error) { + targetContainer, err := getorcreate.Container( + t.Ctx, + data.API, + data.Args.Region, + data.Namespace.ID, + data.Args.Name, + ) if err != nil { return nil, fmt.Errorf("could not get or create container: %w", err) } @@ -427,7 +497,10 @@ type DeployStepDeployContainerResponse struct { Container *container.Container } -func DeployStepDeployContainer(t *tasks.Task, data *DeployStepCreateContainerResponse) (*DeployStepDeployContainerResponse, error) { +func DeployStepDeployContainer( + t *tasks.Task, + data *DeployStepCreateContainerResponse, +) (*DeployStepDeployContainerResponse, error) { targetContainer, err := data.API.DeployContainer(&container.DeployContainerRequest{ Region: data.Args.Region, ContainerID: data.Container.ID, diff --git a/internal/namespaces/container/v1beta1/custom_deploy_helpers.go b/internal/namespaces/container/v1beta1/custom_deploy_helpers.go index 9ab52186b0..7f3b271144 100644 --- a/internal/namespaces/container/v1beta1/custom_deploy_helpers.go +++ b/internal/namespaces/container/v1beta1/custom_deploy_helpers.go @@ -31,7 +31,11 @@ type CustomDockerClient struct { } func NewCustomDockerClient(httpClient *http.Client) (*CustomDockerClient, error) { - dockerClient, err := docker.NewClientWithOpts(docker.FromEnv, docker.WithAPIVersionNegotiation(), docker.WithHTTPClient(httpClient)) + dockerClient, err := docker.NewClientWithOpts( + docker.FromEnv, + docker.WithAPIVersionNegotiation(), + docker.WithHTTPClient(httpClient), + ) if err != nil { return nil, fmt.Errorf("could not connect to Docker: %w", err) } @@ -42,7 +46,11 @@ func NewCustomDockerClient(httpClient *http.Client) (*CustomDockerClient, error) }, nil } -func (c *CustomDockerClient) ContainerAttach(_ context.Context, container string, options container.AttachOptions) (dockertypes.HijackedResponse, error) { +func (c *CustomDockerClient) ContainerAttach( + _ context.Context, + container string, + options container.AttachOptions, +) (dockertypes.HijackedResponse, error) { query := url.Values{} if options.Stream { query.Set("stream", "1") @@ -65,7 +73,7 @@ func (c *CustomDockerClient) ContainerAttach(_ context.Context, container string requestURL := &url.URL{ Scheme: "http", - Host: strings.TrimPrefix(c.Client.DaemonHost(), "unix://"), + Host: strings.TrimPrefix(c.DaemonHost(), "unix://"), Path: fmt.Sprintf("/containers/%s/attach", container), RawQuery: query.Encode(), } diff --git a/internal/namespaces/container/v1beta1/custom_deploy_test.go b/internal/namespaces/container/v1beta1/custom_deploy_test.go index 536487c7aa..10a235d457 100644 --- a/internal/namespaces/container/v1beta1/custom_deploy_test.go +++ b/internal/namespaces/container/v1beta1/custom_deploy_test.go @@ -32,7 +32,11 @@ var ( testDataBuildpackNodePackageLockJSON string ) -func loadTestdataBeforeFunc(path string, filename string, content string) func(ctx *core.BeforeFuncCtx) error { +func loadTestdataBeforeFunc( + path string, + filename string, + content string, +) func(ctx *core.BeforeFuncCtx) error { return func(_ *core.BeforeFuncCtx) error { err := os.WriteFile(filepath.Join(path, filename), []byte(content), 0o600) if err != nil { @@ -72,7 +76,11 @@ func Test_Deploy(t *testing.T) { loadTestdataBeforeFunc(simplePath, "index.html", testdataDockerIndexHTML), loadTestdataBeforeFunc(simplePath, "Dockerfile", testdataDockerDockerfile), ), - Cmd: fmt.Sprintf("scw container deploy name=%s build-source=%s port=80", appName+"-s", simplePath), + Cmd: fmt.Sprintf( + "scw container deploy name=%s build-source=%s port=80", + appName+"-s", + simplePath, + ), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), @@ -112,7 +120,11 @@ func Test_Deploy(t *testing.T) { loadTestdataBeforeFunc(buildArgsPath, "index.html", testdataDockerIndexHTML), loadTestdataBeforeFunc(buildArgsPath, "Dockerfile", testdataDockerDockerfileBuildArgs), ), - Cmd: fmt.Sprintf("scw container deploy name=%s build-source=%s port=80 build-args.TEST=thisisatest", appName+"-ba", buildArgsPath), + Cmd: fmt.Sprintf( + "scw container deploy name=%s build-source=%s port=80 build-args.TEST=thisisatest", + appName+"-ba", + buildArgsPath, + ), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), @@ -131,9 +143,17 @@ func Test_Deploy(t *testing.T) { mkdirAllBeforeFunc(buildpackPath), loadTestdataBeforeFunc(buildpackPath, "index.js", testDataBuildpackNodeIndexJS), loadTestdataBeforeFunc(buildpackPath, "package.json", testDataBuildpackNodePackageJSON), - loadTestdataBeforeFunc(buildpackPath, "package-lock.json", testDataBuildpackNodePackageLockJSON), + loadTestdataBeforeFunc( + buildpackPath, + "package-lock.json", + testDataBuildpackNodePackageLockJSON, + ), + ), + Cmd: fmt.Sprintf( + "scw container deploy name=%s build-source=%s port=3000", + appName+"-bp", + buildpackPath, ), - Cmd: fmt.Sprintf("scw container deploy name=%s build-source=%s port=3000", appName+"-bp", buildpackPath), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), @@ -170,7 +190,11 @@ func testDeleteContainersNamespaceAfter(appName string) func(*core.AfterFuncCtx) return nil } - return core.ExecAfterCmd(fmt.Sprintf("scw container namespace delete %s --wait", namespaceID))(ctx) + return core.ExecAfterCmd( + fmt.Sprintf("scw container namespace delete %s --wait", namespaceID), + )( + ctx, + ) } } diff --git a/internal/namespaces/container/v1beta1/getorcreate/getorcreate.go b/internal/namespaces/container/v1beta1/getorcreate/getorcreate.go index f27cab668d..ddb910db7e 100644 --- a/internal/namespaces/container/v1beta1/getorcreate/getorcreate.go +++ b/internal/namespaces/container/v1beta1/getorcreate/getorcreate.go @@ -8,7 +8,12 @@ import ( "github.com/scaleway/scaleway-sdk-go/scw" ) -func Namespace(ctx context.Context, api *container.API, region scw.Region, name string) (*container.Namespace, error) { +func Namespace( + ctx context.Context, + api *container.API, + region scw.Region, + name string, +) (*container.Namespace, error) { listNamespacesResponse, err := api.ListNamespaces(&container.ListNamespacesRequest{ Region: region, Name: &name, @@ -51,7 +56,13 @@ func Namespace(ctx context.Context, api *container.API, region scw.Region, name return namespace, nil } -func Container(ctx context.Context, api *container.API, region scw.Region, namespaceID string, name string) (*container.Container, error) { +func Container( + ctx context.Context, + api *container.API, + region scw.Region, + namespaceID string, + name string, +) (*container.Container, error) { listContainersResponse, err := api.ListContainers(&container.ListContainersRequest{ Region: region, NamespaceID: namespaceID, @@ -88,7 +99,12 @@ func Container(ctx context.Context, api *container.API, region scw.Region, names return container, nil } -func Registry(ctx context.Context, api *registry.API, region scw.Region, name string) (*registry.Namespace, error) { +func Registry( + ctx context.Context, + api *registry.API, + region scw.Region, + name string, +) (*registry.Namespace, error) { listNamespacesResponse, err := api.ListNamespaces(®istry.ListNamespacesRequest{ Region: region, Name: &name, diff --git a/internal/namespaces/dedibox/v1/dedibox_cli.go b/internal/namespaces/dedibox/v1/dedibox_cli.go index a7b3dba681..d438932d24 100644 --- a/internal/namespaces/dedibox/v1/dedibox_cli.go +++ b/internal/namespaces/dedibox/v1/dedibox_cli.go @@ -131,6 +131,7 @@ func GetGeneratedCommands() *core.Commands { dediboxRpnV2DisableCompatibility(), ) } + func dediboxRoot() *core.Command { return &core.Command{ Short: `Dedibox Phoenix API`, @@ -306,7 +307,12 @@ func dediboxServerList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*dedibox.ListServersRequest) @@ -322,8 +328,8 @@ func dediboxServerList() *core.Command { if err != nil { return nil, err } - return resp.Servers, nil + return resp.Servers, nil }, } } @@ -352,8 +358,8 @@ func dediboxServerGet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.GetServer(request) + return api.GetServer(request) }, } } @@ -375,7 +381,12 @@ func dediboxServerListOptions() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*dedibox.ListSubscribableServerOptionsRequest) @@ -391,8 +402,8 @@ func dediboxServerListOptions() *core.Command { if err != nil { return nil, err } - return resp.ServerOptions, nil + return resp.ServerOptions, nil }, } } @@ -428,8 +439,8 @@ func dediboxServerSubscribeOption() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.SubscribeServerOption(request) + return api.SubscribeServerOption(request) }, } } @@ -473,8 +484,8 @@ func dediboxServerCreate() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.CreateServer(request) + return api.CreateServer(request) }, } } @@ -510,8 +521,8 @@ func dediboxServerSubscribeStorage() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.SubscribeStorageOptions(request) + return api.SubscribeStorageOptions(request) }, } } @@ -554,8 +565,8 @@ func dediboxServerUpdate() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.UpdateServer(request) + return api.UpdateServer(request) }, } } @@ -588,6 +599,7 @@ func dediboxServerReboot() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "server", Verb: "reboot", @@ -624,6 +636,7 @@ func dediboxServerStart() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "server", Verb: "start", @@ -660,6 +673,7 @@ func dediboxServerStop() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "server", Verb: "stop", @@ -696,6 +710,7 @@ func dediboxServerDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "server", Verb: "delete", @@ -729,7 +744,12 @@ func dediboxServerListEvents() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*dedibox.ListServerEventsRequest) @@ -745,8 +765,8 @@ func dediboxServerListEvents() *core.Command { if err != nil { return nil, err } - return resp.Events, nil + return resp.Events, nil }, } } @@ -776,7 +796,12 @@ func dediboxServerListDisks() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*dedibox.ListServerDisksRequest) @@ -792,8 +817,8 @@ func dediboxServerListDisks() *core.Command { if err != nil { return nil, err } - return resp.Disks, nil + return resp.Disks, nil }, } } @@ -822,8 +847,8 @@ func dediboxServiceGet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.GetService(request) + return api.GetService(request) }, } } @@ -852,8 +877,8 @@ func dediboxServiceDelete() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.DeleteService(request) + return api.DeleteService(request) }, } } @@ -883,7 +908,12 @@ func dediboxServiceList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*dedibox.ListServicesRequest) @@ -899,8 +929,8 @@ func dediboxServiceList() *core.Command { if err != nil { return nil, err } - return resp.Services, nil + return resp.Services, nil }, } } @@ -970,7 +1000,18 @@ func dediboxServerInstall() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "efi", "swap", "ext4", "ext3", "ext2", "xfs", "ntfs", "fat32", "ufs"}, + EnumValues: []string{ + "unknown", + "efi", + "swap", + "ext4", + "ext3", + "ext2", + "xfs", + "ntfs", + "fat32", + "ufs", + }, }, { Name: "partitions.{index}.mount-point", @@ -1029,8 +1070,8 @@ func dediboxServerInstall() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.InstallServer(request) + return api.InstallServer(request) }, } } @@ -1059,8 +1100,8 @@ func dediboxServerGetInstall() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.GetServerInstall(request) + return api.GetServerInstall(request) }, } } @@ -1093,6 +1134,7 @@ func dediboxServerCancelInstall() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "server", Verb: "cancel-install", @@ -1132,8 +1174,8 @@ func dediboxServerGetPartitioning() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.GetServerDefaultPartitioning(request) + return api.GetServerDefaultPartitioning(request) }, } } @@ -1174,6 +1216,7 @@ The BMC (Baseboard Management Controller) access is available one hour after the if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "bmc", Verb: "start", @@ -1206,8 +1249,8 @@ func dediboxBmcGet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.GetBMCAccess(request) + return api.GetBMCAccess(request) }, } } @@ -1240,6 +1283,7 @@ func dediboxBmcStop() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "bmc", Verb: "stop", @@ -1264,7 +1308,14 @@ func dediboxOfferList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "price_asc", "price_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + "price_asc", + "price_desc", + }, }, { Name: "commercial-range", @@ -1279,7 +1330,16 @@ func dediboxOfferList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"all", "default", "beta", "reseller", "premium", "volume", "admin", "inactive"}, + EnumValues: []string{ + "all", + "default", + "beta", + "reseller", + "premium", + "volume", + "admin", + "inactive", + }, }, { Name: "project-id", @@ -1323,7 +1383,12 @@ func dediboxOfferList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*dedibox.ListOffersRequest) @@ -1339,8 +1404,8 @@ func dediboxOfferList() *core.Command { if err != nil { return nil, err } - return resp.Offers, nil + return resp.Offers, nil }, } } @@ -1376,8 +1441,8 @@ func dediboxOfferGet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.GetOffer(request) + return api.GetOffer(request) }, } } @@ -1398,7 +1463,12 @@ func dediboxOsList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "released_at_asc", "released_at_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "released_at_asc", + "released_at_desc", + }, }, { Name: "type", @@ -1406,7 +1476,15 @@ func dediboxOsList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_type", "server", "virtu", "panel", "desktop", "custom", "rescue"}, + EnumValues: []string{ + "unknown_type", + "server", + "virtu", + "panel", + "desktop", + "custom", + "rescue", + }, }, { Name: "server-id", @@ -1422,7 +1500,12 @@ func dediboxOsList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*dedibox.ListOSRequest) @@ -1438,8 +1521,8 @@ func dediboxOsList() *core.Command { if err != nil { return nil, err } - return resp.Os, nil + return resp.Os, nil }, } } @@ -1482,8 +1565,8 @@ func dediboxOsGet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.GetOS(request) + return api.GetOS(request) }, } } @@ -1519,8 +1602,8 @@ func dediboxReverseIPUpdate() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.UpdateReverse(request) + return api.UpdateReverse(request) }, } } @@ -1557,8 +1640,8 @@ func dediboxFipCreate() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.CreateFailoverIPs(request) + return api.CreateFailoverIPs(request) }, } } @@ -1598,6 +1681,7 @@ func dediboxFipAttach() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "fip", Verb: "attach", @@ -1634,6 +1718,7 @@ func dediboxFipDetach() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "fip", Verb: "detach", @@ -1681,8 +1766,8 @@ func dediboxFipAttachMac() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.AttachFailoverIPToMacAddress(request) + return api.AttachFailoverIPToMacAddress(request) }, } } @@ -1711,8 +1796,8 @@ func dediboxFipDetachMac() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.DetachFailoverIPFromMacAddress(request) + return api.DetachFailoverIPFromMacAddress(request) }, } } @@ -1745,6 +1830,7 @@ func dediboxFipDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "fip", Verb: "delete", @@ -1792,7 +1878,12 @@ func dediboxFipList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*dedibox.ListFailoverIPsRequest) @@ -1808,8 +1899,8 @@ func dediboxFipList() *core.Command { if err != nil { return nil, err } - return resp.FailoverIPs, nil + return resp.FailoverIPs, nil }, } } @@ -1838,8 +1929,8 @@ func dediboxFipGet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.GetFailoverIP(request) + return api.GetFailoverIP(request) }, } } @@ -1868,8 +1959,8 @@ func dediboxFipGetQuota() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.GetRemainingQuota(request) + return api.GetRemainingQuota(request) }, } } @@ -1898,8 +1989,8 @@ func dediboxRaidGet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.GetRaid(request) + return api.GetRaid(request) }, } } @@ -1947,6 +2038,7 @@ func dediboxRaidUpdate() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "raid", Verb: "update", @@ -1986,8 +2078,8 @@ func dediboxRescueStart() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.StartRescue(request) + return api.StartRescue(request) }, } } @@ -2016,8 +2108,8 @@ func dediboxRescueGet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewAPI(client) - return api.GetRescue(request) + return api.GetRescue(request) }, } } @@ -2050,6 +2142,7 @@ func dediboxRescueStop() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "rescue", Verb: "stop", @@ -2092,8 +2185,8 @@ func dediboxBillingListInvoice() *core.Command { if err != nil { return nil, err } - return resp.Invoices, nil + return resp.Invoices, nil }, } } @@ -2120,8 +2213,8 @@ func dediboxBillingGetInvoice() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewBillingAPI(client) - return api.GetInvoice(request) + return api.GetInvoice(request) }, } } @@ -2148,8 +2241,8 @@ func dediboxBillingDownloadInvoice() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewBillingAPI(client) - return api.DownloadInvoice(request) + return api.DownloadInvoice(request) }, } } @@ -2188,8 +2281,8 @@ func dediboxBillingListRefund() *core.Command { if err != nil { return nil, err } - return resp.Refunds, nil + return resp.Refunds, nil }, } } @@ -2216,8 +2309,8 @@ func dediboxBillingGetRefund() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewBillingAPI(client) - return api.GetRefund(request) + return api.GetRefund(request) }, } } @@ -2244,8 +2337,8 @@ func dediboxBillingDownloadRefund() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewBillingAPI(client) - return api.DownloadRefund(request) + return api.DownloadRefund(request) }, } } @@ -2267,8 +2360,8 @@ func dediboxBillingGetOrderCapacity() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewBillingAPI(client) - return api.CanOrder(request) + return api.CanOrder(request) }, } } @@ -2299,8 +2392,8 @@ func dediboxIPv6BlockGetQuota() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewIPv6BlockAPI(client) - return api.GetIPv6BlockQuotas(request) + return api.GetIPv6BlockQuotas(request) }, } } @@ -2328,8 +2421,8 @@ func dediboxIPv6BlockCreate() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewIPv6BlockAPI(client) - return api.CreateIPv6Block(request) + return api.CreateIPv6Block(request) }, } } @@ -2357,8 +2450,8 @@ func dediboxIPv6BlockGet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewIPv6BlockAPI(client) - return api.GetIPv6Block(request) + return api.GetIPv6Block(request) }, } } @@ -2394,8 +2487,8 @@ If DNS is used, minimum of 2 is necessary and maximum of 5 (no duplicate).`, client := core.ExtractClient(ctx) api := dedibox.NewIPv6BlockAPI(client) - return api.UpdateIPv6Block(request) + return api.UpdateIPv6Block(request) }, } } @@ -2427,6 +2520,7 @@ func dediboxIPv6BlockDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "ipv6-block", Verb: "delete", @@ -2474,8 +2568,8 @@ func dediboxIPv6BlockCreateSubnet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewIPv6BlockAPI(client) - return api.CreateIPv6BlockSubnet(request) + return api.CreateIPv6BlockSubnet(request) }, } } @@ -2503,8 +2597,8 @@ func dediboxIPv6BlockListSubnet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewIPv6BlockAPI(client) - return api.ListIPv6BlockSubnetsAvailable(request) + return api.ListIPv6BlockSubnetsAvailable(request) }, } } @@ -2545,8 +2639,8 @@ func dediboxRpnInfoList() *core.Command { if err != nil { return nil, err } - return resp.Servers, nil + return resp.Servers, nil }, } } @@ -2588,8 +2682,8 @@ func dediboxRpnInfoGet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnAPI(client) - return api.GetRpnStatus(request) + return api.GetRpnStatus(request) }, } } @@ -2630,8 +2724,8 @@ func dediboxSanList() *core.Command { if err != nil { return nil, err } - return resp.RpnSans, nil + return resp.RpnSans, nil }, } } @@ -2659,8 +2753,8 @@ func dediboxSanGet() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnSanAPI(client) - return api.GetRpnSan(request) + return api.GetRpnSan(request) }, } } @@ -2692,6 +2786,7 @@ func dediboxSanDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "san", Verb: "delete", @@ -2724,8 +2819,8 @@ func dediboxSanCreate() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnSanAPI(client) - return api.CreateRpnSan(request) + return api.CreateRpnSan(request) }, } } @@ -2761,8 +2856,8 @@ func dediboxSanListIPs() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnSanAPI(client) - return api.ListIPs(request) + return api.ListIPs(request) }, } } @@ -2801,6 +2896,7 @@ func dediboxSanAddIP() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "san", Verb: "add-ip", @@ -2843,6 +2939,7 @@ func dediboxSanRemoveIP() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "san", Verb: "remove-ip", @@ -2882,8 +2979,8 @@ func dediboxSanListAvailableIPs() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnSanAPI(client) - return api.ListAvailableIPs(request) + return api.ListAvailableIPs(request) }, } } @@ -2924,8 +3021,8 @@ func dediboxRpnV1List() *core.Command { if err != nil { return nil, err } - return resp.RpnGroups, nil + return resp.RpnGroups, nil }, } } @@ -2953,8 +3050,8 @@ func dediboxRpnV1Get() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnV1API(client) - return api.GetRpnGroup(request) + return api.GetRpnGroup(request) }, } } @@ -2997,8 +3094,8 @@ func dediboxRpnV1Create() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnV1API(client) - return api.CreateRpnGroup(request) + return api.CreateRpnGroup(request) }, } } @@ -3030,6 +3127,7 @@ func dediboxRpnV1Delete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "rpn-v1", Verb: "delete", @@ -3068,8 +3166,8 @@ func dediboxRpnV1Update() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnV1API(client) - return api.UpdateRpnGroupName(request) + return api.UpdateRpnGroupName(request) }, } } @@ -3117,8 +3215,8 @@ func dediboxRpnV1ListMembers() *core.Command { if err != nil { return nil, err } - return resp.Members, nil + return resp.Members, nil }, } } @@ -3158,6 +3256,7 @@ func dediboxRpnV1Invite() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "rpn-v1", Verb: "invite", @@ -3201,6 +3300,7 @@ func dediboxRpnV1Leave() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "rpn-v1", Verb: "leave", @@ -3246,8 +3346,8 @@ func dediboxRpnV1AddMembers() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnV1API(client) - return api.AddRpnGroupMembers(request) + return api.AddRpnGroupMembers(request) }, } } @@ -3282,8 +3382,8 @@ func dediboxRpnV1DeleteMembers() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnV1API(client) - return api.DeleteRpnGroupMembers(request) + return api.DeleteRpnGroupMembers(request) }, } } @@ -3324,8 +3424,8 @@ func dediboxRpnV1ListCapableServer() *core.Command { if err != nil { return nil, err } - return resp.Servers, nil + return resp.Servers, nil }, } } @@ -3366,8 +3466,8 @@ func dediboxRpnV1ListCapableSanServer() *core.Command { if err != nil { return nil, err } - return resp.SanServers, nil + return resp.SanServers, nil }, } } @@ -3402,8 +3502,8 @@ func dediboxRpnV1ListInvites() *core.Command { if err != nil { return nil, err } - return resp.Members, nil + return resp.Members, nil }, } } @@ -3435,6 +3535,7 @@ func dediboxRpnV1AcceptInvite() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "rpn-v1", Verb: "accept-invite", @@ -3470,6 +3571,7 @@ func dediboxRpnV1RefuseInvite() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "rpn-v1", Verb: "refuse-invite", @@ -3514,8 +3616,8 @@ func dediboxRpnV2List() *core.Command { if err != nil { return nil, err } - return resp.RpnGroups, nil + return resp.RpnGroups, nil }, } } @@ -3564,8 +3666,8 @@ func dediboxRpnV2ListMembers() *core.Command { if err != nil { return nil, err } - return resp.Members, nil + return resp.Members, nil }, } } @@ -3593,8 +3695,8 @@ func dediboxRpnV2Get() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnV2API(client) - return api.GetRpnV2Group(request) + return api.GetRpnV2Group(request) }, } } @@ -3638,8 +3740,8 @@ func dediboxRpnV2Create() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnV2API(client) - return api.CreateRpnV2Group(request) + return api.CreateRpnV2Group(request) }, } } @@ -3671,6 +3773,7 @@ func dediboxRpnV2Delete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "rpn-v2", Verb: "delete", @@ -3709,8 +3812,8 @@ func dediboxRpnV2Update() *core.Command { client := core.ExtractClient(ctx) api := dedibox.NewRpnV2API(client) - return api.UpdateRpnV2GroupName(request) + return api.UpdateRpnV2GroupName(request) }, } } @@ -3749,6 +3852,7 @@ func dediboxRpnV2AddMembers() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "rpn-v2", Verb: "add-members", @@ -3791,6 +3895,7 @@ func dediboxRpnV2DeleteMembers() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "rpn-v2", Verb: "delete-members", @@ -3835,8 +3940,8 @@ func dediboxRpnV2ListCapableResources() *core.Command { if err != nil { return nil, err } - return resp.Servers, nil + return resp.Servers, nil }, } } @@ -3877,8 +3982,8 @@ func dediboxRpnV2ListLogs() *core.Command { if err != nil { return nil, err } - return resp.Logs, nil + return resp.Logs, nil }, } } @@ -3924,6 +4029,7 @@ func dediboxRpnV2UpdateVlanMembers() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "rpn-v2", Verb: "update-vlan-members", @@ -3966,6 +4072,7 @@ func dediboxRpnV2EnableCompatibility() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "rpn-v2", Verb: "enable-compatibility", @@ -4001,6 +4108,7 @@ func dediboxRpnV2DisableCompatibility() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "rpn-v2", Verb: "disable-compatibility", diff --git a/internal/namespaces/documentdb/v1beta1/custom.go b/internal/namespaces/documentdb/v1beta1/custom.go index 07bec8eb87..336fb18b5c 100644 --- a/internal/namespaces/documentdb/v1beta1/custom.go +++ b/internal/namespaces/documentdb/v1beta1/custom.go @@ -8,17 +8,50 @@ import ( ) var instanceStatusMarshalSpecs = human.EnumMarshalSpecs{ - documentdb.InstanceStatusUnknown: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "unknown"}, - documentdb.InstanceStatusReady: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "ready"}, - documentdb.InstanceStatusProvisioning: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "provisioning"}, - documentdb.InstanceStatusConfiguring: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "configuring"}, - documentdb.InstanceStatusDeleting: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "deleting"}, - documentdb.InstanceStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "error"}, - documentdb.InstanceStatusAutohealing: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "auto-healing"}, - documentdb.InstanceStatusLocked: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "locked"}, - documentdb.InstanceStatusInitializing: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "initialized"}, - documentdb.InstanceStatusDiskFull: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "disk_full"}, - documentdb.InstanceStatusBackuping: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "backuping"}, + documentdb.InstanceStatusUnknown: &human.EnumMarshalSpec{ + Attribute: color.Faint, + Value: "unknown", + }, + documentdb.InstanceStatusReady: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "ready", + }, + documentdb.InstanceStatusProvisioning: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "provisioning", + }, + documentdb.InstanceStatusConfiguring: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "configuring", + }, + documentdb.InstanceStatusDeleting: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "deleting", + }, + documentdb.InstanceStatusError: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "error", + }, + documentdb.InstanceStatusAutohealing: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "auto-healing", + }, + documentdb.InstanceStatusLocked: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "locked", + }, + documentdb.InstanceStatusInitializing: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "initialized", + }, + documentdb.InstanceStatusDiskFull: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "disk_full", + }, + documentdb.InstanceStatusBackuping: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "backuping", + }, documentdb.InstanceStatusSnapshotting: &human.EnumMarshalSpec{Attribute: color.FgBlue}, documentdb.InstanceStatusRestarting: &human.EnumMarshalSpec{Attribute: color.FgBlue}, } @@ -26,7 +59,10 @@ var instanceStatusMarshalSpecs = human.EnumMarshalSpecs{ func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(documentdb.InstanceStatus(""), human.EnumMarshalFunc(instanceStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + documentdb.InstanceStatus(""), + human.EnumMarshalFunc(instanceStatusMarshalSpecs), + ) cmds.MustFind("document-db", "engine", "list").Override(engineListBuilder) diff --git a/internal/namespaces/documentdb/v1beta1/custom_engine.go b/internal/namespaces/documentdb/v1beta1/custom_engine.go index 038696384d..2f372aa954 100644 --- a/internal/namespaces/documentdb/v1beta1/custom_engine.go +++ b/internal/namespaces/documentdb/v1beta1/custom_engine.go @@ -32,25 +32,27 @@ func engineListBuilder(c *core.Command) *core.Command { }, } - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - listEngineResp, err := runner(ctx, argsI) - if err != nil { - return listEngineResp, err - } - engineList := listEngineResp.([]*documentdb.DatabaseEngine) - var res []customEngine - for _, engine := range engineList { - for _, version := range engine.Versions { - res = append(res, customEngine{ - Name: version.Name, - EngineType: engine.Name, - EndOfLife: version.EndOfLife, - }) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + listEngineResp, err := runner(ctx, argsI) + if err != nil { + return listEngineResp, err + } + engineList := listEngineResp.([]*documentdb.DatabaseEngine) + var res []customEngine + for _, engine := range engineList { + for _, version := range engine.Versions { + res = append(res, customEngine{ + Name: version.Name, + EngineType: engine.Name, + EndOfLife: version.EndOfLife, + }) + } } - } - return res, nil - }) + return res, nil + }, + ) return c } diff --git a/internal/namespaces/documentdb/v1beta1/documentdb_cli.go b/internal/namespaces/documentdb/v1beta1/documentdb_cli.go index 6d90ed9154..cf2b3ed0e5 100644 --- a/internal/namespaces/documentdb/v1beta1/documentdb_cli.go +++ b/internal/namespaces/documentdb/v1beta1/documentdb_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/documentdb/v1beta1" + documentdb "github.com/scaleway/scaleway-sdk-go/api/documentdb/v1beta1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -82,6 +82,7 @@ func GetGeneratedCommands() *core.Commands { documentDbEndpointMigrate(), ) } + func documentDbRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Document Databases`, @@ -258,7 +259,12 @@ func documentDbEngineList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*documentdb.ListDatabaseEnginesRequest) @@ -274,8 +280,8 @@ func documentDbEngineList() *core.Command { if err != nil { return nil, err } - return resp.Engines, nil + return resp.Engines, nil }, } } @@ -297,7 +303,12 @@ func documentDbNodeTypeList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*documentdb.ListNodeTypesRequest) @@ -313,8 +324,8 @@ func documentDbNodeTypeList() *core.Command { if err != nil { return nil, err } - return resp.NodeTypes, nil + return resp.NodeTypes, nil }, } } @@ -393,8 +404,8 @@ func documentDbInstanceUpgrade() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.UpgradeInstance(request) + return api.UpgradeInstance(request) }, } } @@ -429,7 +440,15 @@ func documentDbInstanceList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "region", "status_asc", "status_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + "region", + "status_asc", + "status_desc", + }, }, { Name: "project-id", @@ -445,7 +464,12 @@ func documentDbInstanceList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*documentdb.ListInstancesRequest) @@ -461,8 +485,8 @@ func documentDbInstanceList() *core.Command { if err != nil { return nil, err } - return resp.Instances, nil + return resp.Instances, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -523,8 +547,8 @@ func documentDbInstanceGet() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.GetInstance(request) + return api.GetInstance(request) }, } } @@ -653,8 +677,8 @@ func documentDbInstanceCreate() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.CreateInstance(request) + return api.CreateInstance(request) }, } } @@ -746,8 +770,8 @@ func documentDbInstanceUpdate() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.UpdateInstance(request) + return api.UpdateInstance(request) }, } } @@ -776,8 +800,8 @@ func documentDbInstanceDelete() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.DeleteInstance(request) + return api.DeleteInstance(request) }, } } @@ -820,8 +844,8 @@ func documentDbInstanceClone() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.CloneInstance(request) + return api.CloneInstance(request) }, } } @@ -850,8 +874,8 @@ func documentDbInstanceRestart() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.RestartInstance(request) + return api.RestartInstance(request) }, } } @@ -880,8 +904,8 @@ func documentDbInstanceGetCertificate() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.GetInstanceCertificate(request) + return api.GetInstanceCertificate(request) }, } } @@ -914,6 +938,7 @@ func documentDbInstanceRenewCertificate() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "instance", Verb: "renew-certificate", @@ -967,8 +992,8 @@ func documentDbInstanceGetMetrics() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.GetInstanceMetrics(request) + return api.GetInstanceMetrics(request) }, } } @@ -1018,8 +1043,8 @@ func documentDbReadReplicaCreate() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.CreateReadReplica(request) + return api.CreateReadReplica(request) }, } } @@ -1048,8 +1073,8 @@ func documentDbReadReplicaGet() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.GetReadReplica(request) + return api.GetReadReplica(request) }, } } @@ -1078,8 +1103,8 @@ func documentDbReadReplicaDelete() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.DeleteReadReplica(request) + return api.DeleteReadReplica(request) }, } } @@ -1109,8 +1134,8 @@ The configured endpoints do not change.`, client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.ResetReadReplica(request) + return api.ResetReadReplica(request) }, } } @@ -1153,8 +1178,8 @@ func documentDbReadReplicaCreateEndpoint() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.CreateReadReplicaEndpoint(request) + return api.CreateReadReplicaEndpoint(request) }, } } @@ -1191,8 +1216,8 @@ func documentDbLogList() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.ListInstanceLogs(request) + return api.ListInstanceLogs(request) }, } } @@ -1221,8 +1246,8 @@ func documentDbLogGet() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.GetInstanceLog(request) + return api.GetInstanceLog(request) }, } } @@ -1262,6 +1287,7 @@ func documentDbLogPurge() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "log", Verb: "purge", @@ -1294,8 +1320,8 @@ func documentDbLogListDetails() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.ListInstanceLogsDetails(request) + return api.ListInstanceLogsDetails(request) }, } } @@ -1336,8 +1362,8 @@ func documentDbSettingAdd() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.AddInstanceSettings(request) + return api.AddInstanceSettings(request) }, } } @@ -1373,8 +1399,8 @@ func documentDbSettingDelete() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.DeleteInstanceSettings(request) + return api.DeleteInstanceSettings(request) }, } } @@ -1382,7 +1408,7 @@ func documentDbSettingDelete() *core.Command { func documentDbSettingSet() *core.Command { return &core.Command{ Short: `Set Database Instance advanced settings`, - Long: `Update an advanced setting for a Database Instance. Settings added upon database engine initalization can only be defined once, and cannot, therefore, be updated.`, + Long: `Update an advanced setting for a Database Instance. Settings added upon database engine initialization can only be defined once, and cannot, therefore, be updated.`, Namespace: "document-db", Resource: "setting", Verb: "set", @@ -1415,8 +1441,8 @@ func documentDbSettingSet() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.SetInstanceSettings(request) + return api.SetInstanceSettings(request) }, } } @@ -1438,7 +1464,12 @@ func documentDbACLList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*documentdb.ListInstanceACLRulesRequest) @@ -1454,8 +1485,8 @@ func documentDbACLList() *core.Command { if err != nil { return nil, err } - return resp.Rules, nil + return resp.Rules, nil }, } } @@ -1496,8 +1527,8 @@ func documentDbACLAdd() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.AddInstanceACLRules(request) + return api.AddInstanceACLRules(request) }, } } @@ -1538,8 +1569,8 @@ func documentDbACLSet() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.SetInstanceACLRules(request) + return api.SetInstanceACLRules(request) }, } } @@ -1575,8 +1606,8 @@ func documentDbACLDelete() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.DeleteInstanceACLRules(request) + return api.DeleteInstanceACLRules(request) }, } } @@ -1613,7 +1644,12 @@ func documentDbUserList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*documentdb.ListUsersRequest) @@ -1629,8 +1665,8 @@ func documentDbUserList() *core.Command { if err != nil { return nil, err } - return resp.Users, nil + return resp.Users, nil }, } } @@ -1680,8 +1716,8 @@ func documentDbUserCreate() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.CreateUser(request) + return api.CreateUser(request) }, } } @@ -1731,8 +1767,8 @@ func documentDbUserUpdate() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.UpdateUser(request) + return api.UpdateUser(request) }, } } @@ -1772,6 +1808,7 @@ func documentDbUserDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "user", Verb: "delete", @@ -1826,7 +1863,12 @@ func documentDbDatabaseList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*documentdb.ListDatabasesRequest) @@ -1842,8 +1884,8 @@ func documentDbDatabaseList() *core.Command { if err != nil { return nil, err } - return resp.Databases, nil + return resp.Databases, nil }, } } @@ -1879,8 +1921,8 @@ func documentDbDatabaseCreate() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.CreateDatabase(request) + return api.CreateDatabase(request) }, } } @@ -1920,6 +1962,7 @@ func documentDbDatabaseDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "database", Verb: "delete", @@ -1944,7 +1987,12 @@ func documentDbPrivilegeList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"user_name_asc", "user_name_desc", "database_name_asc", "database_name_desc"}, + EnumValues: []string{ + "user_name_asc", + "user_name_desc", + "database_name_asc", + "database_name_desc", + }, }, { Name: "database-name", @@ -1967,7 +2015,12 @@ func documentDbPrivilegeList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*documentdb.ListPrivilegesRequest) @@ -1983,8 +2036,8 @@ func documentDbPrivilegeList() *core.Command { if err != nil { return nil, err } - return resp.Privileges, nil + return resp.Privileges, nil }, } } @@ -2035,8 +2088,8 @@ func documentDbPrivilegeSet() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.SetPrivilege(request) + return api.SetPrivilege(request) }, } } @@ -2064,7 +2117,14 @@ func documentDbSnapshotList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "expires_at_asc", "expires_at_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + "expires_at_asc", + "expires_at_desc", + }, }, { Name: "instance-id", @@ -2087,7 +2147,12 @@ func documentDbSnapshotList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*documentdb.ListSnapshotsRequest) @@ -2103,8 +2168,8 @@ func documentDbSnapshotList() *core.Command { if err != nil { return nil, err } - return resp.Snapshots, nil + return resp.Snapshots, nil }, } } @@ -2133,8 +2198,8 @@ func documentDbSnapshotGet() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.GetSnapshot(request) + return api.GetSnapshot(request) }, } } @@ -2178,8 +2243,8 @@ func documentDbSnapshotCreate() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.CreateSnapshot(request) + return api.CreateSnapshot(request) }, } } @@ -2222,8 +2287,8 @@ func documentDbSnapshotUpdate() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.UpdateSnapshot(request) + return api.UpdateSnapshot(request) }, } } @@ -2252,8 +2317,8 @@ func documentDbSnapshotDelete() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.DeleteSnapshot(request) + return api.DeleteSnapshot(request) }, } } @@ -2303,8 +2368,8 @@ func documentDbSnapshotRestore() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.CreateInstanceFromSnapshot(request) + return api.CreateInstanceFromSnapshot(request) }, } } @@ -2347,8 +2412,8 @@ func documentDbEndpointCreate() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.CreateEndpoint(request) + return api.CreateEndpoint(request) }, } } @@ -2381,6 +2446,7 @@ func documentDbEndpointDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "endpoint", Verb: "delete", @@ -2413,8 +2479,8 @@ func documentDbEndpointGet() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.GetEndpoint(request) + return api.GetEndpoint(request) }, } } @@ -2450,8 +2516,8 @@ func documentDbEndpointMigrate() *core.Command { client := core.ExtractClient(ctx) api := documentdb.NewAPI(client) - return api.MigrateEndpoint(request) + return api.MigrateEndpoint(request) }, } } diff --git a/internal/namespaces/domain/v2beta1/custom.go b/internal/namespaces/domain/v2beta1/custom.go index 335026cf61..66388f943a 100644 --- a/internal/namespaces/domain/v2beta1/custom.go +++ b/internal/namespaces/domain/v2beta1/custom.go @@ -6,7 +6,26 @@ import ( domain "github.com/scaleway/scaleway-sdk-go/api/domain/v2beta1" ) -var domainTypes = []string{"A", "AAAA", "CNAME", "TXT", "SRV", "TLSA", "MX", "NS", "PTR", "CAA", "ALIAS", "LOC", "SSHFP", "HINFO", "RP", "URI", "DS", "NAPTR"} +var domainTypes = []string{ + "A", + "AAAA", + "CNAME", + "TXT", + "SRV", + "TLSA", + "MX", + "NS", + "PTR", + "CAA", + "ALIAS", + "LOC", + "SSHFP", + "HINFO", + "RP", + "URI", + "DS", + "NAPTR", +} const defaultTTL = "3600" @@ -27,8 +46,14 @@ func GetCommands() *core.Commands { cmds.MustFind("dns", "zone", "import").ArgSpecs.GetByName("bind-source.content").CanLoadFile = true - human.RegisterMarshalerFunc(domain.DNSZoneStatus(""), human.EnumMarshalFunc(zoneStatusMarshalSpecs)) - human.RegisterMarshalerFunc(domain.SSLCertificateStatus(""), human.EnumMarshalFunc(certificateStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + domain.DNSZoneStatus(""), + human.EnumMarshalFunc(zoneStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + domain.SSLCertificateStatus(""), + human.EnumMarshalFunc(certificateStatusMarshalSpecs), + ) return cmds } diff --git a/internal/namespaces/domain/v2beta1/custom_record_set.go b/internal/namespaces/domain/v2beta1/custom_record_set.go index c779301199..3ca65592e4 100644 --- a/internal/namespaces/domain/v2beta1/custom_record_set.go +++ b/internal/namespaces/domain/v2beta1/custom_record_set.go @@ -173,8 +173,8 @@ func dnsRecordSetRun(ctx context.Context, argsI interface{}) (i interface{}, e e { Set: &domain.RecordChangeSet{ IDFields: &domain.RecordIdentifier{ - Name: request.Record.Name, - Type: request.Record.Type, + Name: request.Name, + Type: request.Type, }, }, }, @@ -188,7 +188,10 @@ func dnsRecordSetRun(ctx context.Context, argsI interface{}) (i interface{}, e e for _, data := range request.Values { record := *request.Record record.Data = data - dnsRecordSetReq.Changes[0].Set.Records = append(dnsRecordSetReq.Changes[0].Set.Records, &record) + dnsRecordSetReq.Changes[0].Set.Records = append( + dnsRecordSetReq.Changes[0].Set.Records, + &record, + ) } client := core.ExtractClient(ctx) diff --git a/internal/namespaces/domain/v2beta1/domain_cli.go b/internal/namespaces/domain/v2beta1/domain_cli.go index a67c991ccd..b11bd88d28 100644 --- a/internal/namespaces/domain/v2beta1/domain_cli.go +++ b/internal/namespaces/domain/v2beta1/domain_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/domain/v2beta1" + domain "github.com/scaleway/scaleway-sdk-go/api/domain/v2beta1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -50,6 +50,7 @@ func GetGeneratedCommands() *core.Commands { dnsTsigKeyDelete(), ) } + func dnsRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your domains, DNS zones and records`, @@ -126,7 +127,16 @@ func dnsZoneList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"domain_asc", "domain_desc", "subdomain_asc", "subdomain_desc", "created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc"}, + EnumValues: []string{ + "domain_asc", + "domain_desc", + "subdomain_asc", + "subdomain_desc", + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + }, }, { Name: "domain", @@ -195,8 +205,8 @@ func dnsZoneList() *core.Command { if err != nil { return nil, err } - return resp.DNSZones, nil + return resp.DNSZones, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -264,8 +274,8 @@ func dnsZoneCreate() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.CreateDNSZone(request) + return api.CreateDNSZone(request) }, } } @@ -301,8 +311,8 @@ func dnsZoneUpdate() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.UpdateDNSZone(request) + return api.UpdateDNSZone(request) }, } } @@ -351,8 +361,8 @@ func dnsZoneClone() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.CloneDNSZone(request) + return api.CloneDNSZone(request) }, } } @@ -381,8 +391,8 @@ func dnsZoneDelete() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.DeleteDNSZone(request) + return api.DeleteDNSZone(request) }, } } @@ -433,7 +443,30 @@ You can filter records by type and name.`, Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "A", "AAAA", "CNAME", "TXT", "SRV", "TLSA", "MX", "NS", "PTR", "CAA", "ALIAS", "LOC", "SSHFP", "HINFO", "RP", "URI", "DS", "NAPTR", "DNAME", "SVCB", "HTTPS"}, + EnumValues: []string{ + "unknown", + "A", + "AAAA", + "CNAME", + "TXT", + "SRV", + "TLSA", + "MX", + "NS", + "PTR", + "CAA", + "ALIAS", + "LOC", + "SSHFP", + "HINFO", + "RP", + "URI", + "DS", + "NAPTR", + "DNAME", + "SVCB", + "HTTPS", + }, }, { Name: "id", @@ -453,8 +486,8 @@ You can filter records by type and name.`, if err != nil { return nil, err } - return resp.Records, nil + return resp.Records, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -536,7 +569,30 @@ All edits will be versioned.`, Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "A", "AAAA", "CNAME", "TXT", "SRV", "TLSA", "MX", "NS", "PTR", "CAA", "ALIAS", "LOC", "SSHFP", "HINFO", "RP", "URI", "DS", "NAPTR", "DNAME", "SVCB", "HTTPS"}, + EnumValues: []string{ + "unknown", + "A", + "AAAA", + "CNAME", + "TXT", + "SRV", + "TLSA", + "MX", + "NS", + "PTR", + "CAA", + "ALIAS", + "LOC", + "SSHFP", + "HINFO", + "RP", + "URI", + "DS", + "NAPTR", + "DNAME", + "SVCB", + "HTTPS", + }, }, { Name: "changes.{index}.add.records.{index}.comment", @@ -646,7 +702,30 @@ All edits will be versioned.`, Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "A", "AAAA", "CNAME", "TXT", "SRV", "TLSA", "MX", "NS", "PTR", "CAA", "ALIAS", "LOC", "SSHFP", "HINFO", "RP", "URI", "DS", "NAPTR", "DNAME", "SVCB", "HTTPS"}, + EnumValues: []string{ + "unknown", + "A", + "AAAA", + "CNAME", + "TXT", + "SRV", + "TLSA", + "MX", + "NS", + "PTR", + "CAA", + "ALIAS", + "LOC", + "SSHFP", + "HINFO", + "RP", + "URI", + "DS", + "NAPTR", + "DNAME", + "SVCB", + "HTTPS", + }, }, { Name: "changes.{index}.set.id-fields.data", @@ -689,7 +768,30 @@ All edits will be versioned.`, Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "A", "AAAA", "CNAME", "TXT", "SRV", "TLSA", "MX", "NS", "PTR", "CAA", "ALIAS", "LOC", "SSHFP", "HINFO", "RP", "URI", "DS", "NAPTR", "DNAME", "SVCB", "HTTPS"}, + EnumValues: []string{ + "unknown", + "A", + "AAAA", + "CNAME", + "TXT", + "SRV", + "TLSA", + "MX", + "NS", + "PTR", + "CAA", + "ALIAS", + "LOC", + "SSHFP", + "HINFO", + "RP", + "URI", + "DS", + "NAPTR", + "DNAME", + "SVCB", + "HTTPS", + }, }, { Name: "changes.{index}.set.records.{index}.comment", @@ -799,7 +901,30 @@ All edits will be versioned.`, Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "A", "AAAA", "CNAME", "TXT", "SRV", "TLSA", "MX", "NS", "PTR", "CAA", "ALIAS", "LOC", "SSHFP", "HINFO", "RP", "URI", "DS", "NAPTR", "DNAME", "SVCB", "HTTPS"}, + EnumValues: []string{ + "unknown", + "A", + "AAAA", + "CNAME", + "TXT", + "SRV", + "TLSA", + "MX", + "NS", + "PTR", + "CAA", + "ALIAS", + "LOC", + "SSHFP", + "HINFO", + "RP", + "URI", + "DS", + "NAPTR", + "DNAME", + "SVCB", + "HTTPS", + }, }, { Name: "changes.{index}.delete.id-fields.data", @@ -840,8 +965,8 @@ All edits will be versioned.`, client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.UpdateDNSZoneRecords(request) + return api.UpdateDNSZoneRecords(request) }, } } @@ -876,8 +1001,8 @@ func dnsRecordListNameservers() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.ListDNSZoneNameservers(request) + return api.ListDNSZoneNameservers(request) }, } } @@ -917,8 +1042,8 @@ func dnsRecordUpdateNameservers() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.UpdateDNSZoneNameservers(request) + return api.UpdateDNSZoneNameservers(request) }, } } @@ -947,8 +1072,8 @@ All edits will be versioned.`, client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.ClearDNSZoneRecords(request) + return api.ClearDNSZoneRecords(request) }, } } @@ -985,8 +1110,8 @@ func dnsZoneExport() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.ExportRawDNSZone(request) + return api.ExportRawDNSZone(request) }, } } @@ -1058,8 +1183,8 @@ func dnsZoneImport() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.ImportRawDNSZone(request) + return api.ImportRawDNSZone(request) }, } } @@ -1102,8 +1227,8 @@ You can recreate the given DNS zone and its sub DNS zone if needed.`, client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.RefreshDNSZone(request) + return api.RefreshDNSZone(request) }, } } @@ -1136,8 +1261,8 @@ The maximum version count is 100. If the count reaches this limit, the oldest ve if err != nil { return nil, err } - return resp.Versions, nil + return resp.Versions, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -1177,8 +1302,8 @@ func dnsVersionShow() *core.Command { if err != nil { return nil, err } - return resp.Records, nil + return resp.Records, nil }, } } @@ -1205,8 +1330,8 @@ func dnsVersionDiff() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.GetDNSZoneVersionDiff(request) + return api.GetDNSZoneVersionDiff(request) }, } } @@ -1233,8 +1358,8 @@ func dnsVersionRestore() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.RestoreDNSZoneVersion(request) + return api.RestoreDNSZoneVersion(request) }, } } @@ -1261,8 +1386,8 @@ func dnsCertificateGet() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.GetSSLCertificate(request) + return api.GetSSLCertificate(request) }, } } @@ -1295,8 +1420,8 @@ func dnsCertificateCreate() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.CreateSSLCertificate(request) + return api.CreateSSLCertificate(request) }, } } @@ -1334,8 +1459,8 @@ func dnsCertificateList() *core.Command { if err != nil { return nil, err } - return resp.Certificates, nil + return resp.Certificates, nil }, } } @@ -1362,8 +1487,8 @@ func dnsCertificateDelete() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.DeleteSSLCertificate(request) + return api.DeleteSSLCertificate(request) }, } } @@ -1390,8 +1515,8 @@ func dnsTsigKeyGet() *core.Command { client := core.ExtractClient(ctx) api := domain.NewAPI(client) - return api.GetDNSZoneTsigKey(request) + return api.GetDNSZoneTsigKey(request) }, } } @@ -1422,6 +1547,7 @@ func dnsTsigKeyDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "tsig-key", Verb: "delete", diff --git a/internal/namespaces/edge_services/v1alpha1/edge_services_cli.go b/internal/namespaces/edge_services/v1alpha1/edge_services_cli.go index e22324e80e..de584d3e71 100644 --- a/internal/namespaces/edge_services/v1alpha1/edge_services_cli.go +++ b/internal/namespaces/edge_services/v1alpha1/edge_services_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/edge_services/v1alpha1" + edge_services "github.com/scaleway/scaleway-sdk-go/api/edge_services/v1alpha1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -56,6 +56,7 @@ func GetGeneratedCommands() *core.Commands { edgeServicesPurgeRequestGet(), ) } + func edgeServicesRoot() *core.Command { return &core.Command{ Short: `Edge Services API`, @@ -175,8 +176,8 @@ func edgeServicesPipelineList() *core.Command { if err != nil { return nil, err } - return resp.Pipelines, nil + return resp.Pipelines, nil }, } } @@ -219,8 +220,8 @@ func edgeServicesPipelineCreate() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.CreatePipeline(request) + return api.CreatePipeline(request) }, } } @@ -248,8 +249,8 @@ func edgeServicesPipelineGet() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.GetPipeline(request) + return api.GetPipeline(request) }, } } @@ -298,8 +299,8 @@ func edgeServicesPipelineUpdate() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.UpdatePipeline(request) + return api.UpdatePipeline(request) }, } } @@ -331,6 +332,7 @@ func edgeServicesPipelineDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "pipeline", Verb: "delete", @@ -389,8 +391,8 @@ func edgeServicesDNSStageList() *core.Command { if err != nil { return nil, err } - return resp.Stages, nil + return resp.Stages, nil }, } } @@ -440,8 +442,8 @@ func edgeServicesDNSStageCreate() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.CreateDNSStage(request) + return api.CreateDNSStage(request) }, } } @@ -469,8 +471,8 @@ func edgeServicesDNSStageGet() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.GetDNSStage(request) + return api.GetDNSStage(request) }, } } @@ -526,8 +528,8 @@ func edgeServicesDNSStageUpdate() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.UpdateDNSStage(request) + return api.UpdateDNSStage(request) }, } } @@ -559,6 +561,7 @@ func edgeServicesDNSStageDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "dns-stage", Verb: "delete", @@ -624,8 +627,8 @@ func edgeServicesTLSStageList() *core.Command { if err != nil { return nil, err } - return resp.Stages, nil + return resp.Stages, nil }, } } @@ -682,8 +685,8 @@ func edgeServicesTLSStageCreate() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.CreateTLSStage(request) + return api.CreateTLSStage(request) }, } } @@ -711,8 +714,8 @@ func edgeServicesTLSStageGet() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.GetTLSStage(request) + return api.GetTLSStage(request) }, } } @@ -775,8 +778,8 @@ func edgeServicesTLSStageUpdate() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.UpdateTLSStage(request) + return api.UpdateTLSStage(request) }, } } @@ -808,6 +811,7 @@ func edgeServicesTLSStageDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "tls-stage", Verb: "delete", @@ -859,8 +863,8 @@ func edgeServicesCacheStageList() *core.Command { if err != nil { return nil, err } - return resp.Stages, nil + return resp.Stages, nil }, } } @@ -897,8 +901,8 @@ func edgeServicesCacheStageCreate() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.CreateCacheStage(request) + return api.CreateCacheStage(request) }, } } @@ -926,8 +930,8 @@ func edgeServicesCacheStageGet() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.GetCacheStage(request) + return api.GetCacheStage(request) }, } } @@ -969,8 +973,8 @@ func edgeServicesCacheStageUpdate() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.UpdateCacheStage(request) + return api.UpdateCacheStage(request) }, } } @@ -1002,6 +1006,7 @@ func edgeServicesCacheStageDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "cache-stage", Verb: "delete", @@ -1074,8 +1079,8 @@ func edgeServicesBackendStageList() *core.Command { if err != nil { return nil, err } - return resp.Stages, nil + return resp.Stages, nil }, } } @@ -1153,8 +1158,8 @@ func edgeServicesBackendStageCreate() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.CreateBackendStage(request) + return api.CreateBackendStage(request) }, } } @@ -1182,8 +1187,8 @@ func edgeServicesBackendStageGet() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.GetBackendStage(request) + return api.GetBackendStage(request) }, } } @@ -1267,8 +1272,8 @@ func edgeServicesBackendStageUpdate() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.UpdateBackendStage(request) + return api.UpdateBackendStage(request) }, } } @@ -1300,6 +1305,7 @@ func edgeServicesBackendStageDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "backend-stage", Verb: "delete", @@ -1358,8 +1364,8 @@ func edgeServicesPurgeRequestList() *core.Command { if err != nil { return nil, err } - return resp.PurgeRequests, nil + return resp.PurgeRequests, nil }, } } @@ -1401,8 +1407,8 @@ func edgeServicesPurgeRequestCreate() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.CreatePurgeRequest(request) + return api.CreatePurgeRequest(request) }, } } @@ -1430,8 +1436,8 @@ func edgeServicesPurgeRequestGet() *core.Command { client := core.ExtractClient(ctx) api := edge_services.NewAPI(client) - return api.GetPurgeRequest(request) + return api.GetPurgeRequest(request) }, } } diff --git a/internal/namespaces/feedback/custom_test.go b/internal/namespaces/feedback/custom_test.go index 28513c6857..c1bbad77cb 100644 --- a/internal/namespaces/feedback/custom_test.go +++ b/internal/namespaces/feedback/custom_test.go @@ -23,9 +23,11 @@ func Test_FeedbackBug(t *testing.T) { default: observed = cmd.Args[1] } - assert.Equal(t, + assert.Equal( + t, "https://github.com/scaleway/scaleway-cli/issues/new?body=%0A%23%23+Description%3A%0A%0A%23%23+How+to+reproduce%3A%0A%0A%23%23%23+Command+attempted%0A%0A%23%23%23+Expected+Behavior%0A%0A%23%23%23+Actual+Behavior%0A%0A%23%23+More+info%0A%0A%23%23+Version%0A%0AVersion++++++++++0.0.0%26%2343%3Btest%0ABuildDate++++++++unknown%0AGoVersion++++++++runtime.Version%28%29%0AGitBranch++++++++unknown%0AGitCommit++++++++unknown%0AGoArch+++++++++++runtime.GOARCH%0AGoOS+++++++++++++runtime.GOOS%0AUserAgentPrefix++scaleway-cli%0A&issueTemplate=bug_report.md&labels=bug", - observed) + observed, + ) return 0, nil }, @@ -49,9 +51,11 @@ func Test_FeedbackFeature(t *testing.T) { default: observed = cmd.Args[1] } - assert.Equal(t, + assert.Equal( + t, "https://github.com/scaleway/scaleway-cli/issues/new?body=%0A%23%23+Description%0A%0A%23%23+How+this+functionality+would+be+exposed%0A%0A%23%23+References%0A%0A%23%23+Version%0A%0AVersion++++++++++0.0.0%26%2343%3Btest%0ABuildDate++++++++unknown%0AGoVersion++++++++runtime.Version%28%29%0AGitBranch++++++++unknown%0AGitCommit++++++++unknown%0AGoArch+++++++++++runtime.GOARCH%0AGoOS+++++++++++++runtime.GOOS%0AUserAgentPrefix++scaleway-cli%0A&issueTemplate=feature_request.md&labels=enhancement", - observed) + observed, + ) return 0, nil }, diff --git a/internal/namespaces/flexibleip/v1alpha1/custom.go b/internal/namespaces/flexibleip/v1alpha1/custom.go index 7ae02dfbb1..816532d759 100644 --- a/internal/namespaces/flexibleip/v1alpha1/custom.go +++ b/internal/namespaces/flexibleip/v1alpha1/custom.go @@ -9,8 +9,14 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(fip.FlexibleIPStatus(""), human.EnumMarshalFunc(ipStatusMarshalSpecs)) - human.RegisterMarshalerFunc(fip.MACAddressStatus(""), human.EnumMarshalFunc(macAddressStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + fip.FlexibleIPStatus(""), + human.EnumMarshalFunc(ipStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + fip.MACAddressStatus(""), + human.EnumMarshalFunc(macAddressStatusMarshalSpecs), + ) cmds.MustFind("fip", "ip", "create").Override(createIPBuilder) diff --git a/internal/namespaces/flexibleip/v1alpha1/flexibleip_cli.go b/internal/namespaces/flexibleip/v1alpha1/flexibleip_cli.go index cdfce410b8..fc60a3ba59 100644 --- a/internal/namespaces/flexibleip/v1alpha1/flexibleip_cli.go +++ b/internal/namespaces/flexibleip/v1alpha1/flexibleip_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/flexibleip/v1alpha1" + flexibleip "github.com/scaleway/scaleway-sdk-go/api/flexibleip/v1alpha1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -35,6 +35,7 @@ func GetGeneratedCommands() *core.Commands { fipMacDelete(), ) } + func fipRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Elastic Metal servers' flexible public IP addresses`, @@ -108,15 +109,22 @@ func fipIPCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*flexibleip.CreateFlexibleIPRequest) client := core.ExtractClient(ctx) api := flexibleip.NewAPI(client) - return api.CreateFlexibleIP(request) + return api.CreateFlexibleIP(request) }, } } @@ -138,15 +146,22 @@ func fipIPGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*flexibleip.GetFlexibleIPRequest) client := core.ExtractClient(ctx) api := flexibleip.NewAPI(client) - return api.GetFlexibleIP(request) + return api.GetFlexibleIP(request) }, } } @@ -182,7 +197,15 @@ func fipIPList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "ready", "updating", "attached", "error", "detaching", "locked"}, + EnumValues: []string{ + "unknown", + "ready", + "updating", + "attached", + "error", + "detaching", + "locked", + }, }, { Name: "server-ids.{index}", @@ -205,7 +228,15 @@ func fipIPList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*flexibleip.ListFlexibleIPsRequest) @@ -221,8 +252,8 @@ func fipIPList() *core.Command { if err != nil { return nil, err } - return resp.FlexibleIPs, nil + return resp.FlexibleIPs, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -300,15 +331,22 @@ func fipIPUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*flexibleip.UpdateFlexibleIPRequest) client := core.ExtractClient(ctx) api := flexibleip.NewAPI(client) - return api.UpdateFlexibleIP(request) + return api.UpdateFlexibleIP(request) }, } } @@ -330,7 +368,14 @@ func fipIPDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*flexibleip.DeleteFlexibleIPRequest) @@ -341,6 +386,7 @@ func fipIPDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "ip", Verb: "delete", @@ -373,15 +419,22 @@ func fipIPAttach() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*flexibleip.AttachFlexibleIPRequest) client := core.ExtractClient(ctx) api := flexibleip.NewAPI(client) - return api.AttachFlexibleIP(request) + return api.AttachFlexibleIP(request) }, } } @@ -403,15 +456,22 @@ func fipIPDetach() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*flexibleip.DetachFlexibleIPRequest) client := core.ExtractClient(ctx) api := flexibleip.NewAPI(client) - return api.DetachFlexibleIP(request) + return api.DetachFlexibleIP(request) }, } } @@ -441,15 +501,22 @@ func fipMacCreate() *core.Command { Positional: false, EnumValues: []string{"unknown_type", "vmware", "xen", "kvm"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*flexibleip.GenerateMACAddrRequest) client := core.ExtractClient(ctx) api := flexibleip.NewAPI(client) - return api.GenerateMACAddr(request) + return api.GenerateMACAddr(request) }, } } @@ -478,15 +545,22 @@ func fipMacDuplicate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*flexibleip.DuplicateMACAddrRequest) client := core.ExtractClient(ctx) api := flexibleip.NewAPI(client) - return api.DuplicateMACAddr(request) + return api.DuplicateMACAddr(request) }, } } @@ -513,15 +587,22 @@ func fipMacMove() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*flexibleip.MoveMACAddrRequest) client := core.ExtractClient(ctx) api := flexibleip.NewAPI(client) - return api.MoveMACAddr(request) + return api.MoveMACAddr(request) }, } } @@ -543,7 +624,14 @@ func fipMacDelete() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*flexibleip.DeleteMACAddrRequest) @@ -554,6 +642,7 @@ func fipMacDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "mac", Verb: "delete", diff --git a/internal/namespaces/function/v1beta1/custom.go b/internal/namespaces/function/v1beta1/custom.go index 8506c5715f..2d8d67b7da 100644 --- a/internal/namespaces/function/v1beta1/custom.go +++ b/internal/namespaces/function/v1beta1/custom.go @@ -9,9 +9,18 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(function.NamespaceStatus(""), human.EnumMarshalFunc(namespaceStatusMarshalSpecs)) - human.RegisterMarshalerFunc(function.FunctionStatus(""), human.EnumMarshalFunc(functionStatusMarshalSpecs)) - human.RegisterMarshalerFunc(function.CronStatus(""), human.EnumMarshalFunc(cronStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + function.NamespaceStatus(""), + human.EnumMarshalFunc(namespaceStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + function.FunctionStatus(""), + human.EnumMarshalFunc(functionStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + function.CronStatus(""), + human.EnumMarshalFunc(cronStatusMarshalSpecs), + ) if cmdDeploy := functionDeploy(); cmdDeploy != nil { cmds.Add(cmdDeploy) diff --git a/internal/namespaces/function/v1beta1/custom_deploy.go b/internal/namespaces/function/v1beta1/custom_deploy.go index 497b922ca7..293d80c22f 100644 --- a/internal/namespaces/function/v1beta1/custom_deploy.go +++ b/internal/namespaces/function/v1beta1/custom_deploy.go @@ -78,12 +78,30 @@ func functionDeploy() *core.Command { ts := tasks.Begin() if args.NamespaceID != "" { - tasks.Add(ts, "Fetching namespace", DeployStepFetchNamespace(api, args.Region, args.NamespaceID)) + tasks.Add( + ts, + "Fetching namespace", + DeployStepFetchNamespace(api, args.Region, args.NamespaceID), + ) } else { tasks.Add(ts, "Creating or fetching namespace", DeployStepCreateNamespace(api, args.Region, args.Name)) } - tasks.Add(ts, "Creating or fetching function", DeployStepCreateFunction(api, args.Name, args.Runtime)) - tasks.Add(ts, "Uploading function", DeployStepFunctionUpload(httpClient, scwClient, api, args.ZipFile, zipFileStat.Size())) + tasks.Add( + ts, + "Creating or fetching function", + DeployStepCreateFunction(api, args.Name, args.Runtime), + ) + tasks.Add( + ts, + "Uploading function", + DeployStepFunctionUpload( + httpClient, + scwClient, + api, + args.ZipFile, + zipFileStat.Size(), + ), + ) tasks.Add(ts, "Deploying function", DeployStepFunctionDeploy(api, args.Runtime)) return ts.Execute(ctx, nil) @@ -109,7 +127,11 @@ func validateRuntime(api *function.API, region scw.Region, runtime function.Func return fmt.Errorf("invalid runtime %q", runtimeName) } -func DeployStepCreateNamespace(api *function.API, region scw.Region, functionName string) tasks.TaskFunc[any, *function.Namespace] { +func DeployStepCreateNamespace( + api *function.API, + region scw.Region, + functionName string, +) tasks.TaskFunc[any, *function.Namespace] { return func(t *tasks.Task, _ any) (nextArgs *function.Namespace, err error) { namespaceName := functionName @@ -155,7 +177,11 @@ func DeployStepCreateNamespace(api *function.API, region scw.Region, functionNam } } -func DeployStepFetchNamespace(api *function.API, region scw.Region, namespaceID string) tasks.TaskFunc[any, *function.Namespace] { +func DeployStepFetchNamespace( + api *function.API, + region scw.Region, + namespaceID string, +) tasks.TaskFunc[any, *function.Namespace] { return func(_ *tasks.Task, _ any) (nextArgs *function.Namespace, err error) { namespace, err := api.WaitForNamespace(&function.WaitForNamespaceRequest{ NamespaceID: namespaceID, @@ -169,7 +195,11 @@ func DeployStepFetchNamespace(api *function.API, region scw.Region, namespaceID } } -func DeployStepCreateFunction(api *function.API, functionName string, runtime function.FunctionRuntime) tasks.TaskFunc[*function.Namespace, *function.Function] { +func DeployStepCreateFunction( + api *function.API, + functionName string, + runtime function.FunctionRuntime, +) tasks.TaskFunc[*function.Namespace, *function.Function] { return func(t *tasks.Task, namespace *function.Namespace) (*function.Function, error) { functions, err := api.ListFunctions(&function.ListFunctionsRequest{ Name: &functionName, @@ -208,7 +238,13 @@ func DeployStepCreateFunction(api *function.API, functionName string, runtime fu } } -func DeployStepFunctionUpload(httpClient *http.Client, scwClient *scw.Client, api *function.API, zipPath string, zipSize int64) tasks.TaskFunc[*function.Function, *function.Function] { +func DeployStepFunctionUpload( + httpClient *http.Client, + scwClient *scw.Client, + api *function.API, + zipPath string, + zipSize int64, +) tasks.TaskFunc[*function.Function, *function.Function] { return func(t *tasks.Task, fc *function.Function) (nextArgs *function.Function, err error) { uploadURL, err := api.GetFunctionUploadURL(&function.GetFunctionUploadURLRequest{ Region: fc.Region, @@ -255,7 +291,10 @@ func DeployStepFunctionUpload(httpClient *http.Client, scwClient *scw.Client, ap } } -func DeployStepFunctionDeploy(api *function.API, runtime function.FunctionRuntime) tasks.TaskFunc[*function.Function, *function.Function] { +func DeployStepFunctionDeploy( + api *function.API, + runtime function.FunctionRuntime, +) tasks.TaskFunc[*function.Function, *function.Function] { return func(_ *tasks.Task, fc *function.Function) (*function.Function, error) { fc, err := api.UpdateFunction(&function.UpdateFunctionRequest{ Region: fc.Region, diff --git a/internal/namespaces/function/v1beta1/custom_deploy_test.go b/internal/namespaces/function/v1beta1/custom_deploy_test.go index ed1e665fca..c061e9b33e 100644 --- a/internal/namespaces/function/v1beta1/custom_deploy_test.go +++ b/internal/namespaces/function/v1beta1/custom_deploy_test.go @@ -25,7 +25,11 @@ func Test_Deploy(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ Commands: commands, - Cmd: fmt.Sprintf("scw function deploy name=%s runtime=go120 zip-file=%s", functionName, testZip), + Cmd: fmt.Sprintf( + "scw function deploy name=%s runtime=go120 zip-file=%s", + functionName, + testZip, + ), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), diff --git a/internal/namespaces/function/v1beta1/function_cli.go b/internal/namespaces/function/v1beta1/function_cli.go index 665947ea61..822fc5e099 100644 --- a/internal/namespaces/function/v1beta1/function_cli.go +++ b/internal/namespaces/function/v1beta1/function_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/function/v1beta1" + function "github.com/scaleway/scaleway-sdk-go/api/function/v1beta1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -61,6 +61,7 @@ func GetGeneratedCommands() *core.Commands { functionTriggerDelete(), ) } + func functionRoot() *core.Command { return &core.Command{ Short: `Function as a Service API`, @@ -171,7 +172,12 @@ func functionNamespaceList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*function.ListNamespacesRequest) @@ -187,8 +193,8 @@ func functionNamespaceList() *core.Command { if err != nil { return nil, err } - return resp.Namespaces, nil + return resp.Namespaces, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -252,8 +258,8 @@ func functionNamespaceGet() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.GetNamespace(request) + return api.GetNamespace(request) }, } } @@ -316,8 +322,8 @@ func functionNamespaceCreate() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.CreateNamespace(request) + return api.CreateNamespace(request) }, } } @@ -379,8 +385,8 @@ func functionNamespaceUpdate() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.UpdateNamespace(request) + return api.UpdateNamespace(request) }, } } @@ -409,8 +415,8 @@ func functionNamespaceDelete() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.DeleteNamespace(request) + return api.DeleteNamespace(request) }, } } @@ -456,12 +462,17 @@ func functionFunctionList() *core.Command { }, { Name: "organization-id", - Short: `UUID of the Organziation the function belongs to`, + Short: `UUID of the Organization the function belongs to`, Required: false, Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*function.ListFunctionsRequest) @@ -477,8 +488,8 @@ func functionFunctionList() *core.Command { if err != nil { return nil, err } - return resp.Functions, nil + return resp.Functions, nil }, } } @@ -507,8 +518,8 @@ func functionFunctionGet() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.GetFunction(request) + return api.GetFunction(request) }, } } @@ -547,7 +558,7 @@ func functionFunctionCreate() *core.Command { }, { Name: "min-scale", - Short: `Minumum number of instances to scale the function to`, + Short: `Minimum number of instances to scale the function to`, Required: false, Deprecated: false, Positional: false, @@ -565,7 +576,43 @@ func functionFunctionCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_runtime", "golang", "python", "python3", "node8", "node10", "node14", "node16", "node17", "python37", "python38", "python39", "python310", "go113", "go117", "go118", "node18", "rust165", "go119", "python311", "php82", "node19", "go120", "node20", "go121", "node22", "python312", "php83", "go122", "rust179", "go123", "go124", "python313", "rust185", "php84"}, + EnumValues: []string{ + "unknown_runtime", + "golang", + "python", + "python3", + "node8", + "node10", + "node14", + "node16", + "node17", + "python37", + "python38", + "python39", + "python310", + "go113", + "go117", + "go118", + "node18", + "rust165", + "go119", + "python311", + "php82", + "node19", + "go120", + "node20", + "go121", + "node22", + "python312", + "php83", + "go122", + "rust179", + "go123", + "go124", + "python313", + "rust185", + "php84", + }, }, { Name: "memory-limit", @@ -639,8 +686,8 @@ func functionFunctionCreate() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.CreateFunction(request) + return api.CreateFunction(request) }, } } @@ -671,7 +718,7 @@ func functionFunctionUpdate() *core.Command { }, { Name: "min-scale", - Short: `Minumum number of instances to scale the function to`, + Short: `Minimum number of instances to scale the function to`, Required: false, Deprecated: false, Positional: false, @@ -689,7 +736,43 @@ func functionFunctionUpdate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_runtime", "golang", "python", "python3", "node8", "node10", "node14", "node16", "node17", "python37", "python38", "python39", "python310", "go113", "go117", "go118", "node18", "rust165", "go119", "python311", "php82", "node19", "go120", "node20", "go121", "node22", "python312", "php83", "go122", "rust179", "go123", "go124", "python313", "rust185", "php84"}, + EnumValues: []string{ + "unknown_runtime", + "golang", + "python", + "python3", + "node8", + "node10", + "node14", + "node16", + "node17", + "python37", + "python38", + "python39", + "python310", + "go113", + "go117", + "go118", + "node18", + "rust165", + "go119", + "python311", + "php82", + "node19", + "go120", + "node20", + "go121", + "node22", + "python312", + "php83", + "go122", + "rust179", + "go123", + "go124", + "python313", + "rust185", + "php84", + }, }, { Name: "memory-limit", @@ -769,8 +852,8 @@ func functionFunctionUpdate() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.UpdateFunction(request) + return api.UpdateFunction(request) }, } } @@ -799,8 +882,8 @@ func functionFunctionDelete() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.DeleteFunction(request) + return api.DeleteFunction(request) }, } } @@ -829,8 +912,8 @@ func functionFunctionDeploy() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.DeployFunction(request) + return api.DeployFunction(request) }, } } @@ -852,8 +935,8 @@ func functionRuntimeList() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.ListFunctionRuntimes(request) + return api.ListFunctionRuntimes(request) }, } } @@ -889,8 +972,8 @@ func functionFunctionGetUploadURL() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.GetFunctionUploadURL(request) + return api.GetFunctionUploadURL(request) }, } } @@ -919,8 +1002,8 @@ func functionFunctionGetDownloadURL() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.GetFunctionDownloadURL(request) + return api.GetFunctionDownloadURL(request) }, } } @@ -950,7 +1033,12 @@ func functionCronList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*function.ListCronsRequest) @@ -966,8 +1054,8 @@ func functionCronList() *core.Command { if err != nil { return nil, err } - return resp.Crons, nil + return resp.Crons, nil }, } } @@ -996,8 +1084,8 @@ func functionCronGet() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.GetCron(request) + return api.GetCron(request) }, } } @@ -1047,8 +1135,8 @@ func functionCronCreate() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.CreateCron(request) + return api.CreateCron(request) }, } } @@ -1105,8 +1193,8 @@ func functionCronUpdate() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.UpdateCron(request) + return api.UpdateCron(request) }, } } @@ -1135,8 +1223,8 @@ func functionCronDelete() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.DeleteCron(request) + return api.DeleteCron(request) }, } } @@ -1157,16 +1245,26 @@ func functionDomainList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "hostname_asc", "hostname_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "hostname_asc", + "hostname_desc", + }, }, { Name: "function-id", - Short: `UUID of the function the domain is assoicated with`, + Short: `UUID of the function the domain is associated with`, Required: false, Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*function.ListDomainsRequest) @@ -1182,8 +1280,8 @@ func functionDomainList() *core.Command { if err != nil { return nil, err } - return resp.Domains, nil + return resp.Domains, nil }, } } @@ -1212,8 +1310,8 @@ func functionDomainGet() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.GetDomain(request) + return api.GetDomain(request) }, } } @@ -1249,8 +1347,8 @@ func functionDomainCreate() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.CreateDomain(request) + return api.CreateDomain(request) }, } } @@ -1279,8 +1377,8 @@ func functionDomainDelete() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.DeleteDomain(request) + return api.DeleteDomain(request) }, } } @@ -1330,8 +1428,8 @@ func functionTokenCreate() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.CreateToken(request) + return api.CreateToken(request) }, } } @@ -1360,8 +1458,8 @@ func functionTokenGet() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.GetToken(request) + return api.GetToken(request) }, } } @@ -1386,7 +1484,7 @@ func functionTokenList() *core.Command { }, { Name: "function-id", - Short: `UUID of the function the token is assoicated with`, + Short: `UUID of the function the token is associated with`, Required: false, Deprecated: false, Positional: false, @@ -1398,7 +1496,12 @@ func functionTokenList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*function.ListTokensRequest) @@ -1414,8 +1517,8 @@ func functionTokenList() *core.Command { if err != nil { return nil, err } - return resp.Tokens, nil + return resp.Tokens, nil }, } } @@ -1444,8 +1547,8 @@ func functionTokenDelete() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.DeleteToken(request) + return api.DeleteToken(request) }, } } @@ -1537,8 +1640,8 @@ func functionTriggerCreate() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.CreateTrigger(request) + return api.CreateTrigger(request) }, } } @@ -1567,8 +1670,8 @@ func functionTriggerGet() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.GetTrigger(request) + return api.GetTrigger(request) }, } } @@ -1606,7 +1709,12 @@ func functionTriggerList() *core.Command { Positional: false, }, core.ProjectIDArgSpec(), - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*function.ListTriggersRequest) @@ -1622,8 +1730,8 @@ func functionTriggerList() *core.Command { if err != nil { return nil, err } - return resp.Triggers, nil + return resp.Triggers, nil }, } } @@ -1666,8 +1774,8 @@ func functionTriggerUpdate() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.UpdateTrigger(request) + return api.UpdateTrigger(request) }, } } @@ -1696,8 +1804,8 @@ func functionTriggerDelete() *core.Command { client := core.ExtractClient(ctx) api := function.NewAPI(client) - return api.DeleteTrigger(request) + return api.DeleteTrigger(request) }, } } diff --git a/internal/namespaces/iam/v1alpha1/custom.go b/internal/namespaces/iam/v1alpha1/custom.go index f0d65670ae..449107bf86 100644 --- a/internal/namespaces/iam/v1alpha1/custom.go +++ b/internal/namespaces/iam/v1alpha1/custom.go @@ -109,14 +109,18 @@ func InitWithSSHKeyRun(ctx context.Context, _ interface{}) (i interface{}, e err // Early exit if the SSH key is present locally and on Scaleway for _, SSHKey := range listSSHKeysResponse.SSHKeys { if strings.TrimSpace(SSHKey.PublicKey) == strings.TrimSpace(string(localSSHKeyContent)) { - _, _ = interactive.Println("Looks like your local SSH key " + shortenedFilename + " is already present in your Scaleway account.") + _, _ = interactive.Println( + "Looks like your local SSH key " + shortenedFilename + " is already present in your Scaleway account.", + ) return nil, nil } } // Ask user - _, _ = interactive.Println("An SSH key is required if you want to connect to a server. More info at https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/") + _, _ = interactive.Println( + "An SSH key is required if you want to connect to a server. More info at https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/", + ) addSSHKey, err := interactive.PromptBoolWithConfig(&interactive.PromptBoolConfig{ Ctx: ctx, Prompt: "We found an SSH key in " + shortenedFilename + ". Do you want to add it to your Scaleway project?", diff --git a/internal/namespaces/iam/v1alpha1/custom_policy.go b/internal/namespaces/iam/v1alpha1/custom_policy.go index 054c294150..1e523fd674 100644 --- a/internal/namespaces/iam/v1alpha1/custom_policy.go +++ b/internal/namespaces/iam/v1alpha1/custom_policy.go @@ -46,28 +46,30 @@ func iamPolicyGetBuilder(c *core.Command) *core.Command { }, }, } - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { - args := argsI.(*iam.GetPolicyRequest) - api := iam.NewAPI(core.ExtractClient(ctx)) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + args := argsI.(*iam.GetPolicyRequest) + api := iam.NewAPI(core.ExtractClient(ctx)) - respI, err := runner(ctx, argsI) - if err != nil { - return respI, err - } - resp := &PolicyGetInterceptorResponse{ - Policy: respI.(*iam.Policy), - } + respI, err := runner(ctx, argsI) + if err != nil { + return respI, err + } + resp := &PolicyGetInterceptorResponse{ + Policy: respI.(*iam.Policy), + } - rules, err := api.ListRules(&iam.ListRulesRequest{ - PolicyID: args.PolicyID, - }, scw.WithContext(ctx), scw.WithAllPages()) - if err != nil { - return nil, fmt.Errorf("failed to list rules for given policy: %w", err) - } - resp.Rules = rules.Rules + rules, err := api.ListRules(&iam.ListRulesRequest{ + PolicyID: args.PolicyID, + }, scw.WithContext(ctx), scw.WithAllPages()) + if err != nil { + return nil, fmt.Errorf("failed to list rules for given policy: %w", err) + } + resp.Rules = rules.Rules - return resp, nil - }) + return resp, nil + }, + ) return c } diff --git a/internal/namespaces/iam/v1alpha1/custom_policy_test.go b/internal/namespaces/iam/v1alpha1/custom_policy_test.go index cc6fa18d28..c3117552d4 100644 --- a/internal/namespaces/iam/v1alpha1/custom_policy_test.go +++ b/internal/namespaces/iam/v1alpha1/custom_policy_test.go @@ -16,8 +16,14 @@ func Test_getPolicyWithRules(t *testing.T) { account.GetCommands(), ), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Project", "scw account project create name=test-cli-get-policy"), - core.ExecStoreBeforeCmd("Policy", "scw iam policy create name=test-cli-get-policy no-principal=true rules.0.permission-set-names.0=IPAMReadOnly rules.0.project-ids.0={{ .Project.ID }}"), + core.ExecStoreBeforeCmd( + "Project", + "scw account project create name=test-cli-get-policy", + ), + core.ExecStoreBeforeCmd( + "Policy", + "scw iam policy create name=test-cli-get-policy no-principal=true rules.0.permission-set-names.0=IPAMReadOnly rules.0.project-ids.0={{ .Project.ID }}", + ), ), Cmd: `scw iam policy get {{ .Policy.ID }}`, Check: core.TestCheckCombine( diff --git a/internal/namespaces/iam/v1alpha1/custom_rule_test.go b/internal/namespaces/iam/v1alpha1/custom_rule_test.go index aa03d544d6..6633f765c1 100644 --- a/internal/namespaces/iam/v1alpha1/custom_rule_test.go +++ b/internal/namespaces/iam/v1alpha1/custom_rule_test.go @@ -18,8 +18,14 @@ func Test_createRule(t *testing.T) { account.GetCommands(), ), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Project", "scw account project create name=test-cli-iam-create-rule"), - core.ExecStoreBeforeCmd("Policy", "scw iam policy create name=test-cli-iam-create-rule no-principal=true rules.0.permission-set-names.0=IPAMReadOnly rules.0.project-ids.0={{ .Project.ID }}"), + core.ExecStoreBeforeCmd( + "Project", + "scw account project create name=test-cli-iam-create-rule", + ), + core.ExecStoreBeforeCmd( + "Policy", + "scw iam policy create name=test-cli-iam-create-rule no-principal=true rules.0.permission-set-names.0=IPAMReadOnly rules.0.project-ids.0={{ .Project.ID }}", + ), ), Cmd: `scw iam rule create {{ .Policy.ID }} permission-set-names.0=VPCReadOnly project-ids.0={{ .Project.ID }}`, Check: core.TestCheckCombine( @@ -45,12 +51,22 @@ func Test_deleteRule(t *testing.T) { account.GetCommands(), ), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Project", "scw account project create name=test-cli-iam-delete-rule"), - core.ExecStoreBeforeCmd("Policy", "scw iam policy create name=test-cli-iam-delete-rule no-principal=true rules.0.permission-set-names.0=IPAMReadOnly rules.0.project-ids.0={{ .Project.ID }} rules.1.permission-set-names.0=VPCReadOnly rules.1.project-ids.0={{ .Project.ID }}"), + core.ExecStoreBeforeCmd( + "Project", + "scw account project create name=test-cli-iam-delete-rule", + ), + core.ExecStoreBeforeCmd( + "Policy", + "scw iam policy create name=test-cli-iam-delete-rule no-principal=true rules.0.permission-set-names.0=IPAMReadOnly rules.0.project-ids.0={{ .Project.ID }} rules.1.permission-set-names.0=VPCReadOnly rules.1.project-ids.0={{ .Project.ID }}", + ), core.ExecStoreBeforeCmd("Policy", "scw iam policy get {{ .Policy.ID }}"), func(ctx *core.BeforeFuncCtx) error { // Get first Rule ID - policy := testhelpers.MapValue[*iam.PolicyGetInterceptorResponse](t, ctx.Meta, "Policy") + policy := testhelpers.MapValue[*iam.PolicyGetInterceptorResponse]( + t, + ctx.Meta, + "Policy", + ) if len(policy.Rules) != 2 { return errors.New("expected two rules in policy") } diff --git a/internal/namespaces/iam/v1alpha1/iam_cli.go b/internal/namespaces/iam/v1alpha1/iam_cli.go index 0716a81f10..92b7ad706c 100644 --- a/internal/namespaces/iam/v1alpha1/iam_cli.go +++ b/internal/namespaces/iam/v1alpha1/iam_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/iam/v1alpha1" + iam "github.com/scaleway/scaleway-sdk-go/api/iam/v1alpha1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -77,6 +77,7 @@ func GetGeneratedCommands() *core.Commands { iamLogGet(), ) } + func iamRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage Identity and Access Management (IAM) across your Scaleway Organizations, Projects and resources`, @@ -192,7 +193,14 @@ func iamSSHKeyList() *core.Command { Deprecated: false, Positional: false, Default: core.DefaultValueSetter("created_at_asc"), - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "name_asc", "name_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "name_asc", + "name_desc", + }, }, { Name: "name", @@ -233,8 +241,8 @@ func iamSSHKeyList() *core.Command { if err != nil { return nil, err } - return resp.SSHKeys, nil + return resp.SSHKeys, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -291,8 +299,8 @@ func iamSSHKeyCreate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.CreateSSHKey(request) + return api.CreateSSHKey(request) }, Examples: []*core.Example{ { @@ -336,8 +344,8 @@ func iamSSHKeyGet() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.GetSSHKey(request) + return api.GetSSHKey(request) }, } } @@ -378,8 +386,8 @@ func iamSSHKeyUpdate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.UpdateSSHKey(request) + return api.UpdateSSHKey(request) }, } } @@ -410,6 +418,7 @@ func iamSSHKeyDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "ssh-key", Verb: "delete", @@ -451,7 +460,18 @@ func iamUserList() *core.Command { Deprecated: false, Positional: false, Default: core.DefaultValueSetter("created_at_asc"), - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "email_asc", "email_desc", "last_login_asc", "last_login_desc", "username_asc", "username_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "email_asc", + "email_desc", + "last_login_asc", + "last_login_desc", + "username_asc", + "username_desc", + }, }, { Name: "user-ids.{index}", @@ -500,8 +520,8 @@ func iamUserList() *core.Command { if err != nil { return nil, err } - return resp.Users, nil + return resp.Users, nil }, } } @@ -529,8 +549,8 @@ func iamUserGet() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.GetUser(request) + return api.GetUser(request) }, } } @@ -600,8 +620,8 @@ func iamUserUpdate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.UpdateUser(request) + return api.UpdateUser(request) }, } } @@ -633,6 +653,7 @@ func iamUserDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "user", Verb: "delete", @@ -735,8 +756,8 @@ func iamUserCreate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.CreateUser(request) + return api.CreateUser(request) }, } } @@ -771,8 +792,8 @@ func iamUserUpdateUsername() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.UpdateUserUsername(request) + return api.UpdateUserUsername(request) }, } } @@ -807,8 +828,8 @@ func iamUserUpdatePassword() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.UpdateUserPassword(request) + return api.UpdateUserPassword(request) }, } } @@ -830,7 +851,14 @@ func iamApplicationList() *core.Command { Deprecated: false, Positional: false, Default: core.DefaultValueSetter("created_at_asc"), - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "name_asc", "name_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "name_asc", + "name_desc", + }, }, { Name: "name", @@ -872,8 +900,8 @@ func iamApplicationList() *core.Command { if err != nil { return nil, err } - return resp.Applications, nil + return resp.Applications, nil }, } } @@ -917,8 +945,8 @@ func iamApplicationCreate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.CreateApplication(request) + return api.CreateApplication(request) }, } } @@ -946,8 +974,8 @@ func iamApplicationGet() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.GetApplication(request) + return api.GetApplication(request) }, } } @@ -996,8 +1024,8 @@ func iamApplicationUpdate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.UpdateApplication(request) + return api.UpdateApplication(request) }, } } @@ -1029,6 +1057,7 @@ func iamApplicationDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "application", Verb: "delete", @@ -1054,7 +1083,14 @@ func iamGroupList() *core.Command { Deprecated: false, Positional: false, Default: core.DefaultValueSetter("created_at_asc"), - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "name_asc", "name_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "name_asc", + "name_desc", + }, }, { Name: "name", @@ -1103,8 +1139,8 @@ func iamGroupList() *core.Command { if err != nil { return nil, err } - return resp.Groups, nil + return resp.Groups, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -1162,8 +1198,8 @@ func iamGroupCreate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.CreateGroup(request) + return api.CreateGroup(request) }, Examples: []*core.Example{ { @@ -1191,7 +1227,7 @@ func iamGroupCreate() *core.Command { func iamGroupGet() *core.Command { return &core.Command{ Short: `Get a group`, - Long: `Retrive information about a given group, specified by the ` + "`" + `group_id` + "`" + ` parameter. The group's full details, including ` + "`" + `user_ids` + "`" + ` and ` + "`" + `application_ids` + "`" + ` are returned in the response.`, + Long: `Retrieve information about a given group, specified by the ` + "`" + `group_id` + "`" + ` parameter. The group's full details, including ` + "`" + `user_ids` + "`" + ` and ` + "`" + `application_ids` + "`" + ` are returned in the response.`, Namespace: "iam", Resource: "group", Verb: "get", @@ -1211,8 +1247,8 @@ func iamGroupGet() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.GetGroup(request) + return api.GetGroup(request) }, } } @@ -1261,8 +1297,8 @@ func iamGroupUpdate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.UpdateGroup(request) + return api.UpdateGroup(request) }, } } @@ -1301,8 +1337,8 @@ func iamGroupSetMembers() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.SetGroupMembers(request) + return api.SetGroupMembers(request) }, SeeAlsos: []*core.SeeAlso{ { @@ -1354,8 +1390,8 @@ func iamGroupAddMember() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.AddGroupMember(request) + return api.AddGroupMember(request) }, } } @@ -1397,8 +1433,8 @@ func iamGroupAddMembers() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.AddGroupMembers(request) + return api.AddGroupMembers(request) }, } } @@ -1440,8 +1476,8 @@ func iamGroupRemoveMember() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.RemoveGroupMember(request) + return api.RemoveGroupMember(request) }, SeeAlsos: []*core.SeeAlso{ { @@ -1483,6 +1519,7 @@ func iamGroupDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "group", Verb: "delete", @@ -1524,7 +1561,12 @@ func iamPolicyList() *core.Command { Deprecated: false, Positional: false, Default: core.DefaultValueSetter("created_at_asc"), - EnumValues: []string{"policy_name_asc", "policy_name_desc", "created_at_asc", "created_at_desc"}, + EnumValues: []string{ + "policy_name_asc", + "policy_name_desc", + "created_at_asc", + "created_at_desc", + }, }, { Name: "editable", @@ -1594,8 +1636,8 @@ func iamPolicyList() *core.Command { if err != nil { return nil, err } - return resp.Policies, nil + return resp.Policies, nil }, } } @@ -1695,8 +1737,8 @@ func iamPolicyCreate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.CreatePolicy(request) + return api.CreatePolicy(request) }, Examples: []*core.Example{ { @@ -1730,8 +1772,8 @@ func iamPolicyGet() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.GetPolicy(request) + return api.GetPolicy(request) }, } } @@ -1808,8 +1850,8 @@ func iamPolicyUpdate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.UpdatePolicy(request) + return api.UpdatePolicy(request) }, } } @@ -1841,6 +1883,7 @@ func iamPolicyDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "policy", Verb: "delete", @@ -1871,8 +1914,8 @@ func iamPolicyClone() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.ClonePolicy(request) + return api.ClonePolicy(request) }, } } @@ -1928,8 +1971,8 @@ func iamRuleUpdate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.SetRules(request) + return api.SetRules(request) }, } } @@ -1962,8 +2005,8 @@ func iamRuleList() *core.Command { if err != nil { return nil, err } - return resp.Rules, nil + return resp.Rules, nil }, } } @@ -1999,8 +2042,8 @@ func iamPermissionSetList() *core.Command { if err != nil { return nil, err } - return resp.PermissionSets, nil + return resp.PermissionSets, nil }, } } @@ -2022,7 +2065,16 @@ func iamAPIKeyList() *core.Command { Deprecated: false, Positional: false, Default: core.DefaultValueSetter("created_at_asc"), - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "expires_at_asc", "expires_at_desc", "access_key_asc", "access_key_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "expires_at_asc", + "expires_at_desc", + "access_key_asc", + "access_key_desc", + }, }, { Name: "application-id", @@ -2106,8 +2158,8 @@ func iamAPIKeyList() *core.Command { if err != nil { return nil, err } - return resp.APIKeys, nil + return resp.APIKeys, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -2183,8 +2235,8 @@ func iamAPIKeyCreate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.CreateAPIKey(request) + return api.CreateAPIKey(request) }, SeeAlsos: []*core.SeeAlso{ { @@ -2202,7 +2254,7 @@ func iamAPIKeyCreate() *core.Command { func iamAPIKeyGet() *core.Command { return &core.Command{ Short: `Get an API key`, - Long: `Retrive information about an API key, specified by the ` + "`" + `access_key` + "`" + ` parameter. The API key's details, including either the ` + "`" + `user_id` + "`" + ` or ` + "`" + `application_id` + "`" + ` of its bearer are returned in the response. Note that the string value for the ` + "`" + `secret_key` + "`" + ` is nullable, and therefore is not displayed in the response. The ` + "`" + `secret_key` + "`" + ` value is only displayed upon API key creation.`, + Long: `Retrieve information about an API key, specified by the ` + "`" + `access_key` + "`" + ` parameter. The API key's details, including either the ` + "`" + `user_id` + "`" + ` or ` + "`" + `application_id` + "`" + ` of its bearer are returned in the response. Note that the string value for the ` + "`" + `secret_key` + "`" + ` is nullable, and therefore is not displayed in the response. The ` + "`" + `secret_key` + "`" + ` value is only displayed upon API key creation.`, Namespace: "iam", Resource: "api-key", Verb: "get", @@ -2222,8 +2274,8 @@ func iamAPIKeyGet() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.GetAPIKey(request) + return api.GetAPIKey(request) }, } } @@ -2265,8 +2317,8 @@ func iamAPIKeyUpdate() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.UpdateAPIKey(request) + return api.UpdateAPIKey(request) }, } } @@ -2298,6 +2350,7 @@ func iamAPIKeyDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "api-key", Verb: "delete", @@ -2339,7 +2392,12 @@ func iamJwtList() *core.Command { Deprecated: false, Positional: false, Default: core.DefaultValueSetter("created_at_asc"), - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + }, }, { Name: "audience-id", @@ -2366,8 +2424,8 @@ func iamJwtList() *core.Command { if err != nil { return nil, err } - return resp.Jwts, nil + return resp.Jwts, nil }, } } @@ -2395,8 +2453,8 @@ func iamJwtGet() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.GetJWT(request) + return api.GetJWT(request) }, } } @@ -2428,6 +2486,7 @@ func iamJwtDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "jwt", Verb: "delete", @@ -2483,7 +2542,14 @@ func iamLogList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_resource_type", "api_key", "user", "application", "group", "policy"}, + EnumValues: []string{ + "unknown_resource_type", + "api_key", + "user", + "application", + "group", + "policy", + }, }, { Name: "search", @@ -2504,8 +2570,8 @@ func iamLogList() *core.Command { if err != nil { return nil, err } - return resp.Logs, nil + return resp.Logs, nil }, } } @@ -2533,8 +2599,8 @@ func iamLogGet() *core.Command { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - return api.GetLog(request) + return api.GetLog(request) }, } } diff --git a/internal/namespaces/inference/v1beta1/custom.go b/internal/namespaces/inference/v1beta1/custom.go index c40897525f..5981e5f6b9 100644 --- a/internal/namespaces/inference/v1beta1/custom.go +++ b/internal/namespaces/inference/v1beta1/custom.go @@ -9,7 +9,10 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(inference.DeploymentStatus(""), human.EnumMarshalFunc(deployementStateMarshalSpecs)) + human.RegisterMarshalerFunc( + inference.DeploymentStatus(""), + human.EnumMarshalFunc(deployementStateMarshalSpecs), + ) human.RegisterMarshalerFunc(inference.Deployment{}, DeploymentMarshalerFunc) human.RegisterMarshalerFunc([]*inference.Model{}, ListModelMarshalerFunc) diff --git a/internal/namespaces/inference/v1beta1/custom_deployment.go b/internal/namespaces/inference/v1beta1/custom_deployment.go index d029128003..7cc2049a92 100644 --- a/internal/namespaces/inference/v1beta1/custom_deployment.go +++ b/internal/namespaces/inference/v1beta1/custom_deployment.go @@ -97,7 +97,7 @@ func deploymentCreateBuilder(c *core.Command) *core.Command { publicEndpoint = nil } privateNetwork := &inference.EndpointSpecPrivateNetwork{} - if endpoint.EndpointSpec.PrivateNetwork == nil { + if endpoint.PrivateNetwork == nil { privateNetwork = nil } else { privateNetwork.PrivateNetworkID = endpoint.PrivateNetwork.PrivateNetworkID @@ -129,7 +129,8 @@ func deploymentDeleteBuilder(c *core.Command) *core.Command { if err != nil { notFoundError := &scw.ResourceNotFoundError{} responseError := &scw.ResponseError{} - if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) { + if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || + errors.As(err, ¬FoundError) { return &core.SuccessResult{ Resource: "deployment", Verb: "delete", @@ -147,7 +148,11 @@ func deploymentDeleteBuilder(c *core.Command) *core.Command { var completeListNodeTypesCache *inference.ListNodeTypesResponse -func autocompleteDeploymentNodeType(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autocompleteDeploymentNodeType( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { req := request.(*inference.CreateDeploymentRequest) suggestions := core.AutocompleteSuggestions(nil) diff --git a/internal/namespaces/inference/v1beta1/custom_endpoint.go b/internal/namespaces/inference/v1beta1/custom_endpoint.go index f204591113..11eecfb79c 100644 --- a/internal/namespaces/inference/v1beta1/custom_endpoint.go +++ b/internal/namespaces/inference/v1beta1/custom_endpoint.go @@ -42,7 +42,9 @@ func endpointCreateBuilder(c *core.Command) *core.Command { endpointToCreate.Public = publicEndpoint } if endpoint.PrivateNetwork != nil && endpoint.PrivateNetwork.PrivateNetworkID != "" { - endpointToCreate.PrivateNetwork = &inference.EndpointSpecPrivateNetwork{PrivateNetworkID: endpoint.PrivateNetwork.PrivateNetworkID} + endpointToCreate.PrivateNetwork = &inference.EndpointSpecPrivateNetwork{ + PrivateNetworkID: endpoint.PrivateNetwork.PrivateNetworkID, + } } createEndpointreq.Endpoint = &endpointToCreate diff --git a/internal/namespaces/inference/v1beta1/inference_cli.go b/internal/namespaces/inference/v1beta1/inference_cli.go index 47efb75d6a..86ae8ff216 100644 --- a/internal/namespaces/inference/v1beta1/inference_cli.go +++ b/internal/namespaces/inference/v1beta1/inference_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/inference/v1beta1" + inference "github.com/scaleway/scaleway-sdk-go/api/inference/v1beta1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -43,6 +43,7 @@ func GetGeneratedCommands() *core.Commands { inferenceNodeTypeList(), ) } + func inferenceRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Inference services`, @@ -158,8 +159,8 @@ func inferenceDeploymentList() *core.Command { if err != nil { return nil, err } - return resp.Deployments, nil + return resp.Deployments, nil }, } } @@ -188,8 +189,8 @@ func inferenceDeploymentGet() *core.Command { client := core.ExtractClient(ctx) api := inference.NewAPI(client) - return api.GetDeployment(request) + return api.GetDeployment(request) }, } } @@ -277,8 +278,8 @@ func inferenceDeploymentCreate() *core.Command { client := core.ExtractClient(ctx) api := inference.NewAPI(client) - return api.CreateDeployment(request) + return api.CreateDeployment(request) }, } } @@ -335,8 +336,8 @@ func inferenceDeploymentUpdate() *core.Command { client := core.ExtractClient(ctx) api := inference.NewAPI(client) - return api.UpdateDeployment(request) + return api.UpdateDeployment(request) }, } } @@ -365,8 +366,8 @@ func inferenceDeploymentDelete() *core.Command { client := core.ExtractClient(ctx) api := inference.NewAPI(client) - return api.DeleteDeployment(request) + return api.DeleteDeployment(request) }, } } @@ -395,8 +396,8 @@ The CA certificate will be returned as a PEM file.`, client := core.ExtractClient(ctx) api := inference.NewAPI(client) - return api.GetDeploymentCertificate(request) + return api.GetDeploymentCertificate(request) }, } } @@ -440,8 +441,8 @@ func inferenceEndpointCreate() *core.Command { client := core.ExtractClient(ctx) api := inference.NewAPI(client) - return api.CreateEndpoint(request) + return api.CreateEndpoint(request) }, } } @@ -477,8 +478,8 @@ func inferenceEndpointUpdate() *core.Command { client := core.ExtractClient(ctx) api := inference.NewAPI(client) - return api.UpdateEndpoint(request) + return api.UpdateEndpoint(request) }, } } @@ -511,6 +512,7 @@ func inferenceEndpointDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "endpoint", Verb: "delete", @@ -552,8 +554,8 @@ func inferenceACLList() *core.Command { if err != nil { return nil, err } - return resp.Rules, nil + return resp.Rules, nil }, } } @@ -596,8 +598,8 @@ func inferenceACLAdd() *core.Command { client := core.ExtractClient(ctx) api := inference.NewAPI(client) - return api.AddDeploymentACLRules(request) + return api.AddDeploymentACLRules(request) }, } } @@ -640,16 +642,16 @@ func inferenceACLSet() *core.Command { client := core.ExtractClient(ctx) api := inference.NewAPI(client) - return api.SetDeploymentACLRules(request) + return api.SetDeploymentACLRules(request) }, } } func inferenceACLDelete() *core.Command { return &core.Command{ - Short: `Delete an exising ACL`, - Long: `Delete an exising ACL.`, + Short: `Delete an existing ACL`, + Long: `Delete an existing ACL.`, Namespace: "inference", Resource: "acl", Verb: "delete", @@ -674,6 +676,7 @@ func inferenceACLDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "acl", Verb: "delete", @@ -698,7 +701,13 @@ func inferenceModelList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"display_rank_asc", "created_at_asc", "created_at_desc", "name_asc", "name_desc"}, + EnumValues: []string{ + "display_rank_asc", + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + }, }, { Name: "project-id", @@ -737,8 +746,8 @@ func inferenceModelList() *core.Command { if err != nil { return nil, err } - return resp.Models, nil + return resp.Models, nil }, } } @@ -767,8 +776,8 @@ func inferenceModelGet() *core.Command { client := core.ExtractClient(ctx) api := inference.NewAPI(client) - return api.GetModel(request) + return api.GetModel(request) }, } } @@ -806,8 +815,8 @@ func inferenceNodeTypeList() *core.Command { if err != nil { return nil, err } - return resp.NodeTypes, nil + return resp.NodeTypes, nil }, } } diff --git a/internal/namespaces/info/custom.go b/internal/namespaces/info/custom.go index 69b46205c9..6a5dfd4cf7 100644 --- a/internal/namespaces/info/custom.go +++ b/internal/namespaces/info/custom.go @@ -148,8 +148,8 @@ func defaultRegion(ctx context.Context, config *scw.Config, profileName string) setting.Origin = fmt.Sprintf("profile (%s)", profileName) setting.Value = *config.Profiles[profileName].DefaultRegion // Default config - case config.Profile.DefaultRegion != nil: - setting.Value = *config.Profile.DefaultRegion + case config.DefaultRegion != nil: + setting.Value = *config.DefaultRegion setting.Origin = defaultProfileOrigin default: setting.Origin = defaultOrigin @@ -178,8 +178,8 @@ func defaultZone(ctx context.Context, config *scw.Config, profileName string) *s setting.Value = *config.Profiles[profileName].DefaultZone setting.Origin = fmt.Sprintf("profile (%s)", profileName) // Default config - case config.Profile.DefaultZone != nil: - setting.Value = *config.Profile.DefaultZone + case config.DefaultZone != nil: + setting.Value = *config.DefaultZone setting.Origin = defaultProfileOrigin default: setting.Origin = defaultOrigin @@ -203,8 +203,8 @@ func defaultOrganizationID(ctx context.Context, config *scw.Config, profileName setting.Value = *config.Profiles[profileName].DefaultOrganizationID setting.Origin = fmt.Sprintf("profile (%s)", profileName) // Default config - case config.Profile.DefaultOrganizationID != nil: - setting.Value = *config.Profile.DefaultOrganizationID + case config.DefaultOrganizationID != nil: + setting.Value = *config.DefaultOrganizationID setting.Origin = defaultProfileOrigin default: setting.Origin = unknownOrigin @@ -228,8 +228,8 @@ func defaultProjectID(ctx context.Context, config *scw.Config, profileName strin setting.Value = *config.Profiles[profileName].DefaultProjectID setting.Origin = fmt.Sprintf("profile (%s)", profileName) // Default config - case config.Profile.DefaultProjectID != nil: - setting.Value = *config.Profile.DefaultProjectID + case config.DefaultProjectID != nil: + setting.Value = *config.DefaultProjectID setting.Origin = defaultProfileOrigin default: setting.Origin = unknownOrigin @@ -253,8 +253,8 @@ func accessKey(ctx context.Context, config *scw.Config, profileName string) *set setting.Value = *config.Profiles[profileName].AccessKey setting.Origin = fmt.Sprintf("profile (%s)", profileName) // Default config - case config.Profile.AccessKey != nil: - setting.Value = *config.Profile.AccessKey + case config.AccessKey != nil: + setting.Value = *config.AccessKey setting.Origin = defaultProfileOrigin default: setting.Origin = unknownOrigin @@ -274,7 +274,12 @@ func hideSecretKey(k string) string { } } -func secretKey(ctx context.Context, config *scw.Config, profileName string, showSecret bool) *setting { +func secretKey( + ctx context.Context, + config *scw.Config, + profileName string, + showSecret bool, +) *setting { setting := &setting{Key: "secret_key"} switch { // Environment variable check @@ -289,8 +294,8 @@ func secretKey(ctx context.Context, config *scw.Config, profileName string, show setting.Value = *config.Profiles[profileName].SecretKey setting.Origin = fmt.Sprintf("profile (%s)", profileName) // Default config - case config.Profile.SecretKey != nil: - setting.Value = *config.Profile.SecretKey + case config.SecretKey != nil: + setting.Value = *config.SecretKey setting.Origin = defaultProfileOrigin default: setting.Origin = unknownOrigin diff --git a/internal/namespaces/init/init.go b/internal/namespaces/init/init.go index bf9ffa6748..a44b2211fb 100644 --- a/internal/namespaces/init/init.go +++ b/internal/namespaces/init/init.go @@ -173,8 +173,19 @@ Default path for configuration file is based on the following priority order: } if args.ProjectID == "" { - args.ProjectID = getAPIKeyDefaultProjectID(ctx, args.AccessKey, args.SecretKey, args.OrganizationID) - args.ProjectID, err = promptProjectID(ctx, args.AccessKey, args.SecretKey, args.OrganizationID, args.ProjectID) + args.ProjectID = getAPIKeyDefaultProjectID( + ctx, + args.AccessKey, + args.SecretKey, + args.OrganizationID, + ) + args.ProjectID, err = promptProjectID( + ctx, + args.AccessKey, + args.SecretKey, + args.OrganizationID, + args.ProjectID, + ) if err != nil { return nil, err } @@ -233,7 +244,11 @@ Default path for configuration file is based on the following priority order: } // Persist configuration on disk - interactive.Printf("Config saved at %s:\n%s\n", configPath, terminal.Style(fmt.Sprint(config), color.Faint)) + interactive.Printf( + "Config saved at %s:\n%s\n", + configPath, + terminal.Style(fmt.Sprint(config), color.Faint), + ) err = config.SaveTo(configPath) if err != nil { return nil, err @@ -307,11 +322,19 @@ func loadConfigOrEmpty(configPath string, activeProfile string) (*scw.Config, er // getAPIKeyDefaultProjectID tries to find the api-key default project ID // return default project ID (organization ID) if it cannot find it -func getAPIKeyDefaultProjectID(ctx context.Context, accessKey string, secretKey string, organizationID string) string { +func getAPIKeyDefaultProjectID( + ctx context.Context, + accessKey string, + secretKey string, + organizationID string, +) string { client := core.ExtractClient(ctx) api := iam.NewAPI(client) - apiKey, err := api.GetAPIKey(&iam.GetAPIKeyRequest{AccessKey: accessKey}, scw.WithAuthRequest(accessKey, secretKey)) + apiKey, err := api.GetAPIKey( + &iam.GetAPIKeyRequest{AccessKey: accessKey}, + scw.WithAuthRequest(accessKey, secretKey), + ) if err != nil && !is403Error(err) { // If 403 Unauthorized, API Key does not have permissions to get himself // It requires IAM permission to fetch an API Key diff --git a/internal/namespaces/init/init_test.go b/internal/namespaces/init/init_test.go index 024fa44004..75b0c6d13e 100644 --- a/internal/namespaces/init/init_test.go +++ b/internal/namespaces/init/init_test.go @@ -13,7 +13,9 @@ import ( "github.com/stretchr/testify/require" ) -func checkConfig(check func(t *testing.T, ctx *core.CheckFuncCtx, config *scw.Config)) core.TestCheck { +func checkConfig( + check func(t *testing.T, ctx *core.CheckFuncCtx, config *scw.Config), +) core.TestCheck { return func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() homeDir := ctx.OverrideEnv["HOME"] @@ -71,7 +73,10 @@ func TestInit(t *testing.T) { BeforeFunc: core.BeforeFuncCombine( baseBeforeFunc(), func(ctx *core.BeforeFuncCtx) error { - ctx.Meta["CONFIG_PATH"] = path.Join(ctx.Meta["HOME"].(string), "new_config_path.yml") + ctx.Meta["CONFIG_PATH"] = path.Join( + ctx.Meta["HOME"].(string), + "new_config_path.yml", + ) return nil }, @@ -176,7 +181,11 @@ func TestInit(t *testing.T) { core.TestCheckGolden(), checkConfig(func(t *testing.T, _ *core.CheckFuncCtx, config *scw.Config) { t.Helper() - assert.NotNil(t, config.Profiles["test2"], "new profile should have been created") + assert.NotNil( + t, + config.Profiles["test2"], + "new profile should have been created", + ) }), ), TmpHomeDir: true, @@ -251,12 +260,16 @@ func TestInit_Prompt(t *testing.T) { Check: core.TestCheckCombine( core.TestCheckGoldenAndReplacePatterns( core.GoldenReplacement{ - Pattern: regexp.MustCompile("\\s\\sExcept for autocomplete: unsupported OS 'windows'\n"), + Pattern: regexp.MustCompile( + "\\s\\sExcept for autocomplete: unsupported OS 'windows'\n", + ), Replacement: "", OptionalMatch: true, }, core.GoldenReplacement{ - Pattern: regexp.MustCompile(`Except for autocomplete: unsupported OS 'windows'\\n`), + Pattern: regexp.MustCompile( + `Except for autocomplete: unsupported OS 'windows'\\n`, + ), Replacement: "", OptionalMatch: true, }, diff --git a/internal/namespaces/init/prompt.go b/internal/namespaces/init/prompt.go index 2b233b007a..3aff73b965 100644 --- a/internal/namespaces/init/prompt.go +++ b/internal/namespaces/init/prompt.go @@ -49,7 +49,13 @@ func promptManualProjectID(ctx context.Context, defaultProjectID string) (string }) } -func promptProjectID(ctx context.Context, accessKey string, secretKey string, organizationID string, defaultProjectID string) (string, error) { +func promptProjectID( + ctx context.Context, + accessKey string, + secretKey string, + organizationID string, + defaultProjectID string, +) (string, error) { if defaultProjectID == "" { defaultProjectID = organizationID } @@ -225,7 +231,12 @@ func promptDefaultZone(ctx context.Context) (scw.Zone, error) { } // promptProfileOverride prompt user if profileName is getting override in config -func promptProfileOverride(ctx context.Context, config *scw.Config, configPath string, profileName string) error { +func promptProfileOverride( + ctx context.Context, + config *scw.Config, + configPath string, + profileName string, +) error { var profile *scw.Profile var profileExists bool @@ -242,7 +253,10 @@ func promptProfileOverride(ctx context.Context, config *scw.Config, configPath s ` + terminal.Style(fmt.Sprint(profile), color.Faint) + ` `) overrideConfig, err := interactive.PromptBoolWithConfig(&interactive.PromptBoolConfig{ - Prompt: fmt.Sprintf("Do you want to override the current profile (%s) ?", profileName), + Prompt: fmt.Sprintf( + "Do you want to override the current profile (%s) ?", + profileName, + ), DefaultValue: true, Ctx: ctx, }) diff --git a/internal/namespaces/instance/v1/custom.go b/internal/namespaces/instance/v1/custom.go index b513d5be9e..f50b96de6e 100644 --- a/internal/namespaces/instance/v1/custom.go +++ b/internal/namespaces/instance/v1/custom.go @@ -39,7 +39,10 @@ func GetCommands() *core.Commands { // Server // human.RegisterMarshalerFunc(instance.CreateServerResponse{}, marshallNestedField("Server")) - human.RegisterMarshalerFunc(instance.ServerState(""), human.EnumMarshalFunc(serverStateMarshalSpecs)) + human.RegisterMarshalerFunc( + instance.ServerState(""), + human.EnumMarshalFunc(serverStateMarshalSpecs), + ) human.RegisterMarshalerFunc(instance.ServerLocation{}, serverLocationMarshalerFunc) human.RegisterMarshalerFunc([]*instance.Server{}, serversMarshalerFunc) human.RegisterMarshalerFunc(instance.Bootscript{}, bootscriptMarshalerFunc) @@ -74,7 +77,10 @@ func GetCommands() *core.Commands { // // Server-Type // - human.RegisterMarshalerFunc(instance.ServerTypesAvailability(""), human.EnumMarshalFunc(serverTypesAvailabilityMarshalSpecs)) + human.RegisterMarshalerFunc( + instance.ServerTypesAvailability(""), + human.EnumMarshalFunc(serverTypesAvailabilityMarshalSpecs), + ) cmds.MustFind("instance", "server-type", "list").Override(serverTypeListBuilder) @@ -95,7 +101,10 @@ func GetCommands() *core.Commands { // human.RegisterMarshalerFunc(instance.CreateImageResponse{}, marshallNestedField("Image")) human.RegisterMarshalerFunc([]*imageListItem{}, imagesMarshalerFunc) - human.RegisterMarshalerFunc(instance.ImageState(""), human.EnumMarshalFunc(imageStateMarshalSpecs)) + human.RegisterMarshalerFunc( + instance.ImageState(""), + human.EnumMarshalFunc(imageStateMarshalSpecs), + ) cmds.MustFind("instance", "image", "create").Override(imageCreateBuilder) cmds.MustFind("instance", "image", "list").Override(imageListBuilder) @@ -122,7 +131,10 @@ func GetCommands() *core.Commands { // Volume // human.RegisterMarshalerFunc(instance.CreateVolumeResponse{}, marshallNestedField("Volume")) - human.RegisterMarshalerFunc(instance.VolumeState(""), human.EnumMarshalFunc(volumeStateMarshalSpecs)) + human.RegisterMarshalerFunc( + instance.VolumeState(""), + human.EnumMarshalFunc(volumeStateMarshalSpecs), + ) human.RegisterMarshalerFunc(instance.VolumeSummary{}, volumeSummaryMarshalerFunc) human.RegisterMarshalerFunc(map[string]*instance.Volume{}, volumeMapMarshalerFunc) @@ -142,9 +154,18 @@ func GetCommands() *core.Commands { // // Security Group // - human.RegisterMarshalerFunc(instance.CreateSecurityGroupResponse{}, marshallNestedField("SecurityGroup")) - human.RegisterMarshalerFunc(instance.SecurityGroupPolicy(""), human.EnumMarshalFunc(securityGroupPolicyMarshalSpecs)) - human.RegisterMarshalerFunc(instance.SecurityGroupState(""), human.EnumMarshalFunc(securityGroupStateMarshalSpecs)) + human.RegisterMarshalerFunc( + instance.CreateSecurityGroupResponse{}, + marshallNestedField("SecurityGroup"), + ) + human.RegisterMarshalerFunc( + instance.SecurityGroupPolicy(""), + human.EnumMarshalFunc(securityGroupPolicyMarshalSpecs), + ) + human.RegisterMarshalerFunc( + instance.SecurityGroupState(""), + human.EnumMarshalFunc(securityGroupStateMarshalSpecs), + ) cmds.MustFind("instance", "security-group", "create").Override(securityGroupCreateBuilder) cmds.MustFind("instance", "security-group", "get").Override(securityGroupGetBuilder) @@ -159,14 +180,23 @@ func GetCommands() *core.Commands { // // Security Group Rule // - human.RegisterMarshalerFunc(instance.CreateSecurityGroupRuleResponse{}, marshallNestedField("Rule")) - human.RegisterMarshalerFunc(instance.SecurityGroupRuleAction(""), human.EnumMarshalFunc(securityGroupRuleActionMarshalSpecs)) + human.RegisterMarshalerFunc( + instance.CreateSecurityGroupRuleResponse{}, + marshallNestedField("Rule"), + ) + human.RegisterMarshalerFunc( + instance.SecurityGroupRuleAction(""), + human.EnumMarshalFunc(securityGroupRuleActionMarshalSpecs), + ) human.RegisterMarshalerFunc([]*instance.SecurityGroupRule{}, marshalSecurityGroupRules) // // Placement Group // - human.RegisterMarshalerFunc(instance.CreatePlacementGroupResponse{}, marshallNestedField("PlacementGroup")) + human.RegisterMarshalerFunc( + instance.CreatePlacementGroupResponse{}, + marshallNestedField("PlacementGroup"), + ) cmds.MustFind("instance", "placement-group", "create").Override(placementGroupCreateBuilder) cmds.MustFind("instance", "placement-group", "get").Override(placementGroupGetBuilder) @@ -183,7 +213,10 @@ func GetCommands() *core.Commands { // // Private NICs // - human.RegisterMarshalerFunc(instance.PrivateNICState(""), human.EnumMarshalFunc(privateNICStateMarshalSpecs)) + human.RegisterMarshalerFunc( + instance.PrivateNICState(""), + human.EnumMarshalFunc(privateNICStateMarshalSpecs), + ) cmds.MustFind("instance", "private-nic", "get").Override(privateNicGetBuilder) diff --git a/internal/namespaces/instance/v1/custom_image.go b/internal/namespaces/instance/v1/custom_image.go index 7825e3b3d0..dad25f3a28 100644 --- a/internal/namespaces/instance/v1/custom_image.go +++ b/internal/namespaces/instance/v1/custom_image.go @@ -130,24 +130,26 @@ func imageCreateBuilder(c *core.Command) *core.Command { c.ArgsType = reflect.TypeOf(customCreateImageRequest{}) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customCreateImageRequest) - - request := args.CreateImageRequest - request.RootVolume = args.SnapshotID - request.ExtraVolumes = make(map[string]*instance.VolumeTemplate) - request.Organization = args.OrganizationID - request.Project = args.ProjectID - - // Extra volumes need to start at volumeIndex 1. - volumeIndex := 1 - for _, volume := range args.AdditionalVolumes { - request.ExtraVolumes[strconv.Itoa(volumeIndex)] = volume - volumeIndex++ - } + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customCreateImageRequest) + + request := args.CreateImageRequest + request.RootVolume = args.SnapshotID + request.ExtraVolumes = make(map[string]*instance.VolumeTemplate) + request.Organization = args.OrganizationID + request.Project = args.ProjectID + + // Extra volumes need to start at volumeIndex 1. + volumeIndex := 1 + for _, volume := range args.AdditionalVolumes { + request.ExtraVolumes[strconv.Itoa(volumeIndex)] = volume + volumeIndex++ + } - return runner(ctx, request) - }) + return runner(ctx, request) + }, + ) return c } @@ -252,82 +254,84 @@ func imageDeleteBuilder(c *core.Command) *core.Command { Short: "Delete the snapshots attached to this image", }) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customDeleteImageRequest) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customDeleteImageRequest) - api := instance.NewAPI(core.ExtractClient(ctx)) - blockAPI := block.NewAPI(core.ExtractClient(ctx)) + api := instance.NewAPI(core.ExtractClient(ctx)) + blockAPI := block.NewAPI(core.ExtractClient(ctx)) + + // If we want to delete snapshot we must GET image before we delete it + image := (*instance.Image)(nil) + if args.WithSnapshots { + res, err := api.GetImage(&instance.GetImageRequest{ + Zone: args.Zone, + ImageID: args.ImageID, + }) + if err != nil { + return nil, err + } + image = res.Image + } - // If we want to delete snapshot we must GET image before we delete it - image := (*instance.Image)(nil) - if args.WithSnapshots { - res, err := api.GetImage(&instance.GetImageRequest{ - Zone: args.Zone, - ImageID: args.ImageID, - }) + // Call the generated delete + runnerRes, err := runner(ctx, args.DeleteImageRequest) if err != nil { return nil, err } - image = res.Image - } - - // Call the generated delete - runnerRes, err := runner(ctx, args.DeleteImageRequest) - if err != nil { - return nil, err - } - type UnknownSnapshot struct { - ID string - Type instance.VolumeVolumeType - } - - // Once the image is deleted we can delete snapshots. - if args.WithSnapshots { - snapshots := []UnknownSnapshot{ - { - ID: image.RootVolume.ID, - Type: image.RootVolume.VolumeType, - }, - } - for _, extraVolume := range image.ExtraVolumes { - snapshots = append(snapshots, UnknownSnapshot{ - ID: extraVolume.ID, - Type: extraVolume.VolumeType, - }) + type UnknownSnapshot struct { + ID string + Type instance.VolumeVolumeType } - for _, snapshot := range snapshots { - if snapshot.Type == instance.VolumeVolumeTypeSbsSnapshot { - terminalStatus := block.SnapshotStatusAvailable - _, err := blockAPI.WaitForSnapshot(&block.WaitForSnapshotRequest{ - SnapshotID: snapshot.ID, - Zone: args.Zone, - TerminalStatus: &terminalStatus, - }) - if err != nil { - return nil, err - } - err = blockAPI.DeleteSnapshot(&block.DeleteSnapshotRequest{ - Zone: args.Zone, - SnapshotID: snapshot.ID, - }) - if err != nil { - return nil, err - } - } else { - err := api.DeleteSnapshot(&instance.DeleteSnapshotRequest{ - Zone: args.Zone, - SnapshotID: snapshot.ID, + + // Once the image is deleted we can delete snapshots. + if args.WithSnapshots { + snapshots := []UnknownSnapshot{ + { + ID: image.RootVolume.ID, + Type: image.RootVolume.VolumeType, + }, + } + for _, extraVolume := range image.ExtraVolumes { + snapshots = append(snapshots, UnknownSnapshot{ + ID: extraVolume.ID, + Type: extraVolume.VolumeType, }) - if err != nil { - return nil, err + } + for _, snapshot := range snapshots { + if snapshot.Type == instance.VolumeVolumeTypeSbsSnapshot { + terminalStatus := block.SnapshotStatusAvailable + _, err := blockAPI.WaitForSnapshot(&block.WaitForSnapshotRequest{ + SnapshotID: snapshot.ID, + Zone: args.Zone, + TerminalStatus: &terminalStatus, + }) + if err != nil { + return nil, err + } + err = blockAPI.DeleteSnapshot(&block.DeleteSnapshotRequest{ + Zone: args.Zone, + SnapshotID: snapshot.ID, + }) + if err != nil { + return nil, err + } + } else { + err := api.DeleteSnapshot(&instance.DeleteSnapshotRequest{ + Zone: args.Zone, + SnapshotID: snapshot.ID, + }) + if err != nil { + return nil, err + } } } } - } - return runnerRes, nil - }) + return runnerRes, nil + }, + ) return c } diff --git a/internal/namespaces/instance/v1/custom_image_test.go b/internal/namespaces/instance/v1/custom_image_test.go index 43c76ac478..8a373793e8 100644 --- a/internal/namespaces/instance/v1/custom_image_test.go +++ b/internal/namespaces/instance/v1/custom_image_test.go @@ -14,8 +14,14 @@ import ( func Test_ImageCreate(t *testing.T) { t.Run("Create simple image", core.Test(&core.TestConfig{ BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true image=ubuntu-jammy root-volume=l:20G")), - core.ExecStoreBeforeCmd("Snapshot", `scw instance snapshot create volume-id={{ (index .Server.Volumes "0").ID }}`), + core.ExecStoreBeforeCmd( + "Server", + testServerCommand("stopped=true image=ubuntu-jammy root-volume=l:20G"), + ), + core.ExecStoreBeforeCmd( + "Snapshot", + `scw instance snapshot create volume-id={{ (index .Server.Volumes "0").ID }}`, + ), ), Commands: instance.GetCommands(), Cmd: "scw instance image create snapshot-id={{ .Snapshot.Snapshot.ID }} arch=x86_64", @@ -33,9 +39,18 @@ func Test_ImageCreate(t *testing.T) { t.Run("Use additional snapshots", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Server", "scw instance server create type=DEV1-S ip=none image=ubuntu_focal root-volume=local:10GB additional-volumes.0=local:10GB -w"), - core.ExecStoreBeforeCmd("SnapshotA", `scw instance snapshot create -w name=cli-test-image-create-snapshotA volume-id={{ (index .Server.Volumes "0").ID }}`), - core.ExecStoreBeforeCmd("SnapshotB", `scw instance snapshot create -w name=cli-test-image-create-snapshotB volume-id={{ (index .Server.Volumes "1").ID }}`), + core.ExecStoreBeforeCmd( + "Server", + "scw instance server create type=DEV1-S ip=none image=ubuntu_focal root-volume=local:10GB additional-volumes.0=local:10GB -w", + ), + core.ExecStoreBeforeCmd( + "SnapshotA", + `scw instance snapshot create -w name=cli-test-image-create-snapshotA volume-id={{ (index .Server.Volumes "0").ID }}`, + ), + core.ExecStoreBeforeCmd( + "SnapshotB", + `scw instance snapshot create -w name=cli-test-image-create-snapshotB volume-id={{ (index .Server.Volumes "1").ID }}`, + ), ), Cmd: "scw instance image create snapshot-id={{ .SnapshotA.ID }} extra-volumes.0.id={{ .SnapshotB.ID }} arch=x86_64", Check: core.TestCheckCombine( @@ -63,7 +78,11 @@ func Test_ImageDelete(t *testing.T) { t.Helper() // Assert snapshot are deleted with the image api := instanceSDK.NewAPI(ctx.Client) - snapshot := testhelpers.MapValue[*instanceSDK.CreateSnapshotResponse](t, ctx.Meta, "Snapshot") + snapshot := testhelpers.MapValue[*instanceSDK.CreateSnapshotResponse]( + t, + ctx.Meta, + "Snapshot", + ) _, err := api.GetSnapshot(&instanceSDK.GetSnapshotRequest{ SnapshotID: snapshot.Snapshot.ID, @@ -77,14 +96,25 @@ func Test_ImageDelete(t *testing.T) { func createImage(metaKey string) core.BeforeFunc { return core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true image=ubuntu-jammy root-volume=l:20G")), - core.ExecStoreBeforeCmd("Snapshot", `scw instance snapshot create volume-id={{ (index .Server.Volumes "0").ID }}`), - core.ExecStoreBeforeCmd(metaKey, `scw instance image create snapshot-id={{ .Snapshot.Snapshot.ID }} arch=x86_64`), + core.ExecStoreBeforeCmd( + "Server", + testServerCommand("stopped=true image=ubuntu-jammy root-volume=l:20G"), + ), + core.ExecStoreBeforeCmd( + "Snapshot", + `scw instance snapshot create volume-id={{ (index .Server.Volumes "0").ID }}`, + ), + core.ExecStoreBeforeCmd( + metaKey, + `scw instance image create snapshot-id={{ .Snapshot.Snapshot.ID }} arch=x86_64`, + ), ) } func deleteImage(metaKey string) core.AfterFunc { - return core.ExecAfterCmd(`scw instance image delete {{ .` + metaKey + `.Image.ID }} with-snapshots=true`) + return core.ExecAfterCmd( + `scw instance image delete {{ .` + metaKey + `.Image.ID }} with-snapshots=true`, + ) } func Test_ImageList(t *testing.T) { @@ -142,7 +172,10 @@ func Test_ImageUpdate(t *testing.T) { t.Run("Add extra volume", core.Test(&core.TestConfig{ BeforeFunc: core.BeforeFuncCombine( createVolume("Volume", 20, instanceSDK.VolumeVolumeTypeBSSD), - core.ExecStoreBeforeCmd("SnapshotVol", `scw instance snapshot create -w name=snapVol volume-id={{ .Volume.ID }}`), + core.ExecStoreBeforeCmd( + "SnapshotVol", + `scw instance snapshot create -w name=snapVol volume-id={{ .Volume.ID }}`, + ), createImage("ImageExtraVol"), ), Commands: instance.GetCommands(), @@ -151,7 +184,11 @@ func Test_ImageUpdate(t *testing.T) { func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() assert.NotNil(t, ctx.Result) - assert.Equal(t, "snapVol", ctx.Result.(*instanceSDK.UpdateImageResponse).Image.ExtraVolumes["1"].Name) + assert.Equal( + t, + "snapVol", + ctx.Result.(*instanceSDK.UpdateImageResponse).Image.ExtraVolumes["1"].Name, + ) }, core.TestCheckGolden(), core.TestCheckExitCode(0), diff --git a/internal/namespaces/instance/v1/custom_ip.go b/internal/namespaces/instance/v1/custom_ip.go index 12fc13bf29..deff572134 100644 --- a/internal/namespaces/instance/v1/custom_ip.go +++ b/internal/namespaces/instance/v1/custom_ip.go @@ -27,18 +27,20 @@ func ipCreateBuilder(c *core.Command) *core.Command { c.ArgsType = reflect.TypeOf(customCreateIPRequest{}) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customCreateIPRequest) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customCreateIPRequest) - if args.CreateIPRequest == nil { - args.CreateIPRequest = &instance.CreateIPRequest{} - } - request := args.CreateIPRequest - request.Organization = args.OrganizationID - request.Project = args.ProjectID + if args.CreateIPRequest == nil { + args.CreateIPRequest = &instance.CreateIPRequest{} + } + request := args.CreateIPRequest + request.Organization = args.OrganizationID + request.Project = args.ProjectID - return runner(ctx, request) - }) + return runner(ctx, request) + }, + ) return c } @@ -55,18 +57,20 @@ func ipListBuilder(c *core.Command) *core.Command { c.ArgsType = reflect.TypeOf(customListIPsRequest{}) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customListIPsRequest) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customListIPsRequest) - if args.ListIPsRequest == nil { - args.ListIPsRequest = &instance.ListIPsRequest{} - } - request := args.ListIPsRequest - request.Organization = args.OrganizationID - request.Project = args.ProjectID + if args.ListIPsRequest == nil { + args.ListIPsRequest = &instance.ListIPsRequest{} + } + request := args.ListIPsRequest + request.Organization = args.OrganizationID + request.Project = args.ProjectID - return runner(ctx, request) - }) + return runner(ctx, request) + }, + ) return c } @@ -158,7 +162,10 @@ func ipDetachCommand() *core.Command { } ipID = res.IP.ID default: - return nil, fmt.Errorf(`invalid IP "%s", should be either an IP address ID or a reserved flexible IP address`, args.IP) + return nil, fmt.Errorf( + `invalid IP "%s", should be either an IP address ID or a reserved flexible IP address`, + args.IP, + ) } return api.UpdateIP(&instance.UpdateIPRequest{ diff --git a/internal/namespaces/instance/v1/custom_ip_test.go b/internal/namespaces/instance/v1/custom_ip_test.go index d1a2da8a34..bb6e7dacab 100644 --- a/internal/namespaces/instance/v1/custom_ip_test.go +++ b/internal/namespaces/instance/v1/custom_ip_test.go @@ -11,7 +11,10 @@ func Test_IPAttach(t *testing.T) { t.Run("With UUID", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Server", "scw instance server create type=DEV1-S stopped=true ip=none"), + core.ExecStoreBeforeCmd( + "Server", + "scw instance server create type=DEV1-S stopped=true ip=none", + ), createIP("Ip"), ), Cmd: "scw instance ip attach {{ .Ip.Address }} server-id={{ .Server.ID }}", @@ -28,7 +31,10 @@ func Test_IPAttach(t *testing.T) { t.Run("With IP", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Server", "scw instance server create type=DEV1-S stopped=true ip=none"), + core.ExecStoreBeforeCmd( + "Server", + "scw instance server create type=DEV1-S stopped=true ip=none", + ), createIP("Ip"), ), Cmd: "scw instance ip attach {{ .Ip.Address }} server-id={{ .Server.ID }}", @@ -47,9 +53,14 @@ func Test_IPDetach(t *testing.T) { t.Run("With UUID", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Server", "scw instance server create type=DEV1-S stopped=true ip=none"), + core.ExecStoreBeforeCmd( + "Server", + "scw instance server create type=DEV1-S stopped=true ip=none", + ), createIP("Ip"), - core.ExecBeforeCmd("scw instance ip attach {{ .Ip.Address }} server-id={{ .Server.ID }}"), + core.ExecBeforeCmd( + "scw instance ip attach {{ .Ip.Address }} server-id={{ .Server.ID }}", + ), ), Cmd: "scw instance ip detach {{ .Ip.ID }}", Check: core.TestCheckCombine( @@ -66,9 +77,14 @@ func Test_IPDetach(t *testing.T) { t.Run("With IP", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Server", "scw instance server create type=DEV1-S stopped=true ip=none"), + core.ExecStoreBeforeCmd( + "Server", + "scw instance server create type=DEV1-S stopped=true ip=none", + ), createIP("Ip"), - core.ExecBeforeCmd("scw instance ip attach {{ .Ip.Address }} server-id={{ .Server.ID }}"), + core.ExecBeforeCmd( + "scw instance ip attach {{ .Ip.Address }} server-id={{ .Server.ID }}", + ), ), Cmd: "scw instance ip detach {{ .Ip.Address }}", Check: core.TestCheckCombine( diff --git a/internal/namespaces/instance/v1/custom_placement_group.go b/internal/namespaces/instance/v1/custom_placement_group.go index 5a90301d4e..119ce899aa 100644 --- a/internal/namespaces/instance/v1/custom_placement_group.go +++ b/internal/namespaces/instance/v1/custom_placement_group.go @@ -23,10 +23,12 @@ func placementGroupGetBuilder(c *core.Command) *core.Command { return nil, err } - placementGroupServersResponse, err := api.GetPlacementGroupServers(&instance.GetPlacementGroupServersRequest{ - Zone: req.Zone, - PlacementGroupID: req.PlacementGroupID, - }) + placementGroupServersResponse, err := api.GetPlacementGroupServers( + &instance.GetPlacementGroupServersRequest{ + Zone: req.Zone, + PlacementGroupID: req.PlacementGroupID, + }, + ) if err != nil { return nil, err } @@ -62,19 +64,21 @@ func placementGroupCreateBuilder(c *core.Command) *core.Command { c.ArgsType = reflect.TypeOf(customCreatePlacementGroupRequest{}) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customCreatePlacementGroupRequest) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customCreatePlacementGroupRequest) - if args.CreatePlacementGroupRequest == nil { - args.CreatePlacementGroupRequest = &instance.CreatePlacementGroupRequest{} - } + if args.CreatePlacementGroupRequest == nil { + args.CreatePlacementGroupRequest = &instance.CreatePlacementGroupRequest{} + } - request := args.CreatePlacementGroupRequest - request.Organization = args.OrganizationID - request.Project = args.ProjectID + request := args.CreatePlacementGroupRequest + request.Organization = args.OrganizationID + request.Project = args.ProjectID - return runner(ctx, request) - }) + return runner(ctx, request) + }, + ) return c } @@ -91,19 +95,21 @@ func placementGroupListBuilder(c *core.Command) *core.Command { c.ArgsType = reflect.TypeOf(customListPlacementGroupsRequest{}) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customListPlacementGroupsRequest) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customListPlacementGroupsRequest) - if args.ListPlacementGroupsRequest == nil { - args.ListPlacementGroupsRequest = &instance.ListPlacementGroupsRequest{} - } + if args.ListPlacementGroupsRequest == nil { + args.ListPlacementGroupsRequest = &instance.ListPlacementGroupsRequest{} + } - request := args.ListPlacementGroupsRequest - request.Organization = args.OrganizationID - request.Project = args.ProjectID + request := args.ListPlacementGroupsRequest + request.Organization = args.OrganizationID + request.Project = args.ProjectID - return runner(ctx, request) - }) + return runner(ctx, request) + }, + ) return c } diff --git a/internal/namespaces/instance/v1/custom_placement_group_test.go b/internal/namespaces/instance/v1/custom_placement_group_test.go index a12883f355..d050f56075 100644 --- a/internal/namespaces/instance/v1/custom_placement_group_test.go +++ b/internal/namespaces/instance/v1/custom_placement_group_test.go @@ -11,7 +11,10 @@ func Test_GetPlacementGroup(t *testing.T) { t.Run("simple", core.Test(&core.TestConfig{ BeforeFunc: core.BeforeFuncCombine( core.ExecStoreBeforeCmd("PlacementGroup", "scw instance placement-group create"), - core.ExecStoreBeforeCmd("ServerA", "scw instance server create type=DEV1-S image=ubuntu_jammy ip=none stopped=true placement-group-id={{ .PlacementGroup.PlacementGroup.ID }}"), + core.ExecStoreBeforeCmd( + "ServerA", + "scw instance server create type=DEV1-S image=ubuntu_jammy ip=none stopped=true placement-group-id={{ .PlacementGroup.PlacementGroup.ID }}", + ), ), Commands: instance.GetCommands(), Cmd: "scw instance placement-group get {{ .PlacementGroup.PlacementGroup.ID }}", @@ -19,7 +22,9 @@ func Test_GetPlacementGroup(t *testing.T) { core.TestCheckGolden(), ), AfterFunc: core.AfterFuncCombine( - core.ExecAfterCmd("scw instance placement-group delete {{ .PlacementGroup.PlacementGroup.ID }}"), + core.ExecAfterCmd( + "scw instance placement-group delete {{ .PlacementGroup.PlacementGroup.ID }}", + ), core.ExecAfterCmd("scw instance server delete {{ .ServerA.ID }}"), ), })) diff --git a/internal/namespaces/instance/v1/custom_security_group.go b/internal/namespaces/instance/v1/custom_security_group.go index 2670158958..e17bbcee2e 100644 --- a/internal/namespaces/instance/v1/custom_security_group.go +++ b/internal/namespaces/instance/v1/custom_security_group.go @@ -151,13 +151,25 @@ func (sg *customSecurityGroupResponse) MarshalHuman() (out string, err error) { if err != nil { return "", err } - inboundRulesView := b("Inbound Rules (default policy ") + b(defaultInboundPolicy) + b("):\n") + inboundRulesContent + inboundRulesView := b( + "Inbound Rules (default policy ", + ) + b( + defaultInboundPolicy, + ) + b( + "):\n", + ) + inboundRulesContent outboundRulesContent, err := human.Marshal(outboundRules, nil) if err != nil { return "", err } - outboundRulesView := b("Outbound Rules (default policy ") + b(defaultOutboundPolicy) + b("):\n") + outboundRulesContent + outboundRulesView := b( + "Outbound Rules (default policy ", + ) + b( + defaultOutboundPolicy, + ) + b( + "):\n", + ) + outboundRulesContent serversContent, err := human.Marshal(sg.Servers, nil) if err != nil { @@ -195,19 +207,21 @@ func securityGroupCreateBuilder(c *core.Command) *core.Command { c.ArgsType = reflect.TypeOf(customCreateSecurityGroupRequest{}) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customCreateSecurityGroupRequest) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customCreateSecurityGroupRequest) - if args.CreateSecurityGroupRequest == nil { - args.CreateSecurityGroupRequest = &instance.CreateSecurityGroupRequest{} - } + if args.CreateSecurityGroupRequest == nil { + args.CreateSecurityGroupRequest = &instance.CreateSecurityGroupRequest{} + } - request := args.CreateSecurityGroupRequest - request.Organization = args.OrganizationID - request.Project = args.ProjectID + request := args.CreateSecurityGroupRequest + request.Organization = args.OrganizationID + request.Project = args.ProjectID - return runner(ctx, request) - }) + return runner(ctx, request) + }, + ) return c } @@ -223,10 +237,13 @@ func securityGroupGetBuilder(c *core.Command) *core.Command { return nil, err } - securityGroupRules, err := api.ListSecurityGroupRules(&instance.ListSecurityGroupRulesRequest{ - Zone: req.Zone, - SecurityGroupID: securityGroup.SecurityGroup.ID, - }, scw.WithAllPages()) + securityGroupRules, err := api.ListSecurityGroupRules( + &instance.ListSecurityGroupRulesRequest{ + Zone: req.Zone, + SecurityGroupID: securityGroup.SecurityGroup.ID, + }, + scw.WithAllPages(), + ) if err != nil { return nil, err } @@ -252,60 +269,64 @@ func securityGroupListBuilder(c *core.Command) *core.Command { c.ArgsType = reflect.TypeOf(customListSecurityGroupsRequest{}) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customListSecurityGroupsRequest) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customListSecurityGroupsRequest) - if args.ListSecurityGroupsRequest == nil { - args.ListSecurityGroupsRequest = &instance.ListSecurityGroupsRequest{} - } + if args.ListSecurityGroupsRequest == nil { + args.ListSecurityGroupsRequest = &instance.ListSecurityGroupsRequest{} + } - request := args.ListSecurityGroupsRequest - request.Organization = args.OrganizationID - request.Project = args.ProjectID + request := args.ListSecurityGroupsRequest + request.Organization = args.OrganizationID + request.Project = args.ProjectID - return runner(ctx, request) - }) + return runner(ctx, request) + }, + ) return c } func securityGroupDeleteBuilder(c *core.Command) *core.Command { - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { - res, originalErr := runner(ctx, argsI) - if originalErr == nil { - return res, nil - } + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + res, originalErr := runner(ctx, argsI) + if originalErr == nil { + return res, nil + } - if strings.HasSuffix(originalErr.Error(), "group is in use. you cannot delete it.") { - req := argsI.(*instance.DeleteSecurityGroupRequest) - api := instance.NewAPI(core.ExtractClient(ctx)) + if strings.HasSuffix(originalErr.Error(), "group is in use. you cannot delete it.") { + req := argsI.(*instance.DeleteSecurityGroupRequest) + api := instance.NewAPI(core.ExtractClient(ctx)) - newError := &core.CliError{ - Err: errors.New("cannot delete security-group currently in use"), - } + newError := &core.CliError{ + Err: errors.New("cannot delete security-group currently in use"), + } - // Get security-group. - sg, err := api.GetSecurityGroup(&instance.GetSecurityGroupRequest{ - SecurityGroupID: req.SecurityGroupID, - }) - if err != nil { - // Ignore API error and return a minimal error. - return nil, newError - } + // Get security-group. + sg, err := api.GetSecurityGroup(&instance.GetSecurityGroupRequest{ + SecurityGroupID: req.SecurityGroupID, + }) + if err != nil { + // Ignore API error and return a minimal error. + return nil, newError + } - // Create detail message. - hint := "Attach all these instances to another security-group before deleting this one:" - for _, s := range sg.SecurityGroup.Servers { - hint += "\nscw instance server update " + s.ID + " security-group.id=$NEW_SECURITY_GROUP_ID" - } + // Create detail message. + hint := "Attach all these instances to another security-group before deleting this one:" + for _, s := range sg.SecurityGroup.Servers { + hint += "\nscw instance server update " + s.ID + " security-group.id=$NEW_SECURITY_GROUP_ID" + } - newError.Hint = hint + newError.Hint = hint - return nil, newError - } + return nil, newError + } - return nil, originalErr - }) + return nil, originalErr + }, + ) return c } diff --git a/internal/namespaces/instance/v1/custom_server.go b/internal/namespaces/instance/v1/custom_server.go index 5866885936..5ed2f20e90 100644 --- a/internal/namespaces/instance/v1/custom_server.go +++ b/internal/namespaces/instance/v1/custom_server.go @@ -34,8 +34,11 @@ const ( // serverStateMarshalSpecs allows to override the displayed instance.ServerState. var ( serverStateMarshalSpecs = human.EnumMarshalSpecs{ - instance.ServerStateRunning: &human.EnumMarshalSpec{Attribute: color.FgGreen}, - instance.ServerStateStopped: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "archived"}, + instance.ServerStateRunning: &human.EnumMarshalSpec{Attribute: color.FgGreen}, + instance.ServerStateStopped: &human.EnumMarshalSpec{ + Attribute: color.Faint, + Value: "archived", + }, instance.ServerStateStoppedInPlace: &human.EnumMarshalSpec{Attribute: color.Faint}, instance.ServerStateStarting: &human.EnumMarshalSpec{Attribute: color.FgBlue}, instance.ServerStateStopping: &human.EnumMarshalSpec{Attribute: color.FgBlue}, @@ -159,19 +162,21 @@ func serverListBuilder(c *core.Command) *core.Command { c.ArgsType = reflect.TypeOf(customListServersRequest{}) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customListServersRequest) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customListServersRequest) - if args.ListServersRequest == nil { - args.ListServersRequest = &instance.ListServersRequest{} - } + if args.ListServersRequest == nil { + args.ListServersRequest = &instance.ListServersRequest{} + } - request := args.ListServersRequest - request.Organization = args.OrganizationID - request.Project = args.ProjectID + request := args.ListServersRequest + request.Organization = args.OrganizationID + request.Project = args.ProjectID - return runner(ctx, request) - }) + return runner(ctx, request) + }, + ) return c } @@ -573,7 +578,10 @@ func serverAttachIPCommand() *core.Command { } ipID = res.IP.ID default: - return nil, fmt.Errorf(`invalid IP "%s", should be either an IP address ID or a reserved flexible IP address`, args.IP) + return nil, fmt.Errorf( + `invalid IP "%s", should be either an IP address ID or a reserved flexible IP address`, + args.IP, + ) } _, err = api.UpdateIP(&instance.UpdateIPRequest{ @@ -630,7 +638,9 @@ func serverDetachIPCommand() *core.Command { client := core.ExtractClient(ctx) api := instance.NewAPI(client) - serverResponse, err := api.GetServer(&instance.GetServerRequest{ServerID: args.ServerID}) + serverResponse, err := api.GetServer( + &instance.GetServerRequest{ServerID: args.ServerID}, + ) if err != nil { return nil, err } @@ -684,12 +694,13 @@ func serverWaitCommand() *core.Command { Run: func(ctx context.Context, argsI interface{}) (i interface{}, err error) { args := argsI.(*serverWaitRequest) - return instance.NewAPI(core.ExtractClient(ctx)).WaitForServer(&instance.WaitForServerRequest{ - Zone: args.Zone, - ServerID: args.ServerID, - Timeout: scw.TimeDurationPtr(args.Timeout), - RetryInterval: core.DefaultRetryInterval, - }) + return instance.NewAPI(core.ExtractClient(ctx)). + WaitForServer(&instance.WaitForServerRequest{ + Zone: args.Zone, + ServerID: args.ServerID, + Timeout: scw.TimeDurationPtr(args.Timeout), + RetryInterval: core.DefaultRetryInterval, + }) }, ArgSpecs: core.ArgSpecs{ core.WaitTimeoutArgSpec(serverActionTimeout), diff --git a/internal/namespaces/instance/v1/custom_server_action.go b/internal/namespaces/instance/v1/custom_server_action.go index 8933321125..d99bfb6713 100644 --- a/internal/namespaces/instance/v1/custom_server_action.go +++ b/internal/namespaces/instance/v1/custom_server_action.go @@ -365,7 +365,11 @@ func serverTerminateCommand() *core.Command { return nil, err } - deleteBlockVolumes, err := shouldDeleteBlockVolumes(ctx, server, terminateServerArgs.WithBlock) + deleteBlockVolumes, err := shouldDeleteBlockVolumes( + ctx, + server, + terminateServerArgs.WithBlock, + ) if err != nil { return nil, err } @@ -400,7 +404,8 @@ func serverTerminateCommand() *core.Command { return nil, err } - if terminateServerArgs.WithIP && server.Server.PublicIP != nil && !server.Server.PublicIP.Dynamic { + if terminateServerArgs.WithIP && server.Server.PublicIP != nil && + !server.Server.PublicIP.Dynamic { err = api.DeleteIP(&instance.DeleteIPRequest{ Zone: terminateServerArgs.Zone, IP: server.Server.PublicIP.ID, @@ -408,7 +413,10 @@ func serverTerminateCommand() *core.Command { if err != nil { return nil, err } - _, _ = interactive.Printf("successfully deleted ip %s\n", server.Server.PublicIP.Address.String()) + _, _ = interactive.Printf( + "successfully deleted ip %s\n", + server.Server.PublicIP.Address.String(), + ) } return &core.SuccessResult{ @@ -418,7 +426,11 @@ func serverTerminateCommand() *core.Command { } } -func shouldDeleteBlockVolumes(ctx context.Context, server *instance.GetServerResponse, terminateWithBlock withBlock) (bool, error) { +func shouldDeleteBlockVolumes( + ctx context.Context, + server *instance.GetServerResponse, + terminateWithBlock withBlock, +) (bool, error) { switch terminateWithBlock { case withBlockTrue: return true, nil @@ -472,18 +484,21 @@ func getRunServerAction(action instance.ServerAction) core.CommandRunner { Action: action, }) - return &core.SuccessResult{Message: fmt.Sprintf("%s successfully started for the server", action)}, err + return &core.SuccessResult{ + Message: fmt.Sprintf("%s successfully started for the server", action), + }, err } } func waitForServerFunc() core.WaitFunc { return func(ctx context.Context, argsI, _ interface{}) (interface{}, error) { - return instance.NewAPI(core.ExtractClient(ctx)).WaitForServer(&instance.WaitForServerRequest{ - Zone: argsI.(*instanceUniqueActionRequest).Zone, - ServerID: argsI.(*instanceUniqueActionRequest).ServerID, - Timeout: scw.TimeDurationPtr(serverActionTimeout), - RetryInterval: core.DefaultRetryInterval, - }) + return instance.NewAPI(core.ExtractClient(ctx)). + WaitForServer(&instance.WaitForServerRequest{ + Zone: argsI.(*instanceUniqueActionRequest).Zone, + ServerID: argsI.(*instanceUniqueActionRequest).ServerID, + Timeout: scw.TimeDurationPtr(serverActionTimeout), + RetryInterval: core.DefaultRetryInterval, + }) } } @@ -510,18 +525,24 @@ func serverActionCommand() *core.Command { Run: func(ctx context.Context, argsI interface{}) (interface{}, error) { args := argsI.(*instanceActionRequest) - return getRunServerAction(instance.ServerAction(args.Action))(ctx, &instanceUniqueActionRequest{ - Zone: args.Zone, - ServerID: args.ServerID, - }) + return getRunServerAction( + instance.ServerAction(args.Action), + )( + ctx, + &instanceUniqueActionRequest{ + Zone: args.Zone, + ServerID: args.ServerID, + }, + ) }, WaitFunc: func(ctx context.Context, argsI, _ interface{}) (interface{}, error) { - return instance.NewAPI(core.ExtractClient(ctx)).WaitForServer(&instance.WaitForServerRequest{ - Zone: argsI.(*instanceActionRequest).Zone, - ServerID: argsI.(*instanceActionRequest).ServerID, - Timeout: scw.TimeDurationPtr(serverActionTimeout), - RetryInterval: core.DefaultRetryInterval, - }) + return instance.NewAPI(core.ExtractClient(ctx)). + WaitForServer(&instance.WaitForServerRequest{ + Zone: argsI.(*instanceActionRequest).Zone, + ServerID: argsI.(*instanceActionRequest).ServerID, + Timeout: scw.TimeDurationPtr(serverActionTimeout), + RetryInterval: core.DefaultRetryInterval, + }) }, ArgSpecs: argSpecs, Examples: []*core.Example{ diff --git a/internal/namespaces/instance/v1/custom_server_action_test.go b/internal/namespaces/instance/v1/custom_server_action_test.go index d39257386a..0d36669571 100644 --- a/internal/namespaces/instance/v1/custom_server_action_test.go +++ b/internal/namespaces/instance/v1/custom_server_action_test.go @@ -20,9 +20,12 @@ func Test_ServerTerminate(t *testing.T) { interactive.IsInteractive = true t.Run("without IP", core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("image=ubuntu-jammy ip=new -w")), - Cmd: `scw instance server terminate {{ .Server.ID }}`, + Commands: instance.GetCommands(), + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand("image=ubuntu-jammy ip=new -w"), + ), + Cmd: `scw instance server terminate {{ .Server.ID }}`, Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), @@ -37,14 +40,19 @@ func Test_ServerTerminate(t *testing.T) { assert.NoError(t, err) }, ), - AfterFunc: core.ExecAfterCmd(`scw instance ip delete {{ index .Server.PublicIP.ID }}`), + AfterFunc: core.ExecAfterCmd( + `scw instance ip delete {{ index .Server.PublicIP.ID }}`, + ), DisableParallel: true, })) t.Run("with IP", core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("image=ubuntu-jammy ip=new -w")), - Cmd: `scw instance server terminate {{ .Server.ID }} with-ip=true`, + Commands: instance.GetCommands(), + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand("image=ubuntu-jammy ip=new -w"), + ), + Cmd: `scw instance server terminate {{ .Server.ID }} with-ip=true`, Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), @@ -68,23 +76,31 @@ func Test_ServerTerminate(t *testing.T) { instance.GetCommands(), block.GetCommands(), ), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("image=ubuntu-jammy additional-volumes.0=block:10G -w")), - Cmd: `scw instance server terminate {{ .Server.ID }} with-ip=true with-block=false`, + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand("image=ubuntu-jammy additional-volumes.0=block:10G -w"), + ), + Cmd: `scw instance server terminate {{ .Server.ID }} with-ip=true with-block=false`, Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), ), AfterFunc: core.AfterFuncCombine( - core.ExecAfterCmd(`scw block volume wait terminal-status=available {{ (index .Server.Volumes "1").ID }}`), + core.ExecAfterCmd( + `scw block volume wait terminal-status=available {{ (index .Server.Volumes "1").ID }}`, + ), core.ExecAfterCmd(`scw block volume delete {{ (index .Server.Volumes "1").ID }}`), ), DisableParallel: true, })) t.Run("with block", core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("image=ubuntu-jammy additional-volumes.0=block:10G -w")), - Cmd: `scw instance server terminate {{ .Server.ID }} with-ip=true with-block=true -w`, + Commands: instance.GetCommands(), + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand("image=ubuntu-jammy additional-volumes.0=block:10G -w"), + ), + Cmd: `scw instance server terminate {{ .Server.ID }} with-ip=true with-block=true -w`, Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), @@ -111,39 +127,58 @@ func Test_ServerTerminate(t *testing.T) { // since they are using the interactive print func Test_ServerBackup(t *testing.T) { t.Run("simple", core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true image=ubuntu-jammy")), - Cmd: `scw instance server backup {{ .Server.ID }} name=backup`, + Commands: instance.GetCommands(), + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand("stopped=true image=ubuntu-jammy"), + ), + Cmd: `scw instance server backup {{ .Server.ID }} name=backup`, Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), ), AfterFunc: core.AfterFuncCombine( - core.ExecAfterCmd("scw instance image delete {{ .CmdResult.Image.ID }} with-snapshots=true"), - core.ExecAfterCmd("scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=local"), + core.ExecAfterCmd( + "scw instance image delete {{ .CmdResult.Image.ID }} with-snapshots=true", + ), + core.ExecAfterCmd( + "scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=local", + ), ), })) t.Run("With SBS volumes", core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("root-volume=sbs:20G additional-volumes.0=sbs:10G additional-volumes.1=sbs:15G stopped=true image=ubuntu-jammy")), - Cmd: `scw instance server backup {{ .Server.ID }} name=backup`, + Commands: instance.GetCommands(), + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand( + "root-volume=sbs:20G additional-volumes.0=sbs:10G additional-volumes.1=sbs:15G stopped=true image=ubuntu-jammy", + ), + ), + Cmd: `scw instance server backup {{ .Server.ID }} name=backup`, Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), ), AfterFunc: core.AfterFuncCombine( - core.ExecAfterCmd("scw instance image delete {{ .CmdResult.Image.ID }} with-snapshots=true"), - core.ExecAfterCmd("scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=local"), + core.ExecAfterCmd( + "scw instance image delete {{ .CmdResult.Image.ID }} with-snapshots=true", + ), + core.ExecAfterCmd( + "scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=local", + ), ), })) } func Test_ServerAction(t *testing.T) { t.Run("manual poweron", core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true image=ubuntu_jammy")), - Cmd: `scw instance server action {{ .Server.ID }} action=poweron --wait`, + Commands: instance.GetCommands(), + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand("stopped=true image=ubuntu_jammy"), + ), + Cmd: `scw instance server action {{ .Server.ID }} action=poweron --wait`, Check: core.TestCheckCombine( core.TestCheckExitCode(0), func(t *testing.T, ctx *core.CheckFuncCtx) { @@ -160,7 +195,9 @@ func Test_ServerAction(t *testing.T) { core.TestCheckGolden(), ), AfterFunc: core.AfterFuncCombine( - core.ExecAfterCmd("scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=local force-shutdown=true"), + core.ExecAfterCmd( + "scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=local force-shutdown=true", + ), ), })) } diff --git a/internal/namespaces/instance/v1/custom_server_create.go b/internal/namespaces/instance/v1/custom_server_create.go index 51c4209e5b..015c65806a 100644 --- a/internal/namespaces/instance/v1/custom_server_create.go +++ b/internal/namespaces/instance/v1/custom_server_create.go @@ -123,10 +123,14 @@ func serverCreateCommand() *core.Command { CanLoadFile: true, }, { - Name: "boot-type", - Short: "The boot type to use, if empty the local boot will be used. Will be overwritten to bootscript if bootscript-id is set.", - Default: core.DefaultValueSetter(instance.BootTypeLocal.String()), - EnumValues: []string{instance.BootTypeLocal.String(), instance.BootTypeBootscript.String(), instance.BootTypeRescue.String()}, + Name: "boot-type", + Short: "The boot type to use, if empty the local boot will be used. Will be overwritten to bootscript if bootscript-id is set.", + Default: core.DefaultValueSetter(instance.BootTypeLocal.String()), + EnumValues: []string{ + instance.BootTypeLocal.String(), + instance.BootTypeBootscript.String(), + instance.BootTypeRescue.String(), + }, }, { Name: "admin-password-encryption-ssh-key-id", @@ -187,12 +191,13 @@ scw instance server create image=ubuntu_focal ip=$ip`, func instanceWaitServerCreateRun() core.WaitFunc { return func(ctx context.Context, argsI, respI interface{}) (interface{}, error) { - return instance.NewAPI(core.ExtractClient(ctx)).WaitForServer(&instance.WaitForServerRequest{ - Zone: argsI.(*instanceCreateServerRequest).Zone, - ServerID: respI.(*instance.Server).ID, - Timeout: scw.TimeDurationPtr(serverActionTimeout), - RetryInterval: core.DefaultRetryInterval, - }) + return instance.NewAPI(core.ExtractClient(ctx)). + WaitForServer(&instance.WaitForServerRequest{ + Zone: argsI.(*instanceCreateServerRequest).Zone, + ServerID: respI.(*instance.Server).ID, + Timeout: scw.TimeDurationPtr(serverActionTimeout), + RetryInterval: core.DefaultRetryInterval, + }) } } @@ -305,7 +310,10 @@ func instanceServerCreateRun(ctx context.Context, argsI interface{}) (i interfac Content: bytes.NewBufferString(args.CloudInit), }) if err != nil { - logger.Warningf("error while setting up your cloud-init metadata: %s. Note that the server is successfully created.", err) + logger.Warningf( + "error while setting up your cloud-init metadata: %s. Note that the server is successfully created.", + err, + ) } else { logger.Debugf("cloud-init set") } @@ -322,7 +330,10 @@ func instanceServerCreateRun(ctx context.Context, argsI interface{}) (i interfac Action: instance.ServerActionPoweron, }) if err != nil { - logger.Warningf("Cannot start the server: %s. Note that the server is successfully created.", err) + logger.Warningf( + "Cannot start the server: %s. Note that the server is successfully created.", + err, + ) } else { logger.Debugf("server started") } @@ -331,7 +342,10 @@ func instanceServerCreateRun(ctx context.Context, argsI interface{}) (i interfac return server, nil } -func addDefaultVolumes(serverType *instance.ServerType, volumes map[string]*instance.VolumeServerTemplate) map[string]*instance.VolumeServerTemplate { +func addDefaultVolumes( + serverType *instance.ServerType, + volumes map[string]*instance.VolumeServerTemplate, +) map[string]*instance.VolumeServerTemplate { needScratch := false hasScratch := false defaultVolumes := []*instance.VolumeServerTemplate(nil) @@ -371,13 +385,19 @@ func addDefaultVolumes(serverType *instance.ServerType, volumes map[string]*inst return volumes } -func validateImageServerTypeCompatibility(image *instance.Image, serverType *instance.ServerType, commercialType string) error { +func validateImageServerTypeCompatibility( + image *instance.Image, + serverType *instance.ServerType, + commercialType string, +) error { // An instance might not have any constraints on the local volume size if serverType.VolumesConstraint.MaxSize == 0 { return nil } - if image.RootVolume.VolumeType == instance.VolumeVolumeTypeLSSD && image.RootVolume.Size > serverType.VolumesConstraint.MaxSize { - return fmt.Errorf("image %s requires %s on root volume, but root volume is constrained between %s and %s on %s", + if image.RootVolume.VolumeType == instance.VolumeVolumeTypeLSSD && + image.RootVolume.Size > serverType.VolumesConstraint.MaxSize { + return fmt.Errorf( + "image %s requires %s on root volume, but root volume is constrained between %s and %s on %s", image.ID, humanize.Bytes(uint64(image.RootVolume.Size)), humanize.Bytes(uint64(serverType.VolumesConstraint.MinSize)), @@ -390,7 +410,12 @@ func validateImageServerTypeCompatibility(image *instance.Image, serverType *ins } // validateLocalVolumeSizes validates the total size of local volumes. -func validateLocalVolumeSizes(volumes map[string]*instance.VolumeServerTemplate, serverType *instance.ServerType, commercialType string, defaultRootVolumeSize scw.Size) error { +func validateLocalVolumeSizes( + volumes map[string]*instance.VolumeServerTemplate, + serverType *instance.ServerType, + commercialType string, + defaultRootVolumeSize scw.Size, +) error { // Calculate local volume total size. var localVolumeTotalSize scw.Size for _, volume := range volumes { @@ -410,22 +435,37 @@ func validateLocalVolumeSizes(volumes map[string]*instance.VolumeServerTemplate, localVolumeTotalSize += defaultRootVolumeSize // defaultRootVolumeSize may be used for a block volume } - if localVolumeTotalSize < volumeConstraint.MinSize || localVolumeTotalSize > volumeConstraint.MaxSize { + if localVolumeTotalSize < volumeConstraint.MinSize || + localVolumeTotalSize > volumeConstraint.MaxSize { minSize := humanize.Bytes(uint64(volumeConstraint.MinSize)) computedLocal := humanize.Bytes(uint64(localVolumeTotalSize)) if volumeConstraint.MinSize == volumeConstraint.MaxSize { - return fmt.Errorf("%s total local volume size must be equal to %s, got %s", commercialType, minSize, computedLocal) + return fmt.Errorf( + "%s total local volume size must be equal to %s, got %s", + commercialType, + minSize, + computedLocal, + ) } maxSize := humanize.Bytes(uint64(volumeConstraint.MaxSize)) - return fmt.Errorf("%s total local volume size must be between %s and %s, got %s", commercialType, minSize, maxSize, computedLocal) + return fmt.Errorf( + "%s total local volume size must be between %s and %s, got %s", + commercialType, + minSize, + maxSize, + computedLocal, + ) } return nil } -func validateRootVolume(imageRequiredSize scw.Size, rootVolume *instance.VolumeServerTemplate) error { +func validateRootVolume( + imageRequiredSize scw.Size, + rootVolume *instance.VolumeServerTemplate, +) error { if rootVolume == nil { return nil } @@ -438,14 +478,20 @@ func validateRootVolume(imageRequiredSize scw.Size, rootVolume *instance.VolumeS } if rootVolume.Size != nil && *rootVolume.Size < imageRequiredSize { - return fmt.Errorf("first volume size must be at least %s for this image", humanize.Bytes(uint64(imageRequiredSize))) + return fmt.Errorf( + "first volume size must be at least %s for this image", + humanize.Bytes(uint64(imageRequiredSize)), + ) } return nil } // sanitizeVolumeMap removes extra data for API validation. -func sanitizeVolumeMap(serverName string, volumes map[string]*instance.VolumeServerTemplate) map[string]*instance.VolumeServerTemplate { +func sanitizeVolumeMap( + serverName string, + volumes map[string]*instance.VolumeServerTemplate, +) map[string]*instance.VolumeServerTemplate { m := make(map[string]*instance.VolumeServerTemplate) for index, v := range volumes { @@ -486,7 +532,11 @@ func sanitizeVolumeMap(serverName string, volumes map[string]*instance.VolumeSer // Caching listImage response for shell completion var completeListImagesCache *marketplace.ListImagesResponse -func instanceServerCreateImageAutoCompleteFunc(ctx context.Context, prefix string, _ any) core.AutocompleteSuggestions { +func instanceServerCreateImageAutoCompleteFunc( + ctx context.Context, + prefix string, + _ any, +) core.AutocompleteSuggestions { suggestions := core.AutocompleteSuggestions(nil) client := core.ExtractClient(ctx) @@ -512,7 +562,11 @@ func instanceServerCreateImageAutoCompleteFunc(ctx context.Context, prefix strin } // getServerType is a util to get a instance.ServerType by its commercialType -func getServerType(apiInstance *instance.API, zone scw.Zone, commercialType string) *instance.ServerType { +func getServerType( + apiInstance *instance.API, + zone scw.Zone, + commercialType string, +) *instance.ServerType { serverType := (*instance.ServerType)(nil) serverTypesRes, err := apiInstance.ListServersTypes(&instance.ListServersTypesRequest{ diff --git a/internal/namespaces/instance/v1/custom_server_create_builder.go b/internal/namespaces/instance/v1/custom_server_create_builder.go index 1e1ca3c1d2..18510b5eb2 100644 --- a/internal/namespaces/instance/v1/custom_server_create_builder.go +++ b/internal/namespaces/instance/v1/custom_server_create_builder.go @@ -43,7 +43,12 @@ type ServerBuilder struct { // NewServerBuilder creates a new builder for a server with requested commercialType in given zone. // commercialType will be used to validate that added components are supported. -func NewServerBuilder(client *scw.Client, name string, zone scw.Zone, commercialType string) *ServerBuilder { +func NewServerBuilder( + client *scw.Client, + name string, + zone scw.Zone, + commercialType string, +) *ServerBuilder { sb := &ServerBuilder{ createReq: &instance.CreateServerRequest{ Name: name, @@ -106,7 +111,9 @@ func (sb *ServerBuilder) AddDynamicIPRequired(dynamicIPRequired *bool) *ServerBu return sb } -func (sb *ServerBuilder) AddAdminPasswordEncryptionSSHKeyID(adminPasswordEncryptionSSHKeyID *string) *ServerBuilder { +func (sb *ServerBuilder) AddAdminPasswordEncryptionSSHKeyID( + adminPasswordEncryptionSSHKeyID *string, +) *ServerBuilder { if adminPasswordEncryptionSSHKeyID != nil { sb.createReq.AdminPasswordEncryptionSSHKeyID = adminPasswordEncryptionSSHKeyID } @@ -145,12 +152,14 @@ func (sb *ServerBuilder) AddImage(image string) (*ServerBuilder, error) { case !validation.IsUUID(image): imageLabel := strings.ReplaceAll(image, "-", "_") - localImage, err := sb.apiMarketplace.GetLocalImageByLabel(&marketplace.GetLocalImageByLabelRequest{ - ImageLabel: imageLabel, - Zone: sb.createReq.Zone, - CommercialType: sb.createReq.CommercialType, - Type: sb.marketplaceImageType(), - }) + localImage, err := sb.apiMarketplace.GetLocalImageByLabel( + &marketplace.GetLocalImageByLabelRequest{ + ImageLabel: imageLabel, + Zone: sb.createReq.Zone, + CommercialType: sb.createReq.CommercialType, + Type: sb.marketplaceImageType(), + }, + ) if err != nil { return sb, err } @@ -222,7 +231,10 @@ func (sb *ServerBuilder) AddIP(ip string) (*ServerBuilder, error) { case ip == "none": sb.createReq.DynamicIPRequired = scw.BoolPtr(false) default: - return sb, fmt.Errorf(`invalid IP "%s", should be either 'new', 'ipv4', 'ipv6', 'both', 'dynamic', 'none', an IP address ID or a reserved flexible IP address`, ip) + return sb, fmt.Errorf( + `invalid IP "%s", should be either 'new', 'ipv4', 'ipv6', 'both', 'dynamic', 'none', an IP address ID or a reserved flexible IP address`, + ip, + ) } return sb, nil @@ -243,7 +255,10 @@ func (sb *ServerBuilder) addIPID(ipID string) *ServerBuilder { // More format details in buildVolumeTemplate function. // // Also add default volumes to server, ex: scratch storage for GPU servers -func (sb *ServerBuilder) AddVolumes(rootVolume string, additionalVolumes []string) (*ServerBuilder, error) { +func (sb *ServerBuilder) AddVolumes( + rootVolume string, + additionalVolumes []string, +) (*ServerBuilder, error) { if len(additionalVolumes) > 0 || rootVolume != "" { if rootVolume != "" { rootVolumeBuilder, err := NewVolumeBuilder(sb.createReq.Zone, rootVolume) @@ -417,7 +432,8 @@ func (sb *ServerBuilder) BuildPreCreationSetup() *PreServerCreationSetup { // Instance API does not support SBS volumes creation alongside the server, they must be created before then imported. func (sb *ServerBuilder) BuildPreCreationVolumesSetup(setup *PreServerCreationSetup) { for _, volume := range sb.volumes { - if volume.VolumeType != instance.VolumeVolumeTypeSbsVolume || volume.VolumeID != nil || volume.Size == nil { + if volume.VolumeType != instance.VolumeVolumeTypeSbsVolume || volume.VolumeID != nil || + volume.Size == nil { continue } @@ -584,7 +600,10 @@ func NewVolumeBuilder(zone scw.Zone, flagV string) (*VolumeBuilder, error) { } // buildSnapshotVolume builds the requested volume template to create a new volume from a snapshot -func (vb *VolumeBuilder) buildSnapshotVolume(api *instance.API, blockAPI *block.API) (*instance.VolumeServerTemplate, error) { +func (vb *VolumeBuilder) buildSnapshotVolume( + api *instance.API, + blockAPI *block.API, +) (*instance.VolumeServerTemplate, error) { if vb.SnapshotID == nil { return nil, errors.New("tried to build a volume from snapshot with an empty ID") } @@ -600,7 +619,11 @@ func (vb *VolumeBuilder) buildSnapshotVolume(api *instance.API, blockAPI *block. snapshotType := res.Snapshot.VolumeType if snapshotType != instance.VolumeVolumeTypeUnified && snapshotType != vb.VolumeType { - return nil, fmt.Errorf("snapshot of type %s not compatible with requested volume type %s", snapshotType, vb.VolumeType) + return nil, fmt.Errorf( + "snapshot of type %s not compatible with requested volume type %s", + snapshotType, + vb.VolumeType, + ) } return &instance.VolumeServerTemplate{ @@ -632,7 +655,10 @@ func (vb *VolumeBuilder) buildSnapshotVolume(api *instance.API, blockAPI *block. } // buildImportedVolume builds the requested volume template to import an existing volume -func (vb *VolumeBuilder) buildImportedVolume(api *instance.API, blockAPI *block.API) (*instance.VolumeServerTemplate, error) { +func (vb *VolumeBuilder) buildImportedVolume( + api *instance.API, + blockAPI *block.API, +) (*instance.VolumeServerTemplate, error) { if vb.VolumeID == nil { return nil, errors.New("tried to import a volume with an empty ID") } @@ -648,7 +674,11 @@ func (vb *VolumeBuilder) buildImportedVolume(api *instance.API, blockAPI *block. if res != nil { // Check that volume is not already attached to a server. if res.Volume.Server != nil { - return nil, fmt.Errorf("volume %s is already attached to %s server", res.Volume.ID, res.Volume.Server.ID) + return nil, fmt.Errorf( + "volume %s is already attached to %s server", + res.Volume.ID, + res.Volume.Server.ID, + ) } return &instance.VolumeServerTemplate{ @@ -671,7 +701,12 @@ func (vb *VolumeBuilder) buildImportedVolume(api *instance.API, blockAPI *block. } if len(blockRes.References) > 0 { - return nil, fmt.Errorf("volume %s is already attached to %s %s", blockRes.ID, blockRes.References[0].ProductResourceID, blockRes.References[0].ProductResourceType) + return nil, fmt.Errorf( + "volume %s is already attached to %s %s", + blockRes.ID, + blockRes.References[0].ProductResourceID, + blockRes.References[0].ProductResourceType, + ) } return &instance.VolumeServerTemplate{ @@ -689,7 +724,10 @@ func (vb *VolumeBuilder) buildNewVolume() (*instance.VolumeServerTemplate, error } // BuildVolumeServerTemplate builds the requested volume template to be used in a CreateServerRequest -func (vb *VolumeBuilder) BuildVolumeServerTemplate(apiInstance *instance.API, apiBlock *block.API) (*instance.VolumeServerTemplate, error) { +func (vb *VolumeBuilder) BuildVolumeServerTemplate( + apiInstance *instance.API, + apiBlock *block.API, +) (*instance.VolumeServerTemplate, error) { if vb.SnapshotID != nil { return vb.buildSnapshotVolume(apiInstance, apiBlock) } @@ -702,7 +740,11 @@ func (vb *VolumeBuilder) BuildVolumeServerTemplate(apiInstance *instance.API, ap } // ExecutePostCreationSetup executes requests that are required after volume creation. -func (vb *VolumeBuilder) ExecutePostCreationSetup(ctx context.Context, apiBlock *block.API, volumeID string) { +func (vb *VolumeBuilder) ExecutePostCreationSetup( + ctx context.Context, + apiBlock *block.API, + volumeID string, +) { if vb.IOPS != nil { _, err := apiBlock.UpdateVolume(&block.UpdateVolumeRequest{ VolumeID: volumeID, @@ -711,7 +753,8 @@ func (vb *VolumeBuilder) ExecutePostCreationSetup(ctx context.Context, apiBlock scw.WithContext(ctx), ) if err != nil { - core.ExtractLogger(ctx).Warning(fmt.Sprintf("Failed to update volume %s IOPS: %s", volumeID, err.Error())) + core.ExtractLogger(ctx). + Warning(fmt.Sprintf("Failed to update volume %s IOPS: %s", volumeID, err.Error())) } } } diff --git a/internal/namespaces/instance/v1/custom_server_create_test.go b/internal/namespaces/instance/v1/custom_server_create_test.go index b47b513cc8..da234eb4c2 100644 --- a/internal/namespaces/instance/v1/custom_server_create_test.go +++ b/internal/namespaces/instance/v1/custom_server_create_test.go @@ -17,7 +17,9 @@ import ( // deleteServerAfterFunc deletes the created server and its attached volumes and IPs. func deleteServerAfterFunc() core.AfterFunc { - return core.ExecAfterCmd("scw instance server delete {{ .CmdResult.ID }} with-volumes=all with-ip=true force-shutdown=true") + return core.ExecAfterCmd( + "scw instance server delete {{ .CmdResult.ID }} with-volumes=all with-ip=true force-shutdown=true", + ) } // All test below should succeed to create an instance. @@ -34,7 +36,11 @@ func Test_CreateServer(t *testing.T) { func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() assert.NotNil(t, ctx.Result) - assert.Equal(t, "Ubuntu 22.04 Jammy Jellyfish", ctx.Result.(*instanceSDK.Server).Image.Name) + assert.Equal( + t, + "Ubuntu 22.04 Jammy Jellyfish", + ctx.Result.(*instanceSDK.Server).Image.Name, + ) }, core.TestCheckExitCode(0), ), @@ -77,7 +83,11 @@ func Test_CreateServer(t *testing.T) { func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() assert.NotNil(t, ctx.Result) - assert.Equal(t, instanceSDK.ServerStateRunning, ctx.Result.(*instanceSDK.Server).State) + assert.Equal( + t, + instanceSDK.ServerStateRunning, + ctx.Result.(*instanceSDK.Server).State, + ) }, ), AfterFunc: deleteServerAfterFunc(), @@ -90,7 +100,11 @@ func Test_CreateServer(t *testing.T) { func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() assert.NotNil(t, ctx.Result) - assert.Equal(t, "Ubuntu Bionic Beaver", ctx.Result.(*instanceSDK.Server).Image.Name) + assert.Equal( + t, + "Ubuntu Bionic Beaver", + ctx.Result.(*instanceSDK.Server).Image.Name, + ) }, core.TestCheckExitCode(0), ), @@ -127,7 +141,12 @@ func Test_CreateServer(t *testing.T) { server := testhelpers.Value[*instanceSDK.Server](t, ctx.Result) volume := testhelpers.MapTValue(t, server.Volumes, "0") size := volume.Size - assert.Equal(t, 20*scw.GB, instance.SizeValue(size), "Size of volume should be 20 GB") + assert.Equal( + t, + 20*scw.GB, + instance.SizeValue(size), + "Size of volume should be 20 GB", + ) }, core.TestCheckExitCode(0), ), @@ -137,10 +156,18 @@ func Test_CreateServer(t *testing.T) { t.Run("valid single local snapshot", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Server", testServerCommand("image=ubuntu_bionic root-volume=local:20GB stopped=true")), - core.ExecStoreBeforeCmd("Snapshot", `scw instance snapshot create volume-id={{ (index .Server.Volumes "0").ID }}`), + core.ExecStoreBeforeCmd( + "Server", + testServerCommand("image=ubuntu_bionic root-volume=local:20GB stopped=true"), + ), + core.ExecStoreBeforeCmd( + "Snapshot", + `scw instance snapshot create volume-id={{ (index .Server.Volumes "0").ID }}`, + ), + ), + Cmd: testServerCommand( + "image=ubuntu_bionic root-volume=local:{{ .Snapshot.Snapshot.ID }} stopped=true", ), - Cmd: testServerCommand("image=ubuntu_bionic root-volume=local:{{ .Snapshot.Snapshot.ID }} stopped=true"), Check: core.TestCheckCombine( core.TestCheckExitCode(0), func(t *testing.T, ctx *core.CheckFuncCtx) { @@ -149,7 +176,12 @@ func Test_CreateServer(t *testing.T) { server := testhelpers.Value[*instanceSDK.Server](t, ctx.Result) volume := testhelpers.MapTValue(t, server.Volumes, "0") size := volume.Size - assert.Equal(t, 20*scw.GB, instance.SizeValue(size), "Size of volume should be 20 GB") + assert.Equal( + t, + 20*scw.GB, + instance.SizeValue(size), + "Size of volume should be 20 GB", + ) }, ), AfterFunc: core.AfterFuncCombine( @@ -162,10 +194,18 @@ func Test_CreateServer(t *testing.T) { t.Run("valid single local snapshot without image", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Server", testServerCommand("image=ubuntu_bionic root-volume=local:20GB stopped=true")), - core.ExecStoreBeforeCmd("Snapshot", `scw instance snapshot create volume-id={{ (index .Server.Volumes "0").ID }}`), + core.ExecStoreBeforeCmd( + "Server", + testServerCommand("image=ubuntu_bionic root-volume=local:20GB stopped=true"), + ), + core.ExecStoreBeforeCmd( + "Snapshot", + `scw instance snapshot create volume-id={{ (index .Server.Volumes "0").ID }}`, + ), + ), + Cmd: testServerCommand( + "image=none root-volume=local:{{ .Snapshot.Snapshot.ID }} stopped=true", ), - Cmd: testServerCommand("image=none root-volume=local:{{ .Snapshot.Snapshot.ID }} stopped=true"), Check: core.TestCheckCombine( core.TestCheckExitCode(0), func(t *testing.T, ctx *core.CheckFuncCtx) { @@ -174,7 +214,12 @@ func Test_CreateServer(t *testing.T) { server := testhelpers.Value[*instanceSDK.Server](t, ctx.Result) volume := testhelpers.MapTValue(t, server.Volumes, "0") size := volume.Size - assert.Equal(t, 20*scw.GB, instance.SizeValue(size), "Size of volume should be 20 GB") + assert.Equal( + t, + 20*scw.GB, + instance.SizeValue(size), + "Size of volume should be 20 GB", + ) }, ), AfterFunc: core.AfterFuncCombine( @@ -186,7 +231,9 @@ func Test_CreateServer(t *testing.T) { t.Run("valid double local volumes", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), - Cmd: testServerCommand("image=ubuntu_bionic root-volume=local:10GB additional-volumes.0=l:10G stopped=true"), + Cmd: testServerCommand( + "image=ubuntu_bionic root-volume=local:10GB additional-volumes.0=l:10G stopped=true", + ), Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() @@ -194,8 +241,18 @@ func Test_CreateServer(t *testing.T) { server := testhelpers.Value[*instanceSDK.Server](t, ctx.Result) size0 := testhelpers.MapTValue(t, server.Volumes, "0").Size size1 := testhelpers.MapTValue(t, server.Volumes, "1").Size - assert.Equal(t, 10*scw.GB, instance.SizeValue(size0), "Size of volume should be 10 GB") - assert.Equal(t, 10*scw.GB, instance.SizeValue(size1), "Size of volume should be 10 GB") + assert.Equal( + t, + 10*scw.GB, + instance.SizeValue(size0), + "Size of volume should be 10 GB", + ) + assert.Equal( + t, + 10*scw.GB, + instance.SizeValue(size1), + "Size of volume should be 10 GB", + ) }, core.TestCheckExitCode(0), ), @@ -208,10 +265,18 @@ func Test_CreateServer(t *testing.T) { block.GetCommands(), ), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("Server", testServerCommand("image=ubuntu_jammy root-volume=block:20GB stopped=true")), - core.ExecStoreBeforeCmd("Snapshot", `scw block snapshot create volume-id={{ (index .Server.Volumes "0").ID }} -w`), + core.ExecStoreBeforeCmd( + "Server", + testServerCommand("image=ubuntu_jammy root-volume=block:20GB stopped=true"), + ), + core.ExecStoreBeforeCmd( + "Snapshot", + `scw block snapshot create volume-id={{ (index .Server.Volumes "0").ID }} -w`, + ), + ), + Cmd: testServerCommand( + "image=ubuntu_jammy root-volume=block:{{ .Snapshot.ID }} additional-volumes.0=block:{{ .Snapshot.ID }} stopped=true", ), - Cmd: testServerCommand("image=ubuntu_jammy root-volume=block:{{ .Snapshot.ID }} additional-volumes.0=block:{{ .Snapshot.ID }} stopped=true"), Check: core.TestCheckCombine( core.TestCheckExitCode(0), testServerSBSVolumeSize("0", 20), @@ -226,7 +291,9 @@ func Test_CreateServer(t *testing.T) { t.Run("valid additional block volumes", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), - Cmd: testServerCommand("image=ubuntu_jammy additional-volumes.0=b:1G additional-volumes.1=b:5G additional-volumes.2=b:10G stopped=true"), + Cmd: testServerCommand( + "image=ubuntu_jammy additional-volumes.0=b:1G additional-volumes.1=b:5G additional-volumes.2=b:10G stopped=true", + ), Check: core.TestCheckCombine( core.TestCheckExitCode(0), testServerSBSVolumeSize("1", 1), @@ -244,7 +311,9 @@ func Test_CreateServer(t *testing.T) { BeforeFunc: core.BeforeFuncCombine( createSbsVolume("Volume", 20), ), - Cmd: testServerCommand("image=ubuntu_jammy additional-volumes.0={{.Volume.ID}} stopped=true"), + Cmd: testServerCommand( + "image=ubuntu_jammy additional-volumes.0={{.Volume.ID}} stopped=true", + ), Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() @@ -331,7 +400,9 @@ func Test_CreateServer(t *testing.T) { instance.GetCommands(), block.GetCommands(), ), - Cmd: testServerCommand("image=ubuntu_jammy root-volume=sbs:20GB:15000 stopped=true --debug"), + Cmd: testServerCommand( + "image=ubuntu_jammy root-volume=sbs:20GB:15000 stopped=true --debug", + ), Check: core.TestCheckCombine( core.TestCheckExitCode(0), func(t *testing.T, ctx *core.CheckFuncCtx) { @@ -341,7 +412,11 @@ func Test_CreateServer(t *testing.T) { rootVolume, rootVolumeExists := server.Volumes["0"] assert.True(t, rootVolumeExists) - assert.Equal(t, instanceSDK.VolumeServerVolumeTypeSbsVolume, rootVolume.VolumeType) + assert.Equal( + t, + instanceSDK.VolumeServerVolumeTypeSbsVolume, + rootVolume.VolumeType, + ) api := blockSDK.NewAPI(ctx.Client) vol, err := api.WaitForVolume(&blockSDK.WaitForVolumeRequest{ @@ -436,7 +511,9 @@ func Test_CreateServer(t *testing.T) { t.Run("with ipv6", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), - Cmd: testServerCommand("ip=ipv6 dynamic-ip-required=false -w"), // IPv6 is created at runtime + Cmd: testServerCommand( + "ip=ipv6 dynamic-ip-required=false -w", + ), // IPv6 is created at runtime Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() @@ -452,7 +529,9 @@ func Test_CreateServer(t *testing.T) { t.Run("with ipv6 and dynamic ip", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), - Cmd: testServerCommand("dynamic-ip-required=true ip=ipv6 -w"), // IPv6 is created at runtime + Cmd: testServerCommand( + "dynamic-ip-required=true ip=ipv6 -w", + ), // IPv6 is created at runtime Check: core.TestCheckCombine( core.TestCheckExitCode(0), func(t *testing.T, ctx *core.CheckFuncCtx) { @@ -542,7 +621,9 @@ func Test_CreateServerErrors(t *testing.T) { t.Run("Error: invalid total local volumes size: too low 2", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), - Cmd: testServerCommand("image=ubuntu_jammy root-volume=l:5GB additional-volumes.0=block:10GB"), + Cmd: testServerCommand( + "image=ubuntu_jammy root-volume=l:5GB additional-volumes.0=block:10GB", + ), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(1), @@ -563,7 +644,9 @@ func Test_CreateServerErrors(t *testing.T) { t.Run("Error: invalid total local volumes size: too high 1", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), - Cmd: testServerCommand("image=ubuntu_jammy root-volume=local:10GB additional-volumes.0=local:20GB"), + Cmd: testServerCommand( + "image=ubuntu_jammy root-volume=local:10GB additional-volumes.0=local:20GB", + ), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(1), @@ -584,7 +667,9 @@ func Test_CreateServerErrors(t *testing.T) { t.Run("Error: invalid total local volumes size: too high 3", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), BeforeFunc: createVolume("Volume", 20, instanceSDK.VolumeVolumeTypeLSSD), - Cmd: testServerCommand("image=ubuntu_jammy root-volume={{ .Volume.ID }} additional-volumes.0=local:10GB"), + Cmd: testServerCommand( + "image=ubuntu_jammy root-volume={{ .Volume.ID }} additional-volumes.0=local:10GB", + ), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(1), @@ -595,7 +680,9 @@ func Test_CreateServerErrors(t *testing.T) { t.Run("Error: invalid root volume size", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), - Cmd: testServerCommand("image=ubuntu_jammy root-volume=local:2GB additional-volumes.0=local:18GB"), + Cmd: testServerCommand( + "image=ubuntu_jammy root-volume=local:2GB additional-volumes.0=local:18GB", + ), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(1), @@ -617,7 +704,9 @@ func Test_CreateServerErrors(t *testing.T) { t.Run("Error: invalid root volume ID", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), - Cmd: testServerCommand("image=ubuntu_jammy root-volume=29da9ad9-e759-4a56-82c8-f0607f93055c"), + Cmd: testServerCommand( + "image=ubuntu_jammy root-volume=29da9ad9-e759-4a56-82c8-f0607f93055c", + ), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(1), @@ -626,9 +715,16 @@ func Test_CreateServerErrors(t *testing.T) { })) t.Run("Error: already attached additional volume ID", core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("name=cli-test image=ubuntu_jammy root-volume=l:10G additional-volumes.0=l:10G stopped=true")), - Cmd: testServerCommand(`image=ubuntu_jammy root-volume=l:10G additional-volumes.0={{ (index .Server.Volumes "1").ID }} stopped=true`), + Commands: instance.GetCommands(), + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand( + "name=cli-test image=ubuntu_jammy root-volume=l:10G additional-volumes.0=l:10G stopped=true", + ), + ), + Cmd: testServerCommand( + `image=ubuntu_jammy root-volume=l:10G additional-volumes.0={{ (index .Server.Volumes "1").ID }} stopped=true`, + ), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(1), @@ -649,7 +745,9 @@ func Test_CreateServerErrors(t *testing.T) { t.Run("Error: invalid root volume snapshot ID", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), - Cmd: testServerCommand("image=ubuntu_jammy root-volume=local:29da9ad9-e759-4a56-82c8-f0607f93055c"), + Cmd: testServerCommand( + "image=ubuntu_jammy root-volume=local:29da9ad9-e759-4a56-82c8-f0607f93055c", + ), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(1), @@ -659,7 +757,9 @@ func Test_CreateServerErrors(t *testing.T) { t.Run("Error: invalid additional volume snapshot ID", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), - Cmd: testServerCommand("image=ubuntu_jammy additional-volumes.0=block:29da9ad9-e759-4a56-82c8-f0607f93055c"), + Cmd: testServerCommand( + "image=ubuntu_jammy additional-volumes.0=block:29da9ad9-e759-4a56-82c8-f0607f93055c", + ), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(1), @@ -739,10 +839,16 @@ func Test_CreateServerScratchStorage(t *testing.T) { if !exist { t.Fatalf("Expected an additional scratch volume, found none") } - assert.Equal(t, instanceSDK.VolumeServerVolumeTypeScratch, additionalVolume.VolumeType) + assert.Equal( + t, + instanceSDK.VolumeServerVolumeTypeScratch, + additionalVolume.VolumeType, + ) }, ), - AfterFunc: core.ExecAfterCmd("scw instance server delete {{ .CmdResult.ID }} zone=fr-par-2 with-volumes=all with-ip=true force-shutdown=true"), + AfterFunc: core.ExecAfterCmd( + "scw instance server delete {{ .CmdResult.ID }} zone=fr-par-2 with-volumes=all with-ip=true force-shutdown=true", + ), DisableParallel: true, })) } diff --git a/internal/namespaces/instance/v1/custom_server_delete.go b/internal/namespaces/instance/v1/custom_server_delete.go index 26c842f137..d9241a7bf6 100644 --- a/internal/namespaces/instance/v1/custom_server_delete.go +++ b/internal/namespaces/instance/v1/custom_server_delete.go @@ -231,7 +231,11 @@ func errorDeletingResource(err error) error { } } -func serverDeleteVolume(volume *instance.VolumeServer, instanceAPI *instance.API, blockAPI *block.API) error { +func serverDeleteVolume( + volume *instance.VolumeServer, + instanceAPI *instance.API, + blockAPI *block.API, +) error { var err error if volume.VolumeType == instance.VolumeServerVolumeTypeSbsVolume { diff --git a/internal/namespaces/instance/v1/custom_server_rdp.go b/internal/namespaces/instance/v1/custom_server_rdp.go index 9906cc1510..ecab1d21eb 100644 --- a/internal/namespaces/instance/v1/custom_server_rdp.go +++ b/internal/namespaces/instance/v1/custom_server_rdp.go @@ -66,11 +66,13 @@ func instanceServerGetRdpPassword() *core.Command { args := argsI.(*instanceServerGetRdpPasswordRequest) apiInstance := instance.NewAPI(core.ExtractClient(ctx)) - _, err := apiInstance.WaitForServerRDPPassword(&instance.WaitForServerRDPPasswordRequest{ - Zone: args.Zone, - ServerID: args.ServerID, - RetryInterval: core.DefaultRetryInterval, - }) + _, err := apiInstance.WaitForServerRDPPassword( + &instance.WaitForServerRDPPasswordRequest{ + Zone: args.Zone, + ServerID: args.ServerID, + RetryInterval: core.DefaultRetryInterval, + }, + ) if err != nil { return nil, err } @@ -81,7 +83,10 @@ func instanceServerGetRdpPassword() *core.Command { } } -func instanceServerGetRdpPasswordRun(ctx context.Context, argsI interface{}) (i interface{}, e error) { +func instanceServerGetRdpPasswordRun( + ctx context.Context, + argsI interface{}, +) (i interface{}, e error) { args := argsI.(*instanceServerGetRdpPasswordRequest) if strings.HasPrefix(args.Key, "~") { @@ -100,7 +105,10 @@ func instanceServerGetRdpPasswordRun(ctx context.Context, argsI interface{}) (i rsaKey, isRSA := privateKey.(*rsa.PrivateKey) if !isRSA { - return nil, fmt.Errorf("expected rsa private key, got %s", reflect.TypeOf(privateKey).String()) + return nil, fmt.Errorf( + "expected rsa private key, got %s", + reflect.TypeOf(privateKey).String(), + ) } client := core.ExtractClient(ctx) @@ -112,7 +120,8 @@ func instanceServerGetRdpPasswordRun(ctx context.Context, argsI interface{}) (i if err != nil { return nil, err } - if resp.Server.AdminPasswordEncryptedValue == nil || *resp.Server.AdminPasswordEncryptedValue == "" { + if resp.Server.AdminPasswordEncryptedValue == nil || + *resp.Server.AdminPasswordEncryptedValue == "" { return &core.CliError{ Err: errors.New("rdp password is empty"), Message: "RDP password is nil or empty in api response", @@ -122,7 +131,9 @@ func instanceServerGetRdpPasswordRun(ctx context.Context, argsI interface{}) (i }, nil } - encryptedRdpPassword, err := base64.StdEncoding.DecodeString(*resp.Server.AdminPasswordEncryptedValue) + encryptedRdpPassword, err := base64.StdEncoding.DecodeString( + *resp.Server.AdminPasswordEncryptedValue, + ) if err != nil { return nil, fmt.Errorf("failed to decode base64 encoded rdp password: %w", err) } @@ -179,7 +190,8 @@ func parsePrivateKey(ctx context.Context, key []byte) (any, error) { } func completeSSHKeyID(ctx context.Context, prefix string, _ any) core.AutocompleteSuggestions { - resp, err := iam.NewAPI(core.ExtractClient(ctx)).ListSSHKeys(&iam.ListSSHKeysRequest{}, scw.WithAllPages()) + resp, err := iam.NewAPI(core.ExtractClient(ctx)). + ListSSHKeys(&iam.ListSSHKeysRequest{}, scw.WithAllPages()) if err != nil { return nil } diff --git a/internal/namespaces/instance/v1/custom_server_rdp_test.go b/internal/namespaces/instance/v1/custom_server_rdp_test.go index f756dfe72c..ba6d227454 100644 --- a/internal/namespaces/instance/v1/custom_server_rdp_test.go +++ b/internal/namespaces/instance/v1/custom_server_rdp_test.go @@ -33,7 +33,10 @@ func loadRSASSHKey(path string) (*rsa.PrivateKey, error) { if err != nil { return nil, fmt.Errorf("failed to generate key: %w", err) } - privatePEM, err := ssh.MarshalPrivateKey(privateKey, "test-cli-instance-server-get-rdp-password") + privatePEM, err := ssh.MarshalPrivateKey( + privateKey, + "test-cli-instance-server-get-rdp-password", + ) if err != nil { return nil, fmt.Errorf("failed to marshal private key: %w", err) } @@ -53,7 +56,10 @@ func loadRSASSHKey(path string) (*rsa.PrivateKey, error) { privateKey, ok := key.(*rsa.PrivateKey) if !ok { - return nil, fmt.Errorf("failed to assert private key type, expected *rsa.PrivateKey, got: %v", reflect.TypeOf(privateKey)) + return nil, fmt.Errorf( + "failed to assert private key type, expected *rsa.PrivateKey, got: %v", + reflect.TypeOf(privateKey), + ) } return privateKey, nil @@ -67,7 +73,10 @@ func generateRSASSHKey(metaKey string) func(beforeFunc *core.BeforeFuncCtx) erro if err != nil { return fmt.Errorf("failed to load private key: %w", err) } - privatePEM, err := ssh.MarshalPrivateKey(privateKey, "test-cli-instance-server-get-rdp-password") + privatePEM, err := ssh.MarshalPrivateKey( + privateKey, + "test-cli-instance-server-get-rdp-password", + ) if err != nil { return fmt.Errorf("failed to marshal private key: %w", err) } @@ -120,7 +129,10 @@ func Test_ServerGetRdpPassword(t *testing.T) { ), BeforeFunc: core.BeforeFuncCombine( generateRSASSHKey("SSHKey"), - core.ExecStoreBeforeCmd("Server", "scw instance server create type=POP2-2C-8G-WIN image=windows_server_2022 admin-password-encryption-ssh-key-id={{.SSHKey.ID}}"), + core.ExecStoreBeforeCmd( + "Server", + "scw instance server create type=POP2-2C-8G-WIN image=windows_server_2022 admin-password-encryption-ssh-key-id={{.SSHKey.ID}}", + ), ), Cmd: "scw instance server get-rdp-password {{.Server.ID}} --wait", Check: core.TestCheckCombine( diff --git a/internal/namespaces/instance/v1/custom_server_ssh.go b/internal/namespaces/instance/v1/custom_server_ssh.go index a668e1b2e6..faba114be7 100644 --- a/internal/namespaces/instance/v1/custom_server_ssh.go +++ b/internal/namespaces/instance/v1/custom_server_ssh.go @@ -71,15 +71,23 @@ func instanceServerSSHRun(ctx context.Context, argsI interface{}) (i interface{} if serverResp.Server.State != instance.ServerStateRunning { return nil, &core.CliError{ - Err: errors.New("server is not running"), - Hint: fmt.Sprintf("Start the instance with: %s instance server start %s --wait", core.ExtractBinaryName(ctx), serverResp.Server.ID), + Err: errors.New("server is not running"), + Hint: fmt.Sprintf( + "Start the instance with: %s instance server start %s --wait", + core.ExtractBinaryName(ctx), + serverResp.Server.ID, + ), } } if serverResp.Server.PublicIP == nil { return nil, &core.CliError{ - Err: errors.New("server does not have a public IP to connect to"), - Hint: fmt.Sprintf("Add a public IP to the instance with: %s instance server update %s ip=", core.ExtractBinaryName(ctx), serverResp.Server.ID), + Err: errors.New("server does not have a public IP to connect to"), + Hint: fmt.Sprintf( + "Add a public IP to the instance with: %s instance server update %s ip=", + core.ExtractBinaryName(ctx), + serverResp.Server.ID, + ), } } diff --git a/internal/namespaces/instance/v1/custom_server_test.go b/internal/namespaces/instance/v1/custom_server_test.go index 4279294c38..7168dd2d7d 100644 --- a/internal/namespaces/instance/v1/custom_server_test.go +++ b/internal/namespaces/instance/v1/custom_server_test.go @@ -33,7 +33,11 @@ func Test_ServerVolumeUpdate(t *testing.T) { require.NoError(t, ctx.Err) resp := testhelpers.Value[*instanceSDK.AttachVolumeResponse](t, ctx.Result) addedVolume := testhelpers.MapTValue(t, resp.Server.Volumes, "1") - assert.Equal(t, instanceSDK.VolumeServerVolumeTypeSbsVolume, addedVolume.VolumeType) + assert.Equal( + t, + instanceSDK.VolumeServerVolumeTypeSbsVolume, + addedVolume.VolumeType, + ) }, testAttachVolumeServerSBSVolumeSize("0", 10), testAttachVolumeServerSBSVolumeSize("1", 10), @@ -55,7 +59,12 @@ func Test_ServerVolumeUpdate(t *testing.T) { require.NoError(t, ctx.Err) resp := testhelpers.Value[*instanceSDK.AttachVolumeResponse](t, ctx.Result) addedVolume := testhelpers.MapTValue(t, resp.Server.Volumes, "1") - assert.Equal(t, 10*scw.GB, instance.SizeValue(addedVolume.Size), "Size of volume should be 10 GB") + assert.Equal( + t, + 10*scw.GB, + instance.SizeValue(addedVolume.Size), + "Size of volume should be 10 GB", + ) assert.Equal(t, instanceSDK.VolumeServerVolumeTypeLSSD, addedVolume.VolumeType) }, testAttachVolumeServerSBSVolumeSize("0", 10), @@ -82,8 +91,11 @@ func Test_ServerVolumeUpdate(t *testing.T) { block.GetCommands(), instance.GetCommands(), ), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true image=ubuntu-jammy additional-volumes.0=block:10G")), - Cmd: `scw instance server detach-volume volume-id={{ (index .Server.Volumes "1").ID }}`, + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand("stopped=true image=ubuntu-jammy additional-volumes.0=block:10G"), + ), + Cmd: `scw instance server detach-volume volume-id={{ (index .Server.Volumes "1").ID }}`, Check: func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() require.NoError(t, ctx.Err) @@ -93,7 +105,9 @@ func Test_ServerVolumeUpdate(t *testing.T) { assert.Len(t, ctx.Result.(*instanceSDK.DetachVolumeResponse).Server.Volumes, 1) }, AfterFunc: core.AfterFuncCombine( - core.ExecAfterCmd(`scw block volume wait terminal-status=available {{ (index .Server.Volumes "1").ID }}`), + core.ExecAfterCmd( + `scw block volume wait terminal-status=available {{ (index .Server.Volumes "1").ID }}`, + ), core.ExecAfterCmd(`scw block volume delete {{ (index .Server.Volumes "1").ID }}`), deleteServer("Server"), ), @@ -161,16 +175,21 @@ func Test_ServerUpdateCustom(t *testing.T) { createIP("IP2"), // Attach IP1 to Server. - core.ExecStoreBeforeCmd("UpdatedServer", "scw instance server update {{ .Server.ID }} ip={{ .IP1.Address }}"), + core.ExecStoreBeforeCmd( + "UpdatedServer", + "scw instance server update {{ .Server.ID }} ip={{ .IP1.Address }}", + ), ), Cmd: "scw instance server update {{ .Server.ID }} ip={{ .IP2.Address }}", Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() // Test that the Server WAS attached to IP1. - assert.Equal(t, + assert.Equal( + t, ctx.Meta["IP1"].(*instanceSDK.IP).Address, - ctx.Meta["UpdatedServer"].(*instanceSDK.UpdateServerResponse).Server.PublicIP.Address) + ctx.Meta["UpdatedServer"].(*instanceSDK.UpdateServerResponse).Server.PublicIP.Address, + ) // Test that the Server IS attached to IP2. assert.Equal(t, ctx.Meta["IP2"].(*instanceSDK.IP).Address, @@ -185,54 +204,70 @@ func Test_ServerUpdateCustom(t *testing.T) { })) // Placement group cases. - t.Run("Update server placement-group-id from server with placement-group-id", core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.BeforeFuncCombine( - createPlacementGroup("PlacementGroup1"), - createPlacementGroup("PlacementGroup2"), - core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true image=ubuntu-jammy placement-group-id={{ .PlacementGroup1.ID }}")), - ), - Cmd: "scw instance server update {{ .Server.ID }} placement-group-id={{ .PlacementGroup2.ID }}", - Check: core.TestCheckCombine( - core.TestCheckExitCode(0), - func(t *testing.T, ctx *core.CheckFuncCtx) { - t.Helper() - assert.Equal(t, - ctx.Meta["PlacementGroup2"].(*instanceSDK.PlacementGroup).ID, - ctx.Result.(*instanceSDK.UpdateServerResponse).Server.PlacementGroup.ID) - }, - ), - AfterFunc: core.AfterFuncCombine( - deleteServer("Server"), - deletePlacementGroup("PlacementGroup1"), - deletePlacementGroup("PlacementGroup2"), - ), - })) + t.Run( + "Update server placement-group-id from server with placement-group-id", + core.Test(&core.TestConfig{ + Commands: instance.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + createPlacementGroup("PlacementGroup1"), + createPlacementGroup("PlacementGroup2"), + core.ExecStoreBeforeCmd( + "Server", + testServerCommand( + "stopped=true image=ubuntu-jammy placement-group-id={{ .PlacementGroup1.ID }}", + ), + ), + ), + Cmd: "scw instance server update {{ .Server.ID }} placement-group-id={{ .PlacementGroup2.ID }}", + Check: core.TestCheckCombine( + core.TestCheckExitCode(0), + func(t *testing.T, ctx *core.CheckFuncCtx) { + t.Helper() + assert.Equal(t, + ctx.Meta["PlacementGroup2"].(*instanceSDK.PlacementGroup).ID, + ctx.Result.(*instanceSDK.UpdateServerResponse).Server.PlacementGroup.ID) + }, + ), + AfterFunc: core.AfterFuncCombine( + deleteServer("Server"), + deletePlacementGroup("PlacementGroup1"), + deletePlacementGroup("PlacementGroup2"), + ), + }), + ) // Security group cases. - t.Run("Update server security-group-id from server with security-group-id", core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.BeforeFuncCombine( - createSecurityGroup("SecurityGroup1"), - createSecurityGroup("SecurityGroup2"), - core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true image=ubuntu-jammy security-group-id={{ .SecurityGroup1.ID }}")), - ), - Cmd: "scw instance server update {{ .Server.ID }} security-group-id={{ .SecurityGroup2.ID }}", - Check: core.TestCheckCombine( - core.TestCheckExitCode(0), - func(t *testing.T, ctx *core.CheckFuncCtx) { - t.Helper() - assert.Equal(t, - ctx.Meta["SecurityGroup2"].(*instanceSDK.SecurityGroup).ID, - ctx.Result.(*instanceSDK.UpdateServerResponse).Server.SecurityGroup.ID) - }, - ), - AfterFunc: core.AfterFuncCombine( - deleteServer("Server"), - deleteSecurityGroup("SecurityGroup1"), - deleteSecurityGroup("SecurityGroup2"), - ), - })) + t.Run( + "Update server security-group-id from server with security-group-id", + core.Test(&core.TestConfig{ + Commands: instance.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + createSecurityGroup("SecurityGroup1"), + createSecurityGroup("SecurityGroup2"), + core.ExecStoreBeforeCmd( + "Server", + testServerCommand( + "stopped=true image=ubuntu-jammy security-group-id={{ .SecurityGroup1.ID }}", + ), + ), + ), + Cmd: "scw instance server update {{ .Server.ID }} security-group-id={{ .SecurityGroup2.ID }}", + Check: core.TestCheckCombine( + core.TestCheckExitCode(0), + func(t *testing.T, ctx *core.CheckFuncCtx) { + t.Helper() + assert.Equal(t, + ctx.Meta["SecurityGroup2"].(*instanceSDK.SecurityGroup).ID, + ctx.Result.(*instanceSDK.UpdateServerResponse).Server.SecurityGroup.ID) + }, + ), + AfterFunc: core.AfterFuncCombine( + deleteServer("Server"), + deleteSecurityGroup("SecurityGroup1"), + deleteSecurityGroup("SecurityGroup2"), + ), + }), + ) // Volumes cases. t.Run("Volumes", func(t *testing.T) { @@ -258,17 +293,24 @@ func Test_ServerUpdateCustom(t *testing.T) { block.GetCommands(), instance.GetCommands(), ), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true image=ubuntu-jammy additional-volumes.0=block:10G")), - Cmd: `scw instance server update {{ .Server.ID }} volume-ids=none`, + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand("stopped=true image=ubuntu-jammy additional-volumes.0=block:10G"), + ), + Cmd: `scw instance server update {{ .Server.ID }} volume-ids=none`, Check: func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() require.NoError(t, ctx.Err) assert.Empty(t, ctx.Result.(*instanceSDK.UpdateServerResponse).Server.Volumes) }, AfterFunc: core.AfterFuncCombine( - core.ExecAfterCmd(`scw block volume wait terminal-status=available {{ (index .Server.Volumes "0").ID }}`), + core.ExecAfterCmd( + `scw block volume wait terminal-status=available {{ (index .Server.Volumes "0").ID }}`, + ), core.ExecAfterCmd(`scw block volume delete {{ (index .Server.Volumes "0").ID }}`), - core.ExecAfterCmd(`scw block volume wait terminal-status=available {{ (index .Server.Volumes "1").ID }}`), + core.ExecAfterCmd( + `scw block volume wait terminal-status=available {{ (index .Server.Volumes "1").ID }}`, + ), core.ExecAfterCmd(`scw block volume delete {{ (index .Server.Volumes "1").ID }}`), deleteServer("Server"), ), @@ -282,9 +324,12 @@ func Test_ServerDelete(t *testing.T) { interactive.IsInteractive = true t.Run("with all volumes", core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true additional-volumes.0=block:10G")), - Cmd: `scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=all`, + Commands: instance.GetCommands(), + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand("stopped=true additional-volumes.0=block:10G"), + ), + Cmd: `scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=all`, Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), @@ -293,14 +338,19 @@ func Test_ServerDelete(t *testing.T) { })) t.Run("only block volumes", core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true root-volume=l:20G additional-volumes.0=block:10G")), - Cmd: `scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=block`, + Commands: instance.GetCommands(), + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand("stopped=true root-volume=l:20G additional-volumes.0=block:10G"), + ), + Cmd: `scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=block`, Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), ), - AfterFunc: core.ExecAfterCmd(`scw instance volume delete {{ (index .Server.Volumes "0").ID }}`), + AfterFunc: core.ExecAfterCmd( + `scw instance volume delete {{ (index .Server.Volumes "0").ID }}`, + ), DisableParallel: true, })) @@ -309,14 +359,19 @@ func Test_ServerDelete(t *testing.T) { block.GetCommands(), instance.GetCommands(), ), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true additional-volumes.0=block:10G")), - Cmd: `scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=local`, + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand("stopped=true additional-volumes.0=block:10G"), + ), + Cmd: `scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=local`, Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), ), AfterFunc: core.AfterFuncCombine( - core.ExecAfterCmd(`scw block volume wait terminal-status=available {{ (index .Server.Volumes "1").ID }}`), + core.ExecAfterCmd( + `scw block volume wait terminal-status=available {{ (index .Server.Volumes "1").ID }}`, + ), core.ExecAfterCmd(`scw block volume delete {{ (index .Server.Volumes "1").ID }}`), ), DisableParallel: true, @@ -327,8 +382,11 @@ func Test_ServerDelete(t *testing.T) { block.GetCommands(), instance.GetCommands(), ), - BeforeFunc: core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true root-volume=l:20G additional-volumes.0=block:10G")), - Cmd: `scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=none`, + BeforeFunc: core.ExecStoreBeforeCmd( + "Server", + testServerCommand("stopped=true root-volume=l:20G additional-volumes.0=block:10G"), + ), + Cmd: `scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=none`, Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), @@ -355,9 +413,14 @@ func Test_ServerDelete(t *testing.T) { block.GetCommands(), ), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("BlockVolume", "scw block volume create perf-iops=5000 from-empty.size=10G name=cli-test-server-delete-with-sbs-volumes"), + core.ExecStoreBeforeCmd( + "BlockVolume", + "scw block volume create perf-iops=5000 from-empty.size=10G name=cli-test-server-delete-with-sbs-volumes", + ), core.ExecStoreBeforeCmd("Server", testServerCommand("stopped=true image=ubuntu-jammy")), - core.ExecBeforeCmd("scw instance server attach-volume server-id={{ .Server.ID }} volume-id={{ .BlockVolume.ID }}"), + core.ExecBeforeCmd( + "scw instance server attach-volume server-id={{ .Server.ID }} volume-id={{ .BlockVolume.ID }}", + ), ), Cmd: `scw instance server delete {{ .Server.ID }} with-ip=true with-volumes=all`, Check: core.TestCheckCombine( diff --git a/internal/namespaces/instance/v1/custom_server_type.go b/internal/namespaces/instance/v1/custom_server_type.go index 8615a0d978..96dfb0a7be 100644 --- a/internal/namespaces/instance/v1/custom_server_type.go +++ b/internal/namespaces/instance/v1/custom_server_type.go @@ -18,8 +18,14 @@ import ( var serverTypesAvailabilityMarshalSpecs = human.EnumMarshalSpecs{ instance.ServerTypesAvailabilityAvailable: &human.EnumMarshalSpec{Attribute: color.FgGreen}, - instance.ServerTypesAvailabilityScarce: &human.EnumMarshalSpec{Attribute: color.FgYellow, Value: "low stock"}, - instance.ServerTypesAvailabilityShortage: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "out of stock"}, + instance.ServerTypesAvailabilityScarce: &human.EnumMarshalSpec{ + Attribute: color.FgYellow, + Value: "low stock", + }, + instance.ServerTypesAvailabilityShortage: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "out of stock", + }, } // @@ -79,9 +85,12 @@ func serverTypeListBuilder(c *core.Command) *core.Command { serverTypes := []*customServerType(nil) // Get server availabilities. - availabilitiesResponse, err := api.GetServerTypesAvailability(&instance.GetServerTypesAvailabilityRequest{ - Zone: request.Zone, - }, scw.WithAllPages()) + availabilitiesResponse, err := api.GetServerTypesAvailability( + &instance.GetServerTypesAvailabilityRequest{ + Zone: request.Zone, + }, + scw.WithAllPages(), + ) if err != nil { return nil, err } @@ -99,8 +108,12 @@ func serverTypeListBuilder(c *core.Command) *core.Command { } serverTypes = append(serverTypes, &customServerType{ - Name: name, - HourlyPrice: scw.NewMoneyFromFloat(float64(serverType.HourlyPrice), "EUR", 3), + Name: name, + HourlyPrice: scw.NewMoneyFromFloat( + float64(serverType.HourlyPrice), + "EUR", + 3, + ), LocalVolumeMaxSize: serverType.VolumesConstraint.MaxSize, CPU: serverType.Ncpus, GPU: serverType.Gpu, diff --git a/internal/namespaces/instance/v1/custom_snapshot.go b/internal/namespaces/instance/v1/custom_snapshot.go index cc7a419240..09084c9a5b 100644 --- a/internal/namespaces/instance/v1/custom_snapshot.go +++ b/internal/namespaces/instance/v1/custom_snapshot.go @@ -34,37 +34,39 @@ func snapshotCreateBuilder(c *core.Command) *core.Command { c.ArgsType = reflect.TypeOf(customCreateSnapshotRequest{}) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customCreateSnapshotRequest) - - if args.CreateSnapshotRequest == nil { - args.CreateSnapshotRequest = &instance.CreateSnapshotRequest{} - } - - request := args.CreateSnapshotRequest - request.Organization = args.OrganizationID - request.Project = args.ProjectID - - client := core.ExtractClient(ctx) - api := instance.NewAPI(client) - if args.Unified { - request.VolumeType = instance.SnapshotVolumeTypeUnified - } else if request.VolumeID != nil { - // If the snapshot is not unified, we need to set the snapshot volume type to the same type as the volume we target. - // Done only when creating snapshot from volume - volume, err := api.GetVolume(&instance.GetVolumeRequest{ - VolumeID: *args.VolumeID, - Zone: args.Zone, - }) - if err != nil { - return nil, err + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customCreateSnapshotRequest) + + if args.CreateSnapshotRequest == nil { + args.CreateSnapshotRequest = &instance.CreateSnapshotRequest{} } - request.VolumeType = instance.SnapshotVolumeType(volume.Volume.VolumeType) - } + request := args.CreateSnapshotRequest + request.Organization = args.OrganizationID + request.Project = args.ProjectID + + client := core.ExtractClient(ctx) + api := instance.NewAPI(client) + if args.Unified { + request.VolumeType = instance.SnapshotVolumeTypeUnified + } else if request.VolumeID != nil { + // If the snapshot is not unified, we need to set the snapshot volume type to the same type as the volume we target. + // Done only when creating snapshot from volume + volume, err := api.GetVolume(&instance.GetVolumeRequest{ + VolumeID: *args.VolumeID, + Zone: args.Zone, + }) + if err != nil { + return nil, err + } + + request.VolumeType = instance.SnapshotVolumeType(volume.Volume.VolumeType) + } - return runner(ctx, request) - }) + return runner(ctx, request) + }, + ) c.WaitFunc = func(ctx context.Context, argsI, respI interface{}) (interface{}, error) { api := instance.NewAPI(core.ExtractClient(ctx)) @@ -92,19 +94,21 @@ func snapshotListBuilder(c *core.Command) *core.Command { c.ArgsType = reflect.TypeOf(customListSnapshotsRequest{}) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customListSnapshotsRequest) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customListSnapshotsRequest) - if args.ListSnapshotsRequest == nil { - args.ListSnapshotsRequest = &instance.ListSnapshotsRequest{} - } + if args.ListSnapshotsRequest == nil { + args.ListSnapshotsRequest = &instance.ListSnapshotsRequest{} + } - request := args.ListSnapshotsRequest - request.Organization = args.OrganizationID - request.Project = args.ProjectID + request := args.ListSnapshotsRequest + request.Organization = args.OrganizationID + request.Project = args.ProjectID - return runner(ctx, request) - }) + return runner(ctx, request) + }, + ) return c } diff --git a/internal/namespaces/instance/v1/custom_snapshot_test.go b/internal/namespaces/instance/v1/custom_snapshot_test.go index 18a6b27379..b0656791c7 100644 --- a/internal/namespaces/instance/v1/custom_snapshot_test.go +++ b/internal/namespaces/instance/v1/custom_snapshot_test.go @@ -15,7 +15,10 @@ func Test_UpdateSnapshot(t *testing.T) { Commands: instance.GetCommands(), BeforeFunc: core.BeforeFuncCombine( createVolume("Volume", 10, instanceSDK.VolumeVolumeTypeBSSD), - core.ExecStoreBeforeCmd("CreateSnapshot", "scw instance snapshot create volume-id={{ .Volume.ID }} name=cli-test-snapshot-update-tags tags.0=foo tags.1=bar"), + core.ExecStoreBeforeCmd( + "CreateSnapshot", + "scw instance snapshot create volume-id={{ .Volume.ID }} name=cli-test-snapshot-update-tags tags.0=foo tags.1=bar", + ), ), Cmd: "scw instance snapshot update -w {{ .CreateSnapshot.Snapshot.ID }} tags.0=bar tags.1=foo", Check: core.TestCheckCombine( @@ -40,7 +43,10 @@ func Test_UpdateSnapshot(t *testing.T) { Commands: instance.GetCommands(), BeforeFunc: core.BeforeFuncCombine( createVolume("Volume", 10, instanceSDK.VolumeVolumeTypeBSSD), - core.ExecStoreBeforeCmd("CreateSnapshot", "scw instance snapshot create volume-id={{ .Volume.ID }} name=cli-test-snapshot-update-name tags.0=foo tags.1=bar"), + core.ExecStoreBeforeCmd( + "CreateSnapshot", + "scw instance snapshot create volume-id={{ .Volume.ID }} name=cli-test-snapshot-update-name tags.0=foo tags.1=bar", + ), ), Cmd: "scw instance snapshot update -w {{ .CreateSnapshot.Snapshot.ID }} name=cli-test-snapshot-update-name-updated", Check: core.TestCheckCombine( diff --git a/internal/namespaces/instance/v1/custom_ssh_config.go b/internal/namespaces/instance/v1/custom_ssh_config.go index 9ab3355b15..ff17007c1f 100644 --- a/internal/namespaces/instance/v1/custom_ssh_config.go +++ b/internal/namespaces/instance/v1/custom_ssh_config.go @@ -107,8 +107,11 @@ It generate hosts for instance servers, baremetal, apple-silicon and bastions`, } configFilePath := sshconfig.ConfigFilePath(homeDir) - includePrompt := fmt.Sprintf(`Generated config file needs to be included in your default ssh config (%s) -Do you want the include statement to be added at the beginning of your file ?`, sshconfig.DefaultConfigFilePath(homeDir)) + includePrompt := fmt.Sprintf( + `Generated config file needs to be included in your default ssh config (%s) +Do you want the include statement to be added at the beginning of your file ?`, + sshconfig.DefaultConfigFilePath(homeDir), + ) // Generated config needs an include statement in default config included, err := sshconfig.ConfigIsIncluded(homeDir) @@ -131,11 +134,13 @@ Do you want the include statement to be added at the beginning of your file ?`, }, nil } - shouldIncludeConfig, err := interactive.PromptBoolWithConfig(&interactive.PromptBoolConfig{ - Ctx: ctx, - Prompt: includePrompt, - DefaultValue: true, - }) + shouldIncludeConfig, err := interactive.PromptBoolWithConfig( + &interactive.PromptBoolConfig{ + Ctx: ctx, + Prompt: includePrompt, + DefaultValue: true, + }, + ) if err != nil { logger.Warningf("Failed to prompt, skipping include\n") @@ -159,7 +164,10 @@ Do you want the include statement to be added at the beginning of your file ?`, } } -func sshConfigListServers(ctx context.Context, args *sshConfigInstallRequest) ([]sshConfigServer, error) { +func sshConfigListServers( + ctx context.Context, + args *sshConfigInstallRequest, +) ([]sshConfigServer, error) { instanceAPI := instance.NewAPI(core.ExtractClient(ctx)) reqOpts := []scw.RequestOption{scw.WithAllPages()} @@ -199,7 +207,10 @@ func sshConfigListServers(ctx context.Context, args *sshConfigInstallRequest) ([ return servers, nil } -func sshConfigListBaremetalServers(ctx context.Context, args *sshConfigInstallRequest) ([]sshConfigServer, error) { +func sshConfigListBaremetalServers( + ctx context.Context, + args *sshConfigInstallRequest, +) ([]sshConfigServer, error) { baremetalAPI := baremetal.NewAPI(core.ExtractClient(ctx)) baremetalPNAPI := baremetal.NewPrivateNetworkAPI(core.ExtractClient(ctx)) @@ -220,9 +231,11 @@ func sshConfigListBaremetalServers(ctx context.Context, args *sshConfigInstallRe // TODO: check permissions and print warning return nil, err } - listPNs, err := baremetalPNAPI.ListServerPrivateNetworks(&baremetal.PrivateNetworkAPIListServerPrivateNetworksRequest{ - Zone: args.Zone, - }, reqOpts...) + listPNs, err := baremetalPNAPI.ListServerPrivateNetworks( + &baremetal.PrivateNetworkAPIListServerPrivateNetworksRequest{ + Zone: args.Zone, + }, + reqOpts...) if err != nil { // TODO: check permissions and print warning return nil, err @@ -253,7 +266,10 @@ func sshConfigListBaremetalServers(ctx context.Context, args *sshConfigInstallRe return servers, nil } -func sshConfigListAppleSiliconServers(ctx context.Context, args *sshConfigInstallRequest) ([]sshConfigServer, error) { +func sshConfigListAppleSiliconServers( + ctx context.Context, + args *sshConfigInstallRequest, +) ([]sshConfigServer, error) { siliconAPI := applesilicon.NewAPI(core.ExtractClient(ctx)) reqOpts := []scw.RequestOption{scw.WithAllPages()} @@ -286,7 +302,11 @@ func sshConfigListAppleSiliconServers(ctx context.Context, args *sshConfigInstal return servers, nil } -func sshConfigBastionHosts(ctx context.Context, args *sshConfigInstallRequest, servers []sshConfigServer) ([]sshconfig.Host, error) { +func sshConfigBastionHosts( + ctx context.Context, + args *sshConfigInstallRequest, + servers []sshConfigServer, +) ([]sshconfig.Host, error) { gwAPI := vpcgw.NewAPI(core.ExtractClient(ctx)) reqOpts := []scw.RequestOption{scw.WithAllPages()} diff --git a/internal/namespaces/instance/v1/custom_ssh_key_test.go b/internal/namespaces/instance/v1/custom_ssh_key_test.go index 7e2ac244f3..8807349e23 100644 --- a/internal/namespaces/instance/v1/custom_ssh_key_test.go +++ b/internal/namespaces/instance/v1/custom_ssh_key_test.go @@ -41,7 +41,14 @@ func Test_SSHKey(t *testing.T) { t.Run("Add key", core.Test(&core.TestConfig{ Commands: instance.GetCommands(), BeforeFunc: createServer("Server"), - Args: []string{"scw", "instance", "ssh", "add-key", "server-id={{.Server.ID}}", "public-key=" + sshKey}, + Args: []string{ + "scw", + "instance", + "ssh", + "add-key", + "server-id={{.Server.ID}}", + "public-key=" + sshKey, + }, Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), @@ -85,7 +92,14 @@ func Test_SSHKey(t *testing.T) { addSSHKey("Server", sshKey), addSSHKey("Server", sshKey2), ), - Args: []string{"scw", "instance", "ssh", "remove-key", "server-id={{.Server.ID}}", "name=key2"}, + Args: []string{ + "scw", + "instance", + "ssh", + "remove-key", + "server-id={{.Server.ID}}", + "name=key2", + }, Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), diff --git a/internal/namespaces/instance/v1/custom_user_data.go b/internal/namespaces/instance/v1/custom_user_data.go index b4b12cc929..5ccb36f0bf 100644 --- a/internal/namespaces/instance/v1/custom_user_data.go +++ b/internal/namespaces/instance/v1/custom_user_data.go @@ -36,21 +36,23 @@ func userDataSetBuilder(c *core.Command) *core.Command { } func userDataGetBuilder(c *core.Command) *core.Command { - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { - req := argsI.(*instance.GetServerUserDataRequest) - res, err := runner(ctx, argsI) - if err != nil { - if resErr, ok := err.(*scw.ResponseError); ok { - if resErr.StatusCode == http.StatusNotFound { - return nil, fmt.Errorf("'%s' key does not exist", req.Key) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + req := argsI.(*instance.GetServerUserDataRequest) + res, err := runner(ctx, argsI) + if err != nil { + if resErr, ok := err.(*scw.ResponseError); ok { + if resErr.StatusCode == http.StatusNotFound { + return nil, fmt.Errorf("'%s' key does not exist", req.Key) + } } - } - return nil, err - } + return nil, err + } - return res, nil - }) + return res, nil + }, + ) return c } @@ -60,35 +62,37 @@ func userDataListBuilder(c *core.Command) *core.Command { Key string `json:"key"` Value string `json:"value"` } - c.AddInterceptors(func(ctx context.Context, argsI interface{}, _ core.CommandRunner) (interface{}, error) { - client := core.ExtractClient(ctx) - api := instance.NewAPI(client) - args := argsI.(*instance.ListServerUserDataRequest) - res, err := api.GetAllServerUserData(&instance.GetAllServerUserDataRequest{ - Zone: args.Zone, - ServerID: args.ServerID, - }) - if err != nil { - return nil, err - } - var r []userDataRow - for a, v := range res.UserData { - buf := new(strings.Builder) - _, err := io.Copy(buf, v) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, _ core.CommandRunner) (interface{}, error) { + client := core.ExtractClient(ctx) + api := instance.NewAPI(client) + args := argsI.(*instance.ListServerUserDataRequest) + res, err := api.GetAllServerUserData(&instance.GetAllServerUserDataRequest{ + Zone: args.Zone, + ServerID: args.ServerID, + }) if err != nil { return nil, err } - r = append(r, userDataRow{ - Key: a, - Value: buf.String(), + var r []userDataRow + for a, v := range res.UserData { + buf := new(strings.Builder) + _, err := io.Copy(buf, v) + if err != nil { + return nil, err + } + r = append(r, userDataRow{ + Key: a, + Value: buf.String(), + }) + } + sort.Slice(r, func(i, j int) bool { + return r[i].Key < r[j].Key }) - } - sort.Slice(r, func(i, j int) bool { - return r[i].Key < r[j].Key - }) - return r, nil - }) + return r, nil + }, + ) return c } diff --git a/internal/namespaces/instance/v1/custom_user_data_test.go b/internal/namespaces/instance/v1/custom_user_data_test.go index d5ad84e9cd..5b15336f6b 100644 --- a/internal/namespaces/instance/v1/custom_user_data_test.go +++ b/internal/namespaces/instance/v1/custom_user_data_test.go @@ -12,7 +12,9 @@ func Test_UserDataGet(t *testing.T) { t.Run("Get an existing key", core.Test(&core.TestConfig{ BeforeFunc: core.BeforeFuncCombine( createServer("Server"), - core.ExecBeforeCmd("scw instance user-data set server-id={{.Server.ID}} key=happy content=true"), + core.ExecBeforeCmd( + "scw instance user-data set server-id={{.Server.ID}} key=happy content=true", + ), ), Commands: instance.GetCommands(), Cmd: "scw instance user-data get server-id={{.Server.ID}} key=happy", @@ -39,8 +41,12 @@ func Test_UserDataList(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ BeforeFunc: core.BeforeFuncCombine( createServer("Server"), - core.ExecBeforeCmd("scw instance user-data set server-id={{ .Server.ID }} key=foo content=bar"), - core.ExecBeforeCmd("scw instance user-data set server-id={{ .Server.ID }} key=bar content=foo"), + core.ExecBeforeCmd( + "scw instance user-data set server-id={{ .Server.ID }} key=foo content=bar", + ), + core.ExecBeforeCmd( + "scw instance user-data set server-id={{ .Server.ID }} key=bar content=foo", + ), ), Commands: instance.GetCommands(), Cmd: "scw instance user-data list server-id={{ .Server.ID }}", diff --git a/internal/namespaces/instance/v1/custom_volume.go b/internal/namespaces/instance/v1/custom_volume.go index f26c61bd54..5245996354 100644 --- a/internal/namespaces/instance/v1/custom_volume.go +++ b/internal/namespaces/instance/v1/custom_volume.go @@ -55,19 +55,21 @@ func volumeCreateBuilder(c *core.Command) *core.Command { c.ArgsType = reflect.TypeOf(customCreateVolumeRequest{}) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customCreateVolumeRequest) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customCreateVolumeRequest) - if args.CreateVolumeRequest == nil { - args.CreateVolumeRequest = &instance.CreateVolumeRequest{} - } + if args.CreateVolumeRequest == nil { + args.CreateVolumeRequest = &instance.CreateVolumeRequest{} + } - request := args.CreateVolumeRequest - request.Organization = args.OrganizationID - request.Project = args.ProjectID + request := args.CreateVolumeRequest + request.Organization = args.OrganizationID + request.Project = args.ProjectID - return runner(ctx, request) - }) + return runner(ctx, request) + }, + ) return c } @@ -84,19 +86,21 @@ func volumeListBuilder(c *core.Command) *core.Command { c.ArgsType = reflect.TypeOf(customListVolumesRequest{}) - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - args := argsI.(*customListVolumesRequest) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + args := argsI.(*customListVolumesRequest) - if args.ListVolumesRequest == nil { - args.ListVolumesRequest = &instance.ListVolumesRequest{} - } + if args.ListVolumesRequest == nil { + args.ListVolumesRequest = &instance.ListVolumesRequest{} + } - request := args.ListVolumesRequest - request.Organization = args.OrganizationID - request.Project = args.ProjectID + request := args.ListVolumesRequest + request.Organization = args.OrganizationID + request.Project = args.ProjectID - return runner(ctx, request) - }) + return runner(ctx, request) + }, + ) return c } @@ -119,12 +123,13 @@ func volumeWaitCommand() *core.Command { Run: func(ctx context.Context, argsI interface{}) (i interface{}, err error) { args := argsI.(*volumeWaitRequest) - return instance.NewAPI(core.ExtractClient(ctx)).WaitForVolume(&instance.WaitForVolumeRequest{ - Zone: args.Zone, - VolumeID: args.VolumeID, - Timeout: scw.TimeDurationPtr(args.Timeout), - RetryInterval: core.DefaultRetryInterval, - }) + return instance.NewAPI(core.ExtractClient(ctx)). + WaitForVolume(&instance.WaitForVolumeRequest{ + Zone: args.Zone, + VolumeID: args.VolumeID, + Timeout: scw.TimeDurationPtr(args.Timeout), + RetryInterval: core.DefaultRetryInterval, + }) }, ArgSpecs: core.ArgSpecs{ core.WaitTimeoutArgSpec(serverActionTimeout), diff --git a/internal/namespaces/instance/v1/custom_volume_type.go b/internal/namespaces/instance/v1/custom_volume_type.go index 76e55e5869..25cd25daf3 100644 --- a/internal/namespaces/instance/v1/custom_volume_type.go +++ b/internal/namespaces/instance/v1/custom_volume_type.go @@ -14,27 +14,29 @@ func volumeTypeListBuilder(cmd *core.Command) *core.Command { instance.VolumeType } - cmd.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { - res, err := runner(ctx, argsI) - if err != nil { - return res, err - } - - volumeTypes := []*customVolumeType(nil) - for typeName, volumeType := range res.(*instance.ListVolumesTypesResponse).Volumes { - volumeTypes = append(volumeTypes, &customVolumeType{ - Type: typeName, - VolumeType: *volumeType, + cmd.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + res, err := runner(ctx, argsI) + if err != nil { + return res, err + } + + volumeTypes := []*customVolumeType(nil) + for typeName, volumeType := range res.(*instance.ListVolumesTypesResponse).Volumes { + volumeTypes = append(volumeTypes, &customVolumeType{ + Type: typeName, + VolumeType: *volumeType, + }) + } + + // sort for consistent order output + sort.Slice(volumeTypes, func(i, j int) bool { + return volumeTypes[i].Type < volumeTypes[j].Type }) - } - // sort for consistent order output - sort.Slice(volumeTypes, func(i, j int) bool { - return volumeTypes[i].Type < volumeTypes[j].Type - }) - - return volumeTypes, nil - }) + return volumeTypes, nil + }, + ) cmd.AllowAnonymousClient = true diff --git a/internal/namespaces/instance/v1/helpers_test.go b/internal/namespaces/instance/v1/helpers_test.go index edbc67b10c..4c8bc37040 100644 --- a/internal/namespaces/instance/v1/helpers_test.go +++ b/internal/namespaces/instance/v1/helpers_test.go @@ -59,7 +59,11 @@ func deleteServer(metaKey string) core.AfterFunc { } } - return core.ExecAfterCmd("scw instance server delete {{ ." + metaKey + ".ID }} with-ip=true with-volumes=all")(ctx) + return core.ExecAfterCmd( + "scw instance server delete {{ ." + metaKey + ".ID }} with-ip=true with-volumes=all", + )( + ctx, + ) } } @@ -71,9 +75,17 @@ func deleteServer(metaKey string) core.AfterFunc { // register it in the context Meta at metaKey. // //nolint:unparam -func createVolume(metaKey string, sizeInGb int, volumeType instance.VolumeVolumeType) core.BeforeFunc { +func createVolume( + metaKey string, + sizeInGb int, + volumeType instance.VolumeVolumeType, +) core.BeforeFunc { return func(ctx *core.BeforeFuncCtx) error { - cmd := fmt.Sprintf("scw instance volume create name=cli-test size=%dGB volume-type=%s", sizeInGb, volumeType) + cmd := fmt.Sprintf( + "scw instance volume create name=cli-test size=%dGB volume-type=%s", + sizeInGb, + volumeType, + ) res := ctx.ExecuteCmd(strings.Split(cmd, " ")) createVolumeResponse := res.(*instance.CreateVolumeResponse) ctx.Meta[metaKey] = createVolumeResponse.Volume @@ -93,7 +105,11 @@ func deleteVolume(metaKey string) core.AfterFunc { //nolint: unparam //nolint:unparam func createSbsVolume(metaKey string, sizeInGb int) core.BeforeFunc { return func(ctx *core.BeforeFuncCtx) error { - cmd := fmt.Sprintf("scw block volume create name=%s from-empty.size=%dGB perf-iops=5000 -w", ctx.T.Name(), sizeInGb) + cmd := fmt.Sprintf( + "scw block volume create name=%s from-empty.size=%dGB perf-iops=5000 -w", + ctx.T.Name(), + sizeInGb, + ) res := ctx.ExecuteCmd(strings.Split(cmd, " ")) volume := res.(*block.Volume) ctx.Meta[metaKey] = volume @@ -196,7 +212,11 @@ func createNIC() core.BeforeFunc { // testServerSBSVolumeSize checks the size of a volume in an instance server. // The server must be returned by the given instanceFetcher function -func testServerFetcherSBSVolumeSize(volumeKey string, sizeInGB int, serverFetcher func(t *testing.T, ctx *core.CheckFuncCtx) *instance.Server) core.TestCheck { +func testServerFetcherSBSVolumeSize( + volumeKey string, + sizeInGB int, + serverFetcher func(t *testing.T, ctx *core.CheckFuncCtx) *instance.Server, +) core.TestCheck { return func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() server := serverFetcher(t, ctx) @@ -208,33 +228,51 @@ func testServerFetcherSBSVolumeSize(volumeKey string, sizeInGB int, serverFetche }) require.NoError(t, err) - require.Equal(t, scw.Size(sizeInGB)*scw.GB, volume.Size, "Size of volume should be %d GB", sizeInGB) + require.Equal( + t, + scw.Size(sizeInGB)*scw.GB, + volume.Size, + "Size of volume should be %d GB", + sizeInGB, + ) } } // testServerSBSVolumeSize checks the size of a volume in Result's server. // The server must be returned as result of the test's Cmd func testServerSBSVolumeSize(volumeKey string, sizeInGB int) core.TestCheck { - return testServerFetcherSBSVolumeSize(volumeKey, sizeInGB, func(t *testing.T, ctx *core.CheckFuncCtx) *instance.Server { - t.Helper() - - return testhelpers.Value[*instance.Server](t, ctx.Result) - }) + return testServerFetcherSBSVolumeSize( + volumeKey, + sizeInGB, + func(t *testing.T, ctx *core.CheckFuncCtx) *instance.Server { + t.Helper() + + return testhelpers.Value[*instance.Server](t, ctx.Result) + }, + ) } // testAttachVolumeServerSBSVolumeSize is the same as testServerSBSVolumeSize but the test's Cmd must be "scw instance server attach-volume" func testAttachVolumeServerSBSVolumeSize(volumeKey string, sizeInGB int) core.TestCheck { - return testServerFetcherSBSVolumeSize(volumeKey, sizeInGB, func(t *testing.T, ctx *core.CheckFuncCtx) *instance.Server { - t.Helper() - - return testhelpers.Value[*instance.AttachVolumeResponse](t, ctx.Result).Server - }) + return testServerFetcherSBSVolumeSize( + volumeKey, + sizeInGB, + func(t *testing.T, ctx *core.CheckFuncCtx) *instance.Server { + t.Helper() + + return testhelpers.Value[*instance.AttachVolumeResponse](t, ctx.Result).Server + }, + ) } func testServerUpdateServerSBSVolumeSize(volumeKey string, sizeInGB int) core.TestCheck { - return testServerFetcherSBSVolumeSize(volumeKey, sizeInGB, func(t *testing.T, ctx *core.CheckFuncCtx) *instance.Server { - t.Helper() - - return testhelpers.Value[*instance.UpdateServerResponse](t, ctx.Result).Server - }) + return testServerFetcherSBSVolumeSize( + volumeKey, + sizeInGB, + func(t *testing.T, ctx *core.CheckFuncCtx) *instance.Server { + t.Helper() + + return testhelpers.Value[*instance.UpdateServerResponse](t, ctx.Result).Server + }, + ) } diff --git a/internal/namespaces/instance/v1/helpers_types.go b/internal/namespaces/instance/v1/helpers_types.go index b31af9fa21..40b62eeaae 100644 --- a/internal/namespaces/instance/v1/helpers_types.go +++ b/internal/namespaces/instance/v1/helpers_types.go @@ -9,11 +9,16 @@ import ( "github.com/scaleway/scaleway-sdk-go/scw" ) -func completeServerType(ctx context.Context, prefix string, createReq any) core.AutocompleteSuggestions { +func completeServerType( + ctx context.Context, + prefix string, + createReq any, +) core.AutocompleteSuggestions { req := createReq.(*instanceCreateServerRequest) - resp, err := instance.NewAPI(core.ExtractClient(ctx)).ListServersTypes(&instance.ListServersTypesRequest{ - Zone: req.Zone, - }, scw.WithAllPages()) + resp, err := instance.NewAPI(core.ExtractClient(ctx)). + ListServersTypes(&instance.ListServersTypesRequest{ + Zone: req.Zone, + }, scw.WithAllPages()) if err != nil { return nil } diff --git a/internal/namespaces/instance/v1/instance_cli.go b/internal/namespaces/instance/v1/instance_cli.go index 39cdd7e60c..b688a9fb85 100644 --- a/internal/namespaces/instance/v1/instance_cli.go +++ b/internal/namespaces/instance/v1/instance_cli.go @@ -94,6 +94,7 @@ func GetGeneratedCommands() *core.Commands { instanceVolumeApplyMigration(), ) } + func instanceRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Instances`, @@ -291,15 +292,25 @@ func instanceServerTypeGet() *core.Command { // Deprecated: false, ArgsType: reflect.TypeOf(instance.GetServerTypesAvailabilityRequest{}), ArgSpecs: core.ArgSpecs{ - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetServerTypesAvailabilityRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetServerTypesAvailability(request) + return api.GetServerTypesAvailability(request) }, } } @@ -314,15 +325,25 @@ func instanceServerTypeList() *core.Command { // Deprecated: false, ArgsType: reflect.TypeOf(instance.ListServersTypesRequest{}), ArgSpecs: core.ArgSpecs{ - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListServersTypesRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.ListServersTypes(request) + return api.ListServersTypes(request) }, Examples: []*core.Example{ { @@ -347,15 +368,25 @@ func instanceVolumeTypeList() *core.Command { // Deprecated: false, ArgsType: reflect.TypeOf(instance.ListVolumesTypesRequest{}), ArgSpecs: core.ArgSpecs{ - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListVolumesTypesRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.ListVolumesTypes(request) + return api.ListVolumesTypes(request) }, Examples: []*core.Example{ { @@ -428,7 +459,14 @@ func instanceServerList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"running", "stopped", "stopped in place", "starting", "stopping", "locked"}, + EnumValues: []string{ + "running", + "stopped", + "stopped in place", + "starting", + "stopping", + "locked", + }, }, { Name: "tags", @@ -450,7 +488,12 @@ func instanceServerList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"creation_date_desc", "creation_date_asc", "modification_date_desc", "modification_date_asc"}, + EnumValues: []string{ + "creation_date_desc", + "creation_date_asc", + "modification_date_desc", + "modification_date_asc", + }, }, { Name: "private-networks", @@ -480,7 +523,18 @@ func instanceServerList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListServersRequest) @@ -496,8 +550,8 @@ func instanceServerList() *core.Command { if err != nil { return nil, err } - return resp.Servers, nil + return resp.Servers, nil }, Examples: []*core.Example{ { @@ -537,15 +591,25 @@ func instanceServerGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetServerRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetServer(request) + return api.GetServer(request) }, Examples: []*core.Example{ { @@ -629,7 +693,14 @@ func instanceServerUpdate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"l_ssd", "b_ssd", "unified", "scratch", "sbs_volume", "sbs_snapshot"}, + EnumValues: []string{ + "l_ssd", + "b_ssd", + "unified", + "scratch", + "sbs_volume", + "sbs_snapshot", + }, }, { Name: "volumes.{key}.base-snapshot", @@ -724,15 +795,25 @@ func instanceServerUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.UpdateServerRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.UpdateServer(request) + return api.UpdateServer(request) }, Examples: []*core.Example{ { @@ -775,15 +856,25 @@ func instanceServerListActions() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListServerActionsRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.ListServerActions(request) + return api.ListServerActions(request) }, } } @@ -805,15 +896,25 @@ func instanceUserDataList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListServerUserDataRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.ListServerUserData(request) + return api.ListServerUserData(request) }, } } @@ -842,7 +943,17 @@ func instanceUserDataDelete() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.DeleteServerUserDataRequest) @@ -853,6 +964,7 @@ func instanceUserDataDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "user-data", Verb: "delete", @@ -903,7 +1015,17 @@ func instanceUserDataSet() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.SetServerUserDataRequest) @@ -914,6 +1036,7 @@ func instanceUserDataSet() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "user-data", Verb: "set", @@ -946,15 +1069,25 @@ func instanceUserDataGet() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetServerUserDataRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetServerUserData(request) + return api.GetServerUserData(request) }, } } @@ -981,15 +1114,25 @@ If the specified Instance offer is flagged as end of service, the best compatibl Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetServerCompatibleTypesRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetServerCompatibleTypes(request) + return api.GetServerCompatibleTypes(request) }, } } @@ -1040,7 +1183,18 @@ func instanceImageList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListImagesRequest) @@ -1056,8 +1210,8 @@ func instanceImageList() *core.Command { if err != nil { return nil, err } - return resp.Images, nil + return resp.Images, nil }, Examples: []*core.Example{ { @@ -1091,15 +1245,25 @@ func instanceImageGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetImageRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetImage(request) + return api.GetImage(request) }, Examples: []*core.Example{ { @@ -1174,7 +1338,14 @@ func instanceImageCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"l_ssd", "b_ssd", "unified", "scratch", "sbs_volume", "sbs_snapshot"}, + EnumValues: []string{ + "l_ssd", + "b_ssd", + "unified", + "scratch", + "sbs_volume", + "sbs_snapshot", + }, }, { Name: "extra-volumes.{key}.project", @@ -1206,15 +1377,25 @@ func instanceImageCreate() *core.Command { Positional: false, }, core.OrganizationArgSpec(), - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.CreateImageRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.CreateImage(request) + return api.CreateImage(request) }, Examples: []*core.Example{ { @@ -1278,15 +1459,25 @@ func instanceImageUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.UpdateImageRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.UpdateImage(request) + return api.UpdateImage(request) }, } } @@ -1308,7 +1499,17 @@ func instanceImageDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.DeleteImageRequest) @@ -1319,6 +1520,7 @@ func instanceImageDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "image", Verb: "delete", @@ -1382,7 +1584,18 @@ func instanceSnapshotList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListSnapshotsRequest) @@ -1398,8 +1611,8 @@ func instanceSnapshotList() *core.Command { if err != nil { return nil, err } - return resp.Snapshots, nil + return resp.Snapshots, nil }, Examples: []*core.Example{ { @@ -1477,15 +1690,25 @@ func instanceSnapshotCreate() *core.Command { Positional: false, }, core.OrganizationArgSpec(), - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.CreateSnapshotRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.CreateSnapshot(request) + return api.CreateSnapshot(request) }, Examples: []*core.Example{ { @@ -1525,15 +1748,25 @@ func instanceSnapshotGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetSnapshotRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetSnapshot(request) + return api.GetSnapshot(request) }, Examples: []*core.Example{ { @@ -1579,15 +1812,25 @@ func instanceSnapshotUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.UpdateSnapshotRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.UpdateSnapshot(request) + return api.UpdateSnapshot(request) }, } } @@ -1609,7 +1852,17 @@ func instanceSnapshotDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.DeleteSnapshotRequest) @@ -1620,6 +1873,7 @@ func instanceSnapshotDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "snapshot", Verb: "delete", @@ -1669,15 +1923,25 @@ func instanceSnapshotExport() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ExportSnapshotRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.ExportSnapshot(request) + return api.ExportSnapshot(request) }, Examples: []*core.Example{ { @@ -1704,7 +1968,14 @@ func instanceVolumeList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"l_ssd", "b_ssd", "unified", "scratch", "sbs_volume", "sbs_snapshot"}, + EnumValues: []string{ + "l_ssd", + "b_ssd", + "unified", + "scratch", + "sbs_volume", + "sbs_snapshot", + }, }, { Name: "project", @@ -1734,7 +2005,18 @@ func instanceVolumeList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListVolumesRequest) @@ -1750,8 +2032,8 @@ func instanceVolumeList() *core.Command { if err != nil { return nil, err } - return resp.Volumes, nil + return resp.Volumes, nil }, Examples: []*core.Example{ { @@ -1848,7 +2130,14 @@ func instanceVolumeCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"l_ssd", "b_ssd", "unified", "scratch", "sbs_volume", "sbs_snapshot"}, + EnumValues: []string{ + "l_ssd", + "b_ssd", + "unified", + "scratch", + "sbs_volume", + "sbs_snapshot", + }, }, { Name: "size", @@ -1865,15 +2154,25 @@ func instanceVolumeCreate() *core.Command { Positional: false, }, core.OrganizationArgSpec(), - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.CreateVolumeRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.CreateVolume(request) + return api.CreateVolume(request) }, Examples: []*core.Example{ { @@ -1905,15 +2204,25 @@ func instanceVolumeGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetVolumeRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetVolume(request) + return api.GetVolume(request) }, Examples: []*core.Example{ { @@ -1962,15 +2271,25 @@ func instanceVolumeUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.UpdateVolumeRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.UpdateVolume(request) + return api.UpdateVolume(request) }, Examples: []*core.Example{ { @@ -2006,7 +2325,17 @@ func instanceVolumeDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.DeleteVolumeRequest) @@ -2017,6 +2346,7 @@ func instanceVolumeDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "volume", Verb: "delete", @@ -2076,7 +2406,18 @@ func instanceSecurityGroupList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListSecurityGroupsRequest) @@ -2092,8 +2433,8 @@ func instanceSecurityGroupList() *core.Command { if err != nil { return nil, err } - return resp.SecurityGroups, nil + return resp.SecurityGroups, nil }, Examples: []*core.Example{ { @@ -2185,15 +2526,25 @@ func instanceSecurityGroupCreate() *core.Command { Positional: false, }, core.OrganizationArgSpec(), - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.CreateSecurityGroupRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.CreateSecurityGroup(request) + return api.CreateSecurityGroup(request) }, Examples: []*core.Example{ { @@ -2237,15 +2588,25 @@ func instanceSecurityGroupGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetSecurityGroupRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetSecurityGroup(request) + return api.GetSecurityGroup(request) }, Examples: []*core.Example{ { @@ -2273,7 +2634,17 @@ func instanceSecurityGroupDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.DeleteSecurityGroupRequest) @@ -2284,6 +2655,7 @@ func instanceSecurityGroupDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "security-group", Verb: "delete", @@ -2380,15 +2752,25 @@ func instanceSecurityGroupUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.UpdateSecurityGroupRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.UpdateSecurityGroup(request) + return api.UpdateSecurityGroup(request) }, } } @@ -2403,15 +2785,25 @@ func instanceSecurityGroupListDefaultRules() *core.Command { // Deprecated: false, ArgsType: reflect.TypeOf(instance.ListDefaultSecurityGroupRulesRequest{}), ArgSpecs: core.ArgSpecs{ - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListDefaultSecurityGroupRulesRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.ListDefaultSecurityGroupRules(request) + return api.ListDefaultSecurityGroupRules(request) }, } } @@ -2433,7 +2825,18 @@ func instanceSecurityGroupListRules() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListSecurityGroupRulesRequest) @@ -2449,8 +2852,8 @@ func instanceSecurityGroupListRules() *core.Command { if err != nil { return nil, err } - return resp.Rules, nil + return resp.Rules, nil }, } } @@ -2528,15 +2931,25 @@ func instanceSecurityGroupCreateRule() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.CreateSecurityGroupRuleRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.CreateSecurityGroupRule(request) + return api.CreateSecurityGroupRule(request) }, Examples: []*core.Example{ { @@ -2653,15 +3066,25 @@ func instanceSecurityGroupSetRules() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.SetSecurityGroupRulesRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.SetSecurityGroupRules(request) + return api.SetSecurityGroupRules(request) }, } } @@ -2688,7 +3111,17 @@ func instanceSecurityGroupDeleteRule() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.DeleteSecurityGroupRuleRequest) @@ -2699,6 +3132,7 @@ func instanceSecurityGroupDeleteRule() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "security-group", Verb: "delete-rule", @@ -2735,15 +3169,25 @@ func instanceSecurityGroupGetRule() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetSecurityGroupRuleRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetSecurityGroupRule(request) + return api.GetSecurityGroupRule(request) }, Examples: []*core.Example{ { @@ -2830,15 +3274,25 @@ func instanceSecurityGroupUpdateRule() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.UpdateSecurityGroupRuleRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.UpdateSecurityGroupRule(request) + return api.UpdateSecurityGroupRule(request) }, } } @@ -2881,7 +3335,18 @@ func instancePlacementGroupList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListPlacementGroupsRequest) @@ -2897,8 +3362,8 @@ func instancePlacementGroupList() *core.Command { if err != nil { return nil, err } - return resp.PlacementGroups, nil + return resp.PlacementGroups, nil }, Examples: []*core.Example{ { @@ -2956,15 +3421,25 @@ func instancePlacementGroupCreate() *core.Command { EnumValues: []string{"max_availability", "low_latency"}, }, core.OrganizationArgSpec(), - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.CreatePlacementGroupRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.CreatePlacementGroup(request) + return api.CreatePlacementGroup(request) }, Examples: []*core.Example{ { @@ -3012,15 +3487,25 @@ func instancePlacementGroupGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetPlacementGroupRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetPlacementGroup(request) + return api.GetPlacementGroup(request) }, Examples: []*core.Example{ { @@ -3075,15 +3560,25 @@ func instancePlacementGroupSet() *core.Command { Positional: false, }, core.OrganizationArgSpec(), - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.SetPlacementGroupRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.SetPlacementGroup(request) + return api.SetPlacementGroup(request) }, } } @@ -3135,15 +3630,25 @@ func instancePlacementGroupUpdate() *core.Command { Positional: false, EnumValues: []string{"max_availability", "low_latency"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.UpdatePlacementGroupRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.UpdatePlacementGroup(request) + return api.UpdatePlacementGroup(request) }, Examples: []*core.Example{ { @@ -3179,7 +3684,17 @@ func instancePlacementGroupDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.DeletePlacementGroupRequest) @@ -3190,6 +3705,7 @@ func instancePlacementGroupDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "placement-group", Verb: "delete", @@ -3225,15 +3741,25 @@ func instancePlacementGroupGetServers() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetPlacementGroupServersRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetPlacementGroupServers(request) + return api.GetPlacementGroupServers(request) }, } } @@ -3262,15 +3788,25 @@ func instancePlacementGroupSetServers() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.SetPlacementGroupServersRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.SetPlacementGroupServers(request) + return api.SetPlacementGroupServers(request) }, Examples: []*core.Example{ { @@ -3305,15 +3841,25 @@ func instancePlacementGroupUpdateServers() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.UpdatePlacementGroupServersRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.UpdatePlacementGroupServers(request) + return api.UpdatePlacementGroupServers(request) }, } } @@ -3363,7 +3909,18 @@ func instanceIPList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListIPsRequest) @@ -3379,8 +3936,8 @@ func instanceIPList() *core.Command { if err != nil { return nil, err } - return resp.IPs, nil + return resp.IPs, nil }, Examples: []*core.Example{ { @@ -3464,15 +4021,25 @@ func instanceIPCreate() *core.Command { EnumValues: []string{"unknown_iptype", "routed_ipv4", "routed_ipv6"}, }, core.OrganizationArgSpec(), - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.CreateIPRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.CreateIP(request) + return api.CreateIP(request) }, Examples: []*core.Example{ { @@ -3508,15 +4075,25 @@ func instanceIPGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetIPRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetIP(request) + return api.GetIP(request) }, Examples: []*core.Example{ { @@ -3574,15 +4151,25 @@ func instanceIPUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.UpdateIPRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.UpdateIP(request) + return api.UpdateIP(request) }, Examples: []*core.Example{ { @@ -3618,7 +4205,17 @@ func instanceIPDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.DeleteIPRequest) @@ -3629,6 +4226,7 @@ func instanceIPDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "ip", Verb: "delete", @@ -3675,7 +4273,18 @@ func instancePrivateNicList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ListPrivateNICsRequest) @@ -3691,8 +4300,8 @@ func instancePrivateNicList() *core.Command { if err != nil { return nil, err } - return resp.PrivateNics, nil + return resp.PrivateNics, nil }, Examples: []*core.Example{ { @@ -3752,15 +4361,25 @@ func instancePrivateNicCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.CreatePrivateNICRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.CreatePrivateNIC(request) + return api.CreatePrivateNIC(request) }, } } @@ -3789,15 +4408,25 @@ func instancePrivateNicGet() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.GetPrivateNICRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.GetPrivateNIC(request) + return api.GetPrivateNIC(request) }, } } @@ -3833,15 +4462,25 @@ func instancePrivateNicUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.UpdatePrivateNICRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.UpdatePrivateNIC(request) + return api.UpdatePrivateNIC(request) }, Examples: []*core.Example{ { @@ -3876,7 +4515,17 @@ func instancePrivateNicDelete() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.DeletePrivateNICRequest) @@ -3887,6 +4536,7 @@ func instancePrivateNicDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "private-nic", Verb: "delete", @@ -3923,15 +4573,25 @@ The endpoint also returns the validation_key, which must be provided to the [Mig Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.PlanBlockMigrationRequest) client := core.ExtractClient(ctx) api := instance.NewAPI(client) - return api.PlanBlockMigration(request) + return api.PlanBlockMigration(request) }, } } @@ -3967,7 +4627,17 @@ func instanceVolumeApplyMigration() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneFrPar3, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneFrPar3, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*instance.ApplyBlockMigrationRequest) @@ -3978,6 +4648,7 @@ func instanceVolumeApplyMigration() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "volume", Verb: "apply-migration", diff --git a/internal/namespaces/instance/v1/instance_cli_test.go b/internal/namespaces/instance/v1/instance_cli_test.go index d78f820fe2..0f41261fff 100644 --- a/internal/namespaces/instance/v1/instance_cli_test.go +++ b/internal/namespaces/instance/v1/instance_cli_test.go @@ -89,57 +89,69 @@ func Test_ServerUpdate(t *testing.T) { AfterFunc: deleteServer("Server"), })) - t.Run(`No initial placement group & placement-group-id=`, core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.BeforeFuncCombine( - createPlacementGroup("PlacementGroup"), - createServer("Server"), - ), - Cmd: `scw instance server update {{ .Server.ID }} placement-group-id={{ .PlacementGroup.ID }}`, - Check: core.TestCheckCombine( - func(t *testing.T, ctx *core.CheckFuncCtx) { - t.Helper() - require.NoError(t, ctx.Err) - assert.Equal(t, - ctx.Meta["PlacementGroup"].(*instanceSDK.PlacementGroup).ID, - ctx.Result.(*instanceSDK.UpdateServerResponse).Server.PlacementGroup.ID, - ) - }, - core.TestCheckExitCode(0), - ), - AfterFunc: core.AfterFuncCombine( - deleteServer("Server"), - deletePlacementGroup("PlacementGroup"), - ), - })) + t.Run( + `No initial placement group & placement-group-id=`, + core.Test(&core.TestConfig{ + Commands: instance.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + createPlacementGroup("PlacementGroup"), + createServer("Server"), + ), + Cmd: `scw instance server update {{ .Server.ID }} placement-group-id={{ .PlacementGroup.ID }}`, + Check: core.TestCheckCombine( + func(t *testing.T, ctx *core.CheckFuncCtx) { + t.Helper() + require.NoError(t, ctx.Err) + assert.Equal(t, + ctx.Meta["PlacementGroup"].(*instanceSDK.PlacementGroup).ID, + ctx.Result.(*instanceSDK.UpdateServerResponse).Server.PlacementGroup.ID, + ) + }, + core.TestCheckExitCode(0), + ), + AfterFunc: core.AfterFuncCombine( + deleteServer("Server"), + deletePlacementGroup("PlacementGroup"), + ), + }), + ) - t.Run(`No initial placement group & placement-group-id=`, core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: createServer("Server"), - Cmd: `scw instance server update {{ .Server.ID }} placement-group-id=11111111-1111-1111-1111-111111111111`, - Check: core.TestCheckCombine( - core.TestCheckExitCode(1), - core.TestCheckGolden(), - ), - AfterFunc: deleteServer("Server"), - })) + t.Run( + `No initial placement group & placement-group-id=`, + core.Test(&core.TestConfig{ + Commands: instance.GetCommands(), + BeforeFunc: createServer("Server"), + Cmd: `scw instance server update {{ .Server.ID }} placement-group-id=11111111-1111-1111-1111-111111111111`, + Check: core.TestCheckCombine( + core.TestCheckExitCode(1), + core.TestCheckGolden(), + ), + AfterFunc: deleteServer("Server"), + }), + ) - t.Run(`No initial placement group & placement-group-id=`, core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: createServer("Server"), - Cmd: `scw instance server update {{ .Server.ID }} placement-group-id=1111111`, - Check: core.TestCheckCombine( - core.TestCheckExitCode(1), - core.TestCheckGolden(), - ), - AfterFunc: deleteServer("Server"), - })) + t.Run( + `No initial placement group & placement-group-id=`, + core.Test(&core.TestConfig{ + Commands: instance.GetCommands(), + BeforeFunc: createServer("Server"), + Cmd: `scw instance server update {{ .Server.ID }} placement-group-id=1111111`, + Check: core.TestCheckCombine( + core.TestCheckExitCode(1), + core.TestCheckGolden(), + ), + AfterFunc: deleteServer("Server"), + }), + ) t.Run(`Initial placement group & placement-group-id=none`, core.Test(&core.TestConfig{ Commands: instance.GetCommands(), BeforeFunc: core.BeforeFuncCombine( createPlacementGroup("PlacementGroup"), - core.ExecStoreBeforeCmd("Server", testServerCommand("placement-group-id={{ .PlacementGroup.ID }} stopped=true")), + core.ExecStoreBeforeCmd( + "Server", + testServerCommand("placement-group-id={{ .PlacementGroup.ID }} stopped=true"), + ), ), Cmd: `scw instance server update {{ .Server.ID }} placement-group-id=none`, Check: core.TestCheckCombine( @@ -156,36 +168,45 @@ func Test_ServerUpdate(t *testing.T) { ), })) - t.Run(`Initial placement group & placement-group-id=`, core.Test(&core.TestConfig{ - Commands: instance.GetCommands(), - BeforeFunc: core.BeforeFuncCombine( - createPlacementGroup("PlacementGroup"), - core.ExecStoreBeforeCmd("Server", testServerCommand("placement-group-id={{ .PlacementGroup.ID }} stopped=true")), - ), - Cmd: `scw instance server update {{ .Server.ID }} placement-group-id={{ .PlacementGroup.ID }}`, - Check: core.TestCheckCombine( - func(t *testing.T, ctx *core.CheckFuncCtx) { - t.Helper() - require.NoError(t, ctx.Err) - assert.Equal(t, - ctx.Meta["PlacementGroup"].(*instanceSDK.PlacementGroup).ID, - ctx.Result.(*instanceSDK.UpdateServerResponse).Server.PlacementGroup.ID, - ) - }, - core.TestCheckExitCode(0), - ), - AfterFunc: core.AfterFuncCombine( - deleteServer("Server"), - deletePlacementGroup("PlacementGroup"), - ), - })) + t.Run( + `Initial placement group & placement-group-id=`, + core.Test(&core.TestConfig{ + Commands: instance.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + createPlacementGroup("PlacementGroup"), + core.ExecStoreBeforeCmd( + "Server", + testServerCommand("placement-group-id={{ .PlacementGroup.ID }} stopped=true"), + ), + ), + Cmd: `scw instance server update {{ .Server.ID }} placement-group-id={{ .PlacementGroup.ID }}`, + Check: core.TestCheckCombine( + func(t *testing.T, ctx *core.CheckFuncCtx) { + t.Helper() + require.NoError(t, ctx.Err) + assert.Equal(t, + ctx.Meta["PlacementGroup"].(*instanceSDK.PlacementGroup).ID, + ctx.Result.(*instanceSDK.UpdateServerResponse).Server.PlacementGroup.ID, + ) + }, + core.TestCheckExitCode(0), + ), + AfterFunc: core.AfterFuncCombine( + deleteServer("Server"), + deletePlacementGroup("PlacementGroup"), + ), + }), + ) t.Run(`Initial placement group & placement-group-id=`, core.Test(&core.TestConfig{ Commands: instance.GetCommands(), BeforeFunc: core.BeforeFuncCombine( createPlacementGroup("PlacementGroup1"), createPlacementGroup("PlacementGroup2"), - core.ExecStoreBeforeCmd("Server", testServerCommand("placement-group-id={{ .PlacementGroup1.ID }} stopped=true")), + core.ExecStoreBeforeCmd( + "Server", + testServerCommand("placement-group-id={{ .PlacementGroup1.ID }} stopped=true"), + ), ), Cmd: `scw instance server update {{ .Server.ID }} placement-group-id={{ .PlacementGroup2.ID }}`, Check: core.TestCheckCombine( diff --git a/internal/namespaces/interlink/v1beta1/custom.go b/internal/namespaces/interlink/v1beta1/custom.go index c899704850..e1fe31bed9 100644 --- a/internal/namespaces/interlink/v1beta1/custom.go +++ b/internal/namespaces/interlink/v1beta1/custom.go @@ -9,8 +9,14 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(interlink.BgpStatus(""), human.EnumMarshalFunc(bgpStatusMarshalSpecs)) - human.RegisterMarshalerFunc(interlink.LinkStatus(""), human.EnumMarshalFunc(linkStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + interlink.BgpStatus(""), + human.EnumMarshalFunc(bgpStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + interlink.LinkStatus(""), + human.EnumMarshalFunc(linkStatusMarshalSpecs), + ) return cmds } diff --git a/internal/namespaces/interlink/v1beta1/interlink_cli.go b/internal/namespaces/interlink/v1beta1/interlink_cli.go index bf46999769..0a4b0f7bff 100644 --- a/internal/namespaces/interlink/v1beta1/interlink_cli.go +++ b/internal/namespaces/interlink/v1beta1/interlink_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/interlink/v1beta1" + interlink "github.com/scaleway/scaleway-sdk-go/api/interlink/v1beta1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -46,6 +46,7 @@ func GetGeneratedCommands() *core.Commands { interlinkRoutingPolicyDelete(), ) } + func interlinkRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your InterLink services`, @@ -115,7 +116,12 @@ func interlinkPartnerList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*interlink.ListPartnersRequest) @@ -131,8 +137,8 @@ func interlinkPartnerList() *core.Command { if err != nil { return nil, err } - return resp.Partners, nil + return resp.Partners, nil }, } } @@ -161,8 +167,8 @@ func interlinkPartnerGet() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.GetPartner(request) + return api.GetPartner(request) }, } } @@ -213,7 +219,12 @@ func interlinkPopList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*interlink.ListPopsRequest) @@ -229,8 +240,8 @@ func interlinkPopList() *core.Command { if err != nil { return nil, err } - return resp.Pops, nil + return resp.Pops, nil }, } } @@ -259,8 +270,8 @@ func interlinkPopGet() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.GetPop(request) + return api.GetPop(request) }, } } @@ -281,7 +292,14 @@ func interlinkLinkList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "status_asc", "status_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + "status_asc", + "status_desc", + }, }, { Name: "project-id", @@ -310,7 +328,21 @@ func interlinkLinkList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_link_status", "configuring", "failed", "requested", "refused", "expired", "provisioning", "active", "limited_connectivity", "all_down", "deprovisioning", "deleted", "locked"}, + EnumValues: []string{ + "unknown_link_status", + "configuring", + "failed", + "requested", + "refused", + "expired", + "provisioning", + "active", + "limited_connectivity", + "all_down", + "deprovisioning", + "deleted", + "locked", + }, }, { Name: "bgp-v4-status", @@ -377,7 +409,12 @@ func interlinkLinkList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*interlink.ListLinksRequest) @@ -393,8 +430,8 @@ func interlinkLinkList() *core.Command { if err != nil { return nil, err } - return resp.Links, nil + return resp.Links, nil }, } } @@ -423,8 +460,8 @@ func interlinkLinkGet() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.GetLink(request) + return api.GetLink(request) }, } } @@ -432,7 +469,7 @@ func interlinkLinkGet() *core.Command { func interlinkLinkCreate() *core.Command { return &core.Command{ Short: `Create a link`, - Long: `Create a link (InterLink connection) in a given PoP, specifying its various configuration details. For the moment only hosted links (faciliated by partners) are available, though in the future dedicated and shared links will also be possible.`, + Long: `Create a link (InterLink connection) in a given PoP, specifying its various configuration details. For the moment only hosted links (facilitated by partners) are available, though in the future dedicated and shared links will also be possible.`, Namespace: "interlink", Resource: "link", Verb: "create", @@ -496,8 +533,8 @@ func interlinkLinkCreate() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.CreateLink(request) + return api.CreateLink(request) }, } } @@ -540,8 +577,8 @@ func interlinkLinkUpdate() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.UpdateLink(request) + return api.UpdateLink(request) }, } } @@ -570,8 +607,8 @@ func interlinkLinkDelete() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.DeleteLink(request) + return api.DeleteLink(request) }, } } @@ -607,8 +644,8 @@ func interlinkLinkAttachVpc() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.AttachVpc(request) + return api.AttachVpc(request) }, } } @@ -637,8 +674,8 @@ func interlinkLinkDetachVpc() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.DetachVpc(request) + return api.DetachVpc(request) }, } } @@ -674,8 +711,8 @@ func interlinkLinkAttachPolicy() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.AttachRoutingPolicy(request) + return api.AttachRoutingPolicy(request) }, } } @@ -704,8 +741,8 @@ func interlinkLinkDetachPolicy() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.DetachRoutingPolicy(request) + return api.DetachRoutingPolicy(request) }, } } @@ -734,8 +771,8 @@ func interlinkLinkEnablePropagation() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.EnableRoutePropagation(request) + return api.EnableRoutePropagation(request) }, } } @@ -764,8 +801,8 @@ func interlinkLinkDisablePropagation() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.DisableRoutePropagation(request) + return api.DisableRoutePropagation(request) }, } } @@ -816,7 +853,12 @@ func interlinkRoutingPolicyList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*interlink.ListRoutingPoliciesRequest) @@ -832,8 +874,8 @@ func interlinkRoutingPolicyList() *core.Command { if err != nil { return nil, err } - return resp.RoutingPolicies, nil + return resp.RoutingPolicies, nil }, } } @@ -862,8 +904,8 @@ func interlinkRoutingPolicyGet() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.GetRoutingPolicy(request) + return api.GetRoutingPolicy(request) }, } } @@ -914,8 +956,8 @@ func interlinkRoutingPolicyCreate() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.CreateRoutingPolicy(request) + return api.CreateRoutingPolicy(request) }, } } @@ -972,8 +1014,8 @@ func interlinkRoutingPolicyUpdate() *core.Command { client := core.ExtractClient(ctx) api := interlink.NewAPI(client) - return api.UpdateRoutingPolicy(request) + return api.UpdateRoutingPolicy(request) }, } } @@ -1006,6 +1048,7 @@ func interlinkRoutingPolicyDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "routing-policy", Verb: "delete", diff --git a/internal/namespaces/iot/v1/custom.go b/internal/namespaces/iot/v1/custom.go index 19ec403d9d..618a4c5d81 100644 --- a/internal/namespaces/iot/v1/custom.go +++ b/internal/namespaces/iot/v1/custom.go @@ -10,8 +10,14 @@ func GetCommands() *core.Commands { cmds := GetGeneratedCommands() human.RegisterMarshalerFunc(iot.HubStatus(""), human.EnumMarshalFunc(hubStatusMarshalSpecs)) - human.RegisterMarshalerFunc(iot.DeviceMessageFiltersRulePolicy(""), human.EnumMarshalFunc(deviceMessageFiltersRulePolicyMarshalSpecs)) - human.RegisterMarshalerFunc(iot.DeviceStatus(""), human.EnumMarshalFunc(deviceStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + iot.DeviceMessageFiltersRulePolicy(""), + human.EnumMarshalFunc(deviceMessageFiltersRulePolicyMarshalSpecs), + ) + human.RegisterMarshalerFunc( + iot.DeviceStatus(""), + human.EnumMarshalFunc(deviceStatusMarshalSpecs), + ) human.RegisterMarshalerFunc(iot.CreateNetworkResponse{}, iotNetworkCreateResponsedMarshalerFunc) human.RegisterMarshalerFunc(iot.CreateDeviceResponse{}, iotDeviceCreateResponsedMarshalerFunc) diff --git a/internal/namespaces/iot/v1/custom_device.go b/internal/namespaces/iot/v1/custom_device.go index 9f25f23da7..4f3269029e 100644 --- a/internal/namespaces/iot/v1/custom_device.go +++ b/internal/namespaces/iot/v1/custom_device.go @@ -11,12 +11,21 @@ import ( var ( deviceMessageFiltersRulePolicyMarshalSpecs = human.EnumMarshalSpecs{ - iot.DeviceMessageFiltersRulePolicyAccept: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "accept"}, - iot.DeviceMessageFiltersRulePolicyReject: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "reject"}, + iot.DeviceMessageFiltersRulePolicyAccept: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "accept", + }, + iot.DeviceMessageFiltersRulePolicyReject: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "reject", + }, } deviceStatusMarshalSpecs = human.EnumMarshalSpecs{ - iot.DeviceStatusEnabled: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "enabled"}, + iot.DeviceStatusEnabled: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "enabled", + }, iot.DeviceStatusDisabled: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "disabled"}, iot.DeviceStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "error"}, } diff --git a/internal/namespaces/iot/v1/iot_cli.go b/internal/namespaces/iot/v1/iot_cli.go index ccb48e176e..f2d8a595e3 100644 --- a/internal/namespaces/iot/v1/iot_cli.go +++ b/internal/namespaces/iot/v1/iot_cli.go @@ -55,6 +55,7 @@ func GetGeneratedCommands() *core.Commands { iotNetworkDelete(), ) } + func iotRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your IoT hubs and devices`, @@ -115,7 +116,18 @@ func iotHubList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"name_asc", "name_desc", "status_asc", "status_desc", "product_plan_asc", "product_plan_desc", "created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc"}, + EnumValues: []string{ + "name_asc", + "name_desc", + "status_asc", + "status_desc", + "product_plan_asc", + "product_plan_desc", + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + }, }, { Name: "project-id", @@ -154,8 +166,8 @@ func iotHubList() *core.Command { if err != nil { return nil, err } - return resp.Hubs, nil + return resp.Hubs, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -262,8 +274,8 @@ func iotHubCreate() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.CreateHub(request) + return api.CreateHub(request) }, } } @@ -292,8 +304,8 @@ func iotHubGet() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.GetHub(request) + return api.GetHub(request) }, } } @@ -364,8 +376,8 @@ func iotHubUpdate() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.UpdateHub(request) + return api.UpdateHub(request) }, } } @@ -394,8 +406,8 @@ func iotHubEnable() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.EnableHub(request) + return api.EnableHub(request) }, } } @@ -424,8 +436,8 @@ func iotHubDisable() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.DisableHub(request) + return api.DisableHub(request) }, } } @@ -465,6 +477,7 @@ func iotHubDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "hub", Verb: "delete", @@ -511,8 +524,8 @@ func iotHubSetCa() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.SetHubCA(request) + return api.SetHubCA(request) }, } } @@ -540,8 +553,8 @@ func iotHubGetCa() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.GetHubCA(request) + return api.GetHubCA(request) }, } } @@ -562,7 +575,20 @@ func iotDeviceList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"name_asc", "name_desc", "status_asc", "status_desc", "hub_id_asc", "hub_id_desc", "created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "allow_insecure_asc", "allow_insecure_desc"}, + EnumValues: []string{ + "name_asc", + "name_desc", + "status_asc", + "status_desc", + "hub_id_asc", + "hub_id_desc", + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "allow_insecure_asc", + "allow_insecure_desc", + }, }, { Name: "name", @@ -580,7 +606,7 @@ func iotDeviceList() *core.Command { }, { Name: "allow-insecure", - Short: `Defines wheter to filter the allow_insecure flag`, + Short: `Defines whether to filter the allow_insecure flag`, Required: false, Deprecated: false, Positional: false, @@ -609,8 +635,8 @@ func iotDeviceList() *core.Command { if err != nil { return nil, err } - return resp.Devices, nil + return resp.Devices, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -736,8 +762,8 @@ func iotDeviceCreate() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.CreateDevice(request) + return api.CreateDevice(request) }, } } @@ -766,8 +792,8 @@ func iotDeviceGet() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.GetDevice(request) + return api.GetDevice(request) }, } } @@ -854,8 +880,8 @@ func iotDeviceUpdate() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.UpdateDevice(request) + return api.UpdateDevice(request) }, } } @@ -884,8 +910,8 @@ func iotDeviceEnable() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.EnableDevice(request) + return api.EnableDevice(request) }, } } @@ -914,8 +940,8 @@ func iotDeviceDisable() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.DisableDevice(request) + return api.DisableDevice(request) }, } } @@ -944,8 +970,8 @@ func iotDeviceRenewCertificate() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.RenewDeviceCertificate(request) + return api.RenewDeviceCertificate(request) }, } } @@ -981,8 +1007,8 @@ func iotDeviceSetCertificate() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.SetDeviceCertificate(request) + return api.SetDeviceCertificate(request) }, } } @@ -1011,8 +1037,8 @@ func iotDeviceGetCertificate() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.GetDeviceCertificate(request) + return api.GetDeviceCertificate(request) }, } } @@ -1045,6 +1071,7 @@ func iotDeviceDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "device", Verb: "delete", @@ -1084,8 +1111,8 @@ func iotDeviceGetMetrics() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.GetDeviceMetrics(request) + return api.GetDeviceMetrics(request) }, } } @@ -1106,7 +1133,16 @@ func iotRouteList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"name_asc", "name_desc", "hub_id_asc", "hub_id_desc", "type_asc", "type_desc", "created_at_asc", "created_at_desc"}, + EnumValues: []string{ + "name_asc", + "name_desc", + "hub_id_asc", + "hub_id_desc", + "type_asc", + "type_desc", + "created_at_asc", + "created_at_desc", + }, }, { Name: "hub-id", @@ -1138,8 +1174,8 @@ func iotRouteList() *core.Command { if err != nil { return nil, err } - return resp.Routes, nil + return resp.Routes, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -1299,8 +1335,8 @@ func iotRouteCreate() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.CreateRoute(request) + return api.CreateRoute(request) }, } } @@ -1430,8 +1466,8 @@ func iotRouteUpdate() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.UpdateRoute(request) + return api.UpdateRoute(request) }, } } @@ -1460,8 +1496,8 @@ func iotRouteGet() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.GetRoute(request) + return api.GetRoute(request) }, } } @@ -1494,6 +1530,7 @@ func iotRouteDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "route", Verb: "delete", @@ -1518,7 +1555,14 @@ func iotNetworkList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"name_asc", "name_desc", "type_asc", "type_desc", "created_at_asc", "created_at_desc"}, + EnumValues: []string{ + "name_asc", + "name_desc", + "type_asc", + "type_desc", + "created_at_asc", + "created_at_desc", + }, }, { Name: "name", @@ -1557,8 +1601,8 @@ func iotNetworkList() *core.Command { if err != nil { return nil, err } - return resp.Networks, nil + return resp.Networks, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -1633,8 +1677,8 @@ func iotNetworkCreate() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.CreateNetwork(request) + return api.CreateNetwork(request) }, } } @@ -1663,8 +1707,8 @@ func iotNetworkGet() *core.Command { client := core.ExtractClient(ctx) api := iot.NewAPI(client) - return api.GetNetwork(request) + return api.GetNetwork(request) }, } } @@ -1697,6 +1741,7 @@ func iotNetworkDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "network", Verb: "delete", diff --git a/internal/namespaces/ipam/v1/ipam_cli.go b/internal/namespaces/ipam/v1/ipam_cli.go index 0e54b604d3..df113590d4 100644 --- a/internal/namespaces/ipam/v1/ipam_cli.go +++ b/internal/namespaces/ipam/v1/ipam_cli.go @@ -30,6 +30,7 @@ func GetGeneratedCommands() *core.Commands { ipamIPList(), ) } + func ipamRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Scaleway IP addresses with our IP Address Management tool`, @@ -130,8 +131,8 @@ func ipamIPCreate() *core.Command { client := core.ExtractClient(ctx) api := ipam.NewAPI(client) - return api.BookIP(request) + return api.BookIP(request) }, } } @@ -164,6 +165,7 @@ func ipamIPDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "ip", Verb: "delete", @@ -199,6 +201,7 @@ func ipamIPSetRelease() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "ip-set", Verb: "release", @@ -231,8 +234,8 @@ func ipamIPGet() *core.Command { client := core.ExtractClient(ctx) api := ipam.NewAPI(client) - return api.GetIP(request) + return api.GetIP(request) }, } } @@ -282,8 +285,8 @@ func ipamIPUpdate() *core.Command { client := core.ExtractClient(ctx) api := ipam.NewAPI(client) - return api.UpdateIP(request) + return api.UpdateIP(request) }, } } @@ -304,7 +307,14 @@ func ipamIPList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_desc", "created_at_asc", "updated_at_desc", "updated_at_asc", "attached_at_desc", "attached_at_asc"}, + EnumValues: []string{ + "created_at_desc", + "created_at_asc", + "updated_at_desc", + "updated_at_asc", + "attached_at_desc", + "attached_at_asc", + }, }, { Name: "project-id", @@ -375,7 +385,29 @@ func ipamIPList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_type", "custom", "instance_server", "instance_ip", "instance_private_nic", "lb_server", "fip_ip", "vpc_gateway", "vpc_gateway_network", "k8s_node", "k8s_cluster", "rdb_instance", "redis_cluster", "baremetal_server", "baremetal_private_nic", "llm_deployment", "mgdb_instance", "apple_silicon_server", "apple_silicon_private_nic", "serverless_container", "serverless_function"}, + EnumValues: []string{ + "unknown_type", + "custom", + "instance_server", + "instance_ip", + "instance_private_nic", + "lb_server", + "fip_ip", + "vpc_gateway", + "vpc_gateway_network", + "k8s_node", + "k8s_cluster", + "rdb_instance", + "redis_cluster", + "baremetal_server", + "baremetal_private_nic", + "llm_deployment", + "mgdb_instance", + "apple_silicon_server", + "apple_silicon_private_nic", + "serverless_container", + "serverless_function", + }, }, { Name: "resource-types.{index}", @@ -383,7 +415,29 @@ func ipamIPList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_type", "custom", "instance_server", "instance_ip", "instance_private_nic", "lb_server", "fip_ip", "vpc_gateway", "vpc_gateway_network", "k8s_node", "k8s_cluster", "rdb_instance", "redis_cluster", "baremetal_server", "baremetal_private_nic", "llm_deployment", "mgdb_instance", "apple_silicon_server", "apple_silicon_private_nic", "serverless_container", "serverless_function"}, + EnumValues: []string{ + "unknown_type", + "custom", + "instance_server", + "instance_ip", + "instance_private_nic", + "lb_server", + "fip_ip", + "vpc_gateway", + "vpc_gateway_network", + "k8s_node", + "k8s_cluster", + "rdb_instance", + "redis_cluster", + "baremetal_server", + "baremetal_private_nic", + "llm_deployment", + "mgdb_instance", + "apple_silicon_server", + "apple_silicon_private_nic", + "serverless_container", + "serverless_function", + }, }, { Name: "mac-address", @@ -420,7 +474,12 @@ func ipamIPList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*ipam.ListIPsRequest) @@ -436,8 +495,8 @@ func ipamIPList() *core.Command { if err != nil { return nil, err } - return resp.IPs, nil + return resp.IPs, nil }, } } diff --git a/internal/namespaces/jobs/v1alpha1/custom.go b/internal/namespaces/jobs/v1alpha1/custom.go index a3e81b9e65..2a52670d55 100644 --- a/internal/namespaces/jobs/v1alpha1/custom.go +++ b/internal/namespaces/jobs/v1alpha1/custom.go @@ -20,7 +20,10 @@ var jobRunStateMarshalSpecs = human.EnumMarshalSpecs{ func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(jobs.JobRunState(""), human.EnumMarshalFunc(jobRunStateMarshalSpecs)) + human.RegisterMarshalerFunc( + jobs.JobRunState(""), + human.EnumMarshalFunc(jobRunStateMarshalSpecs), + ) cmds.Merge(core.NewCommands( jobsRunWait(), diff --git a/internal/namespaces/jobs/v1alpha1/jobs_cli.go b/internal/namespaces/jobs/v1alpha1/jobs_cli.go index bdd47a52a7..693e297055 100644 --- a/internal/namespaces/jobs/v1alpha1/jobs_cli.go +++ b/internal/namespaces/jobs/v1alpha1/jobs_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/jobs/v1alpha1" + jobs "github.com/scaleway/scaleway-sdk-go/api/jobs/v1alpha1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -39,6 +39,7 @@ func GetGeneratedCommands() *core.Commands { jobsRunList(), ) } + func jobsRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Serverless Jobs`, @@ -168,8 +169,8 @@ func jobsDefinitionCreate() *core.Command { client := core.ExtractClient(ctx) api := jobs.NewAPI(client) - return api.CreateJobDefinition(request) + return api.CreateJobDefinition(request) }, } } @@ -198,8 +199,8 @@ func jobsDefinitionGet() *core.Command { client := core.ExtractClient(ctx) api := jobs.NewAPI(client) - return api.GetJobDefinition(request) + return api.GetJobDefinition(request) }, } } @@ -233,7 +234,12 @@ func jobsDefinitionList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*jobs.ListJobDefinitionsRequest) @@ -249,8 +255,8 @@ func jobsDefinitionList() *core.Command { if err != nil { return nil, err } - return resp.JobDefinitions, nil + return resp.JobDefinitions, nil }, } } @@ -354,8 +360,8 @@ func jobsDefinitionUpdate() *core.Command { client := core.ExtractClient(ctx) api := jobs.NewAPI(client) - return api.UpdateJobDefinition(request) + return api.UpdateJobDefinition(request) }, } } @@ -388,6 +394,7 @@ func jobsDefinitionDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "definition", Verb: "delete", @@ -441,8 +448,8 @@ func jobsDefinitionStart() *core.Command { client := core.ExtractClient(ctx) api := jobs.NewAPI(client) - return api.StartJobDefinition(request) + return api.StartJobDefinition(request) }, } } @@ -495,8 +502,8 @@ func jobsSecretCreate() *core.Command { client := core.ExtractClient(ctx) api := jobs.NewAPI(client) - return api.CreateJobDefinitionSecrets(request) + return api.CreateJobDefinitionSecrets(request) }, } } @@ -532,8 +539,8 @@ func jobsSecretGet() *core.Command { client := core.ExtractClient(ctx) api := jobs.NewAPI(client) - return api.GetJobDefinitionSecret(request) + return api.GetJobDefinitionSecret(request) }, } } @@ -562,8 +569,8 @@ func jobsSecretList() *core.Command { client := core.ExtractClient(ctx) api := jobs.NewAPI(client) - return api.ListJobDefinitionSecrets(request) + return api.ListJobDefinitionSecrets(request) }, } } @@ -620,8 +627,8 @@ func jobsSecretUpdate() *core.Command { client := core.ExtractClient(ctx) api := jobs.NewAPI(client) - return api.UpdateJobDefinitionSecret(request) + return api.UpdateJobDefinitionSecret(request) }, } } @@ -661,6 +668,7 @@ func jobsSecretDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "secret", Verb: "delete", @@ -693,8 +701,8 @@ func jobsRunGet() *core.Command { client := core.ExtractClient(ctx) api := jobs.NewAPI(client) - return api.GetJobRun(request) + return api.GetJobRun(request) }, } } @@ -723,8 +731,8 @@ func jobsRunStop() *core.Command { client := core.ExtractClient(ctx) api := jobs.NewAPI(client) - return api.StopJobRun(request) + return api.StopJobRun(request) }, } } @@ -763,7 +771,16 @@ func jobsRunList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_state", "queued", "scheduled", "running", "succeeded", "failed", "canceled", "internal_error"}, + EnumValues: []string{ + "unknown_state", + "queued", + "scheduled", + "running", + "succeeded", + "failed", + "canceled", + "internal_error", + }, }, { Name: "organization-id", @@ -771,7 +788,12 @@ func jobsRunList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*jobs.ListJobRunsRequest) @@ -787,8 +809,8 @@ func jobsRunList() *core.Command { if err != nil { return nil, err } - return resp.JobRuns, nil + return resp.JobRuns, nil }, } } diff --git a/internal/namespaces/k8s/v1/custom.go b/internal/namespaces/k8s/v1/custom.go index 0d1dc6faa0..6412024509 100644 --- a/internal/namespaces/k8s/v1/custom.go +++ b/internal/namespaces/k8s/v1/custom.go @@ -27,12 +27,19 @@ func GetCommands() *core.Commands { human.RegisterMarshalerFunc(k8s.Version{}, versionMarshalerFunc) human.RegisterMarshalerFunc(k8s.Cluster{}, clusterMarshalerFunc) - human.RegisterMarshalerFunc(k8s.ClusterStatus(""), human.EnumMarshalFunc(clusterStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + k8s.ClusterStatus(""), + human.EnumMarshalFunc(clusterStatusMarshalSpecs), + ) human.RegisterMarshalerFunc(k8s.PoolStatus(""), human.EnumMarshalFunc(poolStatusMarshalSpecs)) human.RegisterMarshalerFunc(k8s.NodeStatus(""), human.EnumMarshalFunc(nodeStatusMarshalSpecs)) - human.RegisterMarshalerFunc(k8s.ListClusterAvailableTypesResponse{}, clusterAvailableTypesListMarshalerFunc) + human.RegisterMarshalerFunc( + k8s.ListClusterAvailableTypesResponse{}, + clusterAvailableTypesListMarshalerFunc, + ) - cmds.MustFind("k8s", "cluster", "list-available-versions").Override(clusterAvailableVersionsListBuilder) + cmds.MustFind("k8s", "cluster", "list-available-versions"). + Override(clusterAvailableVersionsListBuilder) cmds.MustFind("k8s", "cluster", "create").Override(clusterCreateBuilder) cmds.MustFind("k8s", "cluster", "get").Override(clusterGetBuilder) cmds.MustFind("k8s", "cluster", "update").Override(clusterUpdateBuilder) diff --git a/internal/namespaces/k8s/v1/custom_cluster.go b/internal/namespaces/k8s/v1/custom_cluster.go index c1eed4d006..96949c944e 100644 --- a/internal/namespaces/k8s/v1/custom_cluster.go +++ b/internal/namespaces/k8s/v1/custom_cluster.go @@ -92,16 +92,18 @@ func clusterAvailableTypesListMarshalerFunc(i interface{}, opt *human.MarshalOpt } func clusterAvailableVersionsListBuilder(c *core.Command) *core.Command { - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { - originalRes, err := runner(ctx, argsI) - if err != nil { - return nil, err - } + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + originalRes, err := runner(ctx, argsI) + if err != nil { + return nil, err + } - listClusterAvailableVersionsResponse := originalRes.(*k8s.ListClusterAvailableVersionsResponse) + listClusterAvailableVersionsResponse := originalRes.(*k8s.ListClusterAvailableVersionsResponse) - return listClusterAvailableVersionsResponse.Versions, nil - }) + return listClusterAvailableVersionsResponse.Versions, nil + }, + ) return c } @@ -159,7 +161,11 @@ func clusterCreateBuilder(c *core.Command) *core.Command { } } if !validType { - return nil, fmt.Errorf("invalid cluster type %q, must be one of %v", request.Type, validTypes) + return nil, fmt.Errorf( + "invalid cluster type %q, must be one of %v", + request.Type, + validTypes, + ) } } @@ -349,12 +355,13 @@ func waitForClusterFunc(action int) core.WaitFunc { } else { clusterResponse = respI.(*k8s.Cluster) } - cluster, err := k8s.NewAPI(core.ExtractClient(ctx)).WaitForCluster(&k8s.WaitForClusterRequest{ - Region: clusterResponse.Region, - ClusterID: clusterResponse.ID, - Timeout: scw.TimeDurationPtr(clusterActionTimeout), - RetryInterval: core.DefaultRetryInterval, - }) + cluster, err := k8s.NewAPI(core.ExtractClient(ctx)). + WaitForCluster(&k8s.WaitForClusterRequest{ + Region: clusterResponse.Region, + ClusterID: clusterResponse.ID, + Timeout: scw.TimeDurationPtr(clusterActionTimeout), + RetryInterval: core.DefaultRetryInterval, + }) switch action { case clusterActionCreate: return cluster, err @@ -367,7 +374,9 @@ func waitForClusterFunc(action int) core.WaitFunc { // if we get a 404 here, it means the resource was successfully deleted notFoundError := &scw.ResourceNotFoundError{} responseError := &scw.ResponseError{} - if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) { + if errors.As(err, &responseError) && + responseError.StatusCode == http.StatusNotFound || + errors.As(err, ¬FoundError) { return fmt.Sprintf("Cluster %s successfully deleted.", clusterResponse.ID), nil } } @@ -454,7 +463,11 @@ func k8sClusterWaitCommand() *core.Command { // Caching ListClusterTypes response for shell completion var completeListClusterTypesCache *k8s.ListClusterTypesResponse -func autocompleteClusterType(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autocompleteClusterType( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { req := request.(*k8s.CreateClusterRequest) suggestions := core.AutocompleteSuggestions(nil) @@ -483,7 +496,11 @@ func autocompleteClusterType(ctx context.Context, prefix string, request any) co // Caching ListK8SVersions response for shell completion var completeListK8SVersionsCache *k8s.ListVersionsResponse -func autocompleteK8SVersion(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autocompleteK8SVersion( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { req := request.(*k8s.CreateClusterRequest) suggestions := core.AutocompleteSuggestions(nil) diff --git a/internal/namespaces/k8s/v1/custom_execcredentials.go b/internal/namespaces/k8s/v1/custom_execcredentials.go index 4a0422f0be..4d4b469c2b 100644 --- a/internal/namespaces/k8s/v1/custom_execcredentials.go +++ b/internal/namespaces/k8s/v1/custom_execcredentials.go @@ -43,14 +43,17 @@ func k8sExecCredentialRun(ctx context.Context, _ interface{}) (i interface{}, e case config.Profiles[profileName] != nil && config.Profiles[profileName].SecretKey != nil: token = *config.Profiles[profileName].SecretKey // Default config - case config.Profile.SecretKey != nil: - token = *config.Profile.SecretKey + case config.SecretKey != nil: + token = *config.SecretKey default: return nil, errors.New("unable to find secret key") } if !validation.IsSecretKey(token) { - return nil, fmt.Errorf("invalid secret key format '%s', expected a UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", token) + return nil, fmt.Errorf( + "invalid secret key format '%s', expected a UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + token, + ) } execCreds := ExecCredential{ diff --git a/internal/namespaces/k8s/v1/custom_kubeconfig_get_test.go b/internal/namespaces/k8s/v1/custom_kubeconfig_get_test.go index c05fa43665..da60a22050 100644 --- a/internal/namespaces/k8s/v1/custom_kubeconfig_get_test.go +++ b/internal/namespaces/k8s/v1/custom_kubeconfig_get_test.go @@ -16,9 +16,14 @@ func Test_GetKubeconfig(t *testing.T) { // Simple use cases //// t.Run("simple", core.Test(&core.TestConfig{ - Commands: k8s.GetCommands(), - BeforeFunc: createClusterAndWaitAndKubeconfig("get-kubeconfig", "Cluster", "Kubeconfig", kapsuleVersion), - Cmd: "scw k8s kubeconfig get {{ .Cluster.ID }}", + Commands: k8s.GetCommands(), + BeforeFunc: createClusterAndWaitAndKubeconfig( + "get-kubeconfig", + "Cluster", + "Kubeconfig", + kapsuleVersion, + ), + Cmd: "scw k8s kubeconfig get {{ .Cluster.ID }}", Check: core.TestCheckCombine( core.TestCheckGolden(), func(t *testing.T, ctx *core.CheckFuncCtx) { diff --git a/internal/namespaces/k8s/v1/custom_kubeconfig_install.go b/internal/namespaces/k8s/v1/custom_kubeconfig_install.go index 9ddbe73454..7e5c98df24 100644 --- a/internal/namespaces/k8s/v1/custom_kubeconfig_install.go +++ b/internal/namespaces/k8s/v1/custom_kubeconfig_install.go @@ -188,5 +188,9 @@ func k8sKubeconfigInstallRun(ctx context.Context, argsI interface{}) (i interfac return nil, err } - return fmt.Sprintf("Kubeconfig for cluster %s successfully written at %s", request.ClusterID, kubeconfigPath), nil + return fmt.Sprintf( + "Kubeconfig for cluster %s successfully written at %s", + request.ClusterID, + kubeconfigPath, + ), nil } diff --git a/internal/namespaces/k8s/v1/custom_kubeconfig_install_test.go b/internal/namespaces/k8s/v1/custom_kubeconfig_install_test.go index 15149fe546..780bd9f35d 100644 --- a/internal/namespaces/k8s/v1/custom_kubeconfig_install_test.go +++ b/internal/namespaces/k8s/v1/custom_kubeconfig_install_test.go @@ -79,11 +79,15 @@ y7JHcXauRKI7bxgOugSep2d0lhYxJl65CPOCllawcu70Ds34MKi3XkCe20I= { Name: "test", AuthInfo: api.AuthInfo{ - Token: "qotGxuOfD74ajgWir18tMMPicxLIizKg3nt5PKHGbsbNDbGfqNojIdXI", - Username: "test", - Password: "test", - ClientCertificateData: []byte("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMvekNDQWVlZ0F3SUJBZ0lJZERQak80Umphdzh3RFFZSktvWklodmNOQVFFTEJRQXdGVEVUTUJFR0ExVUUKQXhNS2EzVmlaWEp1WlhSbGN6QWVGdzB5TURBek1qTXdPRFEyTkRoYUZ3MHlNVEF6TWpNd09EUTJORGhhTUVFeApGekFWQmdOVkJBb1REbk41YzNSbGJUcHRZWE4wWlhKek1TWXdKQVlEVlFRREV4MXJkV0psTFdGd2FYTmxjblpsCmNpMXJkV0psYkdWMExXTnNhV1Z1ZERDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUIKQU54VjByQ0lBemNsdXIyV1VNb3NqOW1LQmlkclYzcnB5RmNwdnltMmtFVjZaOVo2TTBSRXpyTHo1c3BaWndCTwo1bHZrbEdzL2RJVndFK2pBd2tNWWNRRWlOaTQ2bHU4UFNSei9HVTFkek5mOEF2TXpnRWZER0xUY2x3eUs4di9kCklLenhTUnVOUFFseDZoTUw1bFpDeVBBZ3hqejNEdDZGWmUxUnVUdURWTUhnOWZIaHNwOFZTYnVCbWFYTTU2T0IKLzNZQXJLMXZOTlY0enRlQ3libFZnVUd3QUdKQ09zTlE0d0l4R0xSdjN5TVhtK3V3YVpGeTFxSEh6ZlpXclRpQQpKQ2lQNFVCbDV3bnUzeEhNaFZaemI0RnNCLzBmVEl1WHQ0ZjQ5L201KzdpM01vMEdrMjJNMjAvQldzNURZVmo1CnptSVVxcU9kK09UekdkcjgvcTRsdnQ4Q0F3RUFBYU1uTUNVd0RnWURWUjBQQVFIL0JBUURBZ1dnTUJNR0ExVWQKSlFRTU1Bb0dDQ3NHQVFVRkJ3TUNNQTBHQ1NxR1NJYjNEUUVCQ3dVQUE0SUJBUUNuVFFCWlhsbm1aVWpDNEdscwpKdTZWWEYxN040ckpzWkNVOVR3SEhETlpZNGo5YlZHbG8wZzAva3JTajBId3hNNVU1NXl2WUJDaWNpZzVkSS96Cnd2ZENUQm5FQWIxRWtuZVR1ZkVPYzFtNzBtSzg0dnd3WWZtRVNkY1NXMmJieHBuUFNpak5BdnlTekZTTmZZZDEKMy9FZlRlQjQ0VFNGRGZQVk83YnpKYXBpYVJCTlZocVJQSncwc0lJWGM1Q0hiQzFEMHU5Mk4zRnhCa3JKcFN2UAp1QXBQT2dyNUgwUk5rOEk2TTBjd0FBc1RqdUkxd2Z4MjhJU0FWcmZLUjU4d1Eza1NsZzlUTTQrN01VMFA4eUZHClJXRkIrVFZiMTExYTRDc2RSbWMzQnZtcnFEbjZ2Ny9LOTJ4c0hNeDdBd3FObk1XUDQ4QStoVFNFVFh3U1Btb3cKL040RAotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg=="), - ClientKeyData: []byte("LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcFFJQkFBS0NBUUVBM0ZYU3NJZ0ROeVc2dlpaUXlpeVAyWW9HSjJ0WGV1bklWeW0vS2JhUVJYcG4xbm96ClJFVE9zdlBteWxsbkFFN21XK1NVYXo5MGhYQVQ2TURDUXhoeEFTSTJManFXN3c5SkhQOFpUVjNNMS93Qzh6T0EKUjhNWXROeVhESXJ5LzkwZ3JQRkpHNDA5Q1hIcUV3dm1Wa0xJOENER1BQY08zb1ZsN1ZHNU80TlV3ZUQxOGVHeQpueFZKdTRHWnBjem5vNEgvZGdDc3JXODAxWGpPMTRMSnVWV0JRYkFBWWtJNncxRGpBakVZdEcvZkl4ZWI2N0JwCmtYTFdvY2ZOOWxhdE9JQWtLSS9oUUdYbkNlN2ZFY3lGVm5OdmdXd0gvUjlNaTVlM2gvajMrYm43dUxjeWpRYVQKYll6YlQ4RmF6a05oV1BuT1loU3FvNTM0NVBNWjJ2eityaVcrM3dJREFRQUJBb0lCQVFESDRsdldwaTAwbEZmSwpzbGpzY0d5M2p3MXlLV0VkTW9UNi9mWmNJekRTdHU4SWxhZDRvV3RhMFFWb1FKNittdFZFUENPZy85bjNTK3ZqCjFTcm1yMytrNWFKOVljMlhaaWlQMDZUaW1OdkNmTzg0TGxxTHY2UGtQOUlRSU9XOTFKOVdCVGFyZGdBUFYzWmcKZlFVaThFZFdBSVdXdlJLU01EWjlpd3dkdjFEZTZFUmt4Z0Y2R0NTSXQ2Ri80RS81Uk1VbkJObU1ycjZHWHR5NgorK0cxWExCcWxRdExYVm1yRDAyVW05Y1Yyb2QwOEczTzdUM3VqUWl6ZjR6emx4LzVWWGk0ZTFkVEViY05PRU53Cnlwd3lSajBCdFh2TXVwUXZvdUZRM3I5UmVQL0g5dmp1Q3NiZGF3T1pGQkFDb3J0UVJxcnFodENZMERRK2tiM1AKQWV1SjNnb0JBb0dCQU56QU0rbzBqckhKWGZJVFppSWEwZkV4QkIyNHBpTE5NTmoxaHIxSEJFWjI2eXFucFg5UApTSkRIbXhWREo2UXROZFQxZ3Y5L1MwelF3S2ZzYVZ5M2VYNW9OcU5hVEZERGhPSEoxWDZZUElwREZGTUgwNGV2CnRXV1ZNd21MVU9mdmhQR3NYOW5rdFRlVmxueTlnSUZOK0dkWFRTSlgyOEVIaHE2NGg4ay9IVXFCQW9HQkFQK0UKb2pVcUN3RWJ0UTIzcGRwYjNGRnNwdXZWM0F1aENiNnNmcUlxQ1ovVDRlUXJSSWtPU2luYmlva042ZFR5MVhuNQp6cGlJTEhOQ20wYkl2cVpJZmhkdERsUlcwcGQxbmlGZ2R3c3FacjdFUlFlN29XSHZkbVRwa1NaQ2p1M04zb1NjCjRPSmUwVmxBdWdwMjRsbms2bisxb01ySjJRUjNqQkxQVGUvZ3dKbGZBb0dCQUtBcUhBQ3J6WFNWQThLbDdJNkcKSXhqNlZXQXpIdWRWTlVIVk1zT1dDVFlQQmlWV3FhOHJHUjFpbGRUaGVwdVY2ZDd2bXZKQnE2SzZPMjRiQzM4bgo1OUNkVURkSlJ1RzZXbWx3QmFUcVU5S0ZSUFBSVTlxNDA4WTJjR2RXVzRkTXM0cWRaSlkxYUg1QjNJUDVBb25PCnhwSkVOMFRadGluaGlnaXUvbVkza3NzQkFvR0JBUFZDb0ZnYmhQaUpXZDVTMnRXZnV2aEZMR3ZPbVNwb1p1d28Kc2x5QnNUOUNwOTdWVVRHbEQ3Ymh6allEcnVFQ1BicVk5NThkaGwwVUgrdHZvT0FIVVZDM0V6d05JcExUQ1BmTQptamVUZVkrKzRPdXRSQmkzTzVOZFJqL05QMWd2ZFZraEpCTGxKRmxoY2JHOXIwTE9JZkIzckdFNkloN1JpUmc4CjkvZzZhV1JOQW9HQWJSSG94d1B4MUVlRnRxVDlUdXowZWZUR3RwQTB0bkhDZTN2b2x1L201eEZ6N3BwS29HeUQKRkNPVm5jMmZ3LzQwYUFGTGdHYlFLMFBqTzFCbWZ3cjFvb09aT1hZYnExUXo3Q1cvN3A1OUFkR0VrWXFzdWZZcAp6OXlMd1dBUEdybm9jVjBVQXZ2SHcvbC9OK29NZEdpdmVTdDhRb3RHclgzdm9PTmVsWThCZDRNPQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo="), + Token: "qotGxuOfD74ajgWir18tMMPicxLIizKg3nt5PKHGbsbNDbGfqNojIdXI", + Username: "test", + Password: "test", + ClientCertificateData: []byte( + "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMvekNDQWVlZ0F3SUJBZ0lJZERQak80Umphdzh3RFFZSktvWklodmNOQVFFTEJRQXdGVEVUTUJFR0ExVUUKQXhNS2EzVmlaWEp1WlhSbGN6QWVGdzB5TURBek1qTXdPRFEyTkRoYUZ3MHlNVEF6TWpNd09EUTJORGhhTUVFeApGekFWQmdOVkJBb1REbk41YzNSbGJUcHRZWE4wWlhKek1TWXdKQVlEVlFRREV4MXJkV0psTFdGd2FYTmxjblpsCmNpMXJkV0psYkdWMExXTnNhV1Z1ZERDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUIKQU54VjByQ0lBemNsdXIyV1VNb3NqOW1LQmlkclYzcnB5RmNwdnltMmtFVjZaOVo2TTBSRXpyTHo1c3BaWndCTwo1bHZrbEdzL2RJVndFK2pBd2tNWWNRRWlOaTQ2bHU4UFNSei9HVTFkek5mOEF2TXpnRWZER0xUY2x3eUs4di9kCklLenhTUnVOUFFseDZoTUw1bFpDeVBBZ3hqejNEdDZGWmUxUnVUdURWTUhnOWZIaHNwOFZTYnVCbWFYTTU2T0IKLzNZQXJLMXZOTlY0enRlQ3libFZnVUd3QUdKQ09zTlE0d0l4R0xSdjN5TVhtK3V3YVpGeTFxSEh6ZlpXclRpQQpKQ2lQNFVCbDV3bnUzeEhNaFZaemI0RnNCLzBmVEl1WHQ0ZjQ5L201KzdpM01vMEdrMjJNMjAvQldzNURZVmo1CnptSVVxcU9kK09UekdkcjgvcTRsdnQ4Q0F3RUFBYU1uTUNVd0RnWURWUjBQQVFIL0JBUURBZ1dnTUJNR0ExVWQKSlFRTU1Bb0dDQ3NHQVFVRkJ3TUNNQTBHQ1NxR1NJYjNEUUVCQ3dVQUE0SUJBUUNuVFFCWlhsbm1aVWpDNEdscwpKdTZWWEYxN040ckpzWkNVOVR3SEhETlpZNGo5YlZHbG8wZzAva3JTajBId3hNNVU1NXl2WUJDaWNpZzVkSS96Cnd2ZENUQm5FQWIxRWtuZVR1ZkVPYzFtNzBtSzg0dnd3WWZtRVNkY1NXMmJieHBuUFNpak5BdnlTekZTTmZZZDEKMy9FZlRlQjQ0VFNGRGZQVk83YnpKYXBpYVJCTlZocVJQSncwc0lJWGM1Q0hiQzFEMHU5Mk4zRnhCa3JKcFN2UAp1QXBQT2dyNUgwUk5rOEk2TTBjd0FBc1RqdUkxd2Z4MjhJU0FWcmZLUjU4d1Eza1NsZzlUTTQrN01VMFA4eUZHClJXRkIrVFZiMTExYTRDc2RSbWMzQnZtcnFEbjZ2Ny9LOTJ4c0hNeDdBd3FObk1XUDQ4QStoVFNFVFh3U1Btb3cKL040RAotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==", + ), + ClientKeyData: []byte( + "LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcFFJQkFBS0NBUUVBM0ZYU3NJZ0ROeVc2dlpaUXlpeVAyWW9HSjJ0WGV1bklWeW0vS2JhUVJYcG4xbm96ClJFVE9zdlBteWxsbkFFN21XK1NVYXo5MGhYQVQ2TURDUXhoeEFTSTJManFXN3c5SkhQOFpUVjNNMS93Qzh6T0EKUjhNWXROeVhESXJ5LzkwZ3JQRkpHNDA5Q1hIcUV3dm1Wa0xJOENER1BQY08zb1ZsN1ZHNU80TlV3ZUQxOGVHeQpueFZKdTRHWnBjem5vNEgvZGdDc3JXODAxWGpPMTRMSnVWV0JRYkFBWWtJNncxRGpBakVZdEcvZkl4ZWI2N0JwCmtYTFdvY2ZOOWxhdE9JQWtLSS9oUUdYbkNlN2ZFY3lGVm5OdmdXd0gvUjlNaTVlM2gvajMrYm43dUxjeWpRYVQKYll6YlQ4RmF6a05oV1BuT1loU3FvNTM0NVBNWjJ2eityaVcrM3dJREFRQUJBb0lCQVFESDRsdldwaTAwbEZmSwpzbGpzY0d5M2p3MXlLV0VkTW9UNi9mWmNJekRTdHU4SWxhZDRvV3RhMFFWb1FKNittdFZFUENPZy85bjNTK3ZqCjFTcm1yMytrNWFKOVljMlhaaWlQMDZUaW1OdkNmTzg0TGxxTHY2UGtQOUlRSU9XOTFKOVdCVGFyZGdBUFYzWmcKZlFVaThFZFdBSVdXdlJLU01EWjlpd3dkdjFEZTZFUmt4Z0Y2R0NTSXQ2Ri80RS81Uk1VbkJObU1ycjZHWHR5NgorK0cxWExCcWxRdExYVm1yRDAyVW05Y1Yyb2QwOEczTzdUM3VqUWl6ZjR6emx4LzVWWGk0ZTFkVEViY05PRU53Cnlwd3lSajBCdFh2TXVwUXZvdUZRM3I5UmVQL0g5dmp1Q3NiZGF3T1pGQkFDb3J0UVJxcnFodENZMERRK2tiM1AKQWV1SjNnb0JBb0dCQU56QU0rbzBqckhKWGZJVFppSWEwZkV4QkIyNHBpTE5NTmoxaHIxSEJFWjI2eXFucFg5UApTSkRIbXhWREo2UXROZFQxZ3Y5L1MwelF3S2ZzYVZ5M2VYNW9OcU5hVEZERGhPSEoxWDZZUElwREZGTUgwNGV2CnRXV1ZNd21MVU9mdmhQR3NYOW5rdFRlVmxueTlnSUZOK0dkWFRTSlgyOEVIaHE2NGg4ay9IVXFCQW9HQkFQK0UKb2pVcUN3RWJ0UTIzcGRwYjNGRnNwdXZWM0F1aENiNnNmcUlxQ1ovVDRlUXJSSWtPU2luYmlva042ZFR5MVhuNQp6cGlJTEhOQ20wYkl2cVpJZmhkdERsUlcwcGQxbmlGZ2R3c3FacjdFUlFlN29XSHZkbVRwa1NaQ2p1M04zb1NjCjRPSmUwVmxBdWdwMjRsbms2bisxb01ySjJRUjNqQkxQVGUvZ3dKbGZBb0dCQUtBcUhBQ3J6WFNWQThLbDdJNkcKSXhqNlZXQXpIdWRWTlVIVk1zT1dDVFlQQmlWV3FhOHJHUjFpbGRUaGVwdVY2ZDd2bXZKQnE2SzZPMjRiQzM4bgo1OUNkVURkSlJ1RzZXbWx3QmFUcVU5S0ZSUFBSVTlxNDA4WTJjR2RXVzRkTXM0cWRaSlkxYUg1QjNJUDVBb25PCnhwSkVOMFRadGluaGlnaXUvbVkza3NzQkFvR0JBUFZDb0ZnYmhQaUpXZDVTMnRXZnV2aEZMR3ZPbVNwb1p1d28Kc2x5QnNUOUNwOTdWVVRHbEQ3Ymh6allEcnVFQ1BicVk5NThkaGwwVUgrdHZvT0FIVVZDM0V6d05JcExUQ1BmTQptamVUZVkrKzRPdXRSQmkzTzVOZFJqL05QMWd2ZFZraEpCTGxKRmxoY2JHOXIwTE9JZkIzckdFNkloN1JpUmc4CjkvZzZhV1JOQW9HQWJSSG94d1B4MUVlRnRxVDlUdXowZWZUR3RwQTB0bkhDZTN2b2x1L201eEZ6N3BwS29HeUQKRkNPVm5jMmZ3LzQwYUFGTGdHYlFLMFBqTzFCbWZ3cjFvb09aT1hZYnExUXo3Q1cvN3A1OUFkR0VrWXFzdWZZcAp6OXlMd1dBUEdybm9jVjBVQXZ2SHcvbC9OK29NZEdpdmVTdDhRb3RHclgzdm9PTmVsWThCZDRNPQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=", + ), }, }, }, @@ -107,7 +111,11 @@ func testIfKubeconfigInFile(t *testing.T, filePath string, suffix string, kubeco // t.Log(string(kubeconfig.Clusters[0].Cluster.CertificateAuthorityData)) // panic(string(cluster.Cluster.CertificateAuthorityData)) // panic(string(kubeconfig.Clusters[0].Cluster.CertificateAuthorityData)) - assert.Equal(t, string(kubeconfig.Clusters[0].Cluster.CertificateAuthorityData), string(cluster.Cluster.CertificateAuthorityData)) + assert.Equal( + t, + string(kubeconfig.Clusters[0].Cluster.CertificateAuthorityData), + string(cluster.Cluster.CertificateAuthorityData), + ) assert.Equal(t, kubeconfig.Clusters[0].Cluster.Server, cluster.Cluster.Server) found = true @@ -120,7 +128,11 @@ func testIfKubeconfigInFile(t *testing.T, filePath string, suffix string, kubeco for _, context := range existingKubeconfig.Contexts { if context.Name == kubeconfig.Contexts[0].Name+suffix { assert.Equal(t, kubeconfig.Contexts[0].Context.Cluster+suffix, context.Context.Cluster) - assert.Equal(t, kubeconfig.Contexts[0].Context.AuthInfo+suffix, context.Context.AuthInfo) + assert.Equal( + t, + kubeconfig.Contexts[0].Context.AuthInfo+suffix, + context.Context.AuthInfo, + ) assert.Equal(t, kubeconfig.Contexts[0].Context.Namespace, context.Context.Namespace) found = true @@ -146,14 +158,24 @@ func Test_InstallKubeconfig(t *testing.T) { // Simple use cases //// t.Run("simple", core.Test(&core.TestConfig{ - Commands: k8s.GetCommands(), - BeforeFunc: createClusterAndWaitAndKubeconfig("install-kubeconfig-simple", "Cluster", "Kubeconfig", kapsuleVersion), - Cmd: "scw k8s kubeconfig install {{ .Cluster.ID }}", + Commands: k8s.GetCommands(), + BeforeFunc: createClusterAndWaitAndKubeconfig( + "install-kubeconfig-simple", + "Cluster", + "Kubeconfig", + kapsuleVersion, + ), + Cmd: "scw k8s kubeconfig install {{ .Cluster.ID }}", Check: core.TestCheckCombine( // no golden tests since it's os specific func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - testIfKubeconfigInFile(t, path.Join(os.TempDir(), "cli-test"), "-"+ctx.Meta["Cluster"].(*k8sSDK.Cluster).ID, ctx.Meta["Kubeconfig"].(api.Config)) + testIfKubeconfigInFile( + t, + path.Join(os.TempDir(), "cli-test"), + "-"+ctx.Meta["Cluster"].(*k8sSDK.Cluster).ID, + ctx.Meta["Kubeconfig"].(api.Config), + ) }, core.TestCheckExitCode(0), ), @@ -164,15 +186,32 @@ func Test_InstallKubeconfig(t *testing.T) { })) t.Run("merge", core.Test(&core.TestConfig{ - Commands: k8s.GetCommands(), - BeforeFunc: createClusterAndWaitAndKubeconfigAndPopulateFile("install-kubeconfig-merge", "Cluster", "Kubeconfig", kapsuleVersion, path.Join(os.TempDir(), "cli-merge-test"), []byte(existingKubeconfig)), - Cmd: "scw k8s kubeconfig install {{ .Cluster.ID }}", + Commands: k8s.GetCommands(), + BeforeFunc: createClusterAndWaitAndKubeconfigAndPopulateFile( + "install-kubeconfig-merge", + "Cluster", + "Kubeconfig", + kapsuleVersion, + path.Join(os.TempDir(), "cli-merge-test"), + []byte(existingKubeconfig), + ), + Cmd: "scw k8s kubeconfig install {{ .Cluster.ID }}", Check: core.TestCheckCombine( // no golden tests since it's os specific func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - testIfKubeconfigInFile(t, path.Join(os.TempDir(), "cli-merge-test"), "-"+ctx.Meta["Cluster"].(*k8sSDK.Cluster).ID, ctx.Meta["Kubeconfig"].(api.Config)) - testIfKubeconfigInFile(t, path.Join(os.TempDir(), "cli-merge-test"), "", testKubeconfig) + testIfKubeconfigInFile( + t, + path.Join(os.TempDir(), "cli-merge-test"), + "-"+ctx.Meta["Cluster"].(*k8sSDK.Cluster).ID, + ctx.Meta["Kubeconfig"].(api.Config), + ) + testIfKubeconfigInFile( + t, + path.Join(os.TempDir(), "cli-merge-test"), + "", + testKubeconfig, + ) }, core.TestCheckExitCode(0), ), diff --git a/internal/namespaces/k8s/v1/custom_kubeconfig_uninstall.go b/internal/namespaces/k8s/v1/custom_kubeconfig_uninstall.go index 9df0f62776..20f7aebdaf 100644 --- a/internal/namespaces/k8s/v1/custom_kubeconfig_uninstall.go +++ b/internal/namespaces/k8s/v1/custom_kubeconfig_uninstall.go @@ -104,5 +104,9 @@ func k8sKubeconfigUninstallRun(ctx context.Context, argsI interface{}) (i interf return nil, err } - return fmt.Sprintf("Cluster %s successfully deleted from %s", request.ClusterID, kubeconfigPath), nil + return fmt.Sprintf( + "Cluster %s successfully deleted from %s", + request.ClusterID, + kubeconfigPath, + ), nil } diff --git a/internal/namespaces/k8s/v1/custom_kubeconfig_uninstall_test.go b/internal/namespaces/k8s/v1/custom_kubeconfig_uninstall_test.go index 3087d7879b..7076397803 100644 --- a/internal/namespaces/k8s/v1/custom_kubeconfig_uninstall_test.go +++ b/internal/namespaces/k8s/v1/custom_kubeconfig_uninstall_test.go @@ -16,7 +16,12 @@ import ( // testIfKubeconfigNotInFile checks if the given kubeconfig is not in the given file // it tests if the user, cluster and context of the kubeconfig file are not in the given file -func testIfKubeconfigNotInFile(t *testing.T, filePath string, suffix string, kubeconfig api.Config) { +func testIfKubeconfigNotInFile( + t *testing.T, + filePath string, + suffix string, + kubeconfig api.Config, +) { t.Helper() kubeconfigBytes, err := os.ReadFile(filePath) require.NoError(t, err) @@ -60,14 +65,24 @@ func Test_UninstallKubeconfig(t *testing.T) { // Simple use cases //// t.Run("uninstall", core.Test(&core.TestConfig{ - Commands: k8s.GetCommands(), - BeforeFunc: createClusterAndWaitAndInstallKubeconfig("uninstall-kubeconfig", "Cluster", "Kubeconfig", kapsuleVersion), - Cmd: "scw k8s kubeconfig uninstall {{ .Cluster.ID }}", + Commands: k8s.GetCommands(), + BeforeFunc: createClusterAndWaitAndInstallKubeconfig( + "uninstall-kubeconfig", + "Cluster", + "Kubeconfig", + kapsuleVersion, + ), + Cmd: "scw k8s kubeconfig uninstall {{ .Cluster.ID }}", Check: core.TestCheckCombine( // no golden tests since it's os specific func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - testIfKubeconfigNotInFile(t, path.Join(os.TempDir(), "cli-uninstall-test"), "-"+ctx.Meta["Cluster"].(*k8sSDK.Cluster).ID, ctx.Meta["Kubeconfig"].(api.Config)) + testIfKubeconfigNotInFile( + t, + path.Join(os.TempDir(), "cli-uninstall-test"), + "-"+ctx.Meta["Cluster"].(*k8sSDK.Cluster).ID, + ctx.Meta["Kubeconfig"].(api.Config), + ) }, core.TestCheckExitCode(0), ), @@ -77,9 +92,14 @@ func Test_UninstallKubeconfig(t *testing.T) { }, })) t.Run("empty file", core.Test(&core.TestConfig{ - Commands: k8s.GetCommands(), - BeforeFunc: createClusterAndWaitAndKubeconfig("uninstall-kubeconfig-empty", "EmptyCluster", "Kubeconfig", kapsuleVersion), - Cmd: "scw k8s kubeconfig uninstall {{ .EmptyCluster.ID }}", + Commands: k8s.GetCommands(), + BeforeFunc: createClusterAndWaitAndKubeconfig( + "uninstall-kubeconfig-empty", + "EmptyCluster", + "Kubeconfig", + kapsuleVersion, + ), + Cmd: "scw k8s kubeconfig uninstall {{ .EmptyCluster.ID }}", Check: core.TestCheckCombine( // no golden tests since it's os specific func(t *testing.T, _ *core.CheckFuncCtx) { @@ -95,15 +115,32 @@ func Test_UninstallKubeconfig(t *testing.T) { }, })) t.Run("uninstall-merge", core.Test(&core.TestConfig{ - Commands: k8s.GetCommands(), - BeforeFunc: createClusterAndWaitAndKubeconfigAndPopulateFileAndInstall("uninstall-kubeconfig-merge", "Cluster", "Kubeconfig", kapsuleVersion, path.Join(os.TempDir(), "cli-uninstall-merge-test"), []byte(existingKubeconfig)), - Cmd: "scw k8s kubeconfig uninstall {{ .Cluster.ID }}", + Commands: k8s.GetCommands(), + BeforeFunc: createClusterAndWaitAndKubeconfigAndPopulateFileAndInstall( + "uninstall-kubeconfig-merge", + "Cluster", + "Kubeconfig", + kapsuleVersion, + path.Join(os.TempDir(), "cli-uninstall-merge-test"), + []byte(existingKubeconfig), + ), + Cmd: "scw k8s kubeconfig uninstall {{ .Cluster.ID }}", Check: core.TestCheckCombine( // no golden tests since it's os specific func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - testIfKubeconfigNotInFile(t, path.Join(os.TempDir(), "cli-uninstall-merge-test"), "-"+ctx.Meta["Cluster"].(*k8sSDK.Cluster).ID, ctx.Meta["Kubeconfig"].(api.Config)) - testIfKubeconfigInFile(t, path.Join(os.TempDir(), "cli-uninstall-merge-test"), "", testKubeconfig) + testIfKubeconfigNotInFile( + t, + path.Join(os.TempDir(), "cli-uninstall-merge-test"), + "-"+ctx.Meta["Cluster"].(*k8sSDK.Cluster).ID, + ctx.Meta["Kubeconfig"].(api.Config), + ) + testIfKubeconfigInFile( + t, + path.Join(os.TempDir(), "cli-uninstall-merge-test"), + "", + testKubeconfig, + ) }, core.TestCheckExitCode(0), ), diff --git a/internal/namespaces/k8s/v1/custom_pool.go b/internal/namespaces/k8s/v1/custom_pool.go index dfb9008e5b..d3ae589cb3 100644 --- a/internal/namespaces/k8s/v1/custom_pool.go +++ b/internal/namespaces/k8s/v1/custom_pool.go @@ -88,7 +88,9 @@ func waitForPoolFunc(action int) core.WaitFunc { // if we get a 404 here, it means the resource was successfully deleted notFoundError := &scw.ResourceNotFoundError{} responseError := &scw.ResponseError{} - if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) { + if errors.As(err, &responseError) && + responseError.StatusCode == http.StatusNotFound || + errors.As(err, ¬FoundError) { return fmt.Sprintf("Pool %s successfully deleted.", respI.(*k8s.Pool).ID), nil } } diff --git a/internal/namespaces/k8s/v1/custom_version.go b/internal/namespaces/k8s/v1/custom_version.go index 2d68895d7d..3590d49c4e 100644 --- a/internal/namespaces/k8s/v1/custom_version.go +++ b/internal/namespaces/k8s/v1/custom_version.go @@ -12,16 +12,18 @@ import ( ) func versionListBuilder(c *core.Command) *core.Command { - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { - originalRes, err := runner(ctx, argsI) - if err != nil { - return nil, err - } + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + originalRes, err := runner(ctx, argsI) + if err != nil { + return nil, err + } - versionsResponse := originalRes.(*k8s.ListVersionsResponse) + versionsResponse := originalRes.(*k8s.ListVersionsResponse) - return versionsResponse.Versions, nil - }) + return versionsResponse.Versions, nil + }, + ) return c } diff --git a/internal/namespaces/k8s/v1/helpers_test.go b/internal/namespaces/k8s/v1/helpers_test.go index 7ac541b567..36976f30b1 100644 --- a/internal/namespaces/k8s/v1/helpers_test.go +++ b/internal/namespaces/k8s/v1/helpers_test.go @@ -21,17 +21,39 @@ const ( // createCluster creates a basic cluster with "poolSize" dev1-m as nodes, the given version and // register it in the context Meta at metaKey. -func createCluster(clusterNameSuffix string, metaKey string, version string, poolSize int, nodeType string) core.BeforeFunc { +func createCluster( + clusterNameSuffix string, + metaKey string, + version string, + poolSize int, + nodeType string, +) core.BeforeFunc { return core.ExecStoreBeforeCmd( metaKey, - fmt.Sprintf("scw k8s cluster create name=cli-test-%s version=%s cni=cilium pools.0.node-type=%s pools.0.size=%d pools.0.name=default", clusterNameSuffix, version, nodeType, poolSize)) + fmt.Sprintf( + "scw k8s cluster create name=cli-test-%s version=%s cni=cilium pools.0.node-type=%s pools.0.size=%d pools.0.name=default", + clusterNameSuffix, + version, + nodeType, + poolSize, + ), + ) } // createClusterAndWaitAndKubeconfig creates a basic cluster with 1 dev1-m as node, the given version and // register it in the context Meta at metaKey. -func createClusterAndWaitAndKubeconfig(clusterNameSuffix string, metaKey string, kubeconfigMetaKey string, version string) core.BeforeFunc { +func createClusterAndWaitAndKubeconfig( + clusterNameSuffix string, + metaKey string, + kubeconfigMetaKey string, + version string, +) core.BeforeFunc { return func(ctx *core.BeforeFuncCtx) error { - cmd := fmt.Sprintf("scw k8s cluster create name=cli-test-%s version=%s cni=cilium pools.0.node-type=DEV1-M pools.0.size=1 pools.0.name=default --wait", clusterNameSuffix, version) + cmd := fmt.Sprintf( + "scw k8s cluster create name=cli-test-%s version=%s cni=cilium pools.0.node-type=DEV1-M pools.0.size=1 pools.0.name=default --wait", + clusterNameSuffix, + version, + ) res := ctx.ExecuteCmd(strings.Split(cmd, " ")) cluster := res.(*k8s.Cluster) ctx.Meta[metaKey] = cluster @@ -59,9 +81,18 @@ func createClusterAndWaitAndKubeconfig(clusterNameSuffix string, metaKey string, // createClusterAndWaitAndInstallKubeconfig creates a basic cluster with 1 dev1-m as node, the given version and // register it in the context Meta at metaKey. And install the kubeconfig -func createClusterAndWaitAndInstallKubeconfig(clusterNameSuffix string, metaKey string, kubeconfigMetaKey string, version string) core.BeforeFunc { +func createClusterAndWaitAndInstallKubeconfig( + clusterNameSuffix string, + metaKey string, + kubeconfigMetaKey string, + version string, +) core.BeforeFunc { return func(ctx *core.BeforeFuncCtx) error { - cmd := fmt.Sprintf("scw k8s cluster create name=cli-test-%s version=%s cni=cilium pools.0.node-type=DEV1-M pools.0.size=1 pools.0.name=default --wait", clusterNameSuffix, version) + cmd := fmt.Sprintf( + "scw k8s cluster create name=cli-test-%s version=%s cni=cilium pools.0.node-type=DEV1-M pools.0.size=1 pools.0.name=default --wait", + clusterNameSuffix, + version, + ) res := ctx.ExecuteCmd(strings.Split(cmd, " ")) cluster := res.(*k8s.Cluster) ctx.Meta[metaKey] = cluster @@ -91,9 +122,20 @@ func createClusterAndWaitAndInstallKubeconfig(clusterNameSuffix string, metaKey // createClusterAndWaitAndKubeconfigAndPopulateFile creates a basic cluster with 1 dev1-m as node, the given version and // register it in the context Meta at metaKey. It also populates the given file with the given content -func createClusterAndWaitAndKubeconfigAndPopulateFile(clusterNameSuffix string, metaKey string, kubeconfigMetaKey string, version string, file string, content []byte) core.BeforeFunc { +func createClusterAndWaitAndKubeconfigAndPopulateFile( + clusterNameSuffix string, + metaKey string, + kubeconfigMetaKey string, + version string, + file string, + content []byte, +) core.BeforeFunc { return func(ctx *core.BeforeFuncCtx) error { - cmd := fmt.Sprintf("scw k8s cluster create name=cli-test-%s version=%s cni=cilium pools.0.node-type=DEV1-M pools.0.size=1 pools.0.name=default --wait", clusterNameSuffix, version) + cmd := fmt.Sprintf( + "scw k8s cluster create name=cli-test-%s version=%s cni=cilium pools.0.node-type=DEV1-M pools.0.size=1 pools.0.name=default --wait", + clusterNameSuffix, + version, + ) res := ctx.ExecuteCmd(strings.Split(cmd, " ")) cluster := res.(*k8s.Cluster) ctx.Meta[metaKey] = cluster @@ -122,9 +164,20 @@ func createClusterAndWaitAndKubeconfigAndPopulateFile(clusterNameSuffix string, // createClusterAndWaitAndKubeconfigAndPopulateFileAndInstall creates a basic cluster with 1 dev1-m as node, the given version and // register it in the context Meta at metaKey. It also populates the given file with the given content and install the new kubeconfig -func createClusterAndWaitAndKubeconfigAndPopulateFileAndInstall(clusterNameSuffix string, metaKey string, kubeconfigMetaKey string, version string, file string, content []byte) core.BeforeFunc { +func createClusterAndWaitAndKubeconfigAndPopulateFileAndInstall( + clusterNameSuffix string, + metaKey string, + kubeconfigMetaKey string, + version string, + file string, + content []byte, +) core.BeforeFunc { return func(ctx *core.BeforeFuncCtx) error { - cmd := fmt.Sprintf("scw k8s cluster create name=cli-test-%s version=%s cni=cilium pools.0.node-type=DEV1-M pools.0.size=1 pools.0.name=default --wait", clusterNameSuffix, version) + cmd := fmt.Sprintf( + "scw k8s cluster create name=cli-test-%s version=%s cni=cilium pools.0.node-type=DEV1-M pools.0.size=1 pools.0.name=default --wait", + clusterNameSuffix, + version, + ) res := ctx.ExecuteCmd(strings.Split(cmd, " ")) cluster := res.(*k8s.Cluster) ctx.Meta[metaKey] = cluster @@ -158,5 +211,7 @@ func createClusterAndWaitAndKubeconfigAndPopulateFileAndInstall(clusterNameSuffi // deleteCluster deletes a cluster previously registered in the context Meta at metaKey. func deleteCluster(metaKey string) core.AfterFunc { - return core.ExecAfterCmd("scw k8s cluster delete {{ ." + metaKey + ".ID }} with-additional-resources=true --wait") + return core.ExecAfterCmd( + "scw k8s cluster delete {{ ." + metaKey + ".ID }} with-additional-resources=true --wait", + ) } diff --git a/internal/namespaces/k8s/v1/k8s_cli.go b/internal/namespaces/k8s/v1/k8s_cli.go index 752a93de79..599b45eb64 100644 --- a/internal/namespaces/k8s/v1/k8s_cli.go +++ b/internal/namespaces/k8s/v1/k8s_cli.go @@ -57,6 +57,7 @@ func GetGeneratedCommands() *core.Commands { k8sClusterTypeList(), ) } + func k8sRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage Kubernetes Kapsule and Kosmos clusters`, @@ -147,7 +148,18 @@ func k8sClusterList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "name_asc", "name_desc", "status_asc", "status_desc", "version_asc", "version_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "name_asc", + "name_desc", + "status_asc", + "status_desc", + "version_asc", + "version_desc", + }, }, { Name: "name", @@ -162,7 +174,16 @@ func k8sClusterList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "creating", "ready", "deleting", "deleted", "updating", "locked", "pool_required"}, + EnumValues: []string{ + "unknown", + "creating", + "ready", + "deleting", + "deleted", + "updating", + "locked", + "pool_required", + }, }, { Name: "type", @@ -185,7 +206,12 @@ func k8sClusterList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*k8s.ListClustersRequest) @@ -201,8 +227,8 @@ func k8sClusterList() *core.Command { if err != nil { return nil, err } - return resp.Clusters, nil + return resp.Clusters, nil }, Examples: []*core.Example{ { @@ -312,7 +338,15 @@ func k8sClusterCreate() *core.Command { Required: true, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_cni", "cilium", "calico", "weave", "flannel", "kilo", "none"}, + EnumValues: []string{ + "unknown_cni", + "cilium", + "calico", + "weave", + "flannel", + "kilo", + "none", + }, }, { Name: "pools.{index}.name", @@ -463,7 +497,14 @@ func k8sClusterCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_expander", "random", "most_pods", "least_waste", "priority", "price"}, + EnumValues: []string{ + "unknown_expander", + "random", + "most_pods", + "least_waste", + "priority", + "price", + }, }, { Name: "autoscaler-config.ignore-daemonsets-utilization", @@ -527,7 +568,16 @@ func k8sClusterCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"any", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}, + EnumValues: []string{ + "any", + "monday", + "tuesday", + "wednesday", + "thursday", + "friday", + "saturday", + "sunday", + }, }, { Name: "feature-gates.{index}", @@ -614,8 +664,8 @@ func k8sClusterCreate() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.CreateCluster(request) + return api.CreateCluster(request) }, Examples: []*core.Example{ { @@ -654,8 +704,8 @@ func k8sClusterGet() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.GetCluster(request) + return api.GetCluster(request) }, Examples: []*core.Example{ { @@ -732,7 +782,14 @@ func k8sClusterUpdate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_expander", "random", "most_pods", "least_waste", "priority", "price"}, + EnumValues: []string{ + "unknown_expander", + "random", + "most_pods", + "least_waste", + "priority", + "price", + }, }, { Name: "autoscaler-config.ignore-daemonsets-utilization", @@ -796,7 +853,16 @@ func k8sClusterUpdate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"any", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}, + EnumValues: []string{ + "any", + "monday", + "tuesday", + "wednesday", + "thursday", + "friday", + "saturday", + "sunday", + }, }, { Name: "feature-gates.{index}", @@ -875,8 +941,8 @@ func k8sClusterUpdate() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.UpdateCluster(request) + return api.UpdateCluster(request) }, Examples: []*core.Example{ { @@ -922,8 +988,8 @@ func k8sClusterDelete() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.DeleteCluster(request) + return api.DeleteCluster(request) }, Examples: []*core.Example{ { @@ -976,8 +1042,8 @@ func k8sClusterUpgrade() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.UpgradeCluster(request) + return api.UpgradeCluster(request) }, Examples: []*core.Example{ { @@ -1023,8 +1089,8 @@ func k8sClusterSetType() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.SetClusterType(request) + return api.SetClusterType(request) }, Examples: []*core.Example{ { @@ -1059,8 +1125,8 @@ func k8sClusterListAvailableVersions() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.ListClusterAvailableVersions(request) + return api.ListClusterAvailableVersions(request) }, Examples: []*core.Example{ { @@ -1103,8 +1169,8 @@ func k8sClusterListAvailableTypes() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.ListClusterAvailableTypes(request) + return api.ListClusterAvailableTypes(request) }, Examples: []*core.Example{ { @@ -1175,6 +1241,7 @@ func k8sClusterResetAdminToken() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "cluster", Verb: "reset-admin-token", @@ -1214,8 +1281,8 @@ Make sure to have the necessary Quota before running this command.`, client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.MigrateClusterToSBSCSI(request) + return api.MigrateClusterToSBSCSI(request) }, Examples: []*core.Example{ { @@ -1243,7 +1310,12 @@ func k8sACLList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*k8s.ListClusterACLRulesRequest) @@ -1259,8 +1331,8 @@ func k8sACLList() *core.Command { if err != nil { return nil, err } - return resp.Rules, nil + return resp.Rules, nil }, } } @@ -1310,8 +1382,8 @@ func k8sACLAdd() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.AddClusterACLRules(request) + return api.AddClusterACLRules(request) }, } } @@ -1361,8 +1433,8 @@ func k8sACLSet() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.SetClusterACLRules(request) + return api.SetClusterACLRules(request) }, } } @@ -1395,6 +1467,7 @@ func k8sACLDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "acl", Verb: "delete", @@ -1426,7 +1499,18 @@ func k8sPoolList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "name_asc", "name_desc", "status_asc", "status_desc", "version_asc", "version_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "name_asc", + "name_desc", + "status_asc", + "status_desc", + "version_asc", + "version_desc", + }, }, { Name: "name", @@ -1441,9 +1525,23 @@ func k8sPoolList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "ready", "deleting", "deleted", "scaling", "warning", "locked", "upgrading"}, + EnumValues: []string{ + "unknown", + "ready", + "deleting", + "deleted", + "scaling", + "warning", + "locked", + "upgrading", + }, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*k8s.ListPoolsRequest) @@ -1459,8 +1557,8 @@ func k8sPoolList() *core.Command { if err != nil { return nil, err } - return resp.Pools, nil + return resp.Pools, nil }, Examples: []*core.Example{ { @@ -1671,8 +1769,8 @@ func k8sPoolCreate() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.CreatePool(request) + return api.CreatePool(request) }, Examples: []*core.Example{ { @@ -1715,8 +1813,8 @@ func k8sPoolGet() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.GetPool(request) + return api.GetPool(request) }, Examples: []*core.Example{ { @@ -1759,8 +1857,8 @@ This will drain and replace the nodes in that pool.`, client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.UpgradePool(request) + return api.UpgradePool(request) }, Examples: []*core.Example{ { @@ -1856,8 +1954,8 @@ func k8sPoolUpdate() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.UpdatePool(request) + return api.UpdatePool(request) }, Examples: []*core.Example{ { @@ -1904,8 +2002,8 @@ func k8sPoolDelete() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.DeletePool(request) + return api.DeletePool(request) }, Examples: []*core.Example{ { @@ -1946,7 +2044,18 @@ func k8sNodeList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "name_asc", "name_desc", "status_asc", "status_desc", "version_asc", "version_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "name_asc", + "name_desc", + "status_asc", + "status_desc", + "version_asc", + "version_desc", + }, }, { Name: "name", @@ -1961,9 +2070,27 @@ func k8sNodeList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "creating", "not_ready", "ready", "deleting", "deleted", "locked", "rebooting", "creation_error", "upgrading", "starting", "registering"}, - }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + EnumValues: []string{ + "unknown", + "creating", + "not_ready", + "ready", + "deleting", + "deleted", + "locked", + "rebooting", + "creation_error", + "upgrading", + "starting", + "registering", + }, + }, + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*k8s.ListNodesRequest) @@ -1979,8 +2106,8 @@ func k8sNodeList() *core.Command { if err != nil { return nil, err } - return resp.Nodes, nil + return resp.Nodes, nil }, Examples: []*core.Example{ { @@ -2049,8 +2176,8 @@ func k8sNodeGet() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.GetNode(request) + return api.GetNode(request) }, Examples: []*core.Example{ { @@ -2085,8 +2212,8 @@ func k8sNodeReplace() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.ReplaceNode(request) + return api.ReplaceNode(request) }, Examples: []*core.Example{ { @@ -2121,8 +2248,8 @@ func k8sNodeReboot() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.RebootNode(request) + return api.RebootNode(request) }, Examples: []*core.Example{ { @@ -2171,8 +2298,8 @@ func k8sNodeDelete() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.DeleteNode(request) + return api.DeleteNode(request) }, Examples: []*core.Example{ { @@ -2208,8 +2335,8 @@ func k8sVersionList() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.ListVersions(request) + return api.ListVersions(request) }, Examples: []*core.Example{ { @@ -2264,8 +2391,8 @@ func k8sVersionGet() *core.Command { client := core.ExtractClient(ctx) api := k8s.NewAPI(client) - return api.GetVersion(request) + return api.GetVersion(request) }, Examples: []*core.Example{ { @@ -2286,7 +2413,12 @@ func k8sClusterTypeList() *core.Command { // Deprecated: false, ArgsType: reflect.TypeOf(k8s.ListClusterTypesRequest{}), ArgSpecs: core.ArgSpecs{ - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*k8s.ListClusterTypesRequest) @@ -2302,8 +2434,8 @@ func k8sClusterTypeList() *core.Command { if err != nil { return nil, err } - return resp.ClusterTypes, nil + return resp.ClusterTypes, nil }, } } diff --git a/internal/namespaces/k8s/v1/types/types.go b/internal/namespaces/k8s/v1/types/types.go index 622c06559d..59a0365005 100644 --- a/internal/namespaces/k8s/v1/types/types.go +++ b/internal/namespaces/k8s/v1/types/types.go @@ -109,10 +109,10 @@ type AuthInfo struct { ClientKey string `json:"client-key,omitempty"` // ClientKeyData contains PEM-encoded data from a client key file for TLS. Overrides ClientKey // +optional - ClientKeyData []byte `json:"client-key-data,omitempty" datapolicy:"security-key"` + ClientKeyData []byte `json:"client-key-data,omitempty" datapolicy:"security-key"` // Token is the bearer token for authentication to the kubernetes cluster. // +optional - Token string `json:"token,omitempty" datapolicy:"token"` + Token string `json:"token,omitempty" datapolicy:"token"` // TokenFile is a pointer to a file that contains a bearer token (as described above). If both Token and TokenFile are present, Token takes precedence. // +optional TokenFile string `json:"tokenFile,omitempty"` @@ -133,7 +133,7 @@ type AuthInfo struct { Username string `json:"username,omitempty"` // Password is the password for basic authentication to the kubernetes cluster. // +optional - Password string `json:"password,omitempty" datapolicy:"password"` + Password string `json:"password,omitempty" datapolicy:"password"` // AuthProvider specifies a custom authentication plugin for the kubernetes cluster. // +optional AuthProvider *AuthProviderConfig `json:"auth-provider,omitempty"` diff --git a/internal/namespaces/key_manager/v1alpha1/key_manager_cli.go b/internal/namespaces/key_manager/v1alpha1/key_manager_cli.go index dca2fe6ac6..ff202fd3a7 100644 --- a/internal/namespaces/key_manager/v1alpha1/key_manager_cli.go +++ b/internal/namespaces/key_manager/v1alpha1/key_manager_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/key_manager/v1alpha1" + key_manager "github.com/scaleway/scaleway-sdk-go/api/key_manager/v1alpha1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -38,6 +38,7 @@ func GetGeneratedCommands() *core.Commands { keymanagerKeyDeleteKeyMaterial(), ) } + func keymanagerRoot() *core.Command { return &core.Command{ Short: `Key Manager API`, @@ -131,8 +132,8 @@ func keymanagerKeyCreate() *core.Command { client := core.ExtractClient(ctx) api := key_manager.NewAPI(client) - return api.CreateKey(request) + return api.CreateKey(request) }, } } @@ -161,8 +162,8 @@ func keymanagerKeyGet() *core.Command { client := core.ExtractClient(ctx) api := key_manager.NewAPI(client) - return api.GetKey(request) + return api.GetKey(request) }, } } @@ -226,8 +227,8 @@ func keymanagerKeyUpdate() *core.Command { client := core.ExtractClient(ctx) api := key_manager.NewAPI(client) - return api.UpdateKey(request) + return api.UpdateKey(request) }, } } @@ -260,6 +261,7 @@ func keymanagerKeyDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "key", Verb: "delete", @@ -292,8 +294,8 @@ func keymanagerKeyRotate() *core.Command { client := core.ExtractClient(ctx) api := key_manager.NewAPI(client) - return api.RotateKey(request) + return api.RotateKey(request) }, } } @@ -322,8 +324,8 @@ func keymanagerKeyProtect() *core.Command { client := core.ExtractClient(ctx) api := key_manager.NewAPI(client) - return api.ProtectKey(request) + return api.ProtectKey(request) }, } } @@ -352,8 +354,8 @@ func keymanagerKeyUnprotect() *core.Command { client := core.ExtractClient(ctx) api := key_manager.NewAPI(client) - return api.UnprotectKey(request) + return api.UnprotectKey(request) }, } } @@ -382,8 +384,8 @@ func keymanagerKeyEnable() *core.Command { client := core.ExtractClient(ctx) api := key_manager.NewAPI(client) - return api.EnableKey(request) + return api.EnableKey(request) }, } } @@ -412,8 +414,8 @@ func keymanagerKeyDisable() *core.Command { client := core.ExtractClient(ctx) api := key_manager.NewAPI(client) - return api.DisableKey(request) + return api.DisableKey(request) }, } } @@ -440,7 +442,14 @@ func keymanagerKeyList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"name_asc", "name_desc", "created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc"}, + EnumValues: []string{ + "name_asc", + "name_desc", + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + }, }, { Name: "tags.{index}", @@ -463,7 +472,12 @@ func keymanagerKeyList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*key_manager.ListKeysRequest) @@ -479,8 +493,8 @@ func keymanagerKeyList() *core.Command { if err != nil { return nil, err } - return resp.Keys, nil + return resp.Keys, nil }, } } @@ -527,8 +541,8 @@ The data encryption key is returned in plaintext and ciphertext but it should on client := core.ExtractClient(ctx) api := key_manager.NewAPI(client) - return api.GenerateDataKey(request) + return api.GenerateDataKey(request) }, } } @@ -571,8 +585,8 @@ func keymanagerKeyEncrypt() *core.Command { client := core.ExtractClient(ctx) api := key_manager.NewAPI(client) - return api.Encrypt(request) + return api.Encrypt(request) }, } } @@ -615,8 +629,8 @@ func keymanagerKeyDecrypt() *core.Command { client := core.ExtractClient(ctx) api := key_manager.NewAPI(client) - return api.Decrypt(request) + return api.Decrypt(request) }, } } @@ -659,8 +673,8 @@ func keymanagerKeyImportKeyMaterial() *core.Command { client := core.ExtractClient(ctx) api := key_manager.NewAPI(client) - return api.ImportKeyMaterial(request) + return api.ImportKeyMaterial(request) }, } } @@ -693,6 +707,7 @@ func keymanagerKeyDeleteKeyMaterial() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "key", Verb: "delete-key-material", diff --git a/internal/namespaces/lb/v1/custom.go b/internal/namespaces/lb/v1/custom.go index daf7d0661b..6e16dec0ba 100644 --- a/internal/namespaces/lb/v1/custom.go +++ b/internal/namespaces/lb/v1/custom.go @@ -20,10 +20,19 @@ func warningKapsuleTaggedMessageView() string { func GetCommands() *core.Commands { human.RegisterMarshalerFunc(lb.LBTypeStock(""), human.EnumMarshalFunc(lbTypeStockMarshalSpecs)) human.RegisterMarshalerFunc(lb.LBStatus(""), human.EnumMarshalFunc(lbStatusMarshalSpecs)) - human.RegisterMarshalerFunc(lb.CertificateStatus(""), human.EnumMarshalFunc(certificateStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + lb.CertificateStatus(""), + human.EnumMarshalFunc(certificateStatusMarshalSpecs), + ) human.RegisterMarshalerFunc(lb.ACLActionType(""), human.EnumMarshalFunc(aclMarshalSpecs)) - human.RegisterMarshalerFunc(lb.BackendServerStatsHealthCheckStatus(""), human.EnumMarshalFunc(backendServerStatsHealthCheckStatusMarshalSpecs)) - human.RegisterMarshalerFunc(lb.BackendServerStatsServerState(""), human.EnumMarshalFunc(backendServerStatsServerStateMarshalSpecs)) + human.RegisterMarshalerFunc( + lb.BackendServerStatsHealthCheckStatus(""), + human.EnumMarshalFunc(backendServerStatsHealthCheckStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + lb.BackendServerStatsServerState(""), + human.EnumMarshalFunc(backendServerStatsServerStateMarshalSpecs), + ) human.RegisterMarshalerFunc(lb.LB{}, lbMarshalerFunc) human.RegisterMarshalerFunc(lb.Backend{}, lbBackendMarshalerFunc) human.RegisterMarshalerFunc(lb.Frontend{}, lbFrontendMarshalerFunc) diff --git a/internal/namespaces/lb/v1/custom_backend.go b/internal/namespaces/lb/v1/custom_backend.go index 1eed1b00f0..26a56c62b1 100644 --- a/internal/namespaces/lb/v1/custom_backend.go +++ b/internal/namespaces/lb/v1/custom_backend.go @@ -18,17 +18,44 @@ import ( var ( backendServerStatsHealthCheckStatusMarshalSpecs = human.EnumMarshalSpecs{ - lb.BackendServerStatsHealthCheckStatusPassed: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "passed"}, - lb.BackendServerStatsHealthCheckStatusFailed: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "failed"}, - lb.BackendServerStatsHealthCheckStatusUnknown: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "unknown"}, - lb.BackendServerStatsHealthCheckStatusNeutral: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "neutral"}, - lb.BackendServerStatsHealthCheckStatusCondpass: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "condition passed"}, + lb.BackendServerStatsHealthCheckStatusPassed: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "passed", + }, + lb.BackendServerStatsHealthCheckStatusFailed: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "failed", + }, + lb.BackendServerStatsHealthCheckStatusUnknown: &human.EnumMarshalSpec{ + Attribute: color.Faint, + Value: "unknown", + }, + lb.BackendServerStatsHealthCheckStatusNeutral: &human.EnumMarshalSpec{ + Attribute: color.Faint, + Value: "neutral", + }, + lb.BackendServerStatsHealthCheckStatusCondpass: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "condition passed", + }, } backendServerStatsServerStateMarshalSpecs = human.EnumMarshalSpecs{ - lb.BackendServerStatsServerStateStopped: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "stopped"}, - lb.BackendServerStatsServerStateStarting: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "starting"}, - lb.BackendServerStatsServerStateRunning: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "running"}, - lb.BackendServerStatsServerStateStopping: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "stopping"}, + lb.BackendServerStatsServerStateStopped: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "stopped", + }, + lb.BackendServerStatsServerStateStarting: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "starting", + }, + lb.BackendServerStatsServerStateRunning: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "running", + }, + lb.BackendServerStatsServerStateStopping: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "stopping", + }, } ) @@ -145,7 +172,11 @@ func backendCreateBuilder(c *core.Command) *core.Command { if tmpRequest.UseInstanceServerPublicIP { if server.Server.PublicIP == nil { return nil, &core.CliError{ - Message: fmt.Sprintf("server %s (%s) does not have a public ip", server.Server.ID, server.Server.Name), + Message: fmt.Sprintf( + "server %s (%s) does not have a public ip", + server.Server.ID, + server.Server.Name, + ), } } serverIPs = append(serverIPs, server.Server.PublicIP.Address.String()) @@ -193,7 +224,10 @@ func backendCreateBuilder(c *core.Command) *core.Command { if len(listServersResponse.Servers) == 0 { return nil, &core.CliError{ - Err: fmt.Errorf("there is no server with tag(s) '%v'", strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]")), + Err: fmt.Errorf( + "there is no server with tag(s) '%v'", + strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]"), + ), } } @@ -201,7 +235,11 @@ func backendCreateBuilder(c *core.Command) *core.Command { if tmpRequest.UseInstanceServerPublicIP { if server.PublicIP == nil { return nil, &core.CliError{ - Message: fmt.Sprintf("server %s (%s) does not have a public ip", server.ID, server.Name), + Message: fmt.Sprintf( + "server %s (%s) does not have a public ip", + server.ID, + server.Name, + ), } } serverIPs = append(serverIPs, server.PublicIP.Address.String()) @@ -229,7 +267,10 @@ func backendCreateBuilder(c *core.Command) *core.Command { if len(listServersResponse.Servers) == 0 { return nil, &core.CliError{ - Err: fmt.Errorf("there is no server with tag(s) '%v'", strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]")), + Err: fmt.Errorf( + "there is no server with tag(s) '%v'", + strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]"), + ), } } @@ -326,7 +367,11 @@ func backendAddServersBuilder(c *core.Command) *core.Command { if tmpRequest.UseInstanceServerPublicIP { if server.Server.PublicIP == nil { return nil, &core.CliError{ - Message: fmt.Sprintf("server %s (%s) does not have a public ip", server.Server.ID, server.Server.Name), + Message: fmt.Sprintf( + "server %s (%s) does not have a public ip", + server.Server.ID, + server.Server.Name, + ), } } serverIPs = append(serverIPs, server.Server.PublicIP.Address.String()) @@ -374,7 +419,10 @@ func backendAddServersBuilder(c *core.Command) *core.Command { if len(listServersResponse.Servers) == 0 { return nil, &core.CliError{ - Err: fmt.Errorf("there is no server with tag(s) '%v'", strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]")), + Err: fmt.Errorf( + "there is no server with tag(s) '%v'", + strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]"), + ), } } @@ -382,7 +430,11 @@ func backendAddServersBuilder(c *core.Command) *core.Command { if tmpRequest.UseInstanceServerPublicIP { if server.PublicIP == nil { return nil, &core.CliError{ - Message: fmt.Sprintf("server %s (%s) does not have a public ip", server.ID, server.Name), + Message: fmt.Sprintf( + "server %s (%s) does not have a public ip", + server.ID, + server.Name, + ), } } serverIPs = append(serverIPs, server.PublicIP.Address.String()) @@ -410,7 +462,10 @@ func backendAddServersBuilder(c *core.Command) *core.Command { if len(listServersResponse.Servers) == 0 { return nil, &core.CliError{ - Err: fmt.Errorf("there is no server with tag(s) '%v'", strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]")), + Err: fmt.Errorf( + "there is no server with tag(s) '%v'", + strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]"), + ), } } @@ -495,7 +550,11 @@ func backendRemoveServersBuilder(c *core.Command) *core.Command { if tmpRequest.UseInstanceServerPublicIP { if server.Server.PublicIP == nil { return nil, &core.CliError{ - Message: fmt.Sprintf("server %s (%s) does not have a public ip", server.Server.ID, server.Server.Name), + Message: fmt.Sprintf( + "server %s (%s) does not have a public ip", + server.Server.ID, + server.Server.Name, + ), } } serverIPs = append(serverIPs, server.Server.PublicIP.Address.String()) @@ -543,7 +602,10 @@ func backendRemoveServersBuilder(c *core.Command) *core.Command { if len(listServersResponse.Servers) == 0 { return nil, &core.CliError{ - Err: fmt.Errorf("there is no server with tag(s) '%v'", strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]")), + Err: fmt.Errorf( + "there is no server with tag(s) '%v'", + strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]"), + ), } } @@ -551,7 +613,11 @@ func backendRemoveServersBuilder(c *core.Command) *core.Command { if tmpRequest.UseInstanceServerPublicIP { if server.PublicIP == nil { return nil, &core.CliError{ - Message: fmt.Sprintf("server %s (%s) does not have a public ip", server.ID, server.Name), + Message: fmt.Sprintf( + "server %s (%s) does not have a public ip", + server.ID, + server.Name, + ), } } serverIPs = append(serverIPs, server.PublicIP.Address.String()) @@ -579,7 +645,10 @@ func backendRemoveServersBuilder(c *core.Command) *core.Command { if len(listServersResponse.Servers) == 0 { return nil, &core.CliError{ - Err: fmt.Errorf("there is no server with tag(s) '%v'", strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]")), + Err: fmt.Errorf( + "there is no server with tag(s) '%v'", + strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]"), + ), } } @@ -664,7 +733,11 @@ func backendSetServersBuilder(c *core.Command) *core.Command { if tmpRequest.UseInstanceServerPublicIP { if server.Server.PublicIP == nil { return nil, &core.CliError{ - Message: fmt.Sprintf("server %s (%s) does not have a public ip", server.Server.ID, server.Server.Name), + Message: fmt.Sprintf( + "server %s (%s) does not have a public ip", + server.Server.ID, + server.Server.Name, + ), } } serverIPs = append(serverIPs, server.Server.PublicIP.Address.String()) @@ -712,7 +785,10 @@ func backendSetServersBuilder(c *core.Command) *core.Command { if len(listServersResponse.Servers) == 0 { return nil, &core.CliError{ - Err: fmt.Errorf("there is no server with tag(s) '%v'", strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]")), + Err: fmt.Errorf( + "there is no server with tag(s) '%v'", + strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]"), + ), } } @@ -720,7 +796,11 @@ func backendSetServersBuilder(c *core.Command) *core.Command { if tmpRequest.UseInstanceServerPublicIP { if server.PublicIP == nil { return nil, &core.CliError{ - Message: fmt.Sprintf("server %s (%s) does not have a public ip", server.ID, server.Name), + Message: fmt.Sprintf( + "server %s (%s) does not have a public ip", + server.ID, + server.Name, + ), } } serverIPs = append(serverIPs, server.PublicIP.Address.String()) @@ -748,7 +828,10 @@ func backendSetServersBuilder(c *core.Command) *core.Command { if len(listServersResponse.Servers) == 0 { return nil, &core.CliError{ - Err: fmt.Errorf("there is no server with tag(s) '%v'", strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]")), + Err: fmt.Errorf( + "there is no server with tag(s) '%v'", + strings.Trim(strings.Join(tmpRequest.InstanceServerTag, " - "), "[]"), + ), } } @@ -793,7 +876,9 @@ func interceptBackend() core.CommandInterceptor { } case "CheckMaxRetries": return nil, &core.CliError{ - Err: errors.New("missing or invalid 'health-check.check-max-retries' argument"), + Err: errors.New( + "missing or invalid 'health-check.check-max-retries' argument", + ), } } } diff --git a/internal/namespaces/lb/v1/custom_certificate.go b/internal/namespaces/lb/v1/custom_certificate.go index c717d080ca..c34e2ecfe6 100644 --- a/internal/namespaces/lb/v1/custom_certificate.go +++ b/internal/namespaces/lb/v1/custom_certificate.go @@ -83,7 +83,8 @@ func certificateCreateBuilder(c *core.Command) *core.Command { return nil, err } - if len(res.(*lb.Certificate).LB.Tags) != 0 && res.(*lb.Certificate).LB.Tags[0] == kapsuleTag { + if len(res.(*lb.Certificate).LB.Tags) != 0 && + res.(*lb.Certificate).LB.Tags[0] == kapsuleTag { return warningKapsuleTaggedMessageView(), nil } @@ -105,7 +106,8 @@ func certificateCreateBuilder(c *core.Command) *core.Command { return nil, err } - if len(res.(*lb.Certificate).LB.Tags) != 0 && res.(*lb.Certificate).LB.Tags[0] == kapsuleTag { + if len(res.(*lb.Certificate).LB.Tags) != 0 && + res.(*lb.Certificate).LB.Tags[0] == kapsuleTag { return warningKapsuleTaggedMessageView(), nil } @@ -113,8 +115,12 @@ func certificateCreateBuilder(c *core.Command) *core.Command { } return nil, &core.CliError{ - Err: errors.New("missing required argument"), - Hint: fmt.Sprintf("You need to specify %s or %s", leCommonNameArgSpecs.Name, customeCertificateArgSpecs.Name), + Err: errors.New("missing required argument"), + Hint: fmt.Sprintf( + "You need to specify %s or %s", + leCommonNameArgSpecs.Name, + customeCertificateArgSpecs.Name, + ), Code: 1, } } diff --git a/internal/namespaces/lb/v1/custom_lb.go b/internal/namespaces/lb/v1/custom_lb.go index 021dcc25fd..204b2a1d16 100644 --- a/internal/namespaces/lb/v1/custom_lb.go +++ b/internal/namespaces/lb/v1/custom_lb.go @@ -242,7 +242,8 @@ func lbDeleteBuilder(c *core.Command) *core.Command { if err != nil { notFoundError := &scw.ResourceNotFoundError{} responseError := &scw.ResponseError{} - if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) { + if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || + errors.As(err, ¬FoundError) { return &core.SuccessResult{ Resource: "lb", Verb: "delete", diff --git a/internal/namespaces/lb/v1/helper_test.go b/internal/namespaces/lb/v1/helper_test.go index 79e8b5bdf8..84fb5a28cc 100644 --- a/internal/namespaces/lb/v1/helper_test.go +++ b/internal/namespaces/lb/v1/helper_test.go @@ -60,7 +60,10 @@ func deleteRunningInstance() core.AfterFunc { func createBackend(forwardPort int32) core.BeforeFunc { return core.ExecStoreBeforeCmd( "Backend", - fmt.Sprintf("scw lb backend create lb-id={{ .LB.ID }} name=cli-test forward-protocol=tcp forward-port=%d forward-port-algorithm=roundrobin sticky-sessions=none health-check.port=8888 health-check.check-max-retries=5", forwardPort), + fmt.Sprintf( + "scw lb backend create lb-id={{ .LB.ID }} name=cli-test forward-protocol=tcp forward-port=%d forward-port-algorithm=roundrobin sticky-sessions=none health-check.port=8888 health-check.check-max-retries=5", + forwardPort, + ), ) } @@ -74,13 +77,23 @@ func addIP2Backend(ip string) core.BeforeFunc { func createFrontend(inboundPort int32) core.BeforeFunc { return core.ExecStoreBeforeCmd( "Frontend", - fmt.Sprintf("scw lb frontend create lb-id={{ .LB.ID }} backend-id={{ .Backend.ID }} name=cli-test inbound-port=%d", inboundPort), + fmt.Sprintf( + "scw lb frontend create lb-id={{ .LB.ID }} backend-id={{ .Backend.ID }} name=cli-test inbound-port=%d", + inboundPort, + ), ) } -func createClusterAndWaitAndInstallKubeconfig(metaKey string, kubeconfigMetaKey string, version string) core.BeforeFunc { +func createClusterAndWaitAndInstallKubeconfig( + metaKey string, + kubeconfigMetaKey string, + version string, +) core.BeforeFunc { return func(ctx *core.BeforeFuncCtx) error { - cmd := fmt.Sprintf("scw k8s cluster create name=cli-test version=%s cni=cilium pools.0.node-type=DEV1-M pools.0.size=1 pools.0.name=default --wait", version) + cmd := fmt.Sprintf( + "scw k8s cluster create name=cli-test version=%s cni=cilium pools.0.node-type=DEV1-M pools.0.size=1 pools.0.name=default --wait", + version, + ) res := ctx.ExecuteCmd(strings.Split(cmd, " ")) cluster := res.(*k8s.Cluster) ctx.Meta[metaKey] = cluster @@ -121,7 +134,8 @@ func retrieveLBID(metaKey string) core.BeforeFunc { // We let enough time for kubeconfig to install time.Sleep(5 * time.Second) - cmd, err := exec.Command("bash", "-c", "kubectl -n kube-system get service/traefik-ingress -o jsonpath='{.metadata.annotations.service\\.beta\\.kubernetes\\.io/scw-loadbalancer-id}'").Output() + cmd, err := exec.Command("bash", "-c", "kubectl -n kube-system get service/traefik-ingress -o jsonpath='{.metadata.annotations.service\\.beta\\.kubernetes\\.io/scw-loadbalancer-id}'"). + Output() if err != nil { return err } diff --git a/internal/namespaces/lb/v1/lb_cli.go b/internal/namespaces/lb/v1/lb_cli.go index 472ded002d..17d714642d 100644 --- a/internal/namespaces/lb/v1/lb_cli.go +++ b/internal/namespaces/lb/v1/lb_cli.go @@ -86,6 +86,7 @@ func GetGeneratedCommands() *core.Commands { lbPrivateNetworkDetach(), ) } + func lbRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Scaleway Load Balancer services`, @@ -230,7 +231,17 @@ func lbLBList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIListLBsRequest) @@ -246,8 +257,8 @@ func lbLBList() *core.Command { if err != nil { return nil, err } - return resp.LBs, nil + return resp.LBs, nil }, } } @@ -328,18 +339,32 @@ func lbLBCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"ssl_compatibility_level_unknown", "ssl_compatibility_level_intermediate", "ssl_compatibility_level_modern", "ssl_compatibility_level_old"}, + EnumValues: []string{ + "ssl_compatibility_level_unknown", + "ssl_compatibility_level_intermediate", + "ssl_compatibility_level_modern", + "ssl_compatibility_level_old", + }, }, core.OrganizationIDArgSpec(), - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPICreateLBRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.CreateLB(request) + return api.CreateLB(request) }, } } @@ -361,15 +386,24 @@ func lbLBGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIGetLBRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.GetLB(request) + return api.GetLB(request) }, } } @@ -418,17 +452,31 @@ func lbLBUpdate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"ssl_compatibility_level_unknown", "ssl_compatibility_level_intermediate", "ssl_compatibility_level_modern", "ssl_compatibility_level_old"}, + EnumValues: []string{ + "ssl_compatibility_level_unknown", + "ssl_compatibility_level_intermediate", + "ssl_compatibility_level_modern", + "ssl_compatibility_level_old", + }, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIUpdateLBRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.UpdateLB(request) + return api.UpdateLB(request) }, } } @@ -457,7 +505,16 @@ func lbLBDelete() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIDeleteLBRequest) @@ -468,6 +525,7 @@ func lbLBDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "lb", Verb: "delete", @@ -500,15 +558,24 @@ func lbLBMigrate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIMigrateLBRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.MigrateLB(request) + return api.MigrateLB(request) }, } } @@ -559,7 +626,17 @@ func lbIPList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIListIPsRequest) @@ -575,8 +652,8 @@ func lbIPList() *core.Command { if err != nil { return nil, err } - return resp.IPs, nil + return resp.IPs, nil }, } } @@ -614,15 +691,24 @@ func lbIPCreate() *core.Command { Positional: false, }, core.OrganizationIDArgSpec(), - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPICreateIPRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.CreateIP(request) + return api.CreateIP(request) }, } } @@ -644,15 +730,24 @@ func lbIPGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIGetIPRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.GetIP(request) + return api.GetIP(request) }, } } @@ -674,7 +769,16 @@ func lbIPDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIReleaseIPRequest) @@ -685,6 +789,7 @@ func lbIPDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "ip", Verb: "delete", @@ -731,15 +836,24 @@ func lbIPUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIUpdateIPRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.UpdateIP(request) + return api.UpdateIP(request) }, } } @@ -776,7 +890,17 @@ func lbBackendList() *core.Command { Positional: false, EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIListBackendsRequest) @@ -792,8 +916,8 @@ func lbBackendList() *core.Command { if err != nil { return nil, err } - return resp.Backends, nil + return resp.Backends, nil }, } } @@ -1037,7 +1161,14 @@ func lbBackendCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"proxy_protocol_unknown", "proxy_protocol_none", "proxy_protocol_v1", "proxy_protocol_v2", "proxy_protocol_v2_ssl", "proxy_protocol_v2_ssl_cn"}, + EnumValues: []string{ + "proxy_protocol_unknown", + "proxy_protocol_none", + "proxy_protocol_v1", + "proxy_protocol_v2", + "proxy_protocol_v2_ssl", + "proxy_protocol_v2_ssl_cn", + }, }, { Name: "failover-host", @@ -1088,15 +1219,24 @@ func lbBackendCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPICreateBackendRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.CreateBackend(request) + return api.CreateBackend(request) }, } } @@ -1118,15 +1258,24 @@ func lbBackendGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIGetBackendRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.GetBackend(request) + return api.GetBackend(request) }, } } @@ -1238,7 +1387,14 @@ func lbBackendUpdate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"proxy_protocol_unknown", "proxy_protocol_none", "proxy_protocol_v1", "proxy_protocol_v2", "proxy_protocol_v2_ssl", "proxy_protocol_v2_ssl_cn"}, + EnumValues: []string{ + "proxy_protocol_unknown", + "proxy_protocol_none", + "proxy_protocol_v1", + "proxy_protocol_v2", + "proxy_protocol_v2_ssl", + "proxy_protocol_v2_ssl_cn", + }, }, { Name: "failover-host", @@ -1289,15 +1445,24 @@ func lbBackendUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIUpdateBackendRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.UpdateBackend(request) + return api.UpdateBackend(request) }, } } @@ -1319,7 +1484,16 @@ func lbBackendDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIDeleteBackendRequest) @@ -1330,6 +1504,7 @@ func lbBackendDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "backend", Verb: "delete", @@ -1362,15 +1537,24 @@ func lbBackendAddServers() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIAddBackendServersRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.AddBackendServers(request) + return api.AddBackendServers(request) }, } } @@ -1399,15 +1583,24 @@ func lbBackendRemoveServers() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIRemoveBackendServersRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.RemoveBackendServers(request) + return api.RemoveBackendServers(request) }, } } @@ -1436,15 +1629,24 @@ func lbBackendSetServers() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPISetBackendServersRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.SetBackendServers(request) + return api.SetBackendServers(request) }, } } @@ -1586,15 +1788,24 @@ func lbBackendUpdateHealthcheck() *core.Command { Positional: false, Default: core.DefaultValueSetter("0.5s"), }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIUpdateHealthCheckRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.UpdateHealthCheck(request) + return api.UpdateHealthCheck(request) }, } } @@ -1631,7 +1842,17 @@ func lbFrontendList() *core.Command { Positional: false, EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIListFrontendsRequest) @@ -1647,8 +1868,8 @@ func lbFrontendList() *core.Command { if err != nil { return nil, err } - return resp.Frontends, nil + return resp.Frontends, nil }, } } @@ -1728,15 +1949,24 @@ func lbFrontendCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPICreateFrontendRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.CreateFrontend(request) + return api.CreateFrontend(request) }, } } @@ -1758,15 +1988,24 @@ func lbFrontendGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIGetFrontendRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.GetFrontend(request) + return api.GetFrontend(request) }, } } @@ -1845,15 +2084,24 @@ func lbFrontendUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIUpdateFrontendRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.UpdateFrontend(request) + return api.UpdateFrontend(request) }, } } @@ -1875,7 +2123,16 @@ func lbFrontendDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIDeleteFrontendRequest) @@ -1886,6 +2143,7 @@ func lbFrontendDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "frontend", Verb: "delete", @@ -1919,7 +2177,17 @@ func lbRouteList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIListRoutesRequest) @@ -1935,8 +2203,8 @@ func lbRouteList() *core.Command { if err != nil { return nil, err } - return resp.Routes, nil + return resp.Routes, nil }, } } @@ -1986,15 +2254,24 @@ func lbRouteCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPICreateRouteRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.CreateRoute(request) + return api.CreateRoute(request) }, } } @@ -2016,15 +2293,24 @@ func lbRouteGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIGetRouteRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.GetRoute(request) + return api.GetRoute(request) }, } } @@ -2074,15 +2360,24 @@ func lbRouteUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIUpdateRouteRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.UpdateRoute(request) + return api.UpdateRoute(request) }, } } @@ -2104,7 +2399,16 @@ func lbRouteDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIDeleteRouteRequest) @@ -2115,6 +2419,7 @@ func lbRouteDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "route", Verb: "delete", @@ -2147,15 +2452,24 @@ func lbLBGetStats() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIGetLBStatsRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.GetLBStats(request) + return api.GetLBStats(request) }, } } @@ -2184,7 +2498,17 @@ func lbBackendListStatistics() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIListBackendStatsRequest) @@ -2200,8 +2524,8 @@ func lbBackendListStatistics() *core.Command { if err != nil { return nil, err } - return resp.BackendServersStats, nil + return resp.BackendServersStats, nil }, } } @@ -2238,7 +2562,17 @@ func lbACLList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIListACLsRequest) @@ -2254,8 +2588,8 @@ func lbACLList() *core.Command { if err != nil { return nil, err } - return resp.ACLs, nil + return resp.ACLs, nil }, } } @@ -2328,7 +2662,13 @@ func lbACLCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"acl_http_filter_none", "path_begin", "path_end", "regex", "http_header_match"}, + EnumValues: []string{ + "acl_http_filter_none", + "path_begin", + "path_end", + "regex", + "http_header_match", + }, }, { Name: "match.http-filter-value.{index}", @@ -2365,15 +2705,24 @@ func lbACLCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPICreateACLRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.CreateACL(request) + return api.CreateACL(request) }, } } @@ -2395,15 +2744,24 @@ func lbACLGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIGetACLRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.GetACL(request) + return api.GetACL(request) }, } } @@ -2475,7 +2833,13 @@ func lbACLUpdate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"acl_http_filter_none", "path_begin", "path_end", "regex", "http_header_match"}, + EnumValues: []string{ + "acl_http_filter_none", + "path_begin", + "path_end", + "regex", + "http_header_match", + }, }, { Name: "match.http-filter-value.{index}", @@ -2512,15 +2876,24 @@ func lbACLUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIUpdateACLRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.UpdateACL(request) + return api.UpdateACL(request) }, } } @@ -2542,7 +2915,16 @@ func lbACLDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIDeleteACLRequest) @@ -2553,6 +2935,7 @@ func lbACLDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "acl", Verb: "delete", @@ -2621,7 +3004,13 @@ func lbACLSet() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"acl_http_filter_none", "path_begin", "path_end", "regex", "http_header_match"}, + EnumValues: []string{ + "acl_http_filter_none", + "path_begin", + "path_end", + "regex", + "http_header_match", + }, }, { Name: "acls.{index}.match.http-filter-value.{index}", @@ -2665,15 +3054,24 @@ func lbACLSet() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPISetACLsRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.SetACLs(request) + return api.SetACLs(request) }, } } @@ -2724,15 +3122,24 @@ func lbCertificateCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPICreateCertificateRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.CreateCertificate(request) + return api.CreateCertificate(request) }, } } @@ -2769,7 +3176,17 @@ func lbCertificateList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIListCertificatesRequest) @@ -2785,8 +3202,8 @@ func lbCertificateList() *core.Command { if err != nil { return nil, err } - return resp.Certificates, nil + return resp.Certificates, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -2846,15 +3263,24 @@ func lbCertificateGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIGetCertificateRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.GetCertificate(request) + return api.GetCertificate(request) }, } } @@ -2883,15 +3309,24 @@ func lbCertificateUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIUpdateCertificateRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.UpdateCertificate(request) + return api.UpdateCertificate(request) }, } } @@ -2913,7 +3348,16 @@ func lbCertificateDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIDeleteCertificateRequest) @@ -2924,6 +3368,7 @@ func lbCertificateDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "certificate", Verb: "delete", @@ -2942,7 +3387,17 @@ func lbLBTypesList() *core.Command { // Deprecated: false, ArgsType: reflect.TypeOf(lb.ZonedAPIListLBTypesRequest{}), ArgSpecs: core.ArgSpecs{ - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIListLBTypesRequest) @@ -2958,8 +3413,8 @@ func lbLBTypesList() *core.Command { if err != nil { return nil, err } - return resp.LBTypes, nil + return resp.LBTypes, nil }, } } @@ -2997,15 +3452,24 @@ func lbSubscriberCreate() *core.Command { }, core.ProjectIDArgSpec(), core.OrganizationIDArgSpec(), - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPICreateSubscriberRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.CreateSubscriber(request) + return api.CreateSubscriber(request) }, } } @@ -3027,15 +3491,24 @@ func lbSubscriberGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIGetSubscriberRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.GetSubscriber(request) + return api.GetSubscriber(request) }, } } @@ -3079,7 +3552,17 @@ func lbSubscriberList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIListSubscriberRequest) @@ -3095,8 +3578,8 @@ func lbSubscriberList() *core.Command { if err != nil { return nil, err } - return resp.Subscribers, nil + return resp.Subscribers, nil }, } } @@ -3139,15 +3622,24 @@ func lbSubscriberUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIUpdateSubscriberRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.UpdateSubscriber(request) + return api.UpdateSubscriber(request) }, } } @@ -3169,7 +3661,16 @@ func lbSubscriberDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIDeleteSubscriberRequest) @@ -3180,6 +3681,7 @@ func lbSubscriberDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "subscriber", Verb: "delete", @@ -3212,15 +3714,24 @@ func lbSubscriberSubscribe() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPISubscribeToLBRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.SubscribeToLB(request) + return api.SubscribeToLB(request) }, } } @@ -3242,15 +3753,24 @@ func lbSubscriberUnsubscribe() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIUnsubscribeFromLBRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.UnsubscribeFromLB(request) + return api.UnsubscribeFromLB(request) }, } } @@ -3280,7 +3800,17 @@ func lbPrivateNetworkList() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIListLBPrivateNetworksRequest) @@ -3296,8 +3826,8 @@ func lbPrivateNetworkList() *core.Command { if err != nil { return nil, err } - return resp.PrivateNetwork, nil + return resp.PrivateNetwork, nil }, } } @@ -3333,15 +3863,24 @@ func lbPrivateNetworkAttach() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIAttachPrivateNetworkRequest) client := core.ExtractClient(ctx) api := lb.NewZonedAPI(client) - return api.AttachPrivateNetwork(request) + return api.AttachPrivateNetwork(request) }, } } @@ -3370,7 +3909,16 @@ func lbPrivateNetworkDetach() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*lb.ZonedAPIDetachPrivateNetworkRequest) @@ -3381,6 +3929,7 @@ func lbPrivateNetworkDetach() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "private-network", Verb: "detach", diff --git a/internal/namespaces/login/webcallback/webcallback.go b/internal/namespaces/login/webcallback/webcallback.go index 272c03411f..3e8499f51f 100644 --- a/internal/namespaces/login/webcallback/webcallback.go +++ b/internal/namespaces/login/webcallback/webcallback.go @@ -76,7 +76,11 @@ func (wb *WebCallback) Start() error { // Trigger will trigger currently waiting callback. Made for tests func (wb *WebCallback) Trigger(token string, timeout time.Duration) error { - req, err := http.NewRequest(http.MethodGet, "http://localhost:"+strconv.Itoa(wb.port)+"/callback", nil) + req, err := http.NewRequest( + http.MethodGet, + "http://localhost:"+strconv.Itoa(wb.port)+"/callback", + nil, + ) if err != nil { return err } diff --git a/internal/namespaces/marketplace/v2/marketplace_cli.go b/internal/namespaces/marketplace/v2/marketplace_cli.go index 6b23510dea..d473a330a1 100644 --- a/internal/namespaces/marketplace/v2/marketplace_cli.go +++ b/internal/namespaces/marketplace/v2/marketplace_cli.go @@ -34,6 +34,7 @@ func GetGeneratedCommands() *core.Commands { marketplaceCategoryGet(), ) } + func marketplaceRoot() *core.Command { return &core.Command{ Short: `This API allows you to find available images for use when launching a Scaleway Instance`, @@ -94,7 +95,14 @@ func marketplaceImageList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"name_asc", "name_desc", "created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc"}, + EnumValues: []string{ + "name_asc", + "name_desc", + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + }, }, { Name: "arch", @@ -128,8 +136,8 @@ func marketplaceImageList() *core.Command { if err != nil { return nil, err } - return resp.Images, nil + return resp.Images, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -192,8 +200,8 @@ func marketplaceImageGet() *core.Command { client := core.ExtractClient(ctx) api := marketplace.NewAPI(client) - return api.GetImage(request) + return api.GetImage(request) }, } } @@ -232,8 +240,8 @@ func marketplaceVersionList() *core.Command { if err != nil { return nil, err } - return resp.Versions, nil + return resp.Versions, nil }, } } @@ -260,8 +268,8 @@ func marketplaceVersionGet() *core.Command { client := core.ExtractClient(ctx) api := marketplace.NewAPI(client) - return api.GetVersion(request) + return api.GetVersion(request) }, } } @@ -331,8 +339,8 @@ func marketplaceLocalImageList() *core.Command { if err != nil { return nil, err } - return resp.LocalImages, nil + return resp.LocalImages, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -379,8 +387,8 @@ func marketplaceLocalImageGet() *core.Command { client := core.ExtractClient(ctx) api := marketplace.NewAPI(client) - return api.GetLocalImage(request) + return api.GetLocalImage(request) }, } } @@ -405,8 +413,8 @@ func marketplaceCategoryList() *core.Command { if err != nil { return nil, err } - return resp.Categories, nil + return resp.Categories, nil }, } } @@ -433,8 +441,8 @@ func marketplaceCategoryGet() *core.Command { client := core.ExtractClient(ctx) api := marketplace.NewAPI(client) - return api.GetCategory(request) + return api.GetCategory(request) }, } } diff --git a/internal/namespaces/mnq/v1beta1/custom.go b/internal/namespaces/mnq/v1beta1/custom.go index 13a0d4ebd1..2507cf428e 100644 --- a/internal/namespaces/mnq/v1beta1/custom.go +++ b/internal/namespaces/mnq/v1beta1/custom.go @@ -9,7 +9,10 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(mnq.SnsInfoStatus(""), human.EnumMarshalFunc(mnqSqsInfoStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + mnq.SnsInfoStatus(""), + human.EnumMarshalFunc(mnqSqsInfoStatusMarshalSpecs), + ) cmds.MustFind("mnq", "nats", "get-account").Override(mnqNatsGetAccountBuilder) cmds.MustFind("mnq", "nats", "list-credentials").Override(mnqNatsListCredentialsBuilder) diff --git a/internal/namespaces/mnq/v1beta1/custom_nats.go b/internal/namespaces/mnq/v1beta1/custom_nats.go index 68997f7aa3..a8f8bbe6e0 100644 --- a/internal/namespaces/mnq/v1beta1/custom_nats.go +++ b/internal/namespaces/mnq/v1beta1/custom_nats.go @@ -86,8 +86,12 @@ Credentials and context file are saved in your nats context folder with 0600 per } return &core.SuccessResult{ - Message: "Nats context successfully created", - Details: fmt.Sprintf("%s nats credentials was created\nSelect context using `nats context select %s`", credentials.Name, natsAccount.Name), + Message: "Nats context successfully created", + Details: fmt.Sprintf( + "%s nats credentials was created\nSelect context using `nats context select %s`", + credentials.Name, + natsAccount.Name, + ), Resource: contextPath, }, nil }, @@ -108,7 +112,11 @@ func mnqNatsListCredentialsBuilder(c *core.Command) *core.Command { var completeListNatsAccountIDCache *mnq.ListNatsAccountsResponse -func autocompleteNatsAccountID(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autocompleteNatsAccountID( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { region := scw.Region("") switch req := request.(type) { case *mnq.NatsAPIGetNatsAccountRequest: diff --git a/internal/namespaces/mnq/v1beta1/custom_nats_helpers.go b/internal/namespaces/mnq/v1beta1/custom_nats_helpers.go index f90bef64b7..36a174c3a3 100644 --- a/internal/namespaces/mnq/v1beta1/custom_nats_helpers.go +++ b/internal/namespaces/mnq/v1beta1/custom_nats_helpers.go @@ -56,7 +56,12 @@ func natsContextFrom(account *mnq.NatsAccount, credsPath string) ([]byte, error) return b, nil } -func writeFile(ctx context.Context, dir string, entity *NatsEntity, extension string) (string, error) { +func writeFile( + ctx context.Context, + dir string, + entity *NatsEntity, + extension string, +) (string, error) { path := filepath.Join(dir, entity.Name+"."+extension) if err := makeDirectoryIfNotExists(dir); err != nil { return "", wrapError(err, "Failed to create directory", entity.Name, path) @@ -93,7 +98,11 @@ func getNATSContextDir(ctx context.Context) (string, error) { return xdgConfigHome, nil } -func saveNATSCredentials(ctx context.Context, creds *mnq.NatsCredentials, natsAccount *mnq.NatsAccount) (string, error) { +func saveNATSCredentials( + ctx context.Context, + creds *mnq.NatsCredentials, + natsAccount *mnq.NatsAccount, +) (string, error) { natsContextDir, err := getNATSContextDir(ctx) if err != nil { return "", err @@ -125,7 +134,11 @@ func saveNATSCredentials(ctx context.Context, creds *mnq.NatsCredentials, natsAc return contextPath, nil } -func getNatsAccountID(ctx context.Context, args *CreateContextRequest, api *mnq.NatsAPI) (*mnq.NatsAccount, error) { +func getNatsAccountID( + ctx context.Context, + args *CreateContextRequest, + api *mnq.NatsAPI, +) (*mnq.NatsAccount, error) { var natsAccount *mnq.NatsAccount if args.NatsAccountID == "" { natsAccountsResp, err := api.ListNatsAccounts(&mnq.NatsAPIListNatsAccountsRequest{ @@ -134,7 +147,11 @@ func getNatsAccountID(ctx context.Context, args *CreateContextRequest, api *mnq. if err != nil { return nil, fmt.Errorf("failed to list nats account: %w", err) } - natsAccount, err = promptNatsAccounts(ctx, natsAccountsResp.NatsAccounts, natsAccountsResp.TotalCount) + natsAccount, err = promptNatsAccounts( + ctx, + natsAccountsResp.NatsAccounts, + natsAccountsResp.TotalCount, + ) if err != nil { return nil, fmt.Errorf("failed to list nats account: %w", err) } diff --git a/internal/namespaces/mnq/v1beta1/custom_nats_prompt.go b/internal/namespaces/mnq/v1beta1/custom_nats_prompt.go index 0da09614c2..7b4b773dfc 100644 --- a/internal/namespaces/mnq/v1beta1/custom_nats_prompt.go +++ b/internal/namespaces/mnq/v1beta1/custom_nats_prompt.go @@ -9,13 +9,21 @@ import ( mnq "github.com/scaleway/scaleway-sdk-go/api/mnq/v1beta1" ) -func promptNatsAccounts(ctx context.Context, natsAccounts []*mnq.NatsAccount, totalCount uint64) (*mnq.NatsAccount, error) { +func promptNatsAccounts( + ctx context.Context, + natsAccounts []*mnq.NatsAccount, + totalCount uint64, +) (*mnq.NatsAccount, error) { if totalCount == 0 { - return nil, errors.New("no nats account found, please create a NATS account with 'scw mnq nats create-account'") + return nil, errors.New( + "no nats account found, please create a NATS account with 'scw mnq nats create-account'", + ) } if !interactive.IsInteractive { - return nil, errors.New("failed to create NATS context: Multiple NATS accounts found. Please provide an account ID explicitly as the command is not running in interactive mode") + return nil, errors.New( + "failed to create NATS context: Multiple NATS accounts found. Please provide an account ID explicitly as the command is not running in interactive mode", + ) } if totalCount == 1 { return natsAccounts[0], nil diff --git a/internal/namespaces/mnq/v1beta1/custom_nats_test.go b/internal/namespaces/mnq/v1beta1/custom_nats_test.go index 7c50253586..7ec4fcf014 100644 --- a/internal/namespaces/mnq/v1beta1/custom_nats_test.go +++ b/internal/namespaces/mnq/v1beta1/custom_nats_test.go @@ -25,37 +25,49 @@ func Test_CreateContext(t *testing.T) { Replacement: "credential-placeholder", }, core.GoldenReplacement{ - Pattern: regexp.MustCompile("(Select context using `nats context select )cli[\\w-]*`"), + Pattern: regexp.MustCompile( + "(Select context using `nats context select )cli[\\w-]*`", + ), Replacement: "Select context using `nats context select context-placeholder`", }, ), func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() result, isSuccessResult := ctx.Result.(*core.SuccessResult) - assert.True(t, isSuccessResult, "Expected result to be of type *core.SuccessResult, got %s", reflect.TypeOf(result).String()) + assert.True( + t, + isSuccessResult, + "Expected result to be of type *core.SuccessResult, got %s", + reflect.TypeOf(result).String(), + ) assert.NotNil(t, result) expectedContextFile := result.Resource if !mnq.FileExists(expectedContextFile) { - t.Errorf("Expected credentials file not found expected [%s] ", expectedContextFile) + t.Errorf( + "Expected credentials file not found expected [%s] ", + expectedContextFile, + ) } else { ctx.Meta["deleteFiles"] = []string{expectedContextFile} } }, ), - AfterFunc: core.AfterFuncCombine(deleteNATSAccount("NATS"), func(ctx *core.AfterFuncCtx) error { - if ctx.Meta["deleteFiles"] == nil { - return nil - } - filesToDelete := ctx.Meta["deleteFiles"].([]string) - for _, file := range filesToDelete { - err := os.Remove(file) - if err != nil { - t.Errorf("Failed to delete the file : %s", err) + AfterFunc: core.AfterFuncCombine( + deleteNATSAccount("NATS"), + func(ctx *core.AfterFuncCtx) error { + if ctx.Meta["deleteFiles"] == nil { + return nil + } + filesToDelete := ctx.Meta["deleteFiles"].([]string) + for _, file := range filesToDelete { + err := os.Remove(file) + if err != nil { + t.Errorf("Failed to delete the file : %s", err) + } } - } - return nil - }, + return nil + }, ), })) } diff --git a/internal/namespaces/mnq/v1beta1/custom_sns.go b/internal/namespaces/mnq/v1beta1/custom_sns.go index 261c73a0b2..1baa36d678 100644 --- a/internal/namespaces/mnq/v1beta1/custom_sns.go +++ b/internal/namespaces/mnq/v1beta1/custom_sns.go @@ -22,7 +22,11 @@ func mnqSnsGetCredentialsBuilder(c *core.Command) *core.Command { var completeSnsInfoCache *mnq.SnsInfo -func autocompleteSnsProjectID(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autocompleteSnsProjectID( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { _ = prefix req := request.(*mnq.SnsAPIListSnsCredentialsRequest) suggestions := core.AutocompleteSuggestions(nil) @@ -47,7 +51,11 @@ func autocompleteSnsProjectID(ctx context.Context, prefix string, request any) c var completeSnsListCredentials *mnq.ListSnsCredentialsResponse -func autocompleteSnsCredentialsID(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autocompleteSnsCredentialsID( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { req := request.(*mnq.SnsAPIGetSnsCredentialsRequest) suggestions := core.AutocompleteSuggestions(nil) diff --git a/internal/namespaces/mnq/v1beta1/custom_sqs.go b/internal/namespaces/mnq/v1beta1/custom_sqs.go index 4f1f591563..d52001dffb 100644 --- a/internal/namespaces/mnq/v1beta1/custom_sqs.go +++ b/internal/namespaces/mnq/v1beta1/custom_sqs.go @@ -30,7 +30,11 @@ func mnqSqsGetCredentialsBuilder(c *core.Command) *core.Command { var completeSqsInfoCache *mnq.SqsInfo -func autocompleteSqsProjectID(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autocompleteSqsProjectID( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { _ = prefix req := request.(*mnq.SqsAPIListSqsCredentialsRequest) suggestions := core.AutocompleteSuggestions(nil) @@ -53,7 +57,11 @@ func autocompleteSqsProjectID(ctx context.Context, prefix string, request any) c var completeSqsListCredentials *mnq.ListSqsCredentialsResponse -func autocompleteSqsCredentialsID(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autocompleteSqsCredentialsID( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { req := request.(*mnq.SqsAPIGetSqsCredentialsRequest) suggestions := core.AutocompleteSuggestions(nil) diff --git a/internal/namespaces/mnq/v1beta1/mnq_cli.go b/internal/namespaces/mnq/v1beta1/mnq_cli.go index f403a29990..ec067a63a5 100644 --- a/internal/namespaces/mnq/v1beta1/mnq_cli.go +++ b/internal/namespaces/mnq/v1beta1/mnq_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/mnq/v1beta1" + mnq "github.com/scaleway/scaleway-sdk-go/api/mnq/v1beta1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -50,6 +50,7 @@ func GetGeneratedCommands() *core.Commands { mnqSqsListCredentials(), ) } + func mnqRoot() *core.Command { return &core.Command{ Short: `These APIs allow you to manage your Messaging and Queuing NATS, Queues and Topics and Events services`, @@ -111,8 +112,8 @@ func mnqNatsCreateAccount() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewNatsAPI(client) - return api.CreateNatsAccount(request) + return api.CreateNatsAccount(request) }, } } @@ -145,6 +146,7 @@ func mnqNatsDeleteAccount() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "nats", Verb: "delete-account", @@ -184,8 +186,8 @@ func mnqNatsUpdateAccount() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewNatsAPI(client) - return api.UpdateNatsAccount(request) + return api.UpdateNatsAccount(request) }, } } @@ -214,8 +216,8 @@ func mnqNatsGetAccount() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewNatsAPI(client) - return api.GetNatsAccount(request) + return api.GetNatsAccount(request) }, } } @@ -243,7 +245,14 @@ func mnqNatsListAccounts() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "name_asc", "name_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "name_asc", + "name_desc", + }, }, core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.Region(core.AllLocalities)), }, @@ -261,8 +270,8 @@ func mnqNatsListAccounts() *core.Command { if err != nil { return nil, err } - return resp.NatsAccounts, nil + return resp.NatsAccounts, nil }, } } @@ -299,8 +308,8 @@ func mnqNatsCreateCredentials() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewNatsAPI(client) - return api.CreateNatsCredentials(request) + return api.CreateNatsCredentials(request) }, } } @@ -333,6 +342,7 @@ func mnqNatsDeleteCredentials() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "nats", Verb: "delete-credentials", @@ -365,8 +375,8 @@ func mnqNatsGetCredentials() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewNatsAPI(client) - return api.GetNatsCredentials(request) + return api.GetNatsCredentials(request) }, } } @@ -401,7 +411,14 @@ func mnqNatsListCredentials() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "name_asc", "name_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "name_asc", + "name_desc", + }, }, core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.Region(core.AllLocalities)), }, @@ -419,8 +436,8 @@ func mnqNatsListCredentials() *core.Command { if err != nil { return nil, err } - return resp.NatsCredentials, nil + return resp.NatsCredentials, nil }, } } @@ -443,8 +460,8 @@ func mnqSnsActivate() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewSnsAPI(client) - return api.ActivateSns(request) + return api.ActivateSns(request) }, } } @@ -467,8 +484,8 @@ func mnqSnsGetInfo() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewSnsAPI(client) - return api.GetSnsInfo(request) + return api.GetSnsInfo(request) }, } } @@ -491,8 +508,8 @@ func mnqSnsDeactivate() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewSnsAPI(client) - return api.DeactivateSns(request) + return api.DeactivateSns(request) }, } } @@ -544,8 +561,8 @@ func mnqSnsCreateCredentials() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewSnsAPI(client) - return api.CreateSnsCredentials(request) + return api.CreateSnsCredentials(request) }, } } @@ -578,6 +595,7 @@ func mnqSnsDeleteCredentials() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "sns", Verb: "delete-credentials", @@ -638,8 +656,8 @@ func mnqSnsUpdateCredentials() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewSnsAPI(client) - return api.UpdateSnsCredentials(request) + return api.UpdateSnsCredentials(request) }, } } @@ -668,8 +686,8 @@ func mnqSnsGetCredentials() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewSnsAPI(client) - return api.GetSnsCredentials(request) + return api.GetSnsCredentials(request) }, } } @@ -697,7 +715,14 @@ func mnqSnsListCredentials() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "name_asc", "name_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "name_asc", + "name_desc", + }, }, core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.Region(core.AllLocalities)), }, @@ -715,8 +740,8 @@ func mnqSnsListCredentials() *core.Command { if err != nil { return nil, err } - return resp.SnsCredentials, nil + return resp.SnsCredentials, nil }, } } @@ -739,8 +764,8 @@ func mnqSqsActivate() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewSqsAPI(client) - return api.ActivateSqs(request) + return api.ActivateSqs(request) }, } } @@ -763,8 +788,8 @@ func mnqSqsGetInfo() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewSqsAPI(client) - return api.GetSqsInfo(request) + return api.GetSqsInfo(request) }, } } @@ -787,8 +812,8 @@ func mnqSqsDeactivate() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewSqsAPI(client) - return api.DeactivateSqs(request) + return api.DeactivateSqs(request) }, } } @@ -840,8 +865,8 @@ func mnqSqsCreateCredentials() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewSqsAPI(client) - return api.CreateSqsCredentials(request) + return api.CreateSqsCredentials(request) }, } } @@ -874,6 +899,7 @@ func mnqSqsDeleteCredentials() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "sqs", Verb: "delete-credentials", @@ -934,8 +960,8 @@ func mnqSqsUpdateCredentials() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewSqsAPI(client) - return api.UpdateSqsCredentials(request) + return api.UpdateSqsCredentials(request) }, } } @@ -964,8 +990,8 @@ func mnqSqsGetCredentials() *core.Command { client := core.ExtractClient(ctx) api := mnq.NewSqsAPI(client) - return api.GetSqsCredentials(request) + return api.GetSqsCredentials(request) }, } } @@ -993,7 +1019,14 @@ func mnqSqsListCredentials() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "name_asc", "name_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "name_asc", + "name_desc", + }, }, core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.Region(core.AllLocalities)), }, @@ -1011,8 +1044,8 @@ func mnqSqsListCredentials() *core.Command { if err != nil { return nil, err } - return resp.SqsCredentials, nil + return resp.SqsCredentials, nil }, } } diff --git a/internal/namespaces/mongodb/v1alpha1/custom.go b/internal/namespaces/mongodb/v1alpha1/custom.go index 2507b891de..2b9c6cce41 100644 --- a/internal/namespaces/mongodb/v1alpha1/custom.go +++ b/internal/namespaces/mongodb/v1alpha1/custom.go @@ -9,9 +9,18 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(mongodb.SnapshotStatus(""), human.EnumMarshalFunc(snapshotStatusMarshalSpecs)) - human.RegisterMarshalerFunc(mongodb.InstanceStatus(""), human.EnumMarshalFunc(instanceStatusMarshalSpecs)) - human.RegisterMarshalerFunc(mongodb.NodeTypeStock(""), human.EnumMarshalFunc(nodeTypeStockMarshalSpecs)) + human.RegisterMarshalerFunc( + mongodb.SnapshotStatus(""), + human.EnumMarshalFunc(snapshotStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + mongodb.InstanceStatus(""), + human.EnumMarshalFunc(instanceStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + mongodb.NodeTypeStock(""), + human.EnumMarshalFunc(nodeTypeStockMarshalSpecs), + ) cmds.MustFind("mongodb", "instance", "create").Override(instanceCreateBuilder) diff --git a/internal/namespaces/mongodb/v1alpha1/custom_instance.go b/internal/namespaces/mongodb/v1alpha1/custom_instance.go index 7cae144386..5d5e2dfe6d 100644 --- a/internal/namespaces/mongodb/v1alpha1/custom_instance.go +++ b/internal/namespaces/mongodb/v1alpha1/custom_instance.go @@ -12,14 +12,38 @@ import ( ) var instanceStatusMarshalSpecs = human.EnumMarshalSpecs{ - mongodb.InstanceStatusConfiguring: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "configuring"}, - mongodb.InstanceStatusDeleting: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "deleting"}, - mongodb.InstanceStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "error"}, - mongodb.InstanceStatusInitializing: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "initializing"}, - mongodb.InstanceStatusLocked: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "locked"}, - mongodb.InstanceStatusProvisioning: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "provisioning"}, - mongodb.InstanceStatusReady: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "ready"}, - mongodb.InstanceStatusSnapshotting: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "snapshotting"}, + mongodb.InstanceStatusConfiguring: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "configuring", + }, + mongodb.InstanceStatusDeleting: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "deleting", + }, + mongodb.InstanceStatusError: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "error", + }, + mongodb.InstanceStatusInitializing: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "initializing", + }, + mongodb.InstanceStatusLocked: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "locked", + }, + mongodb.InstanceStatusProvisioning: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "provisioning", + }, + mongodb.InstanceStatusReady: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "ready", + }, + mongodb.InstanceStatusSnapshotting: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "snapshotting", + }, } func instanceCreateBuilder(c *core.Command) *core.Command { @@ -45,7 +69,11 @@ func fetchLatestEngine(ctx context.Context) (string, string) { var completeListNodeTypeCache *mongodb.ListNodeTypesResponse -func autoCompleteNodeType(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autoCompleteNodeType( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { region := scw.Region("") switch req := request.(type) { case *mongodb.CreateInstanceRequest: diff --git a/internal/namespaces/mongodb/v1alpha1/custom_nodetype.go b/internal/namespaces/mongodb/v1alpha1/custom_nodetype.go index 5a2b85131f..f5f04247c2 100644 --- a/internal/namespaces/mongodb/v1alpha1/custom_nodetype.go +++ b/internal/namespaces/mongodb/v1alpha1/custom_nodetype.go @@ -7,7 +7,16 @@ import ( ) var nodeTypeStockMarshalSpecs = human.EnumMarshalSpecs{ - mongodb.NodeTypeStockAvailable: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "available"}, - mongodb.NodeTypeStockLowStock: &human.EnumMarshalSpec{Attribute: color.FgYellow, Value: "low stock"}, - mongodb.NodeTypeStockOutOfStock: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "out of stock"}, + mongodb.NodeTypeStockAvailable: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "available", + }, + mongodb.NodeTypeStockLowStock: &human.EnumMarshalSpec{ + Attribute: color.FgYellow, + Value: "low stock", + }, + mongodb.NodeTypeStockOutOfStock: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "out of stock", + }, } diff --git a/internal/namespaces/mongodb/v1alpha1/custom_snapshot.go b/internal/namespaces/mongodb/v1alpha1/custom_snapshot.go index 560607dd9a..1150de2d82 100644 --- a/internal/namespaces/mongodb/v1alpha1/custom_snapshot.go +++ b/internal/namespaces/mongodb/v1alpha1/custom_snapshot.go @@ -7,10 +7,25 @@ import ( ) var snapshotStatusMarshalSpecs = human.EnumMarshalSpecs{ - mongodb.SnapshotStatusCreating: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "creating"}, - mongodb.SnapshotStatusDeleting: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "deleting"}, - mongodb.SnapshotStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "error"}, - mongodb.SnapshotStatusLocked: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "locked"}, - mongodb.SnapshotStatusReady: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "ready"}, - mongodb.SnapshotStatusRestoring: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "restoring"}, + mongodb.SnapshotStatusCreating: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "creating", + }, + mongodb.SnapshotStatusDeleting: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "deleting", + }, + mongodb.SnapshotStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "error"}, + mongodb.SnapshotStatusLocked: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "locked", + }, + mongodb.SnapshotStatusReady: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "ready", + }, + mongodb.SnapshotStatusRestoring: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "restoring", + }, } diff --git a/internal/namespaces/mongodb/v1alpha1/mongodb_cli.go b/internal/namespaces/mongodb/v1alpha1/mongodb_cli.go index cd86831224..daa04b9141 100644 --- a/internal/namespaces/mongodb/v1alpha1/mongodb_cli.go +++ b/internal/namespaces/mongodb/v1alpha1/mongodb_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/mongodb/v1alpha1" + mongodb "github.com/scaleway/scaleway-sdk-go/api/mongodb/v1alpha1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -45,6 +45,7 @@ func GetGeneratedCommands() *core.Commands { mongodbUserUpdate(), ) } + func mongodbRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Managed Databases for MongoDB®`, @@ -143,8 +144,8 @@ func mongodbNodeTypeList() *core.Command { if err != nil { return nil, err } - return resp.NodeTypes, nil + return resp.NodeTypes, nil }, } } @@ -181,8 +182,8 @@ func mongodbVersionList() *core.Command { if err != nil { return nil, err } - return resp.Versions, nil + return resp.Versions, nil }, } } @@ -217,7 +218,14 @@ func mongodbInstanceList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "status_asc", "status_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + "status_asc", + "status_desc", + }, }, { Name: "project-id", @@ -249,8 +257,8 @@ func mongodbInstanceList() *core.Command { if err != nil { return nil, err } - return resp.Instances, nil + return resp.Instances, nil }, } } @@ -279,8 +287,8 @@ func mongodbInstanceGet() *core.Command { client := core.ExtractClient(ctx) api := mongodb.NewAPI(client) - return api.GetInstance(request) + return api.GetInstance(request) }, } } @@ -375,8 +383,8 @@ func mongodbInstanceCreate() *core.Command { client := core.ExtractClient(ctx) api := mongodb.NewAPI(client) - return api.CreateInstance(request) + return api.CreateInstance(request) }, } } @@ -419,8 +427,8 @@ func mongodbInstanceUpdate() *core.Command { client := core.ExtractClient(ctx) api := mongodb.NewAPI(client) - return api.UpdateInstance(request) + return api.UpdateInstance(request) }, } } @@ -449,8 +457,8 @@ func mongodbInstanceDelete() *core.Command { client := core.ExtractClient(ctx) api := mongodb.NewAPI(client) - return api.DeleteInstance(request) + return api.DeleteInstance(request) }, } } @@ -486,8 +494,8 @@ func mongodbInstanceUpgrade() *core.Command { client := core.ExtractClient(ctx) api := mongodb.NewAPI(client) - return api.UpgradeInstance(request) + return api.UpgradeInstance(request) }, } } @@ -516,8 +524,8 @@ func mongodbInstanceGetCertificate() *core.Command { client := core.ExtractClient(ctx) api := mongodb.NewAPI(client) - return api.GetInstanceCertificate(request) + return api.GetInstanceCertificate(request) }, } } @@ -560,8 +568,8 @@ func mongodbSnapshotCreate() *core.Command { client := core.ExtractClient(ctx) api := mongodb.NewAPI(client) - return api.CreateSnapshot(request) + return api.CreateSnapshot(request) }, } } @@ -590,8 +598,8 @@ func mongodbSnapshotGet() *core.Command { client := core.ExtractClient(ctx) api := mongodb.NewAPI(client) - return api.GetSnapshot(request) + return api.GetSnapshot(request) }, } } @@ -634,8 +642,8 @@ func mongodbSnapshotUpdate() *core.Command { client := core.ExtractClient(ctx) api := mongodb.NewAPI(client) - return api.UpdateSnapshot(request) + return api.UpdateSnapshot(request) }, } } @@ -693,8 +701,8 @@ func mongodbSnapshotRestore() *core.Command { client := core.ExtractClient(ctx) api := mongodb.NewAPI(client) - return api.RestoreSnapshot(request) + return api.RestoreSnapshot(request) }, } } @@ -729,7 +737,14 @@ func mongodbSnapshotList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "expires_at_asc", "expires_at_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + "expires_at_asc", + "expires_at_desc", + }, }, { Name: "project-id", @@ -761,8 +776,8 @@ func mongodbSnapshotList() *core.Command { if err != nil { return nil, err } - return resp.Snapshots, nil + return resp.Snapshots, nil }, } } @@ -791,8 +806,8 @@ func mongodbSnapshotDelete() *core.Command { client := core.ExtractClient(ctx) api := mongodb.NewAPI(client) - return api.DeleteSnapshot(request) + return api.DeleteSnapshot(request) }, } } @@ -845,8 +860,8 @@ func mongodbUserList() *core.Command { if err != nil { return nil, err } - return resp.Users, nil + return resp.Users, nil }, } } @@ -889,8 +904,8 @@ func mongodbUserUpdate() *core.Command { client := core.ExtractClient(ctx) api := mongodb.NewAPI(client) - return api.UpdateUser(request) + return api.UpdateUser(request) }, } } diff --git a/internal/namespaces/object/v1/custom_bucket.go b/internal/namespaces/object/v1/custom_bucket.go index a3d4f3c816..66a7883532 100644 --- a/internal/namespaces/object/v1/custom_bucket.go +++ b/internal/namespaces/object/v1/custom_bucket.go @@ -384,7 +384,11 @@ func getBucketEndpoint(name, region string) (string, error) { return fmt.Sprintf("https://%s.s3.%s.scw.cloud", name, region), nil } -func countBucketObjects(ctx context.Context, client *s3.Client, name string) (nbObjects, nbParts int64, totalSize scw.Size, err error) { +func countBucketObjects( + ctx context.Context, + client *s3.Client, + name string, +) (nbObjects, nbParts int64, totalSize scw.Size, err error) { var size int64 // count full objects @@ -404,7 +408,10 @@ func countBucketObjects(ctx context.Context, client *s3.Client, name string) (nb Bucket: &name, }) if err != nil { - return nbObjects, nbParts, totalSize, fmt.Errorf("could not list multipart uploads: %w", err) + return nbObjects, nbParts, totalSize, fmt.Errorf( + "could not list multipart uploads: %w", + err, + ) } for _, upload := range multipartUploads.Uploads { partsList, err := client.ListParts(ctx, &s3.ListPartsInput{ @@ -484,7 +491,11 @@ func putBucketACL(ctx context.Context, client *s3.Client, name string, acl strin // Caching ListBuckets response for shell completion var completeListBucketsCache []types.Bucket -func autocompleteBucketName(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autocompleteBucketName( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { var region scw.Region switch t := request.(type) { case bucketConfigArgs: diff --git a/internal/namespaces/object/v1/custom_bucket_test.go b/internal/namespaces/object/v1/custom_bucket_test.go index d640eac824..360cf0e6d3 100644 --- a/internal/namespaces/object/v1/custom_bucket_test.go +++ b/internal/namespaces/object/v1/custom_bucket_test.go @@ -45,7 +45,10 @@ func Test_BucketCreate(t *testing.T) { t.Run("With tags", core.Test(&core.TestConfig{ Commands: object.GetCommands(), - Cmd: fmt.Sprintf("scw object bucket create %s tags.0=\"key1=value1\" tags.1=\"key2=value2\"", bucketName2), + Cmd: fmt.Sprintf( + "scw object bucket create %s tags.0=\"key1=value1\" tags.1=\"key2=value2\"", + bucketName2, + ), Check: core.TestCheckCombine( core.TestCheckS3Golden(), core.TestCheckExitCode(0), @@ -226,7 +229,10 @@ func Test_BucketUpdate(t *testing.T) { t.Run("All options", core.Test(&core.TestConfig{ Commands: object.GetCommands(), BeforeFunc: createBucket(bucketName2), - Cmd: fmt.Sprintf("scw object bucket update %s enable-versioning=true acl=public-read-write tags.0=\"key1=value1\" tags.1=\"key2=value2\"", bucketName2), + Cmd: fmt.Sprintf( + "scw object bucket update %s enable-versioning=true acl=public-read-write tags.0=\"key1=value1\" tags.1=\"key2=value2\"", + bucketName2, + ), Check: core.TestCheckCombine( core.TestCheckS3Golden(), core.TestCheckExitCode(0), diff --git a/internal/namespaces/object/v1/custom_config_install_test.go b/internal/namespaces/object/v1/custom_config_install_test.go index f4a5981665..47117416c2 100644 --- a/internal/namespaces/object/v1/custom_config_install_test.go +++ b/internal/namespaces/object/v1/custom_config_install_test.go @@ -30,7 +30,12 @@ func Test_ConfigInstall(t *testing.T) { Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - filePath := path.Join(ctx.OverrideEnv["HOME"], ".config", "rclone", "rclone.conf") + filePath := path.Join( + ctx.OverrideEnv["HOME"], + ".config", + "rclone", + "rclone.conf", + ) assert.FileExists(t, filePath) }, core.TestCheckExitCode(0), diff --git a/internal/namespaces/rdb/v1/custom.go b/internal/namespaces/rdb/v1/custom.go index 4aa9047f9a..7f8182181b 100644 --- a/internal/namespaces/rdb/v1/custom.go +++ b/internal/namespaces/rdb/v1/custom.go @@ -16,11 +16,26 @@ func GetCommands() *core.Commands { human.RegisterMarshalerFunc(CustomACLResult{}, rdbACLCustomResultMarshalerFunc) human.RegisterMarshalerFunc(rdbEndpointCustomResult{}, rdbEndpointCustomResultMarshalerFunc) - human.RegisterMarshalerFunc(rdb.InstanceStatus(""), human.EnumMarshalFunc(instanceStatusMarshalSpecs)) - human.RegisterMarshalerFunc(rdb.DatabaseBackupStatus(""), human.EnumMarshalFunc(backupStatusMarshalSpecs)) - human.RegisterMarshalerFunc(rdb.InstanceLogStatus(""), human.EnumMarshalFunc(logStatusMarshalSpecs)) - human.RegisterMarshalerFunc(rdb.NodeTypeStock(""), human.EnumMarshalFunc(nodeTypeStockMarshalSpecs)) - human.RegisterMarshalerFunc(rdb.ACLRuleAction(""), human.EnumMarshalFunc(aclRuleActionMarshalSpecs)) + human.RegisterMarshalerFunc( + rdb.InstanceStatus(""), + human.EnumMarshalFunc(instanceStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + rdb.DatabaseBackupStatus(""), + human.EnumMarshalFunc(backupStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + rdb.InstanceLogStatus(""), + human.EnumMarshalFunc(logStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + rdb.NodeTypeStock(""), + human.EnumMarshalFunc(nodeTypeStockMarshalSpecs), + ) + human.RegisterMarshalerFunc( + rdb.ACLRuleAction(""), + human.EnumMarshalFunc(aclRuleActionMarshalSpecs), + ) cmds.Merge(core.NewCommands( aclEditCommand(), diff --git a/internal/namespaces/rdb/v1/custom_acl_test.go b/internal/namespaces/rdb/v1/custom_acl_test.go index 0ab2053770..d6e63ba8c8 100644 --- a/internal/namespaces/rdb/v1/custom_acl_test.go +++ b/internal/namespaces/rdb/v1/custom_acl_test.go @@ -10,9 +10,12 @@ import ( func Test_AddACL(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb acl add 1.2.3.4 instance-id={{ .Instance.ID }} --wait", + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb acl add 1.2.3.4 instance-id={{ .Instance.ID }} --wait", Check: core.TestCheckCombine( core.TestCheckGolden(), func(t *testing.T, ctx *core.CheckFuncCtx) { @@ -24,9 +27,12 @@ func Test_AddACL(t *testing.T) { })) t.Run("Simple with description", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb acl add 1.2.3.4 instance-id={{ .Instance.ID }} description=some-unique-description --wait", + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb acl add 1.2.3.4 instance-id={{ .Instance.ID }} description=some-unique-description --wait", Check: core.TestCheckCombine( core.TestCheckGolden(), func(t *testing.T, ctx *core.CheckFuncCtx) { @@ -38,28 +44,42 @@ func Test_AddACL(t *testing.T) { })) t.Run("Multiple", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb acl add 1.2.3.4 192.168.1.0/30 10.10.10.10 instance-id={{ .Instance.ID }} --wait", + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb acl add 1.2.3.4 192.168.1.0/30 10.10.10.10 instance-id={{ .Instance.ID }} --wait", Check: core.TestCheckCombine( core.TestCheckGolden(), func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - verifyACL(t, ctx, []string{"0.0.0.0/0", "1.2.3.4/32", "192.168.1.0/30", "10.10.10.10/32"}) + verifyACL( + t, + ctx, + []string{"0.0.0.0/0", "1.2.3.4/32", "192.168.1.0/30", "10.10.10.10/32"}, + ) }, ), AfterFunc: deleteInstance(), })) t.Run("Multiple with description", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb acl add 1.2.3.4 192.168.1.0/30 10.10.10.10 instance-id={{ .Instance.ID }} description=some-unique-description --wait", + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb acl add 1.2.3.4 192.168.1.0/30 10.10.10.10 instance-id={{ .Instance.ID }} description=some-unique-description --wait", Check: core.TestCheckCombine( core.TestCheckGolden(), func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - verifyACL(t, ctx, []string{"0.0.0.0/0", "1.2.3.4/32", "192.168.1.0/30", "10.10.10.10/32"}) + verifyACL( + t, + ctx, + []string{"0.0.0.0/0", "1.2.3.4/32", "192.168.1.0/30", "10.10.10.10/32"}, + ) }, ), AfterFunc: deleteInstance(), @@ -68,9 +88,12 @@ func Test_AddACL(t *testing.T) { func Test_DeleteACL(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb acl delete 0.0.0.0/0 instance-id={{ .Instance.ID }} --wait", + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb acl delete 0.0.0.0/0 instance-id={{ .Instance.ID }} --wait", Check: core.TestCheckCombine( core.TestCheckGolden(), func(t *testing.T, ctx *core.CheckFuncCtx) { @@ -84,8 +107,11 @@ func Test_DeleteACL(t *testing.T) { t.Run("Multiple when set", core.Test(&core.TestConfig{ Commands: rdb.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}"), - core.ExecBeforeCmd("scw rdb acl add 1.2.3.4 192.168.1.0/32 10.10.10.10 instance-id={{ .Instance.ID }} --wait"), + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + core.ExecBeforeCmd( + "scw rdb acl add 1.2.3.4 192.168.1.0/32 10.10.10.10 instance-id={{ .Instance.ID }} --wait", + ), ), Cmd: "scw rdb acl delete 1.2.3.4/32 192.168.1.0/32 10.10.10.10/32 instance-id={{ .Instance.ID }} --wait", Check: core.TestCheckCombine( @@ -101,8 +127,11 @@ func Test_DeleteACL(t *testing.T) { t.Run("Multiple when not set", core.Test(&core.TestConfig{ Commands: rdb.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}"), - core.ExecBeforeCmd("scw rdb acl add 192.168.1.0/32 instance-id={{ .Instance.ID }} --wait"), + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + core.ExecBeforeCmd( + "scw rdb acl add 192.168.1.0/32 instance-id={{ .Instance.ID }} --wait", + ), ), Cmd: "scw rdb acl delete 1.2.3.4/32 192.168.1.0/32 10.10.10.10/32 instance-id={{ .Instance.ID }} --wait", Check: core.TestCheckCombine( @@ -118,9 +147,12 @@ func Test_DeleteACL(t *testing.T) { func Test_SetACL(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb acl set 1.2.3.4 instance-id={{ .Instance.ID }} descriptions.0=something --wait", + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb acl set 1.2.3.4 instance-id={{ .Instance.ID }} descriptions.0=something --wait", Check: core.TestCheckCombine( core.TestCheckGolden(), func(t *testing.T, ctx *core.CheckFuncCtx) { @@ -136,8 +168,11 @@ func Test_SetACL(t *testing.T) { t.Run("Multiple", core.Test(&core.TestConfig{ Commands: rdb.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}"), - core.ExecBeforeCmd("scw rdb acl add 1.2.3.4 192.168.1.0/32 10.10.10.10 instance-id={{ .Instance.ID }} --wait"), + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + core.ExecBeforeCmd( + "scw rdb acl add 1.2.3.4 192.168.1.0/32 10.10.10.10 instance-id={{ .Instance.ID }} --wait", + ), ), Cmd: "scw rdb acl set 1.2.3.4 192.168.1.0/31 11.11.11.11 instance-id={{ .Instance.ID }} descriptions.0=first descriptions.1=second descriptions.2=third --wait", Check: core.TestCheckCombine( diff --git a/internal/namespaces/rdb/v1/custom_backup.go b/internal/namespaces/rdb/v1/custom_backup.go index cd7a99ae3d..e96565595b 100644 --- a/internal/namespaces/rdb/v1/custom_backup.go +++ b/internal/namespaces/rdb/v1/custom_backup.go @@ -25,13 +25,34 @@ const ( ) var backupStatusMarshalSpecs = human.EnumMarshalSpecs{ - rdb.DatabaseBackupStatusUnknown: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "unknown"}, - rdb.DatabaseBackupStatusCreating: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "creating"}, - rdb.DatabaseBackupStatusReady: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "ready"}, - rdb.DatabaseBackupStatusRestoring: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "restoring"}, - rdb.DatabaseBackupStatusDeleting: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "deleting"}, - rdb.DatabaseBackupStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "error"}, - rdb.DatabaseBackupStatusExporting: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "exporting"}, + rdb.DatabaseBackupStatusUnknown: &human.EnumMarshalSpec{ + Attribute: color.Faint, + Value: "unknown", + }, + rdb.DatabaseBackupStatusCreating: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "creating", + }, + rdb.DatabaseBackupStatusReady: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "ready", + }, + rdb.DatabaseBackupStatusRestoring: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "restoring", + }, + rdb.DatabaseBackupStatusDeleting: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "deleting", + }, + rdb.DatabaseBackupStatusError: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "error", + }, + rdb.DatabaseBackupStatusExporting: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "exporting", + }, } type backupWaitRequest struct { @@ -201,38 +222,40 @@ func backupListBuilder(c *core.Command) *core.Command { }, } - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - listBackupResp, err := runner(ctx, argsI) - if err != nil { - return listBackupResp, err - } - backupList := listBackupResp.([]*rdb.DatabaseBackup) - var res []customBackup - for _, backup := range backupList { - isExported := false - if backup.DownloadURL != nil { - isExported = true + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + listBackupResp, err := runner(ctx, argsI) + if err != nil { + return listBackupResp, err + } + backupList := listBackupResp.([]*rdb.DatabaseBackup) + var res []customBackup + for _, backup := range backupList { + isExported := false + if backup.DownloadURL != nil { + isExported = true + } + res = append(res, customBackup{ + ID: backup.ID, + InstanceID: backup.InstanceID, + DatabaseName: backup.DatabaseName, + Name: backup.Name, + Status: backup.Status, + Size: backup.Size, + ExpiresAt: backup.ExpiresAt, + CreatedAt: backup.CreatedAt, + UpdatedAt: backup.UpdatedAt, + InstanceName: backup.InstanceName, + IsExported: isExported, + URLExpired: urlExpired(backup.DownloadURLExpiresAt), + Region: backup.Region, + SameRegion: backup.SameRegion, + }) } - res = append(res, customBackup{ - ID: backup.ID, - InstanceID: backup.InstanceID, - DatabaseName: backup.DatabaseName, - Name: backup.Name, - Status: backup.Status, - Size: backup.Size, - ExpiresAt: backup.ExpiresAt, - CreatedAt: backup.CreatedAt, - UpdatedAt: backup.UpdatedAt, - InstanceName: backup.InstanceName, - IsExported: isExported, - URLExpired: urlExpired(backup.DownloadURLExpiresAt), - Region: backup.Region, - SameRegion: backup.SameRegion, - }) - } - return res, nil - }) + return res, nil + }, + ) return c } @@ -269,7 +292,11 @@ func backupResultMarshallerFunc(i interface{}, _ *human.MarshalOpt) (string, err return "", err } - return fmt.Sprintf("Backup downloaded to %s successfully (%s written)", backupResult.FileName, sizeStr), nil + return fmt.Sprintf( + "Backup downloaded to %s successfully (%s written)", + backupResult.FileName, + sizeStr, + ), nil } func backupDownloadCommand() *core.Command { diff --git a/internal/namespaces/rdb/v1/custom_endpoint.go b/internal/namespaces/rdb/v1/custom_endpoint.go index 0673540e2e..d31b409fee 100644 --- a/internal/namespaces/rdb/v1/custom_endpoint.go +++ b/internal/namespaces/rdb/v1/custom_endpoint.go @@ -95,7 +95,9 @@ func endpointCreateBuilder(c *core.Command) *core.Command { PrivateNetwork: args.PrivateNetwork, LoadBalancer: args.LoadBalancer, } - endpointRequest, err := endpointRequestFromCustom([]*rdbEndpointSpecCustom{customEndpointSpec}) + endpointRequest, err := endpointRequestFromCustom( + []*rdbEndpointSpecCustom{customEndpointSpec}, + ) if err != nil { return nil, err } @@ -250,13 +252,16 @@ func endpointListCommand() *core.Command { } } -func endpointRequestFromCustom(customEndpoints []*rdbEndpointSpecCustom) ([]*rdb.EndpointSpec, error) { +func endpointRequestFromCustom( + customEndpoints []*rdbEndpointSpecCustom, +) ([]*rdb.EndpointSpec, error) { endpoints := []*rdb.EndpointSpec(nil) for _, customEndpoint := range customEndpoints { switch { case customEndpoint.PrivateNetwork != nil && customEndpoint.PrivateNetwork.EndpointSpecPrivateNetwork != nil: ipamConfig := &rdb.EndpointSpecPrivateNetworkIpamConfig{} - if !customEndpoint.PrivateNetwork.EnableIpam || customEndpoint.PrivateNetwork.ServiceIP != nil { + if !customEndpoint.PrivateNetwork.EnableIpam || + customEndpoint.PrivateNetwork.ServiceIP != nil { ipamConfig = nil } endpoints = append(endpoints, &rdb.EndpointSpec{ diff --git a/internal/namespaces/rdb/v1/custom_endpoint_test.go b/internal/namespaces/rdb/v1/custom_endpoint_test.go index 62af0ba5a8..75c37d7ae6 100644 --- a/internal/namespaces/rdb/v1/custom_endpoint_test.go +++ b/internal/namespaces/rdb/v1/custom_endpoint_test.go @@ -27,7 +27,12 @@ func Test_EndpointCreate(t *testing.T) { func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() instance := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance - checkEndpoints(t, ctx.Client, instance, []string{privateEndpointStatic, publicEndpoint}) + checkEndpoints( + t, + ctx.Client, + instance, + []string{privateEndpointStatic, publicEndpoint}, + ) }, ), AfterFunc: deleteInstance(), @@ -45,7 +50,12 @@ func Test_EndpointCreate(t *testing.T) { func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() instance := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance - checkEndpoints(t, ctx.Client, instance, []string{privateEndpointStatic, publicEndpoint}) + checkEndpoints( + t, + ctx.Client, + instance, + []string{privateEndpointStatic, publicEndpoint}, + ) }, ), AfterFunc: core.AfterFuncCombine( @@ -66,7 +76,12 @@ func Test_EndpointCreate(t *testing.T) { func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() instance := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance - checkEndpoints(t, ctx.Client, instance, []string{privateEndpointIpam, publicEndpoint}) + checkEndpoints( + t, + ctx.Client, + instance, + []string{privateEndpointIpam, publicEndpoint}, + ) }, ), AfterFunc: core.AfterFuncCombine( @@ -162,7 +177,12 @@ func Test_EndpointGet(t *testing.T) { func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() instance := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance - checkEndpoints(t, ctx.Client, instance, []string{publicEndpoint, privateEndpointStatic}) + checkEndpoints( + t, + ctx.Client, + instance, + []string{publicEndpoint, privateEndpointStatic}, + ) }, ), AfterFunc: core.AfterFuncCombine( @@ -184,7 +204,12 @@ func Test_EndpointGet(t *testing.T) { func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() instance := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance - checkEndpoints(t, ctx.Client, instance, []string{publicEndpoint, privateEndpointStatic}) + checkEndpoints( + t, + ctx.Client, + instance, + []string{publicEndpoint, privateEndpointStatic}, + ) }, ), AfterFunc: core.AfterFuncCombine( @@ -213,7 +238,12 @@ func Test_EndpointList(t *testing.T) { })) } -func checkEndpoints(t *testing.T, client *scw.Client, instance *rdbSDK.Instance, expected []string) { +func checkEndpoints( + t *testing.T, + client *scw.Client, + instance *rdbSDK.Instance, + expected []string, +) { t.Helper() rdbAPI := rdbSDK.NewAPI(client) ipamAPI := ipam.NewAPI(client) diff --git a/internal/namespaces/rdb/v1/custom_engine.go b/internal/namespaces/rdb/v1/custom_engine.go index 8a4dca1f95..57153bf987 100644 --- a/internal/namespaces/rdb/v1/custom_engine.go +++ b/internal/namespaces/rdb/v1/custom_engine.go @@ -32,25 +32,27 @@ func engineListBuilder(c *core.Command) *core.Command { }, } - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { - listEngineResp, err := runner(ctx, argsI) - if err != nil { - return listEngineResp, err - } - engineList := listEngineResp.([]*rdb.DatabaseEngine) - var res []customEngine - for _, engine := range engineList { - for _, version := range engine.Versions { - res = append(res, customEngine{ - Name: version.Name, - EngineType: engine.Name, - EndOfLife: version.EndOfLife, - }) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) { + listEngineResp, err := runner(ctx, argsI) + if err != nil { + return listEngineResp, err + } + engineList := listEngineResp.([]*rdb.DatabaseEngine) + var res []customEngine + for _, engine := range engineList { + for _, version := range engine.Versions { + res = append(res, customEngine{ + Name: version.Name, + EngineType: engine.Name, + EndOfLife: version.EndOfLife, + }) + } } - } - return res, nil - }) + return res, nil + }, + ) return c } diff --git a/internal/namespaces/rdb/v1/custom_instance.go b/internal/namespaces/rdb/v1/custom_instance.go index 560ecd09c3..1174f9dd60 100644 --- a/internal/namespaces/rdb/v1/custom_instance.go +++ b/internal/namespaces/rdb/v1/custom_instance.go @@ -32,17 +32,50 @@ const ( ) var instanceStatusMarshalSpecs = human.EnumMarshalSpecs{ - rdbSDK.InstanceStatusUnknown: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "unknown"}, - rdbSDK.InstanceStatusReady: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "ready"}, - rdbSDK.InstanceStatusProvisioning: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "provisioning"}, - rdbSDK.InstanceStatusConfiguring: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "configuring"}, - rdbSDK.InstanceStatusDeleting: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "deleting"}, - rdbSDK.InstanceStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "error"}, - rdbSDK.InstanceStatusAutohealing: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "auto-healing"}, - rdbSDK.InstanceStatusLocked: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "locked"}, - rdbSDK.InstanceStatusInitializing: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "initialized"}, - rdbSDK.InstanceStatusDiskFull: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "disk_full"}, - rdbSDK.InstanceStatusBackuping: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "backuping"}, + rdbSDK.InstanceStatusUnknown: &human.EnumMarshalSpec{ + Attribute: color.Faint, + Value: "unknown", + }, + rdbSDK.InstanceStatusReady: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "ready", + }, + rdbSDK.InstanceStatusProvisioning: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "provisioning", + }, + rdbSDK.InstanceStatusConfiguring: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "configuring", + }, + rdbSDK.InstanceStatusDeleting: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "deleting", + }, + rdbSDK.InstanceStatusError: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "error", + }, + rdbSDK.InstanceStatusAutohealing: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "auto-healing", + }, + rdbSDK.InstanceStatusLocked: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "locked", + }, + rdbSDK.InstanceStatusInitializing: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "initialized", + }, + rdbSDK.InstanceStatusDiskFull: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "disk_full", + }, + rdbSDK.InstanceStatusBackuping: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "backuping", + }, } type serverWaitRequest struct { @@ -177,7 +210,11 @@ var completeListNodeTypeCache *rdbSDK.ListNodeTypesResponse var completeListEngineCache *rdbSDK.ListDatabaseEnginesResponse -func autoCompleteNodeType(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autoCompleteNodeType( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { region := scw.Region("") switch req := request.(type) { case *rdbSDK.CreateInstanceRequest: @@ -210,7 +247,11 @@ func autoCompleteNodeType(ctx context.Context, prefix string, request any) core. return suggestions } -func autoCompleteDatabaseEngines(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autoCompleteDatabaseEngines( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { req := request.(rdbCreateInstanceRequestCustom) suggestion := core.AutocompleteSuggestions(nil) client := core.ExtractClient(ctx) @@ -266,8 +307,8 @@ func instanceCreateBuilder(c *core.Command) *core.Command { c.WaitFunc = func(ctx context.Context, _, respI interface{}) (interface{}, error) { api := rdbSDK.NewAPI(core.ExtractClient(ctx)) instance, err := api.WaitForInstance(&rdbSDK.WaitForInstanceRequest{ - InstanceID: respI.(CreateInstanceResult).Instance.ID, - Region: respI.(CreateInstanceResult).Instance.Region, + InstanceID: respI.(CreateInstanceResult).ID, + Region: respI.(CreateInstanceResult).Region, Timeout: scw.TimeDurationPtr(instanceActionTimeout), RetryInterval: core.DefaultRetryInterval, }) @@ -301,7 +342,9 @@ func instanceCreateBuilder(c *core.Command) *core.Command { fmt.Printf("\n") } - createInstanceRequest.InitEndpoints, err = endpointRequestFromCustom(customRequest.InitEndpoints) + createInstanceRequest.InitEndpoints, err = endpointRequestFromCustom( + customRequest.InitEndpoints, + ) if err != nil { return nil, err } @@ -340,10 +383,11 @@ func instanceGetBuilder(c *core.Command) *core.Command { args := argsI.(*rdbSDK.GetInstanceRequest) - acls, err := rdbSDK.NewAPI(core.ExtractClient(ctx)).ListInstanceACLRules(&rdbSDK.ListInstanceACLRulesRequest{ - Region: args.Region, - InstanceID: args.InstanceID, - }, scw.WithAllPages()) + acls, err := rdbSDK.NewAPI(core.ExtractClient(ctx)). + ListInstanceACLRules(&rdbSDK.ListInstanceACLRulesRequest{ + Region: args.Region, + InstanceID: args.InstanceID, + }, scw.WithAllPages()) if err != nil { return nil, err } @@ -589,7 +633,8 @@ func instanceDeleteBuilder(c *core.Command) *core.Command { // if we get a 404 here, it means the resource was successfully deleted notFoundError := &scw.ResourceNotFoundError{} responseError := &scw.ResponseError{} - if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) { + if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || + errors.As(err, ¬FoundError) { return instance, nil } @@ -669,7 +714,12 @@ func passwordFileExist(ctx context.Context, family engineFamily) bool { case PostgreSQL: switch runtime.GOOS { case "windows": - passwordFilePath = path.Join(core.ExtractUserHomeDir(ctx), core.ExtractEnv(ctx, "APPDATA"), "postgresql", "pgpass.conf") + passwordFilePath = path.Join( + core.ExtractUserHomeDir(ctx), + core.ExtractEnv(ctx, "APPDATA"), + "postgresql", + "pgpass.conf", + ) default: passwordFilePath = path.Join(core.ExtractUserHomeDir(ctx), ".pgpass") } @@ -731,7 +781,11 @@ func getPrivateEndpoint(endpoints []*rdbSDK.Endpoint) (*rdbSDK.Endpoint, error) return nil, fmt.Errorf("%s", errorMessagePrivateEndpointNotFound) } -func createConnectCommandLineArgs(endpoint *rdbSDK.Endpoint, family engineFamily, args *instanceConnectArgs) ([]string, error) { +func createConnectCommandLineArgs( + endpoint *rdbSDK.Endpoint, + family engineFamily, + args *instanceConnectArgs, +) ([]string, error) { database := "rdb" if args.Database != nil { database = *args.Database diff --git a/internal/namespaces/rdb/v1/custom_instance_test.go b/internal/namespaces/rdb/v1/custom_instance_test.go index b99411457e..edfde4ffbd 100644 --- a/internal/namespaces/rdb/v1/custom_instance_test.go +++ b/internal/namespaces/rdb/v1/custom_instance_test.go @@ -24,21 +24,27 @@ const ( func Test_ListInstance(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb instance list", - Check: core.TestCheckGolden(), - AfterFunc: deleteInstance(), + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb instance list", + Check: core.TestCheckGolden(), + AfterFunc: deleteInstance(), })) } func Test_CloneInstance(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb instance clone {{ .Instance.ID }} node-type=DB-DEV-M name=foobar --wait", - Check: core.TestCheckGolden(), - AfterFunc: deleteInstance(), + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb instance clone {{ .Instance.ID }} node-type=DB-DEV-M name=foobar --wait", + Check: core.TestCheckGolden(), + AfterFunc: deleteInstance(), })) } @@ -59,7 +65,12 @@ func Test_CreateInstance(t *testing.T) { t.Run("With password generator", core.Test(&core.TestConfig{ Commands: rdb.GetCommands(), - Cmd: fmt.Sprintf(strings.Replace(baseCommand, "password=%s", "generate-password=true", 1), name, engine, user), + Cmd: fmt.Sprintf( + strings.Replace(baseCommand, "password=%s", "generate-password=true", 1), + name, + engine, + user, + ), // do not check the golden as the password generated locally and on CI will necessarily be different Check: core.TestCheckCombine( core.TestCheckExitCode(0), @@ -98,13 +109,24 @@ func Test_CreateInstanceInitEndpoints(t *testing.T) { t.Run("With public and static private endpoint", core.Test(&core.TestConfig{ Commands: cmds, BeforeFunc: createPN(), - Cmd: fmt.Sprintf(baseCommand+privateNetworkStaticSpec+loadBalancerSpec, name, engine, user, password), + Cmd: fmt.Sprintf( + baseCommand+privateNetworkStaticSpec+loadBalancerSpec, + name, + engine, + user, + password, + ), Check: core.TestCheckCombine( core.TestCheckGolden(), func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() instance := ctx.Result.(rdb.CreateInstanceResult).Instance - checkEndpoints(t, ctx.Client, instance, []string{publicEndpoint, privateEndpointStatic}) + checkEndpoints( + t, + ctx.Client, + instance, + []string{publicEndpoint, privateEndpointStatic}, + ) }, ), AfterFunc: core.AfterFuncCombine( @@ -134,13 +156,24 @@ func Test_CreateInstanceInitEndpoints(t *testing.T) { t.Run("With public and IPAM private endpoint", core.Test(&core.TestConfig{ Commands: cmds, BeforeFunc: createPN(), - Cmd: fmt.Sprintf(baseCommand+privateNetworkIpamSpec+loadBalancerSpec, name, engine, user, password), + Cmd: fmt.Sprintf( + baseCommand+privateNetworkIpamSpec+loadBalancerSpec, + name, + engine, + user, + password, + ), Check: core.TestCheckCombine( core.TestCheckGolden(), func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() instance := ctx.Result.(rdb.CreateInstanceResult).Instance - checkEndpoints(t, ctx.Client, instance, []string{publicEndpoint, privateEndpointIpam}) + checkEndpoints( + t, + ctx.Client, + instance, + []string{publicEndpoint, privateEndpointIpam}, + ) }, ), AfterFunc: core.AfterFuncCombine( @@ -152,29 +185,38 @@ func Test_CreateInstanceInitEndpoints(t *testing.T) { func Test_GetInstance(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb instance get {{ .Instance.ID }}", - Check: core.TestCheckGolden(), - AfterFunc: deleteInstance(), + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb instance get {{ .Instance.ID }}", + Check: core.TestCheckGolden(), + AfterFunc: deleteInstance(), })) } func Test_UpgradeInstance(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb instance upgrade {{ .Instance.ID }} node-type=DB-DEV-M --wait", - Check: core.TestCheckGolden(), - AfterFunc: deleteInstance(), + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb instance upgrade {{ .Instance.ID }} node-type=DB-DEV-M --wait", + Check: core.TestCheckGolden(), + AfterFunc: deleteInstance(), })) } func Test_UpdateInstance(t *testing.T) { t.Run("Update instance name", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb instance update {{ .Instance.ID }} name=foo --wait", + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb instance update {{ .Instance.ID }} name=foo --wait", Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() @@ -187,9 +229,12 @@ func Test_UpdateInstance(t *testing.T) { })) t.Run("Update instance tags", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb instance update {{ .Instance.ID }} tags.0=a --wait", + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb instance update {{ .Instance.ID }} tags.0=a --wait", Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() @@ -202,9 +247,12 @@ func Test_UpdateInstance(t *testing.T) { })) t.Run("Set a timezone", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb instance update {{ .Instance.ID }} settings.0.name=timezone settings.0.value=UTC --wait", + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb instance update {{ .Instance.ID }} settings.0.name=timezone settings.0.value=UTC --wait", Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() @@ -218,9 +266,12 @@ func Test_UpdateInstance(t *testing.T) { })) t.Run("Modify default work_mem from 4 to 8 MB", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb instance update {{ .Instance.ID }} settings.0.name=work_mem settings.0.value=8 --wait", + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb instance update {{ .Instance.ID }} settings.0.name=work_mem settings.0.value=8 --wait", Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() @@ -238,10 +289,12 @@ func Test_UpdateInstance(t *testing.T) { BeforeFunc: core.BeforeFuncCombine( fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}"), - core.ExecBeforeCmd("scw rdb instance update {{ .Instance.ID }} settings.0.name=work_mem settings.0.value=8"+ - " settings.1.name=max_connections settings.1.value=200"+ - " settings.2.name=effective_cache_size settings.2.value=1000"+ - " name=foo1 --wait"), + core.ExecBeforeCmd( + "scw rdb instance update {{ .Instance.ID }} settings.0.name=work_mem settings.0.value=8"+ + " settings.1.name=max_connections settings.1.value=200"+ + " settings.2.name=effective_cache_size settings.2.value=1000"+ + " name=foo1 --wait", + ), ), Cmd: "scw rdb instance update {{ .Instance.ID }} settings.0.name=work_mem settings.0.value=16" + " settings.1.name=max_connections settings.1.value=150" + @@ -251,9 +304,17 @@ func Test_UpdateInstance(t *testing.T) { Check: core.TestCheckCombine( func(t *testing.T, ctx *core.CheckFuncCtx) { t.Helper() - assert.Equal(t, "effective_cache_size", ctx.Result.(*rdbSDK.Instance).Settings[0].Name) + assert.Equal( + t, + "effective_cache_size", + ctx.Result.(*rdbSDK.Instance).Settings[0].Name, + ) assert.Equal(t, "1200", ctx.Result.(*rdbSDK.Instance).Settings[0].Value) - assert.Equal(t, "maintenance_work_mem", ctx.Result.(*rdbSDK.Instance).Settings[1].Name) + assert.Equal( + t, + "maintenance_work_mem", + ctx.Result.(*rdbSDK.Instance).Settings[1].Name, + ) assert.Equal(t, "200", ctx.Result.(*rdbSDK.Instance).Settings[1].Value) assert.Equal(t, "max_connections", ctx.Result.(*rdbSDK.Instance).Settings[2].Name) assert.Equal(t, "150", ctx.Result.(*rdbSDK.Instance).Settings[2].Value) @@ -281,8 +342,11 @@ func Test_Connect(t *testing.T) { core.TestCheckGolden(), core.TestCheckExitCode(0), ), - OverrideExec: core.OverrideExecSimple("mysql --host {{ .Instance.Endpoint.IP }} --port {{ .Instance.Endpoint.Port }} --database rdb --user {{ .username }}", 0), - AfterFunc: deleteInstance(), + OverrideExec: core.OverrideExecSimple( + "mysql --host {{ .Instance.Endpoint.IP }} --port {{ .Instance.Endpoint.Port }} --database rdb --user {{ .username }}", + 0, + ), + AfterFunc: deleteInstance(), })) t.Run("psql", core.Test(&core.TestConfig{ @@ -295,8 +359,11 @@ func Test_Connect(t *testing.T) { core.TestCheckGolden(), core.TestCheckExitCode(0), ), - OverrideExec: core.OverrideExecSimple("psql --host {{ .Instance.Endpoint.IP }} --port {{ .Instance.Endpoint.Port }} --username {{ .username }} --dbname rdb", 0), - AfterFunc: deleteInstance(), + OverrideExec: core.OverrideExecSimple( + "psql --host {{ .Instance.Endpoint.IP }} --port {{ .Instance.Endpoint.Port }} --username {{ .username }} --dbname rdb", + 0, + ), + AfterFunc: deleteInstance(), })) t.Run("psql", core.Test(&core.TestConfig{ Commands: rdb.GetCommands(), @@ -310,8 +377,11 @@ func Test_Connect(t *testing.T) { core.TestCheckGolden(), core.TestCheckExitCode(0), ), - OverrideExec: core.OverrideExecSimple("psql --host {{ .Instance.Endpoint.IP }} --port {{ .Instance.Endpoint.Port }} --username {{ .username }} --dbname rdb", 0), - AfterFunc: deleteInstance(), + OverrideExec: core.OverrideExecSimple( + "psql --host {{ .Instance.Endpoint.IP }} --port {{ .Instance.Endpoint.Port }} --username {{ .username }} --dbname rdb", + 0, + ), + AfterFunc: deleteInstance(), })) } diff --git a/internal/namespaces/rdb/v1/custom_log.go b/internal/namespaces/rdb/v1/custom_log.go index 2a6fd83b84..d7dccacadc 100644 --- a/internal/namespaces/rdb/v1/custom_log.go +++ b/internal/namespaces/rdb/v1/custom_log.go @@ -11,10 +11,13 @@ import ( ) var logStatusMarshalSpecs = human.EnumMarshalSpecs{ - rdb.InstanceLogStatusUnknown: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "unknown"}, - rdb.InstanceLogStatusReady: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "ready"}, - rdb.InstanceLogStatusCreating: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "creating"}, - rdb.InstanceLogStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "error"}, + rdb.InstanceLogStatusUnknown: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "unknown"}, + rdb.InstanceLogStatusReady: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "ready"}, + rdb.InstanceLogStatusCreating: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + Value: "creating", + }, + rdb.InstanceLogStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "error"}, } func logPrepareBuilder(c *core.Command) *core.Command { diff --git a/internal/namespaces/rdb/v1/custom_node_type.go b/internal/namespaces/rdb/v1/custom_node_type.go index d3912bffea..cec2d56b23 100644 --- a/internal/namespaces/rdb/v1/custom_node_type.go +++ b/internal/namespaces/rdb/v1/custom_node_type.go @@ -7,8 +7,17 @@ import ( ) var nodeTypeStockMarshalSpecs = human.EnumMarshalSpecs{ - rdb.NodeTypeStockAvailable: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "available"}, - rdb.NodeTypeStockUnknown: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "unknown"}, - rdb.NodeTypeStockLowStock: &human.EnumMarshalSpec{Attribute: color.FgYellow, Value: "low stock"}, - rdb.NodeTypeStockOutOfStock: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "out of stock"}, + rdb.NodeTypeStockAvailable: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + Value: "available", + }, + rdb.NodeTypeStockUnknown: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "unknown"}, + rdb.NodeTypeStockLowStock: &human.EnumMarshalSpec{ + Attribute: color.FgYellow, + Value: "low stock", + }, + rdb.NodeTypeStockOutOfStock: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + Value: "out of stock", + }, } diff --git a/internal/namespaces/rdb/v1/custom_url.go b/internal/namespaces/rdb/v1/custom_url.go index 294e0e34df..0523eba9f2 100644 --- a/internal/namespaces/rdb/v1/custom_url.go +++ b/internal/namespaces/rdb/v1/custom_url.go @@ -87,7 +87,11 @@ func generateURL(ctx context.Context, argsI interface{}) (interface{}, error) { return nil, fmt.Errorf("failed to list users for instance %q", args.InstanceID) } if users.TotalCount != 1 { - return nil, fmt.Errorf("expected 1 user with the name %q, got %d", args.User, users.TotalCount) + return nil, fmt.Errorf( + "expected 1 user with the name %q, got %d", + args.User, + users.TotalCount, + ) } u.User = url.User(users.Users[0].Name) @@ -121,7 +125,11 @@ func generateURL(ctx context.Context, argsI interface{}) (interface{}, error) { return nil, fmt.Errorf("failed to list databases for instance %q", args.InstanceID) } if databases.TotalCount != 1 { - return nil, fmt.Errorf("expected 1 database with the name %q, got %d", args.Db, databases.TotalCount) + return nil, fmt.Errorf( + "expected 1 database with the name %q, got %d", + args.Db, + databases.TotalCount, + ) } u = u.JoinPath(databases.Databases[0].Name) } diff --git a/internal/namespaces/rdb/v1/custom_url_test.go b/internal/namespaces/rdb/v1/custom_url_test.go index 9e5d1fc82c..f110f2e6e7 100644 --- a/internal/namespaces/rdb/v1/custom_url_test.go +++ b/internal/namespaces/rdb/v1/custom_url_test.go @@ -24,7 +24,11 @@ func Test_UserGetURL(t *testing.T) { t.Helper() ip := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance.Endpoints[0].IP port := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance.Endpoints[0].Port - expected := fmt.Sprintf("postgresql://%s@%s", user, net.JoinHostPort(ip.String(), strconv.Itoa(int(port)))) + expected := fmt.Sprintf( + "postgresql://%s@%s", + user, + net.JoinHostPort(ip.String(), strconv.Itoa(int(port))), + ) assert.Equal(t, expected, ctx.Result) }, ), @@ -43,7 +47,11 @@ func Test_UserGetURL(t *testing.T) { t.Helper() ip := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance.Endpoints[0].IP port := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance.Endpoints[0].Port - expected := fmt.Sprintf("mysql://%s@%s", user, net.JoinHostPort(ip.String(), strconv.Itoa(int(port)))) + expected := fmt.Sprintf( + "mysql://%s@%s", + user, + net.JoinHostPort(ip.String(), strconv.Itoa(int(port))), + ) assert.Equal(t, expected, ctx.Result) }, ), @@ -57,8 +65,15 @@ func Test_UserGetURL(t *testing.T) { t.Run("With custom user", core.Test(&core.TestConfig{ Commands: rdb.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}"), - core.ExecBeforeCmd(fmt.Sprintf("scw rdb user create instance-id={{ $.Instance.ID }} name=%s password=%s is-admin=false", customUserName, customUserPassword)), + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + core.ExecBeforeCmd( + fmt.Sprintf( + "scw rdb user create instance-id={{ $.Instance.ID }} name=%s password=%s is-admin=false", + customUserName, + customUserPassword, + ), + ), ), Cmd: "scw rdb user get-url {{ $.Instance.ID }} user=" + customUserName, Check: core.TestCheckCombine( @@ -67,7 +82,11 @@ func Test_UserGetURL(t *testing.T) { t.Helper() ip := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance.Endpoints[0].IP port := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance.Endpoints[0].Port - expected := fmt.Sprintf("postgresql://%s@%s", customUserName, net.JoinHostPort(ip.String(), strconv.Itoa(int(port)))) + expected := fmt.Sprintf( + "postgresql://%s@%s", + customUserName, + net.JoinHostPort(ip.String(), strconv.Itoa(int(port))), + ) assert.Equal(t, expected, ctx.Result) }, ), @@ -77,8 +96,11 @@ func Test_UserGetURL(t *testing.T) { t.Run("With custom database", core.Test(&core.TestConfig{ Commands: rdb.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}"), - core.ExecBeforeCmd("scw rdb database create instance-id={{ $.Instance.ID }} name="+customDBName), + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + core.ExecBeforeCmd( + "scw rdb database create instance-id={{ $.Instance.ID }} name="+customDBName, + ), ), Cmd: "scw rdb user get-url {{ $.Instance.ID }} db=" + customDBName, Check: core.TestCheckCombine( @@ -87,7 +109,12 @@ func Test_UserGetURL(t *testing.T) { t.Helper() ip := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance.Endpoints[0].IP port := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance.Endpoints[0].Port - expected := fmt.Sprintf("postgresql://%s@%s/%s", user, net.JoinHostPort(ip.String(), strconv.Itoa(int(port))), customDBName) + expected := fmt.Sprintf( + "postgresql://%s@%s/%s", + user, + net.JoinHostPort(ip.String(), strconv.Itoa(int(port))), + customDBName, + ) assert.Equal(t, expected, ctx.Result) }, ), @@ -108,7 +135,11 @@ func Test_DatabaseGetURL(t *testing.T) { t.Helper() ip := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance.Endpoints[0].IP port := ctx.Meta["Instance"].(rdb.CreateInstanceResult).Instance.Endpoints[0].Port - expected := fmt.Sprintf("postgresql://%s@%s", user, net.JoinHostPort(ip.String(), strconv.Itoa(int(port)))) + expected := fmt.Sprintf( + "postgresql://%s@%s", + user, + net.JoinHostPort(ip.String(), strconv.Itoa(int(port))), + ) assert.Equal(t, expected, ctx.Result) }, ), diff --git a/internal/namespaces/rdb/v1/custom_user.go b/internal/namespaces/rdb/v1/custom_user.go index 343b4dbe3a..5bbf7dfc0a 100644 --- a/internal/namespaces/rdb/v1/custom_user.go +++ b/internal/namespaces/rdb/v1/custom_user.go @@ -78,7 +78,8 @@ func userListBuilder(c *core.Command) *core.Command { case rdb.PermissionReadwrite: user.ReadWrite = append(user.ReadWrite, privilege.DatabaseName) default: - core.ExtractLogger(ctx).Errorf("unsupported permission value %s", privilege.Permission) + core.ExtractLogger(ctx). + Errorf("unsupported permission value %s", privilege.Permission) } } diff --git a/internal/namespaces/rdb/v1/custom_user_test.go b/internal/namespaces/rdb/v1/custom_user_test.go index e213e939cb..6f5edcf2b4 100644 --- a/internal/namespaces/rdb/v1/custom_user_test.go +++ b/internal/namespaces/rdb/v1/custom_user_test.go @@ -10,27 +10,43 @@ import ( func Test_ListUser(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: "scw rdb user list instance-id={{ .Instance.ID }}", - Check: core.TestCheckGolden(), - AfterFunc: deleteInstance(), + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: "scw rdb user list instance-id={{ .Instance.ID }}", + Check: core.TestCheckGolden(), + AfterFunc: deleteInstance(), })) } func Test_CreateUser(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: fmt.Sprintf("scw rdb user create instance-id={{ $.Instance.Instance.ID }} name=%s password=%s", name, password), - Check: core.TestCheckGolden(), - AfterFunc: deleteInstance(), + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: fmt.Sprintf( + "scw rdb user create instance-id={{ $.Instance.Instance.ID }} name=%s password=%s", + name, + password, + ), + Check: core.TestCheckGolden(), + AfterFunc: deleteInstance(), })) t.Run("With password generator", core.Test(&core.TestConfig{ - Commands: rdb.GetCommands(), - BeforeFunc: core.BeforeFuncCombine(fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}")), - Cmd: fmt.Sprintf("scw rdb user create instance-id={{ $.Instance.Instance.ID }} name=%s generate-password=true", name), + Commands: rdb.GetCommands(), + BeforeFunc: core.BeforeFuncCombine( + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + ), + Cmd: fmt.Sprintf( + "scw rdb user create instance-id={{ $.Instance.Instance.ID }} name=%s generate-password=true", + name, + ), // do not check the golden as the password generated locally and on CI will necessarily be different Check: core.TestCheckExitCode(0), AfterFunc: deleteInstance(), @@ -41,10 +57,20 @@ func Test_UpdateUser(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ Commands: rdb.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}"), - core.ExecBeforeCmd(fmt.Sprintf("scw rdb user create instance-id={{ $.Instance.Instance.ID }} name=%s password=%s", name, password)), + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + core.ExecBeforeCmd( + fmt.Sprintf( + "scw rdb user create instance-id={{ $.Instance.Instance.ID }} name=%s password=%s", + name, + password, + ), + ), + ), + Cmd: fmt.Sprintf( + "scw rdb user update instance-id={{ $.Instance.Instance.ID }} name=%s password=Newp1ssw0rd! is-admin=true", + name, ), - Cmd: fmt.Sprintf("scw rdb user update instance-id={{ $.Instance.Instance.ID }} name=%s password=Newp1ssw0rd! is-admin=true", name), Check: core.TestCheckGolden(), AfterFunc: deleteInstance(), })) @@ -52,10 +78,20 @@ func Test_UpdateUser(t *testing.T) { t.Run("With password generator", core.Test(&core.TestConfig{ Commands: rdb.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - fetchLatestEngine("PostgreSQL"), createInstance("{{.latestEngine}}"), - core.ExecBeforeCmd(fmt.Sprintf("scw rdb user create instance-id={{ $.Instance.Instance.ID }} name=%s password=%s", name, password)), + fetchLatestEngine("PostgreSQL"), + createInstance("{{.latestEngine}}"), + core.ExecBeforeCmd( + fmt.Sprintf( + "scw rdb user create instance-id={{ $.Instance.Instance.ID }} name=%s password=%s", + name, + password, + ), + ), + ), + Cmd: fmt.Sprintf( + "scw rdb user update instance-id={{ $.Instance.Instance.ID }} name=%s generate-password=true is-admin=true", + name, ), - Cmd: fmt.Sprintf("scw rdb user update instance-id={{ $.Instance.Instance.ID }} name=%s generate-password=true is-admin=true", name), // do not check the golden as the password generated locally and on CI will necessarily be different Check: core.TestCheckExitCode(0), AfterFunc: deleteInstance(), diff --git a/internal/namespaces/rdb/v1/helper_test.go b/internal/namespaces/rdb/v1/helper_test.go index 0f59179260..b1067f4886 100644 --- a/internal/namespaces/rdb/v1/helper_test.go +++ b/internal/namespaces/rdb/v1/helper_test.go @@ -48,7 +48,13 @@ func createInstanceWithPrivateNetwork() core.BeforeFunc { func createInstanceWithPrivateNetworkAndLoadBalancer() core.BeforeFunc { return core.ExecStoreBeforeCmd( "Instance", - fmt.Sprintf(baseCommand+privateNetworkStaticSpec+loadBalancerSpec, name, engine, user, password), + fmt.Sprintf( + baseCommand+privateNetworkStaticSpec+loadBalancerSpec, + name, + engine, + user, + password, + ), ) } diff --git a/internal/namespaces/rdb/v1/rdb_cli.go b/internal/namespaces/rdb/v1/rdb_cli.go index 7c4b9f46b8..66b8ad5281 100644 --- a/internal/namespaces/rdb/v1/rdb_cli.go +++ b/internal/namespaces/rdb/v1/rdb_cli.go @@ -91,6 +91,7 @@ func GetGeneratedCommands() *core.Commands { rdbEndpointMigrate(), ) } + func rdbRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Managed Databases for PostgreSQL and MySQL`, @@ -276,7 +277,12 @@ func rdbEngineList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*rdb.ListDatabaseEnginesRequest) @@ -292,8 +298,8 @@ func rdbEngineList() *core.Command { if err != nil { return nil, err } - return resp.Engines, nil + return resp.Engines, nil }, } } @@ -315,7 +321,12 @@ func rdbNodeTypeList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*rdb.ListNodeTypesRequest) @@ -331,8 +342,8 @@ func rdbNodeTypeList() *core.Command { if err != nil { return nil, err } - return resp.NodeTypes, nil + return resp.NodeTypes, nil }, } } @@ -360,7 +371,14 @@ func rdbBackupList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "status_asc", "status_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + "status_asc", + "status_desc", + }, }, { Name: "instance-id", @@ -383,7 +401,12 @@ func rdbBackupList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*rdb.ListDatabaseBackupsRequest) @@ -399,8 +422,8 @@ func rdbBackupList() *core.Command { if err != nil { return nil, err } - return resp.DatabaseBackups, nil + return resp.DatabaseBackups, nil }, } } @@ -451,8 +474,8 @@ func rdbBackupCreate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.CreateDatabaseBackup(request) + return api.CreateDatabaseBackup(request) }, } } @@ -481,8 +504,8 @@ func rdbBackupGet() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.GetDatabaseBackup(request) + return api.GetDatabaseBackup(request) }, } } @@ -525,8 +548,8 @@ func rdbBackupUpdate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.UpdateDatabaseBackup(request) + return api.UpdateDatabaseBackup(request) }, } } @@ -555,8 +578,8 @@ func rdbBackupDelete() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.DeleteDatabaseBackup(request) + return api.DeleteDatabaseBackup(request) }, } } @@ -599,8 +622,8 @@ func rdbBackupRestore() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.RestoreDatabaseBackup(request) + return api.RestoreDatabaseBackup(request) }, } } @@ -629,8 +652,8 @@ func rdbBackupExport() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.ExportDatabaseBackup(request) + return api.ExportDatabaseBackup(request) }, } } @@ -716,8 +739,8 @@ func rdbInstanceUpgrade() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.UpgradeInstance(request) + return api.UpgradeInstance(request) }, } } @@ -752,7 +775,15 @@ func rdbInstanceList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "region", "status_asc", "status_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + "region", + "status_asc", + "status_desc", + }, }, { Name: "project-id", @@ -768,7 +799,12 @@ func rdbInstanceList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*rdb.ListInstancesRequest) @@ -784,8 +820,8 @@ func rdbInstanceList() *core.Command { if err != nil { return nil, err } - return resp.Instances, nil + return resp.Instances, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -846,8 +882,8 @@ func rdbInstanceGet() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.GetInstance(request) + return api.GetInstance(request) }, } } @@ -982,8 +1018,8 @@ func rdbInstanceCreate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.CreateInstance(request) + return api.CreateInstance(request) }, } } @@ -1075,8 +1111,8 @@ func rdbInstanceUpdate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.UpdateInstance(request) + return api.UpdateInstance(request) }, } } @@ -1105,8 +1141,8 @@ func rdbInstanceDelete() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.DeleteInstance(request) + return api.DeleteInstance(request) }, } } @@ -1149,8 +1185,8 @@ func rdbInstanceClone() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.CloneInstance(request) + return api.CloneInstance(request) }, } } @@ -1179,8 +1215,8 @@ func rdbInstanceRestart() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.RestartInstance(request) + return api.RestartInstance(request) }, } } @@ -1209,8 +1245,8 @@ func rdbInstanceGetCertificate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.GetInstanceCertificate(request) + return api.GetInstanceCertificate(request) }, } } @@ -1243,6 +1279,7 @@ func rdbInstanceRenewCertificate() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "instance", Verb: "renew-certificate", @@ -1296,8 +1333,8 @@ func rdbInstanceGetMetrics() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.GetInstanceMetrics(request) + return api.GetInstanceMetrics(request) }, } } @@ -1347,8 +1384,8 @@ func rdbReadReplicaCreate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.CreateReadReplica(request) + return api.CreateReadReplica(request) }, } } @@ -1377,8 +1414,8 @@ func rdbReadReplicaGet() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.GetReadReplica(request) + return api.GetReadReplica(request) }, } } @@ -1407,8 +1444,8 @@ func rdbReadReplicaDelete() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.DeleteReadReplica(request) + return api.DeleteReadReplica(request) }, } } @@ -1438,8 +1475,8 @@ The configured endpoints do not change.`, client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.ResetReadReplica(request) + return api.ResetReadReplica(request) }, } } @@ -1482,8 +1519,8 @@ func rdbReadReplicaCreateEndpoint() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.CreateReadReplicaEndpoint(request) + return api.CreateReadReplicaEndpoint(request) }, } } @@ -1526,8 +1563,8 @@ func rdbLogPrepare() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.PrepareInstanceLogs(request) + return api.PrepareInstanceLogs(request) }, } } @@ -1564,8 +1601,8 @@ func rdbLogList() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.ListInstanceLogs(request) + return api.ListInstanceLogs(request) }, } } @@ -1594,8 +1631,8 @@ func rdbLogGet() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.GetInstanceLog(request) + return api.GetInstanceLog(request) }, } } @@ -1635,6 +1672,7 @@ func rdbLogPurge() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "log", Verb: "purge", @@ -1667,8 +1705,8 @@ func rdbLogListDetails() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.ListInstanceLogsDetails(request) + return api.ListInstanceLogsDetails(request) }, } } @@ -1709,8 +1747,8 @@ func rdbSettingAdd() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.AddInstanceSettings(request) + return api.AddInstanceSettings(request) }, } } @@ -1746,8 +1784,8 @@ func rdbSettingDelete() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.DeleteInstanceSettings(request) + return api.DeleteInstanceSettings(request) }, } } @@ -1755,7 +1793,7 @@ func rdbSettingDelete() *core.Command { func rdbSettingSet() *core.Command { return &core.Command{ Short: `Set Database Instance advanced settings`, - Long: `Update an advanced setting for a Database Instance. Settings added upon database engine initalization can only be defined once, and cannot, therefore, be updated.`, + Long: `Update an advanced setting for a Database Instance. Settings added upon database engine initialization can only be defined once, and cannot, therefore, be updated.`, Namespace: "rdb", Resource: "setting", Verb: "set", @@ -1788,8 +1826,8 @@ func rdbSettingSet() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.SetInstanceSettings(request) + return api.SetInstanceSettings(request) }, } } @@ -1811,7 +1849,12 @@ func rdbACLList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*rdb.ListInstanceACLRulesRequest) @@ -1827,8 +1870,8 @@ func rdbACLList() *core.Command { if err != nil { return nil, err } - return resp.Rules, nil + return resp.Rules, nil }, } } @@ -1869,8 +1912,8 @@ func rdbACLAdd() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.AddInstanceACLRules(request) + return api.AddInstanceACLRules(request) }, } } @@ -1911,8 +1954,8 @@ func rdbACLSet() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.SetInstanceACLRules(request) + return api.SetInstanceACLRules(request) }, } } @@ -1948,8 +1991,8 @@ func rdbACLDelete() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.DeleteInstanceACLRules(request) + return api.DeleteInstanceACLRules(request) }, } } @@ -1986,7 +2029,12 @@ func rdbUserList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*rdb.ListUsersRequest) @@ -2002,8 +2050,8 @@ func rdbUserList() *core.Command { if err != nil { return nil, err } - return resp.Users, nil + return resp.Users, nil }, } } @@ -2053,8 +2101,8 @@ func rdbUserCreate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.CreateUser(request) + return api.CreateUser(request) }, } } @@ -2104,8 +2152,8 @@ func rdbUserUpdate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.UpdateUser(request) + return api.UpdateUser(request) }, } } @@ -2145,6 +2193,7 @@ func rdbUserDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "user", Verb: "delete", @@ -2199,7 +2248,12 @@ func rdbDatabaseList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*rdb.ListDatabasesRequest) @@ -2215,8 +2269,8 @@ func rdbDatabaseList() *core.Command { if err != nil { return nil, err } - return resp.Databases, nil + return resp.Databases, nil }, } } @@ -2252,8 +2306,8 @@ func rdbDatabaseCreate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.CreateDatabase(request) + return api.CreateDatabase(request) }, } } @@ -2293,6 +2347,7 @@ func rdbDatabaseDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "database", Verb: "delete", @@ -2317,7 +2372,12 @@ func rdbPrivilegeList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"user_name_asc", "user_name_desc", "database_name_asc", "database_name_desc"}, + EnumValues: []string{ + "user_name_asc", + "user_name_desc", + "database_name_asc", + "database_name_desc", + }, }, { Name: "database-name", @@ -2340,7 +2400,12 @@ func rdbPrivilegeList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*rdb.ListPrivilegesRequest) @@ -2356,8 +2421,8 @@ func rdbPrivilegeList() *core.Command { if err != nil { return nil, err } - return resp.Privileges, nil + return resp.Privileges, nil }, } } @@ -2408,8 +2473,8 @@ func rdbPrivilegeSet() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.SetPrivilege(request) + return api.SetPrivilege(request) }, } } @@ -2437,7 +2502,14 @@ func rdbSnapshotList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "expires_at_asc", "expires_at_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + "expires_at_asc", + "expires_at_desc", + }, }, { Name: "instance-id", @@ -2460,7 +2532,12 @@ func rdbSnapshotList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*rdb.ListSnapshotsRequest) @@ -2476,8 +2553,8 @@ func rdbSnapshotList() *core.Command { if err != nil { return nil, err } - return resp.Snapshots, nil + return resp.Snapshots, nil }, } } @@ -2506,8 +2583,8 @@ func rdbSnapshotGet() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.GetSnapshot(request) + return api.GetSnapshot(request) }, } } @@ -2551,8 +2628,8 @@ func rdbSnapshotCreate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.CreateSnapshot(request) + return api.CreateSnapshot(request) }, } } @@ -2595,8 +2672,8 @@ func rdbSnapshotUpdate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.UpdateSnapshot(request) + return api.UpdateSnapshot(request) }, } } @@ -2625,8 +2702,8 @@ func rdbSnapshotDelete() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.DeleteSnapshot(request) + return api.DeleteSnapshot(request) }, } } @@ -2676,8 +2753,8 @@ func rdbSnapshotRestore() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.CreateInstanceFromSnapshot(request) + return api.CreateInstanceFromSnapshot(request) }, } } @@ -2720,8 +2797,8 @@ func rdbEndpointCreate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.CreateEndpoint(request) + return api.CreateEndpoint(request) }, } } @@ -2754,6 +2831,7 @@ func rdbEndpointDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "endpoint", Verb: "delete", @@ -2786,8 +2864,8 @@ func rdbEndpointGet() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.GetEndpoint(request) + return api.GetEndpoint(request) }, } } @@ -2823,8 +2901,8 @@ func rdbEndpointMigrate() *core.Command { client := core.ExtractClient(ctx) api := rdb.NewAPI(client) - return api.MigrateEndpoint(request) + return api.MigrateEndpoint(request) }, } } diff --git a/internal/namespaces/redis/v1/custom_cluster.go b/internal/namespaces/redis/v1/custom_cluster.go index e0afbfafe5..ab39b57838 100644 --- a/internal/namespaces/redis/v1/custom_cluster.go +++ b/internal/namespaces/redis/v1/custom_cluster.go @@ -76,13 +76,16 @@ func clusterCreateBuilder(c *core.Command) *core.Command { if !customEndpoint.PrivateNetwork.EnableIpam { ipamConfig = nil } - createClusterRequest.Endpoints = append(createClusterRequest.Endpoints, &redis.EndpointSpec{ - PrivateNetwork: &redis.EndpointSpecPrivateNetworkSpec{ - ID: customEndpoint.PrivateNetwork.ID, - ServiceIPs: customEndpoint.PrivateNetwork.ServiceIPs, - IpamConfig: ipamConfig, + createClusterRequest.Endpoints = append( + createClusterRequest.Endpoints, + &redis.EndpointSpec{ + PrivateNetwork: &redis.EndpointSpecPrivateNetworkSpec{ + ID: customEndpoint.PrivateNetwork.ID, + ServiceIPs: customEndpoint.PrivateNetwork.ServiceIPs, + IpamConfig: ipamConfig, + }, }, - }) + ) } cluster, err := api.CreateCluster(createClusterRequest) @@ -109,7 +112,8 @@ func clusterDeleteBuilder(c *core.Command) *core.Command { // if we get a 404 here, it means the resource was successfully deleted notFoundError := &scw.ResourceNotFoundError{} responseError := &scw.ResponseError{} - if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) { + if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || + errors.As(err, ¬FoundError) { return cluster, nil } @@ -147,7 +151,14 @@ func clusterWaitCommand() *core.Command { Required: true, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), core.WaitTimeoutArgSpec(redisActionTimeout), }, Examples: []*core.Example{ @@ -160,15 +171,17 @@ func clusterWaitCommand() *core.Command { } func ACLAddListBuilder(c *core.Command) *core.Command { - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { - originalResp, err := runner(ctx, argsI) - if err != nil { - return nil, err - } - ACLAddResponse := originalResp.(*redis.AddACLRulesResponse) + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + originalResp, err := runner(ctx, argsI) + if err != nil { + return nil, err + } + ACLAddResponse := originalResp.(*redis.AddACLRulesResponse) - return ACLAddResponse.ACLRules, nil - }) + return ACLAddResponse.ACLRules, nil + }, + ) return c } @@ -222,7 +235,11 @@ var completeClusterCache *redis.Cluster var completeClusterVersionCache *redis.ListClusterVersionsResponse -func autoCompleteSettingsName(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autoCompleteSettingsName( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { suggestions := core.AutocompleteSuggestions(nil) req := request.(*redis.AddClusterSettingsRequest) client := core.ExtractClient(ctx) @@ -262,7 +279,11 @@ func autoCompleteSettingsName(ctx context.Context, prefix string, request any) c var completeRedisNoteTypeCache *redis.ListNodeTypesResponse -func autoCompleteNodeType(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions { +func autoCompleteNodeType( + ctx context.Context, + prefix string, + request any, +) core.AutocompleteSuggestions { suggestions := core.AutocompleteSuggestions(nil) req := request.(*redis.MigrateClusterRequest) client := core.ExtractClient(ctx) diff --git a/internal/namespaces/redis/v1/custom_cluster_test.go b/internal/namespaces/redis/v1/custom_cluster_test.go index 69448746ba..6df4558148 100644 --- a/internal/namespaces/redis/v1/custom_cluster_test.go +++ b/internal/namespaces/redis/v1/custom_cluster_test.go @@ -87,10 +87,16 @@ func Test_Endpoints(t *testing.T) { }, ), ), - Cmd: fmt.Sprintf("scw redis cluster create --wait name=%s version=7.0.5 node-type=RED1-micro user-name=admin password=P@sSw0Rd --wait "+ - "endpoints.0.private-network.id={{ .%s.ID }} endpoints.0.private-network.service-ips.0=%s "+ - "endpoints.1.private-network.id={{ .%s.ID }} endpoints.1.private-network.service-ips.0=%s", - "2-static-priv-endpoints", metaNamePNA, serviceIPsA, metaNamePNB, serviceIPsB), + Cmd: fmt.Sprintf( + "scw redis cluster create --wait name=%s version=7.0.5 node-type=RED1-micro user-name=admin password=P@sSw0Rd --wait "+ + "endpoints.0.private-network.id={{ .%s.ID }} endpoints.0.private-network.service-ips.0=%s "+ + "endpoints.1.private-network.id={{ .%s.ID }} endpoints.1.private-network.service-ips.0=%s", + "2-static-priv-endpoints", + metaNamePNA, + serviceIPsA, + metaNamePNB, + serviceIPsB, + ), Check: core.TestCheckCombine( core.TestCheckGolden(), func(t *testing.T, ctx *core.CheckFuncCtx) { @@ -275,7 +281,11 @@ func deletePrivateNetwork(metaName string) core.AfterFunc { return core.ExecAfterCmd(fmt.Sprintf("scw vpc private-network delete {{ .%s.ID }}", metaName)) } -func checkEndpoints(t *testing.T, endpoints []*redisSDK.Endpoint, nbExpectedPub, nbExpectedPrivStatic, nbExpectedPrivIpam int) { +func checkEndpoints( + t *testing.T, + endpoints []*redisSDK.Endpoint, + nbExpectedPub, nbExpectedPrivStatic, nbExpectedPrivIpam int, +) { t.Helper() expectedEndpoints := map[string]int{ "public": nbExpectedPub, @@ -304,7 +314,15 @@ func checkEndpoints(t *testing.T, endpoints []*redisSDK.Endpoint, nbExpectedPub, nbActualPub := nbExpectedPub - expectedEndpoints["public"] nbActualPrivStatic := nbExpectedPrivStatic - expectedEndpoints["private-static"] nbActualPrivIpam := nbExpectedPrivIpam - expectedEndpoints["private-ipam"] - t.Errorf("expected %d public endpoint(s), %d static private endpoint(s) and %d IPAM private endpoint(s), "+ - "got respectively %d, %d and %d", nbExpectedPub, nbExpectedPrivStatic, nbExpectedPrivIpam, nbActualPub, nbActualPrivStatic, nbActualPrivIpam) + t.Errorf( + "expected %d public endpoint(s), %d static private endpoint(s) and %d IPAM private endpoint(s), "+ + "got respectively %d, %d and %d", + nbExpectedPub, + nbExpectedPrivStatic, + nbExpectedPrivIpam, + nbActualPub, + nbActualPrivStatic, + nbActualPrivIpam, + ) } } diff --git a/internal/namespaces/redis/v1/redis_cli.go b/internal/namespaces/redis/v1/redis_cli.go index 879856deea..433d7479cf 100644 --- a/internal/namespaces/redis/v1/redis_cli.go +++ b/internal/namespaces/redis/v1/redis_cli.go @@ -51,6 +51,7 @@ func GetGeneratedCommands() *core.Commands { redisEndpointUpdate(), ) } + func redisRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Managed Databases for Redis™`, @@ -225,15 +226,22 @@ func redisClusterCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.CreateClusterRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.CreateCluster(request) + return api.CreateCluster(request) }, } } @@ -283,15 +291,22 @@ func redisClusterUpdate() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.UpdateClusterRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.UpdateCluster(request) + return api.UpdateCluster(request) }, } } @@ -313,15 +328,22 @@ func redisClusterGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.GetClusterRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.GetCluster(request) + return api.GetCluster(request) }, } } @@ -379,7 +401,15 @@ func redisClusterList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.ListClustersRequest) @@ -395,8 +425,8 @@ func redisClusterList() *core.Command { if err != nil { return nil, err } - return resp.Clusters, nil + return resp.Clusters, nil }, } } @@ -439,15 +469,22 @@ func redisClusterMigrate() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.MigrateClusterRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.MigrateCluster(request) + return api.MigrateCluster(request) }, } } @@ -469,15 +506,22 @@ func redisClusterDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.DeleteClusterRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.DeleteCluster(request) + return api.DeleteCluster(request) }, } } @@ -520,15 +564,22 @@ func redisClusterMetrics() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.GetClusterMetricsRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.GetClusterMetrics(request) + return api.GetClusterMetrics(request) }, } } @@ -550,7 +601,15 @@ func redisNodeTypeList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.ListNodeTypesRequest) @@ -566,8 +625,8 @@ func redisNodeTypeList() *core.Command { if err != nil { return nil, err } - return resp.NodeTypes, nil + return resp.NodeTypes, nil }, } } @@ -610,7 +669,15 @@ func redisVersionList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.ListClusterVersionsRequest) @@ -626,8 +693,8 @@ func redisVersionList() *core.Command { if err != nil { return nil, err } - return resp.Versions, nil + return resp.Versions, nil }, } } @@ -649,15 +716,22 @@ func redisClusterGetCertificate() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.GetClusterCertificateRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.GetClusterCertificate(request) + return api.GetClusterCertificate(request) }, } } @@ -679,15 +753,22 @@ func redisClusterRenewCertificate() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.RenewClusterCertificateRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.RenewClusterCertificate(request) + return api.RenewClusterCertificate(request) }, } } @@ -723,15 +804,22 @@ func redisSettingAdd() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.AddClusterSettingsRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.AddClusterSettings(request) + return api.AddClusterSettings(request) }, } } @@ -760,15 +848,22 @@ func redisSettingDelete() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.DeleteClusterSettingRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.DeleteClusterSetting(request) + return api.DeleteClusterSetting(request) }, } } @@ -776,7 +871,7 @@ func redisSettingDelete() *core.Command { func redisSettingSet() *core.Command { return &core.Command{ Short: `Set advanced settings`, - Long: `Update an advanced setting for a Redis™ Database Instance (Redis™ cluster). Settings added upon database engine initalization can only be defined once, and cannot, therefore, be updated.`, + Long: `Update an advanced setting for a Redis™ Database Instance (Redis™ cluster). Settings added upon database engine initialization can only be defined once, and cannot, therefore, be updated.`, Namespace: "redis", Resource: "setting", Verb: "set", @@ -804,15 +899,22 @@ func redisSettingSet() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.SetClusterSettingsRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.SetClusterSettings(request) + return api.SetClusterSettings(request) }, } } @@ -848,15 +950,22 @@ func redisACLSet() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.SetACLRulesRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.SetACLRules(request) + return api.SetACLRules(request) }, } } @@ -892,15 +1001,22 @@ func redisACLAdd() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.AddACLRulesRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.AddACLRules(request) + return api.AddACLRules(request) }, } } @@ -922,15 +1038,22 @@ func redisACLDelete() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.DeleteACLRuleRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.DeleteACLRule(request) + return api.DeleteACLRule(request) }, } } @@ -952,15 +1075,22 @@ func redisACLGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.GetACLRuleRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.GetACLRule(request) + return api.GetACLRule(request) }, } } @@ -996,15 +1126,22 @@ func redisEndpointSet() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.SetEndpointsRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.SetEndpoints(request) + return api.SetEndpoints(request) }, } } @@ -1040,15 +1177,22 @@ func redisEndpointAdd() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.AddEndpointsRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.AddEndpoints(request) + return api.AddEndpoints(request) }, } } @@ -1070,15 +1214,22 @@ func redisEndpointDelete() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.DeleteEndpointRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.DeleteEndpoint(request) + return api.DeleteEndpoint(request) }, } } @@ -1100,15 +1251,22 @@ func redisEndpointGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.GetEndpointRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.GetEndpoint(request) + return api.GetEndpoint(request) }, } } @@ -1144,15 +1302,22 @@ func redisEndpointUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZonePlWaw1, scw.ZonePlWaw2), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*redis.UpdateEndpointRequest) client := core.ExtractClient(ctx) api := redis.NewAPI(client) - return api.UpdateEndpoint(request) + return api.UpdateEndpoint(request) }, } } diff --git a/internal/namespaces/registry/v1/custom.go b/internal/namespaces/registry/v1/custom.go index adbf9bca44..3947064eec 100644 --- a/internal/namespaces/registry/v1/custom.go +++ b/internal/namespaces/registry/v1/custom.go @@ -30,9 +30,18 @@ func GetCommands() *core.Commands { cmds.MustFind("registry", "image", "get").Override(imageGetBuilder) cmds.MustFind("registry", "image", "list").Override(imageListBuilder) - human.RegisterMarshalerFunc(registry.NamespaceStatus(""), human.EnumMarshalFunc(namespaceStatusMarshalSpecs)) - human.RegisterMarshalerFunc(registry.ImageStatus(""), human.EnumMarshalFunc(imageStatusMarshalSpecs)) - human.RegisterMarshalerFunc(registry.TagStatus(""), human.EnumMarshalFunc(tagStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + registry.NamespaceStatus(""), + human.EnumMarshalFunc(namespaceStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + registry.ImageStatus(""), + human.EnumMarshalFunc(imageStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + registry.TagStatus(""), + human.EnumMarshalFunc(tagStatusMarshalSpecs), + ) return cmds } diff --git a/internal/namespaces/registry/v1/custom_docker_helper.go b/internal/namespaces/registry/v1/custom_docker_helper.go index 699345d449..1f5af34fc5 100644 --- a/internal/namespaces/registry/v1/custom_docker_helper.go +++ b/internal/namespaces/registry/v1/custom_docker_helper.go @@ -88,7 +88,9 @@ func registrySetupDockerHelperRun(ctx context.Context, argsI interface{}) (i int helperScriptContent := buf.String() // Warning - _, _ = interactive.Println("To enable the Docker credential helper we need to create the file " + helperScriptPath + " with the following lines:\n") + _, _ = interactive.Println( + "To enable the Docker credential helper we need to create the file " + helperScriptPath + " with the following lines:\n", + ) _, _ = interactive.Println(helperScriptContent) // Early exit if user disagrees @@ -123,8 +125,19 @@ func registrySetupDockerHelperRun(ctx context.Context, argsI interface{}) (i int _, _ = interactive.Println() _, err = exec.LookPath("docker-credential-" + binaryName) if err != nil { - _, _ = interactive.Println(fmt.Sprintf("docker-credential-%s is not present in your $PATH, you should add %s to your $PATH to make it work.", binaryName, path.Dir(helperScriptPath))) - _, _ = interactive.Println(fmt.Sprintf("You can add it by adding `export PATH=$PATH:%s` to your `.bashrc`, `.fishrc` or `.zshrc`", path.Dir(helperScriptPath))) + _, _ = interactive.Println( + fmt.Sprintf( + "docker-credential-%s is not present in your $PATH, you should add %s to your $PATH to make it work.", + binaryName, + path.Dir(helperScriptPath), + ), + ) + _, _ = interactive.Println( + fmt.Sprintf( + "You can add it by adding `export PATH=$PATH:%s` to your `.bashrc`, `.fishrc` or `.zshrc`", + path.Dir(helperScriptPath), + ), + ) } else { _, _ = interactive.PrintlnWithoutIndent("Docker credential helper successfully installed.") _, _ = interactive.PrintlnWithoutIndent("The Docker credential helper will now take care of the authentication for you.") diff --git a/internal/namespaces/registry/v1/custom_docker_helper_test.go b/internal/namespaces/registry/v1/custom_docker_helper_test.go index c19af381cd..f03a36becb 100644 --- a/internal/namespaces/registry/v1/custom_docker_helper_test.go +++ b/internal/namespaces/registry/v1/custom_docker_helper_test.go @@ -35,7 +35,11 @@ func TestRegistryInstallDockerHelperCommand(t *testing.T) { dockerConfigPath := path.Join(ctx.Meta["HOME"].(string), ".docker", "config.json") dockerConfigContent, err := os.ReadFile(dockerConfigPath) require.NoError(t, err) - assert.JSONEq(t, "{\n \"credHelpers\": {\n \"rg.fr-par.scw.cloud\": \"scw\",\n \"rg.nl-ams.scw.cloud\": \"scw\",\n \"rg.pl-waw.scw.cloud\": \"scw\"\n }\n}\n", string(dockerConfigContent)) + assert.JSONEq( + t, + "{\n \"credHelpers\": {\n \"rg.fr-par.scw.cloud\": \"scw\",\n \"rg.nl-ams.scw.cloud\": \"scw\",\n \"rg.pl-waw.scw.cloud\": \"scw\"\n }\n}\n", + string(dockerConfigContent), + ) }, AfterFunc: nil, TmpHomeDir: true, @@ -54,7 +58,11 @@ func TestRegistryInstallDockerHelperCommand(t *testing.T) { scriptPath := path.Join(ctx.Meta["HOME"].(string), "docker-credential-scw") scriptContent, err := os.ReadFile(scriptPath) require.NoError(t, err) - assert.Equal(t, "#!/bin/sh\nPROFILE_NAME=\"profile01\"\nif [[ ! -z \"$SCW_PROFILE\" ]]\nthen \n\tPROFILE_NAME=\"$SCW_PROFILE\"\nfi\nscw --profile $PROFILE_NAME registry docker-helper \"$@\"\n", string(scriptContent)) + assert.Equal( + t, + "#!/bin/sh\nPROFILE_NAME=\"profile01\"\nif [[ ! -z \"$SCW_PROFILE\" ]]\nthen \n\tPROFILE_NAME=\"$SCW_PROFILE\"\nfi\nscw --profile $PROFILE_NAME registry docker-helper \"$@\"\n", + string(scriptContent), + ) }, AfterFunc: nil, TmpHomeDir: true, diff --git a/internal/namespaces/registry/v1/custom_image.go b/internal/namespaces/registry/v1/custom_image.go index 4f23ab7eaf..40d5a8ef31 100644 --- a/internal/namespaces/registry/v1/custom_image.go +++ b/internal/namespaces/registry/v1/custom_image.go @@ -123,12 +123,19 @@ func imageListBuilder(c *core.Command) *core.Command { var customRes []customImage for _, image := range listImage { img := customImage{ - Image: *image, - FullName: fmt.Sprintf("%s/%s", namespaceEndpointByID[image.NamespaceID], image.Name), + Image: *image, + FullName: fmt.Sprintf( + "%s/%s", + namespaceEndpointByID[image.NamespaceID], + image.Name, + ), } if image.Visibility == registry.ImageVisibilityInherit { - img.ExplicitVisibility = fmt.Sprintf("%s (inherit)", namespaceVisibilityByID[image.NamespaceID]) + img.ExplicitVisibility = fmt.Sprintf( + "%s (inherit)", + namespaceVisibilityByID[image.NamespaceID], + ) } else { img.ExplicitVisibility = image.Visibility.String() } diff --git a/internal/namespaces/registry/v1/custom_image_test.go b/internal/namespaces/registry/v1/custom_image_test.go index cc84b1c94f..ef1ad37b62 100644 --- a/internal/namespaces/registry/v1/custom_image_test.go +++ b/internal/namespaces/registry/v1/custom_image_test.go @@ -13,8 +13,14 @@ func Test_ImageList(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ Commands: registry.GetCommands(), BeforeFunc: core.BeforeFuncCombine( - core.ExecStoreBeforeCmd("PublicNamespace", "scw registry namespace create name=cli-public-namespace-{{randint}} is-public=true"), - core.ExecStoreBeforeCmd("PrivateNamespace", "scw registry namespace create name=cli-private-namespace-{{randint}} is-public=false"), + core.ExecStoreBeforeCmd( + "PublicNamespace", + "scw registry namespace create name=cli-public-namespace-{{randint}} is-public=true", + ), + core.ExecStoreBeforeCmd( + "PrivateNamespace", + "scw registry namespace create name=cli-private-namespace-{{randint}} is-public=false", + ), core.BeforeFuncWhenUpdatingCassette( core.ExecBeforeCmd("scw registry login"), ), @@ -78,7 +84,12 @@ func Test_ImageList(t *testing.T) { })) } -func setupImage(dockerImage string, namespaceEndpoint string, imageName string, visibility registrySDK.ImageVisibility) core.BeforeFunc { +func setupImage( + dockerImage string, + namespaceEndpoint string, + imageName string, + visibility registrySDK.ImageVisibility, +) core.BeforeFunc { return func(ctx *core.BeforeFuncCtx) error { namespaceEndpoint := ctx.Meta.Render(namespaceEndpoint) remote := fmt.Sprintf("%s/%s:latest", namespaceEndpoint, imageName) @@ -88,7 +99,11 @@ func setupImage(dockerImage string, namespaceEndpoint string, imageName string, core.BeforeFuncOsExec("docker", "tag", dockerImage, remote), core.BeforeFuncOsExec("docker", "push", remote), core.ExecStoreBeforeCmd("ImageListResult", "scw registry image list name="+imageName), - core.ExecBeforeCmd("scw registry image update {{ (index .ImageListResult 0).ID }} visibility="+visibility.String()), - )(ctx) + core.ExecBeforeCmd( + "scw registry image update {{ (index .ImageListResult 0).ID }} visibility="+visibility.String(), + ), + )( + ctx, + ) } } diff --git a/internal/namespaces/registry/v1/custom_login_test.go b/internal/namespaces/registry/v1/custom_login_test.go index 63530299f9..1dd242b1c8 100644 --- a/internal/namespaces/registry/v1/custom_login_test.go +++ b/internal/namespaces/registry/v1/custom_login_test.go @@ -21,7 +21,11 @@ func Test_Login(t *testing.T) { core.TestCheckExitCode(0), ), OverrideExec: func(ctx *core.ExecFuncCtx, cmd *exec.Cmd) (exitCode int, err error) { - assert.Equal(t, "docker login -u scaleway --password-stdin rg.fr-par.scw.cloud", strings.Join(cmd.Args, " ")) + assert.Equal( + t, + "docker login -u scaleway --password-stdin rg.fr-par.scw.cloud", + strings.Join(cmd.Args, " "), + ) stdin, err := io.ReadAll(cmd.Stdin) secret, _ := ctx.Client.GetSecretKey() require.NoError(t, err) @@ -38,7 +42,11 @@ func Test_Login(t *testing.T) { core.TestCheckExitCode(0), ), OverrideExec: func(ctx *core.ExecFuncCtx, cmd *exec.Cmd) (exitCode int, err error) { - assert.Equal(t, "podman login -u scaleway --password-stdin rg.fr-par.scw.cloud", strings.Join(cmd.Args, " ")) + assert.Equal( + t, + "podman login -u scaleway --password-stdin rg.fr-par.scw.cloud", + strings.Join(cmd.Args, " "), + ) stdin, err := io.ReadAll(cmd.Stdin) secret, _ := ctx.Client.GetSecretKey() require.NoError(t, err) diff --git a/internal/namespaces/registry/v1/registry_cli.go b/internal/namespaces/registry/v1/registry_cli.go index 1646440388..1dd47f7321 100644 --- a/internal/namespaces/registry/v1/registry_cli.go +++ b/internal/namespaces/registry/v1/registry_cli.go @@ -37,6 +37,7 @@ func GetGeneratedCommands() *core.Commands { registryTagDelete(), ) } + func registryRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Container Registry resources`, @@ -94,7 +95,14 @@ func registryNamespaceList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "description_asc", "description_desc", "name_asc", "name_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "description_asc", + "description_desc", + "name_asc", + "name_desc", + }, }, { Name: "project-id", @@ -117,7 +125,12 @@ func registryNamespaceList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*registry.ListNamespacesRequest) @@ -133,8 +146,8 @@ func registryNamespaceList() *core.Command { if err != nil { return nil, err } - return resp.Namespaces, nil + return resp.Namespaces, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -207,8 +220,8 @@ func registryNamespaceGet() *core.Command { client := core.ExtractClient(ctx) api := registry.NewAPI(client) - return api.GetNamespace(request) + return api.GetNamespace(request) }, } } @@ -254,8 +267,8 @@ func registryNamespaceCreate() *core.Command { client := core.ExtractClient(ctx) api := registry.NewAPI(client) - return api.CreateNamespace(request) + return api.CreateNamespace(request) }, } } @@ -298,8 +311,8 @@ func registryNamespaceUpdate() *core.Command { client := core.ExtractClient(ctx) api := registry.NewAPI(client) - return api.UpdateNamespace(request) + return api.UpdateNamespace(request) }, } } @@ -328,8 +341,8 @@ func registryNamespaceDelete() *core.Command { client := core.ExtractClient(ctx) api := registry.NewAPI(client) - return api.DeleteNamespace(request) + return api.DeleteNamespace(request) }, } } @@ -380,7 +393,12 @@ func registryImageList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*registry.ListImagesRequest) @@ -396,8 +414,8 @@ func registryImageList() *core.Command { if err != nil { return nil, err } - return resp.Images, nil + return resp.Images, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -458,8 +476,8 @@ func registryImageGet() *core.Command { client := core.ExtractClient(ctx) api := registry.NewAPI(client) - return api.GetImage(request) + return api.GetImage(request) }, } } @@ -496,8 +514,8 @@ func registryImageUpdate() *core.Command { client := core.ExtractClient(ctx) api := registry.NewAPI(client) - return api.UpdateImage(request) + return api.UpdateImage(request) }, } } @@ -526,8 +544,8 @@ func registryImageDelete() *core.Command { client := core.ExtractClient(ctx) api := registry.NewAPI(client) - return api.DeleteImage(request) + return api.DeleteImage(request) }, } } @@ -564,7 +582,12 @@ func registryTagList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*registry.ListTagsRequest) @@ -580,8 +603,8 @@ func registryTagList() *core.Command { if err != nil { return nil, err } - return resp.Tags, nil + return resp.Tags, nil }, } } @@ -610,8 +633,8 @@ func registryTagGet() *core.Command { client := core.ExtractClient(ctx) api := registry.NewAPI(client) - return api.GetTag(request) + return api.GetTag(request) }, } } @@ -647,8 +670,8 @@ func registryTagDelete() *core.Command { client := core.ExtractClient(ctx) api := registry.NewAPI(client) - return api.DeleteTag(request) + return api.DeleteTag(request) }, } } diff --git a/internal/namespaces/secret/v1beta1/secret_cli.go b/internal/namespaces/secret/v1beta1/secret_cli.go index 65f08b2997..8446f1f5ba 100644 --- a/internal/namespaces/secret/v1beta1/secret_cli.go +++ b/internal/namespaces/secret/v1beta1/secret_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/secret/v1beta1" + secret "github.com/scaleway/scaleway-sdk-go/api/secret/v1beta1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -41,6 +41,7 @@ func GetGeneratedCommands() *core.Commands { secretVersionDisable(), ) } + func secretRoot() *core.Command { return &core.Command{ Short: `Secret Manager API`, @@ -105,7 +106,15 @@ func secretSecretCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_type", "opaque", "certificate", "key_value", "basic_credentials", "database_credentials", "ssh_key"}, + EnumValues: []string{ + "unknown_type", + "opaque", + "certificate", + "key_value", + "basic_credentials", + "database_credentials", + "ssh_key", + }, }, { Name: "path", @@ -150,8 +159,8 @@ func secretSecretCreate() *core.Command { client := core.ExtractClient(ctx) api := secret.NewAPI(client) - return api.CreateSecret(request) + return api.CreateSecret(request) }, Examples: []*core.Example{ { @@ -186,8 +195,8 @@ func secretSecretGet() *core.Command { client := core.ExtractClient(ctx) api := secret.NewAPI(client) - return api.GetSecret(request) + return api.GetSecret(request) }, } } @@ -266,8 +275,8 @@ func secretSecretUpdate() *core.Command { client := core.ExtractClient(ctx) api := secret.NewAPI(client) - return api.UpdateSecret(request) + return api.UpdateSecret(request) }, } } @@ -300,6 +309,7 @@ func secretSecretDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "secret", Verb: "delete", @@ -336,7 +346,14 @@ func secretSecretList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"name_asc", "name_desc", "created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc"}, + EnumValues: []string{ + "name_asc", + "name_desc", + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + }, }, { Name: "tags.{index}", @@ -372,7 +389,15 @@ func secretSecretList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_type", "opaque", "certificate", "key_value", "basic_credentials", "database_credentials", "ssh_key"}, + EnumValues: []string{ + "unknown_type", + "opaque", + "certificate", + "key_value", + "basic_credentials", + "database_credentials", + "ssh_key", + }, }, { Name: "scheduled-for-deletion", @@ -388,7 +413,12 @@ func secretSecretList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*secret.ListSecretsRequest) @@ -404,8 +434,8 @@ func secretSecretList() *core.Command { if err != nil { return nil, err } - return resp.Secrets, nil + return resp.Secrets, nil }, } } @@ -434,8 +464,8 @@ func secretSecretProtect() *core.Command { client := core.ExtractClient(ctx) api := secret.NewAPI(client) - return api.ProtectSecret(request) + return api.ProtectSecret(request) }, Examples: []*core.Example{ { @@ -470,8 +500,8 @@ func secretSecretUnprotect() *core.Command { client := core.ExtractClient(ctx) api := secret.NewAPI(client) - return api.UnprotectSecret(request) + return api.UnprotectSecret(request) }, Examples: []*core.Example{ { @@ -518,6 +548,7 @@ func secretSecretAddOwner() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "secret", Verb: "add-owner", @@ -578,8 +609,8 @@ func secretVersionCreate() *core.Command { client := core.ExtractClient(ctx) api := secret.NewAPI(client) - return api.CreateSecretVersion(request) + return api.CreateSecretVersion(request) }, } } @@ -615,8 +646,8 @@ func secretVersionGet() *core.Command { client := core.ExtractClient(ctx) api := secret.NewAPI(client) - return api.GetSecretVersion(request) + return api.GetSecretVersion(request) }, } } @@ -681,8 +712,8 @@ func secretVersionUpdate() *core.Command { client := core.ExtractClient(ctx) api := secret.NewAPI(client) - return api.UpdateSecretVersion(request) + return api.UpdateSecretVersion(request) }, } } @@ -722,6 +753,7 @@ func secretVersionDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "version", Verb: "delete", @@ -759,9 +791,20 @@ func secretVersionList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_status", "enabled", "disabled", "deleted", "scheduled_for_deletion"}, + EnumValues: []string{ + "unknown_status", + "enabled", + "disabled", + "deleted", + "scheduled_for_deletion", + }, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*secret.ListSecretVersionsRequest) @@ -777,8 +820,8 @@ func secretVersionList() *core.Command { if err != nil { return nil, err } - return resp.Versions, nil + return resp.Versions, nil }, } } @@ -814,8 +857,8 @@ func secretVersionAccess() *core.Command { client := core.ExtractClient(ctx) api := secret.NewAPI(client) - return api.AccessSecretVersion(request) + return api.AccessSecretVersion(request) }, } } @@ -859,8 +902,8 @@ func secretVersionAccessByPath() *core.Command { client := core.ExtractClient(ctx) api := secret.NewAPI(client) - return api.AccessSecretVersionByPath(request) + return api.AccessSecretVersionByPath(request) }, } } @@ -896,8 +939,8 @@ func secretVersionEnable() *core.Command { client := core.ExtractClient(ctx) api := secret.NewAPI(client) - return api.EnableSecretVersion(request) + return api.EnableSecretVersion(request) }, } } @@ -933,8 +976,8 @@ func secretVersionDisable() *core.Command { client := core.ExtractClient(ctx) api := secret.NewAPI(client) - return api.DisableSecretVersion(request) + return api.DisableSecretVersion(request) }, } } diff --git a/internal/namespaces/serverless_sqldb/v1alpha1/custom.go b/internal/namespaces/serverless_sqldb/v1alpha1/custom.go index 59574c804e..fa9c807c3f 100644 --- a/internal/namespaces/serverless_sqldb/v1alpha1/custom.go +++ b/internal/namespaces/serverless_sqldb/v1alpha1/custom.go @@ -9,28 +9,56 @@ import ( var ( sdbSQLDatabaseStatusMarshalSpecs = human.EnumMarshalSpecs{ - serverless_sqldb.DatabaseStatusUnknownStatus: &human.EnumMarshalSpec{Attribute: color.Faint}, - serverless_sqldb.DatabaseStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed}, - serverless_sqldb.DatabaseStatusCreating: &human.EnumMarshalSpec{Attribute: color.FgBlue}, - serverless_sqldb.DatabaseStatusReady: &human.EnumMarshalSpec{Attribute: color.FgGreen}, - serverless_sqldb.DatabaseStatusDeleting: &human.EnumMarshalSpec{Attribute: color.FgBlue}, - serverless_sqldb.DatabaseStatusRestoring: &human.EnumMarshalSpec{Attribute: color.FgBlue}, - serverless_sqldb.DatabaseStatusLocked: &human.EnumMarshalSpec{Attribute: color.FgRed}, + serverless_sqldb.DatabaseStatusUnknownStatus: &human.EnumMarshalSpec{ + Attribute: color.Faint, + }, + serverless_sqldb.DatabaseStatusError: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + }, + serverless_sqldb.DatabaseStatusCreating: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + }, + serverless_sqldb.DatabaseStatusReady: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + }, + serverless_sqldb.DatabaseStatusDeleting: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + }, + serverless_sqldb.DatabaseStatusRestoring: &human.EnumMarshalSpec{ + Attribute: color.FgBlue, + }, + serverless_sqldb.DatabaseStatusLocked: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + }, } sdbSQLDatabaseBackupStatusMarshalSpecs = human.EnumMarshalSpecs{ - serverless_sqldb.DatabaseBackupStatusUnknownStatus: &human.EnumMarshalSpec{Attribute: color.Faint}, - serverless_sqldb.DatabaseBackupStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed}, - serverless_sqldb.DatabaseBackupStatusReady: &human.EnumMarshalSpec{Attribute: color.FgGreen}, - serverless_sqldb.DatabaseBackupStatusLocked: &human.EnumMarshalSpec{Attribute: color.FgRed}, + serverless_sqldb.DatabaseBackupStatusUnknownStatus: &human.EnumMarshalSpec{ + Attribute: color.Faint, + }, + serverless_sqldb.DatabaseBackupStatusError: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + }, + serverless_sqldb.DatabaseBackupStatusReady: &human.EnumMarshalSpec{ + Attribute: color.FgGreen, + }, + serverless_sqldb.DatabaseBackupStatusLocked: &human.EnumMarshalSpec{ + Attribute: color.FgRed, + }, } ) func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(serverless_sqldb.DatabaseStatus(""), human.EnumMarshalFunc(sdbSQLDatabaseStatusMarshalSpecs)) - human.RegisterMarshalerFunc(serverless_sqldb.DatabaseBackupStatus(""), human.EnumMarshalFunc(sdbSQLDatabaseBackupStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + serverless_sqldb.DatabaseStatus(""), + human.EnumMarshalFunc(sdbSQLDatabaseStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + serverless_sqldb.DatabaseBackupStatus(""), + human.EnumMarshalFunc(sdbSQLDatabaseBackupStatusMarshalSpecs), + ) return cmds } diff --git a/internal/namespaces/serverless_sqldb/v1alpha1/serverless_sqldb_cli.go b/internal/namespaces/serverless_sqldb/v1alpha1/serverless_sqldb_cli.go index e7a84d07cc..c7b6844d5c 100644 --- a/internal/namespaces/serverless_sqldb/v1alpha1/serverless_sqldb_cli.go +++ b/internal/namespaces/serverless_sqldb/v1alpha1/serverless_sqldb_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/serverless_sqldb/v1alpha1" + serverless_sqldb "github.com/scaleway/scaleway-sdk-go/api/serverless_sqldb/v1alpha1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -33,6 +33,7 @@ func GetGeneratedCommands() *core.Commands { sdbSQLBackupExport(), ) } + func sdbSQLRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Serverless SQL Databases`, @@ -105,8 +106,8 @@ func sdbSQLDatabaseCreate() *core.Command { client := core.ExtractClient(ctx) api := serverless_sqldb.NewAPI(client) - return api.CreateDatabase(request) + return api.CreateDatabase(request) }, } } @@ -135,8 +136,8 @@ func sdbSQLDatabaseGet() *core.Command { client := core.ExtractClient(ctx) api := serverless_sqldb.NewAPI(client) - return api.GetDatabase(request) + return api.GetDatabase(request) }, } } @@ -165,8 +166,8 @@ func sdbSQLDatabaseDelete() *core.Command { client := core.ExtractClient(ctx) api := serverless_sqldb.NewAPI(client) - return api.DeleteDatabase(request) + return api.DeleteDatabase(request) }, } } @@ -220,8 +221,8 @@ func sdbSQLDatabaseList() *core.Command { if err != nil { return nil, err } - return resp.Databases, nil + return resp.Databases, nil }, } } @@ -264,8 +265,8 @@ func sdbSQLDatabaseUpdate() *core.Command { client := core.ExtractClient(ctx) api := serverless_sqldb.NewAPI(client) - return api.UpdateDatabase(request) + return api.UpdateDatabase(request) }, } } @@ -301,8 +302,8 @@ func sdbSQLDatabaseRestore() *core.Command { client := core.ExtractClient(ctx) api := serverless_sqldb.NewAPI(client) - return api.RestoreDatabaseFromBackup(request) + return api.RestoreDatabaseFromBackup(request) }, } } @@ -331,8 +332,8 @@ func sdbSQLBackupGet() *core.Command { client := core.ExtractClient(ctx) api := serverless_sqldb.NewAPI(client) - return api.GetDatabaseBackup(request) + return api.GetDatabaseBackup(request) }, } } @@ -392,8 +393,8 @@ func sdbSQLBackupList() *core.Command { if err != nil { return nil, err } - return resp.Backups, nil + return resp.Backups, nil }, } } @@ -422,8 +423,8 @@ func sdbSQLBackupExport() *core.Command { client := core.ExtractClient(ctx) api := serverless_sqldb.NewAPI(client) - return api.ExportDatabaseBackup(request) + return api.ExportDatabaseBackup(request) }, } } diff --git a/internal/namespaces/tem/v1alpha1/custom.go b/internal/namespaces/tem/v1alpha1/custom.go index 4d8be4321b..b6ba6ef2d0 100644 --- a/internal/namespaces/tem/v1alpha1/custom.go +++ b/internal/namespaces/tem/v1alpha1/custom.go @@ -9,7 +9,10 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(tem.DomainStatus(""), human.EnumMarshalFunc(domainStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + tem.DomainStatus(""), + human.EnumMarshalFunc(domainStatusMarshalSpecs), + ) human.RegisterMarshalerFunc(tem.EmailStatus(""), human.EnumMarshalFunc(emailStatusMarshalSpecs)) cmds.MustFind("tem", "domain", "get").Override(domainGetBuilder) diff --git a/internal/namespaces/tem/v1alpha1/tem_cli.go b/internal/namespaces/tem/v1alpha1/tem_cli.go index 260955c87b..66474528ff 100644 --- a/internal/namespaces/tem/v1alpha1/tem_cli.go +++ b/internal/namespaces/tem/v1alpha1/tem_cli.go @@ -8,7 +8,7 @@ import ( "reflect" "github.com/scaleway/scaleway-cli/v2/core" - "github.com/scaleway/scaleway-sdk-go/api/tem/v1alpha1" + tem "github.com/scaleway/scaleway-sdk-go/api/tem/v1alpha1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -53,6 +53,7 @@ func GetGeneratedCommands() *core.Commands { temProjectConsumptionGet(), ) } + func temRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Transactional Email services`, @@ -261,8 +262,8 @@ func temEmailCreate() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.CreateEmail(request) + return api.CreateEmail(request) }, } } @@ -291,8 +292,8 @@ func temEmailGet() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.GetEmail(request) + return api.GetEmail(request) }, } } @@ -391,7 +392,20 @@ func temEmailList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_desc", "created_at_asc", "updated_at_desc", "updated_at_asc", "status_desc", "status_asc", "mail_from_desc", "mail_from_asc", "mail_rcpt_desc", "mail_rcpt_asc", "subject_desc", "subject_asc"}, + EnumValues: []string{ + "created_at_desc", + "created_at_asc", + "updated_at_desc", + "updated_at_asc", + "status_desc", + "status_asc", + "mail_from_desc", + "mail_from_asc", + "mail_rcpt_desc", + "mail_rcpt_asc", + "subject_desc", + "subject_asc", + }, }, { Name: "flags.{index}", @@ -399,7 +413,17 @@ func temEmailList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_flag", "soft_bounce", "hard_bounce", "spam", "mailbox_full", "mailbox_not_found", "greylisted", "send_before_expiration", "blocklisted"}, + EnumValues: []string{ + "unknown_flag", + "soft_bounce", + "hard_bounce", + "spam", + "mailbox_full", + "mailbox_not_found", + "greylisted", + "send_before_expiration", + "blocklisted", + }, }, core.RegionArgSpec(scw.RegionFrPar, scw.Region(core.AllLocalities)), }, @@ -417,8 +441,8 @@ func temEmailList() *core.Command { if err != nil { return nil, err } - return resp.Emails, nil + return resp.Emails, nil }, } } @@ -475,8 +499,8 @@ func temEmailGetStatistics() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.GetStatistics(request) + return api.GetStatistics(request) }, } } @@ -505,8 +529,8 @@ func temEmailCancel() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.CancelEmail(request) + return api.CancelEmail(request) }, } } @@ -550,8 +574,8 @@ func temDomainCreate() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.CreateDomain(request) + return api.CreateDomain(request) }, } } @@ -580,8 +604,8 @@ func temDomainGet() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.GetDomain(request) + return api.GetDomain(request) }, } } @@ -609,7 +633,16 @@ func temDomainList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "checked", "unchecked", "invalid", "locked", "revoked", "pending", "autoconfiguring"}, + EnumValues: []string{ + "unknown", + "checked", + "unchecked", + "invalid", + "locked", + "revoked", + "pending", + "autoconfiguring", + }, }, { Name: "name", @@ -641,8 +674,8 @@ func temDomainList() *core.Command { if err != nil { return nil, err } - return resp.Domains, nil + return resp.Domains, nil }, } } @@ -671,8 +704,8 @@ func temDomainRevoke() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.RevokeDomain(request) + return api.RevokeDomain(request) }, } } @@ -701,8 +734,8 @@ func temDomainCheck() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.CheckDomain(request) + return api.CheckDomain(request) }, } } @@ -731,8 +764,8 @@ func temDomainGetLastStatus() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.GetDomainLastStatus(request) + return api.GetDomainLastStatus(request) }, } } @@ -768,8 +801,8 @@ func temDomainUpdate() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.UpdateDomain(request) + return api.UpdateDomain(request) }, } } @@ -805,7 +838,17 @@ func temWebhookCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_type", "email_queued", "email_dropped", "email_deferred", "email_delivered", "email_spam", "email_mailbox_not_found", "email_blocklisted", "blocklist_created"}, + EnumValues: []string{ + "unknown_type", + "email_queued", + "email_dropped", + "email_deferred", + "email_delivered", + "email_spam", + "email_mailbox_not_found", + "email_blocklisted", + "blocklist_created", + }, }, { Name: "sns-arn", @@ -821,8 +864,8 @@ func temWebhookCreate() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.CreateWebhook(request) + return api.CreateWebhook(request) }, } } @@ -882,8 +925,8 @@ func temWebhookList() *core.Command { if err != nil { return nil, err } - return resp.Webhooks, nil + return resp.Webhooks, nil }, } } @@ -912,8 +955,8 @@ func temWebhookGet() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.GetWebhook(request) + return api.GetWebhook(request) }, } } @@ -948,7 +991,17 @@ func temWebhookUpdate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_type", "email_queued", "email_dropped", "email_deferred", "email_delivered", "email_spam", "email_mailbox_not_found", "email_blocklisted", "blocklist_created"}, + EnumValues: []string{ + "unknown_type", + "email_queued", + "email_dropped", + "email_deferred", + "email_delivered", + "email_spam", + "email_mailbox_not_found", + "email_blocklisted", + "blocklist_created", + }, }, { Name: "sns-arn", @@ -964,8 +1017,8 @@ func temWebhookUpdate() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.UpdateWebhook(request) + return api.UpdateWebhook(request) }, } } @@ -998,6 +1051,7 @@ func temWebhookDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "webhook", Verb: "delete", @@ -1044,7 +1098,17 @@ func temWebhookListEvents() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_type", "email_queued", "email_dropped", "email_deferred", "email_delivered", "email_spam", "email_mailbox_not_found", "email_blocklisted", "blocklist_created"}, + EnumValues: []string{ + "unknown_type", + "email_queued", + "email_dropped", + "email_deferred", + "email_delivered", + "email_spam", + "email_mailbox_not_found", + "email_blocklisted", + "blocklist_created", + }, }, { Name: "statuses.{index}", @@ -1091,8 +1155,8 @@ func temWebhookListEvents() *core.Command { if err != nil { return nil, err } - return resp.WebhookEvents, nil + return resp.WebhookEvents, nil }, } } @@ -1113,7 +1177,12 @@ func temBlocklistsList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_desc", "created_at_asc", "ends_at_desc", "ends_at_asc"}, + EnumValues: []string{ + "created_at_desc", + "created_at_asc", + "ends_at_desc", + "ends_at_asc", + }, }, { Name: "domain-id", @@ -1160,8 +1229,8 @@ func temBlocklistsList() *core.Command { if err != nil { return nil, err } - return resp.Blocklists, nil + return resp.Blocklists, nil }, } } @@ -1212,8 +1281,8 @@ func temBlocklistsCreate() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.BulkCreateBlocklists(request) + return api.BulkCreateBlocklists(request) }, } } @@ -1246,6 +1315,7 @@ func temBlocklistsDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "blocklists", Verb: "delete", @@ -1280,8 +1350,8 @@ func temOffersUpdate() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.UpdateOfferSubscription(request) + return api.UpdateOfferSubscription(request) }, } } @@ -1303,8 +1373,8 @@ func temOffersList() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.ListOffers(request) + return api.ListOffers(request) }, } } @@ -1327,8 +1397,8 @@ func temProjectConsumptionGet() *core.Command { client := core.ExtractClient(ctx) api := tem.NewAPI(client) - return api.GetProjectConsumption(request) + return api.GetProjectConsumption(request) }, } } diff --git a/internal/namespaces/test/v1/test_cli.go b/internal/namespaces/test/v1/test_cli.go index 75a58338ad..59ce6f8f9c 100644 --- a/internal/namespaces/test/v1/test_cli.go +++ b/internal/namespaces/test/v1/test_cli.go @@ -32,6 +32,7 @@ func GetGeneratedCommands() *core.Commands { testHumanSmoke(), ) } + func testRoot() *core.Command { return &core.Command{ Short: `No Auth Service for end-to-end testing`, @@ -88,8 +89,8 @@ Hint: you can use other test commands by setting the SCW_SECRET_KEY env variable client := core.ExtractClient(ctx) api := test.NewAPI(client) - return api.Register(request) + return api.Register(request) }, } } @@ -109,7 +110,14 @@ func testHumanList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "updated_at_asc", "updated_at_desc", "height_asc", "height_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "updated_at_asc", + "updated_at_desc", + "height_asc", + "height_desc", + }, }, { Name: "project-id", @@ -134,8 +142,8 @@ func testHumanList() *core.Command { if err != nil { return nil, err } - return resp.Humans, nil + return resp.Humans, nil }, } } @@ -163,8 +171,8 @@ func testHumanGet() *core.Command { client := core.ExtractClient(ctx) api := test.NewAPI(client) - return api.GetHuman(request) + return api.GetHuman(request) }, } } @@ -226,7 +234,17 @@ func testHumanCreate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "amber", "blue", "brown", "gray", "green", "hazel", "red", "violet"}, + EnumValues: []string{ + "unknown", + "amber", + "blue", + "brown", + "gray", + "green", + "hazel", + "red", + "violet", + }, }, { Name: "name", @@ -242,8 +260,8 @@ func testHumanCreate() *core.Command { client := core.ExtractClient(ctx) api := test.NewAPI(client) - return api.CreateHuman(request) + return api.CreateHuman(request) }, Examples: []*core.Example{ { @@ -318,7 +336,17 @@ func testHumanUpdate() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "amber", "blue", "brown", "gray", "green", "hazel", "red", "violet"}, + EnumValues: []string{ + "unknown", + "amber", + "blue", + "brown", + "gray", + "green", + "hazel", + "red", + "violet", + }, }, { Name: "name", @@ -332,8 +360,8 @@ func testHumanUpdate() *core.Command { client := core.ExtractClient(ctx) api := test.NewAPI(client) - return api.UpdateHuman(request) + return api.UpdateHuman(request) }, } } @@ -361,8 +389,8 @@ func testHumanDelete() *core.Command { client := core.ExtractClient(ctx) api := test.NewAPI(client) - return api.DeleteHuman(request) + return api.DeleteHuman(request) }, } } @@ -390,8 +418,8 @@ func testHumanRun() *core.Command { client := core.ExtractClient(ctx) api := test.NewAPI(client) - return api.RunHuman(request) + return api.RunHuman(request) }, Examples: []*core.Example{ { @@ -426,8 +454,8 @@ func testHumanSmoke() *core.Command { client := core.ExtractClient(ctx) api := test.NewAPI(client) - return api.SmokeHuman(request) + return api.SmokeHuman(request) }, } } diff --git a/internal/namespaces/vpc/v2/custom_private_network.go b/internal/namespaces/vpc/v2/custom_private_network.go index 116106fd64..358c313210 100644 --- a/internal/namespaces/vpc/v2/custom_private_network.go +++ b/internal/namespaces/vpc/v2/custom_private_network.go @@ -201,7 +201,10 @@ type customGateway struct { GatewayNetworkID string `json:"gateway_network_id"` } -func listCustomInstanceServers(client *scw.Client, pn *vpc.PrivateNetwork) ([]customInstanceServer, error) { +func listCustomInstanceServers( + client *scw.Client, + pn *vpc.PrivateNetwork, +) ([]customInstanceServer, error) { instanceAPI := instance.NewAPI(client) regionZones := pn.Region.GetZones() @@ -235,7 +238,10 @@ func listCustomInstanceServers(client *scw.Client, pn *vpc.PrivateNetwork) ([]cu return customInstanceServers, nil } -func listCustomBaremetalServers(client *scw.Client, pn *vpc.PrivateNetwork) ([]customBaremetalServer, error) { +func listCustomBaremetalServers( + client *scw.Client, + pn *vpc.PrivateNetwork, +) ([]customBaremetalServer, error) { baremetalPNAPI := baremetal.NewPrivateNetworkAPI(client) baremetalAPI := baremetal.NewAPI(client) @@ -245,10 +251,13 @@ func listCustomBaremetalServers(client *scw.Client, pn *vpc.PrivateNetwork) ([]c var customBaremetalServers []customBaremetalServer for _, zone := range zones { - listBaremetalServers, err := baremetalPNAPI.ListServerPrivateNetworks(&baremetal.PrivateNetworkAPIListServerPrivateNetworksRequest{ - Zone: zone, - PrivateNetworkID: &pn.ID, - }, scw.WithAllPages()) + listBaremetalServers, err := baremetalPNAPI.ListServerPrivateNetworks( + &baremetal.PrivateNetworkAPIListServerPrivateNetworksRequest{ + Zone: zone, + PrivateNetworkID: &pn.ID, + }, + scw.WithAllPages(), + ) if err != nil { return nil, err } diff --git a/internal/namespaces/vpc/v2/vpc_cli.go b/internal/namespaces/vpc/v2/vpc_cli.go index fcc51d968a..ee7f640af8 100644 --- a/internal/namespaces/vpc/v2/vpc_cli.go +++ b/internal/namespaces/vpc/v2/vpc_cli.go @@ -46,6 +46,7 @@ func GetGeneratedCommands() *core.Commands { vpcRouteList(), ) } + func vpcRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Virtual Private Clouds (VPCs) and Private Networks`, @@ -164,7 +165,12 @@ func vpcVpcList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpc.ListVPCsRequest) @@ -180,8 +186,8 @@ func vpcVpcList() *core.Command { if err != nil { return nil, err } - return resp.Vpcs, nil + return resp.Vpcs, nil }, } } @@ -226,8 +232,8 @@ func vpcVpcCreate() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.CreateVPC(request) + return api.CreateVPC(request) }, } } @@ -256,8 +262,8 @@ func vpcVpcGet() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.GetVPC(request) + return api.GetVPC(request) }, } } @@ -300,8 +306,8 @@ func vpcVpcUpdate() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.UpdateVPC(request) + return api.UpdateVPC(request) }, } } @@ -334,6 +340,7 @@ func vpcVpcDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "vpc", Verb: "delete", @@ -409,7 +416,12 @@ func vpcPrivateNetworkList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpc.ListPrivateNetworksRequest) @@ -425,8 +437,8 @@ func vpcPrivateNetworkList() *core.Command { if err != nil { return nil, err } - return resp.PrivateNetworks, nil + return resp.PrivateNetworks, nil }, } } @@ -478,8 +490,8 @@ func vpcPrivateNetworkCreate() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.CreatePrivateNetwork(request) + return api.CreatePrivateNetwork(request) }, } } @@ -508,8 +520,8 @@ func vpcPrivateNetworkGet() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.GetPrivateNetwork(request) + return api.GetPrivateNetwork(request) }, } } @@ -552,8 +564,8 @@ func vpcPrivateNetworkUpdate() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.UpdatePrivateNetwork(request) + return api.UpdatePrivateNetwork(request) }, } } @@ -586,6 +598,7 @@ func vpcPrivateNetworkDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "private-network", Verb: "delete", @@ -618,8 +631,8 @@ func vpcPrivateNetworkEnableDHCP() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.EnableDHCP(request) + return api.EnableDHCP(request) }, } } @@ -648,8 +661,8 @@ func vpcRouteEnableRouting() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.EnableRouting(request) + return api.EnableRouting(request) }, } } @@ -713,8 +726,8 @@ func vpcRouteCreate() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.CreateRoute(request) + return api.CreateRoute(request) }, } } @@ -743,8 +756,8 @@ func vpcRouteGet() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.GetRoute(request) + return api.GetRoute(request) }, } } @@ -808,8 +821,8 @@ func vpcRouteUpdate() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.UpdateRoute(request) + return api.UpdateRoute(request) }, } } @@ -842,6 +855,7 @@ func vpcRouteDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "route", Verb: "delete", @@ -881,8 +895,8 @@ func vpcRuleGet() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.GetACL(request) + return api.GetACL(request) }, } } @@ -991,8 +1005,8 @@ func vpcRuleSet() *core.Command { client := core.ExtractClient(ctx) api := vpc.NewAPI(client) - return api.SetACL(request) + return api.SetACL(request) }, } } @@ -1013,7 +1027,14 @@ func vpcRouteList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "destination_asc", "destination_desc", "prefix_len_asc", "prefix_len_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "destination_asc", + "destination_desc", + "prefix_len_asc", + "prefix_len_desc", + }, }, { Name: "vpc-id", @@ -1042,7 +1063,13 @@ func vpcRouteList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_type", "vpc_gateway_network", "instance_private_nic", "baremetal_private_nic", "apple_silicon_private_nic"}, + EnumValues: []string{ + "unknown_type", + "vpc_gateway_network", + "instance_private_nic", + "baremetal_private_nic", + "apple_silicon_private_nic", + }, }, { Name: "contains", @@ -1077,8 +1104,8 @@ func vpcRouteList() *core.Command { if err != nil { return nil, err } - return resp.Routes, nil + return resp.Routes, nil }, } } diff --git a/internal/namespaces/vpcgw/v1/custom.go b/internal/namespaces/vpcgw/v1/custom.go index 684b6fe7c3..094c85073f 100644 --- a/internal/namespaces/vpcgw/v1/custom.go +++ b/internal/namespaces/vpcgw/v1/custom.go @@ -9,8 +9,14 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(vpcgw.GatewayNetworkStatus(""), human.EnumMarshalFunc(gatewayNetworkStatusMarshalSpecs)) - human.RegisterMarshalerFunc(vpcgw.GatewayStatus(""), human.EnumMarshalFunc(gatewayStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + vpcgw.GatewayNetworkStatus(""), + human.EnumMarshalFunc(gatewayNetworkStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + vpcgw.GatewayStatus(""), + human.EnumMarshalFunc(gatewayStatusMarshalSpecs), + ) human.RegisterMarshalerFunc(vpcgw.Gateway{}, gatewayMarshalerFunc) human.RegisterMarshalerFunc(vpcgw.GatewayNetwork{}, gatewayNetworkMarshalerFunc) diff --git a/internal/namespaces/vpcgw/v1/custom_gateway_network.go b/internal/namespaces/vpcgw/v1/custom_gateway_network.go index 9262a60dfc..3fbc10cd2f 100644 --- a/internal/namespaces/vpcgw/v1/custom_gateway_network.go +++ b/internal/namespaces/vpcgw/v1/custom_gateway_network.go @@ -51,7 +51,8 @@ func gatewayNetworkDeleteBuilder(c *core.Command) *core.Command { if err != nil { notFoundError := &scw.ResourceNotFoundError{} responseError := &scw.ResponseError{} - if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) { + if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || + errors.As(err, ¬FoundError) { return &core.SuccessResult{ Resource: "gateway-network", Verb: "delete", diff --git a/internal/namespaces/vpcgw/v1/custom_gateway_type.go b/internal/namespaces/vpcgw/v1/custom_gateway_type.go index 5d0d7efc98..60905e379e 100644 --- a/internal/namespaces/vpcgw/v1/custom_gateway_type.go +++ b/internal/namespaces/vpcgw/v1/custom_gateway_type.go @@ -8,16 +8,18 @@ import ( ) func vpcgwGatewayTypeListBuilder(c *core.Command) *core.Command { - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { - res, err := runner(ctx, argsI) - if err != nil { - return nil, err - } + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + res, err := runner(ctx, argsI) + if err != nil { + return nil, err + } - typesResponse := res.(*vpcgw.ListGatewayTypesResponse) + typesResponse := res.(*vpcgw.ListGatewayTypesResponse) - return typesResponse.Types, nil - }) + return typesResponse.Types, nil + }, + ) return c } diff --git a/internal/namespaces/vpcgw/v1/vpcgw_cli.go b/internal/namespaces/vpcgw/v1/vpcgw_cli.go index 31680f014e..63699895f1 100644 --- a/internal/namespaces/vpcgw/v1/vpcgw_cli.go +++ b/internal/namespaces/vpcgw/v1/vpcgw_cli.go @@ -66,6 +66,7 @@ func GetGeneratedCommands() *core.Commands { vpcGwGatewayMigrateToV2(), ) } + func vpcGwRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Public Gateways`, @@ -153,7 +154,16 @@ func vpcGwGatewayList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "type_asc", "type_desc", "status_asc", "status_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + "type_asc", + "type_desc", + "status_asc", + "status_desc", + }, }, { Name: "project-id", @@ -189,7 +199,18 @@ func vpcGwGatewayList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "stopped", "allocating", "configuring", "running", "stopping", "failed", "deleting", "deleted", "locked"}, + EnumValues: []string{ + "unknown", + "stopped", + "allocating", + "configuring", + "running", + "stopping", + "failed", + "deleting", + "deleted", + "locked", + }, }, { Name: "private-network-id", @@ -205,7 +226,17 @@ func vpcGwGatewayList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.ListGatewaysRequest) @@ -221,8 +252,8 @@ func vpcGwGatewayList() *core.Command { if err != nil { return nil, err } - return resp.Gateways, nil + return resp.Gateways, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -279,15 +310,24 @@ func vpcGwGatewayGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.GetGatewayRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.GetGateway(request) + return api.GetGateway(request) }, } } @@ -361,15 +401,24 @@ func vpcGwGatewayCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.CreateGatewayRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.CreateGateway(request) + return api.CreateGateway(request) }, } } @@ -433,15 +482,24 @@ func vpcGwGatewayUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.UpdateGatewayRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.UpdateGateway(request) + return api.UpdateGateway(request) }, } } @@ -470,7 +528,16 @@ func vpcGwGatewayDelete() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.DeleteGatewayRequest) @@ -481,6 +548,7 @@ func vpcGwGatewayDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "gateway", Verb: "delete", @@ -513,15 +581,24 @@ func vpcGwGatewayUpgrade() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.UpgradeGatewayRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.UpgradeGateway(request) + return api.UpgradeGateway(request) }, } } @@ -543,7 +620,16 @@ func vpcGwGatewayEnableIPMobility() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.EnableIPMobilityRequest) @@ -554,6 +640,7 @@ func vpcGwGatewayEnableIPMobility() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "gateway", Verb: "enable-ip-mobility", @@ -578,7 +665,12 @@ func vpcGwGatewayNetworkList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "status_asc", "status_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "status_asc", + "status_desc", + }, }, { Name: "gateway-id", @@ -614,9 +706,27 @@ func vpcGwGatewayNetworkList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown", "created", "attaching", "configuring", "ready", "detaching", "deleted"}, - }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + EnumValues: []string{ + "unknown", + "created", + "attaching", + "configuring", + "ready", + "detaching", + "deleted", + }, + }, + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.ListGatewayNetworksRequest) @@ -632,8 +742,8 @@ func vpcGwGatewayNetworkList() *core.Command { if err != nil { return nil, err } - return resp.GatewayNetworks, nil + return resp.GatewayNetworks, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -690,15 +800,24 @@ func vpcGwGatewayNetworkGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.GetGatewayNetworkRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.GetGatewayNetwork(request) + return api.GetGatewayNetwork(request) }, } } @@ -769,15 +888,24 @@ func vpcGwGatewayNetworkCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.CreateGatewayNetworkRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.CreateGatewayNetwork(request) + return api.CreateGatewayNetwork(request) }, } } @@ -841,15 +969,24 @@ func vpcGwGatewayNetworkUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.UpdateGatewayNetworkRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.UpdateGatewayNetwork(request) + return api.UpdateGatewayNetwork(request) }, } } @@ -878,7 +1015,16 @@ func vpcGwGatewayNetworkDelete() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.DeleteGatewayNetworkRequest) @@ -889,6 +1035,7 @@ func vpcGwGatewayNetworkDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "gateway-network", Verb: "delete", @@ -913,7 +1060,12 @@ func vpcGwDHCPList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "subnet_asc", "subnet_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "subnet_asc", + "subnet_desc", + }, }, { Name: "project-id", @@ -943,7 +1095,17 @@ func vpcGwDHCPList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.ListDHCPsRequest) @@ -959,8 +1121,8 @@ func vpcGwDHCPList() *core.Command { if err != nil { return nil, err } - return resp.Dhcps, nil + return resp.Dhcps, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -1041,15 +1203,24 @@ func vpcGwDHCPGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.GetDHCPRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.GetDHCP(request) + return api.GetDHCP(request) }, } } @@ -1156,15 +1327,24 @@ func vpcGwDHCPCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.CreateDHCPRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.CreateDHCP(request) + return api.CreateDHCP(request) }, } } @@ -1277,15 +1457,24 @@ func vpcGwDHCPUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.UpdateDHCPRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.UpdateDHCP(request) + return api.UpdateDHCP(request) }, } } @@ -1307,7 +1496,16 @@ func vpcGwDHCPDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.DeleteDHCPRequest) @@ -1318,6 +1516,7 @@ func vpcGwDHCPDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "dhcp", Verb: "delete", @@ -1342,7 +1541,14 @@ func vpcGwDHCPEntryList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "ip_address_asc", "ip_address_desc", "hostname_asc", "hostname_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "ip_address_asc", + "ip_address_desc", + "hostname_asc", + "hostname_desc", + }, }, { Name: "gateway-network-id", @@ -1380,7 +1586,17 @@ func vpcGwDHCPEntryList() *core.Command { Positional: false, EnumValues: []string{"unknown", "reservation", "lease"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.ListDHCPEntriesRequest) @@ -1396,8 +1612,8 @@ func vpcGwDHCPEntryList() *core.Command { if err != nil { return nil, err } - return resp.DHCPEntries, nil + return resp.DHCPEntries, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -1448,15 +1664,24 @@ func vpcGwDHCPEntryGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.GetDHCPEntryRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.GetDHCPEntry(request) + return api.GetDHCPEntry(request) }, } } @@ -1492,15 +1717,24 @@ func vpcGwDHCPEntryCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.CreateDHCPEntryRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.CreateDHCPEntry(request) + return api.CreateDHCPEntry(request) }, } } @@ -1529,15 +1763,24 @@ func vpcGwDHCPEntryUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.UpdateDHCPEntryRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.UpdateDHCPEntry(request) + return api.UpdateDHCPEntry(request) }, } } @@ -1573,15 +1816,24 @@ func vpcGwDHCPEntrySet() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.SetDHCPEntriesRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.SetDHCPEntries(request) + return api.SetDHCPEntries(request) }, } } @@ -1603,7 +1855,16 @@ func vpcGwDHCPEntryDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.DeleteDHCPEntryRequest) @@ -1614,6 +1875,7 @@ func vpcGwDHCPEntryDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "dhcp-entry", Verb: "delete", @@ -1638,7 +1900,12 @@ func vpcGwPatRuleList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "public_port_asc", "public_port_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "public_port_asc", + "public_port_desc", + }, }, { Name: "gateway-id", @@ -1662,7 +1929,17 @@ func vpcGwPatRuleList() *core.Command { Positional: false, EnumValues: []string{"unknown", "both", "tcp", "udp"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.ListPATRulesRequest) @@ -1678,8 +1955,8 @@ func vpcGwPatRuleList() *core.Command { if err != nil { return nil, err } - return resp.PatRules, nil + return resp.PatRules, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -1730,15 +2007,24 @@ func vpcGwPatRuleGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.GetPATRuleRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.GetPATRule(request) + return api.GetPATRule(request) }, } } @@ -1789,15 +2075,24 @@ func vpcGwPatRuleCreate() *core.Command { Positional: false, EnumValues: []string{"unknown", "both", "tcp", "udp"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.CreatePATRuleRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.CreatePATRule(request) + return api.CreatePATRule(request) }, } } @@ -1848,15 +2143,24 @@ func vpcGwPatRuleUpdate() *core.Command { Positional: false, EnumValues: []string{"unknown", "both", "tcp", "udp"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.UpdatePATRuleRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.UpdatePATRule(request) + return api.UpdatePATRule(request) }, } } @@ -1907,15 +2211,24 @@ func vpcGwPatRuleSet() *core.Command { Positional: false, EnumValues: []string{"unknown", "both", "tcp", "udp"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.SetPATRulesRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.SetPATRules(request) + return api.SetPATRules(request) }, } } @@ -1937,7 +2250,16 @@ func vpcGwPatRuleDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.DeletePATRuleRequest) @@ -1948,6 +2270,7 @@ func vpcGwPatRuleDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "pat-rule", Verb: "delete", @@ -1966,15 +2289,24 @@ func vpcGwGatewayTypeList() *core.Command { // Deprecated: false, ArgsType: reflect.TypeOf(vpcgw.ListGatewayTypesRequest{}), ArgSpecs: core.ArgSpecs{ - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.ListGatewayTypesRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.ListGatewayTypes(request) + return api.ListGatewayTypes(request) }, } } @@ -1995,7 +2327,14 @@ func vpcGwIPList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "ip_asc", "ip_desc", "reverse_asc", "reverse_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "ip_asc", + "ip_desc", + "reverse_asc", + "reverse_desc", + }, }, { Name: "project-id", @@ -2032,7 +2371,17 @@ func vpcGwIPList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.ListIPsRequest) @@ -2048,8 +2397,8 @@ func vpcGwIPList() *core.Command { if err != nil { return nil, err } - return resp.IPs, nil + return resp.IPs, nil }, View: &core.View{Fields: []*core.ViewField{ { @@ -2100,15 +2449,24 @@ func vpcGwIPGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.GetIPRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.GetIP(request) + return api.GetIP(request) }, } } @@ -2131,15 +2489,24 @@ func vpcGwIPCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.CreateIPRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.CreateIP(request) + return api.CreateIP(request) }, } } @@ -2182,15 +2549,24 @@ func vpcGwIPUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.UpdateIPRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.UpdateIP(request) + return api.UpdateIP(request) }, } } @@ -2212,7 +2588,16 @@ func vpcGwIPDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.DeleteIPRequest) @@ -2223,6 +2608,7 @@ func vpcGwIPDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "ip", Verb: "delete", @@ -2248,15 +2634,24 @@ func vpcGwGatewayRefreshSSHKeys() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.RefreshSSHKeysRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) - return api.RefreshSSHKeys(request) + return api.RefreshSSHKeys(request) }, } } @@ -2278,7 +2673,16 @@ func vpcGwGatewayMigrateToV2() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.MigrateToV2Request) @@ -2289,6 +2693,7 @@ func vpcGwGatewayMigrateToV2() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "gateway", Verb: "migrate-to-v2", diff --git a/internal/namespaces/webhosting/v1/custom.go b/internal/namespaces/webhosting/v1/custom.go index e7800f9510..96a89334b6 100644 --- a/internal/namespaces/webhosting/v1/custom.go +++ b/internal/namespaces/webhosting/v1/custom.go @@ -9,9 +9,18 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() - human.RegisterMarshalerFunc(webhosting.HostingStatus(""), human.EnumMarshalFunc(hostingStatusMarshalSpecs)) - human.RegisterMarshalerFunc(webhosting.DNSRecordsStatus(""), human.EnumMarshalFunc(hostingDNSMarshalSpecs)) - human.RegisterMarshalerFunc(webhosting.NameserverStatus(""), human.EnumMarshalFunc(nameserverMarshalSpecs)) + human.RegisterMarshalerFunc( + webhosting.HostingStatus(""), + human.EnumMarshalFunc(hostingStatusMarshalSpecs), + ) + human.RegisterMarshalerFunc( + webhosting.DNSRecordsStatus(""), + human.EnumMarshalFunc(hostingDNSMarshalSpecs), + ) + human.RegisterMarshalerFunc( + webhosting.NameserverStatus(""), + human.EnumMarshalFunc(nameserverMarshalSpecs), + ) cmds.MustFind("webhosting", "offer", "list").Override(webhostingOfferListBuilder) diff --git a/internal/namespaces/webhosting/v1/webhosting_cli.go b/internal/namespaces/webhosting/v1/webhosting_cli.go index 0316313c3f..db2e214f89 100644 --- a/internal/namespaces/webhosting/v1/webhosting_cli.go +++ b/internal/namespaces/webhosting/v1/webhosting_cli.go @@ -62,6 +62,7 @@ func GetGeneratedCommands() *core.Commands { webhostingWebsiteList(), ) } + func webhostingRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Web Hosting services`, @@ -170,7 +171,12 @@ func webhostingControlPanelList() *core.Command { // Deprecated: false, ArgsType: reflect.TypeOf(webhosting.ControlPanelAPIListControlPanelsRequest{}), ArgSpecs: core.ArgSpecs{ - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*webhosting.ControlPanelAPIListControlPanelsRequest) @@ -186,8 +192,8 @@ func webhostingControlPanelList() *core.Command { if err != nil { return nil, err } - return resp.ControlPanels, nil + return resp.ControlPanels, nil }, } } @@ -242,8 +248,8 @@ func webhostingDatabaseCreate() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewDatabaseAPI(client) - return api.CreateDatabase(request) + return api.CreateDatabase(request) }, } } @@ -273,7 +279,12 @@ func webhostingDatabaseList() *core.Command { Positional: false, EnumValues: []string{"database_name_asc", "database_name_desc"}, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*webhosting.DatabaseAPIListDatabasesRequest) @@ -289,8 +300,8 @@ func webhostingDatabaseList() *core.Command { if err != nil { return nil, err } - return resp.Databases, nil + return resp.Databases, nil }, } } @@ -326,8 +337,8 @@ func webhostingDatabaseGet() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewDatabaseAPI(client) - return api.GetDatabase(request) + return api.GetDatabase(request) }, } } @@ -363,8 +374,8 @@ func webhostingDatabaseDelete() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewDatabaseAPI(client) - return api.DeleteDatabase(request) + return api.DeleteDatabase(request) }, } } @@ -407,8 +418,8 @@ func webhostingDatabaseUserCreate() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewDatabaseAPI(client) - return api.CreateDatabaseUser(request) + return api.CreateDatabaseUser(request) }, } } @@ -438,7 +449,12 @@ func webhostingDatabaseUserList() *core.Command { Positional: false, EnumValues: []string{"username_asc", "username_desc"}, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*webhosting.DatabaseAPIListDatabaseUsersRequest) @@ -454,8 +470,8 @@ func webhostingDatabaseUserList() *core.Command { if err != nil { return nil, err } - return resp.Users, nil + return resp.Users, nil }, } } @@ -491,8 +507,8 @@ func webhostingDatabaseUserGet() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewDatabaseAPI(client) - return api.GetDatabaseUser(request) + return api.GetDatabaseUser(request) }, } } @@ -528,8 +544,8 @@ func webhostingDatabaseUserDelete() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewDatabaseAPI(client) - return api.DeleteDatabaseUser(request) + return api.DeleteDatabaseUser(request) }, } } @@ -572,8 +588,8 @@ func webhostingDatabaseUserChangePassword() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewDatabaseAPI(client) - return api.ChangeDatabaseUserPassword(request) + return api.ChangeDatabaseUserPassword(request) }, } } @@ -616,8 +632,8 @@ func webhostingDatabaseUserAssign() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewDatabaseAPI(client) - return api.AssignDatabaseUser(request) + return api.AssignDatabaseUser(request) }, } } @@ -660,8 +676,8 @@ func webhostingDatabaseUserUnassign() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewDatabaseAPI(client) - return api.UnassignDatabaseUser(request) + return api.UnassignDatabaseUser(request) }, } } @@ -690,8 +706,8 @@ func webhostingDNSRecordsGetDNSRecords() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewDnsAPI(client) - return api.GetDomainDNSRecords(request) + return api.GetDomainDNSRecords(request) }, Examples: []*core.Example{ { @@ -727,8 +743,8 @@ func webhostingDomainCheckOwnership() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewDnsAPI(client) - return api.CheckUserOwnsDomain(request) + return api.CheckUserOwnsDomain(request) }, } } @@ -833,8 +849,8 @@ func webhostingDomainSyncDNSRecords() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewDnsAPI(client) - return api.SyncDomainDNSRecords(request) + return api.SyncDomainDNSRecords(request) }, } } @@ -871,7 +887,12 @@ func webhostingOfferList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*webhosting.OfferAPIListOffersRequest) @@ -887,8 +908,8 @@ func webhostingOfferList() *core.Command { if err != nil { return nil, err } - return resp.Offers, nil + return resp.Offers, nil }, } } @@ -1027,8 +1048,8 @@ func webhostingHostingCreate() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewHostingAPI(client) - return api.CreateHosting(request) + return api.CreateHosting(request) }, } } @@ -1064,7 +1085,15 @@ func webhostingHostingList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_status", "delivering", "ready", "deleting", "error", "locked", "migrating"}, + EnumValues: []string{ + "unknown_status", + "delivering", + "ready", + "deleting", + "error", + "locked", + "migrating", + }, }, { Name: "domain", @@ -1094,7 +1123,12 @@ func webhostingHostingList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*webhosting.HostingAPIListHostingsRequest) @@ -1110,8 +1144,8 @@ func webhostingHostingList() *core.Command { if err != nil { return nil, err } - return resp.Hostings, nil + return resp.Hostings, nil }, Examples: []*core.Example{ { @@ -1146,8 +1180,8 @@ func webhostingHostingGet() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewHostingAPI(client) - return api.GetHosting(request) + return api.GetHosting(request) }, Examples: []*core.Example{ { @@ -1224,8 +1258,8 @@ func webhostingHostingUpdate() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewHostingAPI(client) - return api.UpdateHosting(request) + return api.UpdateHosting(request) }, Examples: []*core.Example{ { @@ -1264,8 +1298,8 @@ func webhostingHostingDelete() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewHostingAPI(client) - return api.DeleteHosting(request) + return api.DeleteHosting(request) }, Examples: []*core.Example{ { @@ -1300,8 +1334,8 @@ func webhostingHostingCreateSession() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewHostingAPI(client) - return api.CreateSession(request) + return api.CreateSession(request) }, } } @@ -1351,8 +1385,8 @@ func webhostingFtpAccountCreate() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewFtpAccountAPI(client) - return api.CreateFtpAccount(request) + return api.CreateFtpAccount(request) }, } } @@ -1389,7 +1423,12 @@ func webhostingFtpAccountList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*webhosting.FtpAccountAPIListFtpAccountsRequest) @@ -1405,8 +1444,8 @@ func webhostingFtpAccountList() *core.Command { if err != nil { return nil, err } - return resp.FtpAccounts, nil + return resp.FtpAccounts, nil }, } } @@ -1442,8 +1481,8 @@ func webhostingFtpAccountDelete() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewFtpAccountAPI(client) - return api.RemoveFtpAccount(request) + return api.RemoveFtpAccount(request) }, } } @@ -1493,8 +1532,8 @@ func webhostingMailAccountCreate() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewMailAccountAPI(client) - return api.CreateMailAccount(request) + return api.CreateMailAccount(request) }, } } @@ -1531,7 +1570,12 @@ func webhostingMailAccountList() *core.Command { Deprecated: false, Positional: false, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*webhosting.MailAccountAPIListMailAccountsRequest) @@ -1547,8 +1591,8 @@ func webhostingMailAccountList() *core.Command { if err != nil { return nil, err } - return resp.MailAccounts, nil + return resp.MailAccounts, nil }, } } @@ -1591,8 +1635,8 @@ func webhostingMailAccountDelete() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewMailAccountAPI(client) - return api.RemoveMailAccount(request) + return api.RemoveMailAccount(request) }, } } @@ -1642,8 +1686,8 @@ func webhostingMailAccountChangePassword() *core.Command { client := core.ExtractClient(ctx) api := webhosting.NewMailAccountAPI(client) - return api.ChangeMailAccountPassword(request) + return api.ChangeMailAccountPassword(request) }, } } @@ -1673,7 +1717,12 @@ func webhostingWebsiteList() *core.Command { Positional: false, EnumValues: []string{"domain_asc", "domain_desc"}, }, - core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw, scw.Region(core.AllLocalities)), + core.RegionArgSpec( + scw.RegionFrPar, + scw.RegionNlAms, + scw.RegionPlWaw, + scw.Region(core.AllLocalities), + ), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*webhosting.WebsiteAPIListWebsitesRequest) @@ -1689,8 +1738,8 @@ func webhostingWebsiteList() *core.Command { if err != nil { return nil, err } - return resp.Websites, nil + return resp.Websites, nil }, } } diff --git a/internal/passwordgenerator/password_generator.go b/internal/passwordgenerator/password_generator.go index 724c0309ac..f17f7b345f 100644 --- a/internal/passwordgenerator/password_generator.go +++ b/internal/passwordgenerator/password_generator.go @@ -17,7 +17,9 @@ const ( func GeneratePassword(length, minNumbers, minLower, minUpper, minSymbol int) (string, error) { if length < (minNumbers + minLower + minUpper + minSymbol) { - return "", errors.New("length is less than the sum of minNumbers, minLower, minUpper, and minSymbol") + return "", errors.New( + "length is less than the sum of minNumbers, minLower, minUpper, and minSymbol", + ) } var password strings.Builder diff --git a/internal/pkg/shlex/shlex.go b/internal/pkg/shlex/shlex.go index d98308bce3..63108215df 100644 --- a/internal/pkg/shlex/shlex.go +++ b/internal/pkg/shlex/shlex.go @@ -20,27 +20,27 @@ shell-style rules for quoting and commenting. The basic use case uses the default ASCII lexer to split a string into sub-strings: - shlex.Split("one \"two three\" four") -> []string{"one", "two three", "four"} + shlex.Split("one \"two three\" four") -> []string{"one", "two three", "four"} To process a stream of strings: - l := NewLexer(os.Stdin) - for ; token, err := l.Next(); err != nil { - // process token - } + l := NewLexer(os.Stdin) + for ; token, err := l.Next(); err != nil { + // process token + } To access the raw token stream (which includes tokens for comments): - t := NewTokenizer(os.Stdin) - for ; token, err := t.Next(); err != nil { - // process token - } - + t := NewTokenizer(os.Stdin) + for ; token, err := t.Next(); err != nil { + // process token + } */ package shlex import ( "bufio" + "errors" "fmt" "io" "strings" @@ -71,6 +71,7 @@ func (a *Token) Equal(b *Token) bool { if a.tokenType != b.tokenType { return false } + return a.value == b.value } @@ -130,6 +131,7 @@ func newDefaultClassifier() tokenClassifier { t.addRuneClass(nonEscapingQuoteRunes, nonEscapingQuoteRuneClass) t.addRuneClass(escapeRunes, escapeRuneClass) t.addRuneClass(commentRunes, commentRuneClass) + return t } @@ -143,7 +145,6 @@ type Lexer Tokenizer // NewLexer creates a new lexer from an input stream. func NewLexer(r io.Reader) *Lexer { - return (*Lexer)(NewTokenizer(r)) } @@ -176,9 +177,11 @@ type Tokenizer struct { func NewTokenizer(r io.Reader) *Tokenizer { input := bufio.NewReader(r) classifier := newDefaultClassifier() + return &Tokenizer{ input: *input, - classifier: classifier} + classifier: classifier, + } } // scanStream scans the stream for the next token using the internal state machine. @@ -248,14 +251,18 @@ func (t *Tokenizer) scanStream() (*Token, error) { { token := &Token{ tokenType: tokenType, - value: string(value)} + value: string(value), + } + return token, err } case spaceRuneClass: { token := &Token{ tokenType: tokenType, - value: string(value)} + value: string(value), + } + return token, err } case escapingQuoteRuneClass: @@ -281,10 +288,12 @@ func (t *Tokenizer) scanStream() (*Token, error) { switch nextRuneType { case eofRuneClass: { - err = fmt.Errorf("EOF found after escape character") + err = errors.New("EOF found after escape character") token := &Token{ tokenType: tokenType, - value: string(value)} + value: string(value), + } + return token, err } default: @@ -299,10 +308,12 @@ func (t *Tokenizer) scanStream() (*Token, error) { switch nextRuneType { case eofRuneClass: { - err = fmt.Errorf("EOF found after escape character") + err = errors.New("EOF found after escape character") token := &Token{ tokenType: tokenType, - value: string(value)} + value: string(value), + } + return token, err } default: @@ -317,10 +328,12 @@ func (t *Tokenizer) scanStream() (*Token, error) { switch nextRuneType { case eofRuneClass: { - err = fmt.Errorf("EOF found when expecting closing quote") + err = errors.New("EOF found when expecting closing quote") token := &Token{ tokenType: tokenType, - value: string(value)} + value: string(value), + } + return token, err } case escapingQuoteRuneClass: @@ -342,10 +355,12 @@ func (t *Tokenizer) scanStream() (*Token, error) { switch nextRuneType { case eofRuneClass: { - err = fmt.Errorf("EOF found when expecting closing quote") + err = errors.New("EOF found when expecting closing quote") token := &Token{ tokenType: tokenType, - value: string(value)} + value: string(value), + } + return token, err } case nonEscapingQuoteRuneClass: @@ -365,7 +380,9 @@ func (t *Tokenizer) scanStream() (*Token, error) { { token := &Token{ tokenType: tokenType, - value: string(value)} + value: string(value), + } + return token, err } case spaceRuneClass: @@ -374,7 +391,9 @@ func (t *Tokenizer) scanStream() (*Token, error) { state = startState token := &Token{ tokenType: tokenType, - value: string(value)} + value: string(value), + } + return token, err } else { value = append(value, nextRune) @@ -409,6 +428,7 @@ func Split(s string) ([]string, error) { if err == io.EOF { return subStrings, nil } + return subStrings, err } subStrings = append(subStrings, word) diff --git a/internal/pkg/shlex/shlex_test.go b/internal/pkg/shlex/shlex_test.go index f9f9e0c798..a5ea449383 100644 --- a/internal/pkg/shlex/shlex_test.go +++ b/internal/pkg/shlex/shlex_test.go @@ -21,11 +21,9 @@ import ( "testing" ) -var ( - // one two "three four" "five \"six\"" seven#eight # nine # ten - // eleven 'twelve\' - testString = "one two \"three four\" \"five \\\"six\\\"\" seven#eight # nine # ten\n eleven 'twelve\\' thirteen=13 fourteen/14" -) +// one two "three four" "five \"six\"" seven#eight # nine # ten +// eleven 'twelve\' +var testString = "one two \"three four\" \"five \\\"six\\\"\" seven#eight # nine # ten\n eleven 'twelve\\' thirteen=13 fourteen/14" func TestClassifier(t *testing.T) { classifier := newDefaultClassifier() @@ -33,7 +31,8 @@ func TestClassifier(t *testing.T) { ' ': spaceRuneClass, '"': escapingQuoteRuneClass, '\'': nonEscapingQuoteRuneClass, - '#': commentRuneClass} + '#': commentRuneClass, + } for runeChar, want := range tests { got := classifier.ClassifyRune(runeChar) if got != want { @@ -45,16 +44,17 @@ func TestClassifier(t *testing.T) { func TestTokenizer(t *testing.T) { testInput := strings.NewReader(testString) expectedTokens := []*Token{ - &Token{WordToken, "one"}, - &Token{WordToken, "two"}, - &Token{WordToken, "three four"}, - &Token{WordToken, "five \"six\""}, - &Token{WordToken, "seven#eight"}, - &Token{CommentToken, " nine # ten"}, - &Token{WordToken, "eleven"}, - &Token{WordToken, "twelve\\"}, - &Token{WordToken, "thirteen=13"}, - &Token{WordToken, "fourteen/14"}} + {WordToken, "one"}, + {WordToken, "two"}, + {WordToken, "three four"}, + {WordToken, "five \"six\""}, + {WordToken, "seven#eight"}, + {CommentToken, " nine # ten"}, + {WordToken, "eleven"}, + {WordToken, "twelve\\"}, + {WordToken, "thirteen=13"}, + {WordToken, "fourteen/14"}, + } tokenizer := NewTokenizer(testInput) for i, want := range expectedTokens { @@ -70,7 +70,17 @@ func TestTokenizer(t *testing.T) { func TestLexer(t *testing.T) { testInput := strings.NewReader(testString) - expectedStrings := []string{"one", "two", "three four", "five \"six\"", "seven#eight", "eleven", "twelve\\", "thirteen=13", "fourteen/14"} + expectedStrings := []string{ + "one", + "two", + "three four", + "five \"six\"", + "seven#eight", + "eleven", + "twelve\\", + "thirteen=13", + "fourteen/14", + } lexer := NewLexer(testInput) for i, want := range expectedStrings { @@ -85,7 +95,17 @@ func TestLexer(t *testing.T) { } func TestSplit(t *testing.T) { - want := []string{"one", "two", "three four", "five \"six\"", "seven#eight", "eleven", "twelve\\", "thirteen=13", "fourteen/14"} + want := []string{ + "one", + "two", + "three four", + "five \"six\"", + "seven#eight", + "eleven", + "twelve\\", + "thirteen=13", + "fourteen/14", + } got, err := Split(testString) if err != nil { t.Error(err) diff --git a/internal/platform/terminal/terminal_client.go b/internal/platform/terminal/terminal_client.go index 5797e67f5c..b578e279a8 100644 --- a/internal/platform/terminal/terminal_client.go +++ b/internal/platform/terminal/terminal_client.go @@ -12,7 +12,11 @@ import ( "github.com/scaleway/scaleway-sdk-go/validation" ) -func (p *Platform) CreateClient(httpClient *http.Client, configPath string, profileName string) (*scw.Client, error) { +func (p *Platform) CreateClient( + httpClient *http.Client, + configPath string, + profileName string, +) (*scw.Client, error) { profile := scw.LoadEnvProfile() // Default path is based on the following priority order: @@ -123,7 +127,10 @@ func validateClient(client *scw.Client) error { if !validation.IsAccessKey(accessKey) { return &platform.ClientError{ - Err: fmt.Errorf("invalid access key format '%s', expected SCWXXXXXXXXXXXXXXXXX format", accessKey), + Err: fmt.Errorf( + "invalid access key format '%s', expected SCWXXXXXXXXXXXXXXXXX format", + accessKey, + ), } } @@ -137,7 +144,10 @@ func validateClient(client *scw.Client) error { if !validation.IsSecretKey(secretKey) { return &platform.ClientError{ - Err: fmt.Errorf("invalid secret key format '%s', expected a UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", secretKey), + Err: fmt.Errorf( + "invalid secret key format '%s', expected a UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + secretKey, + ), } } @@ -151,7 +161,10 @@ func validateClient(client *scw.Client) error { if !validation.IsOrganizationID(defaultOrganizationID) { return &platform.ClientError{ - Err: fmt.Errorf("invalid organization ID format '%s', expected a UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", defaultOrganizationID), + Err: fmt.Errorf( + "invalid organization ID format '%s', expected a UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + defaultOrganizationID, + ), } } @@ -170,7 +183,11 @@ func validateClient(client *scw.Client) error { } return &platform.ClientError{ - Err: fmt.Errorf("invalid default zone format '%s', available zones are: %s", defaultZone, strings.Join(zones, ", ")), + Err: fmt.Errorf( + "invalid default zone format '%s', available zones are: %s", + defaultZone, + strings.Join(zones, ", "), + ), } } @@ -189,7 +206,11 @@ func validateClient(client *scw.Client) error { } return &platform.ClientError{ - Err: fmt.Errorf("invalid default region format '%s', available regions are: %s", defaultRegion, strings.Join(regions, ", ")), + Err: fmt.Errorf( + "invalid default region format '%s', available regions are: %s", + defaultRegion, + strings.Join(regions, ", "), + ), } } diff --git a/internal/qa/argspec.go b/internal/qa/argspec.go index 0a32f168ef..e007e2a0d8 100644 --- a/internal/qa/argspec.go +++ b/internal/qa/argspec.go @@ -30,7 +30,10 @@ func testArgSpecInvalidError(commands *core.Commands) []error { for _, arg := range command.ArgSpecs { _, err := args.GetArgType(command.ArgsType, arg.Name) if err != nil { - errors = append(errors, &ArgSpecInvalidError{Command: command, argSpec: arg, innerError: err}) + errors = append( + errors, + &ArgSpecInvalidError{Command: command, argSpec: arg, innerError: err}, + ) continue } @@ -66,7 +69,10 @@ func testArgSpecMissingError(commands *core.Commands) []error { for _, argSpecName := range supposedArgSpecs { if command.ArgSpecs.GetByName(argSpecName) == nil { - errors = append(errors, &ArgSpecMissingError{Command: command, argName: argSpecName}) + errors = append( + errors, + &ArgSpecMissingError{Command: command, argName: argSpecName}, + ) } } } diff --git a/internal/qa/qa.go b/internal/qa/qa.go index 9717459f1f..78cd6eeab5 100644 --- a/internal/qa/qa.go +++ b/internal/qa/qa.go @@ -77,7 +77,9 @@ type WellKnownArgOrderError struct { } func (err WellKnownArgOrderError) Error() string { - return "well-known arg order must be respected '" + err.Command.GetCommandLine("scw") + "', arg '" + err.Argspec.Name + "'" + return "well-known arg order must be respected '" + err.Command.GetCommandLine( + "scw", + ) + "', arg '" + err.Argspec.Name + "'" } type WellKnownArgAtTheEndError struct { @@ -86,7 +88,9 @@ type WellKnownArgAtTheEndError struct { } func (err WellKnownArgAtTheEndError) Error() string { - return "well-known arg must be at the end'" + err.Command.GetCommandLine("scw") + "', arg '" + err.Argspec.Name + "'" + return "well-known arg must be at the end'" + err.Command.GetCommandLine( + "scw", + ) + "', arg '" + err.Argspec.Name + "'" } const ( @@ -157,7 +161,9 @@ type ArgMustUseDashError struct { } func (err ArgMustUseDashError) Error() string { - return "arg must use dash for command '" + err.Command.GetCommandLine("scw") + "', arg '" + err.Argspec.Name + "'" + return "arg must use dash for command '" + err.Command.GetCommandLine( + "scw", + ) + "', arg '" + err.Argspec.Name + "'" } func testArgMustUseDashError(commands *core.Commands) []error { @@ -182,7 +188,9 @@ type PositionalArgMustBeRequiredError struct { } func (err PositionalArgMustBeRequiredError) Error() string { - return "positional argument must be required '" + err.Command.GetCommandLine("scw") + "', arg '" + err.Argspec.Name + "'" + return "positional argument must be required '" + err.Command.GetCommandLine( + "scw", + ) + "', arg '" + err.Argspec.Name + "'" } func testPositionalArgMustBeRequiredError(commands *core.Commands) []error { @@ -207,7 +215,11 @@ type ExampleCanHaveOnlyOneTypeOfExampleError struct { } func (err ExampleCanHaveOnlyOneTypeOfExampleError) Error() string { - return "arg must use dash for command '" + err.Command.GetCommandLine("scw") + "', example #" + strconv.Itoa(err.ExampleIndex) + return "arg must use dash for command '" + err.Command.GetCommandLine( + "scw", + ) + "', example #" + strconv.Itoa( + err.ExampleIndex, + ) } func testExampleCanHaveOnlyOneTypeOfExampleError(commands *core.Commands) []error { @@ -235,8 +247,15 @@ type DifferentLocalizationForNamespaceError struct { } func (err DifferentLocalizationForNamespaceError) Error() string { - return fmt.Sprintf("different localization for commands '%v', '%v': %v, %v", - err.Command1.GetCommandLine("scw"), err.Command2.GetCommandLine("scw"), err.ArgNames1, err.ArgNames2) + return fmt.Sprintf( + "different localization for commands '%v', '%v': %v, %v", + err.Command1.GetCommandLine( + "scw", + ), + err.Command2.GetCommandLine("scw"), + err.ArgNames1, + err.ArgNames2, + ) } func testDifferentLocalizationForNamespaceError(commands *core.Commands) []error { @@ -247,18 +266,30 @@ func testDifferentLocalizationForNamespaceError(commands *core.Commands) []error continue } - samePathLength := strings.Count(command1.GetCommandLine("scw"), " ") == strings.Count(command2.GetCommandLine("scw"), " ") + samePathLength := strings.Count( + command1.GetCommandLine("scw"), + " ", + ) == strings.Count( + command2.GetCommandLine("scw"), + " ", + ) sameNamespace := command1.Namespace == command2.Namespace - c1HasRegionOnly := command1.ArgSpecs.GetByName("region") != nil && command1.ArgSpecs.GetByName("zone") == nil - c2HasRegionOnly := command2.ArgSpecs.GetByName("region") != nil && command2.ArgSpecs.GetByName("zone") == nil + c1HasRegionOnly := command1.ArgSpecs.GetByName("region") != nil && + command1.ArgSpecs.GetByName("zone") == nil + c2HasRegionOnly := command2.ArgSpecs.GetByName("region") != nil && + command2.ArgSpecs.GetByName("zone") == nil - c1HasZoneOnly := command1.ArgSpecs.GetByName("region") == nil && command1.ArgSpecs.GetByName("zone") != nil - c2HasZoneOnly := command2.ArgSpecs.GetByName("region") == nil && command2.ArgSpecs.GetByName("zone") != nil + c1HasZoneOnly := command1.ArgSpecs.GetByName("region") == nil && + command1.ArgSpecs.GetByName("zone") != nil + c2HasZoneOnly := command2.ArgSpecs.GetByName("region") == nil && + command2.ArgSpecs.GetByName("zone") != nil - c1NoRegionNoZone := command1.ArgSpecs.GetByName("region") == nil && command1.ArgSpecs.GetByName("zone") == nil - c2NoRegionNoZone := command2.ArgSpecs.GetByName("region") == nil && command2.ArgSpecs.GetByName("zone") == nil + c1NoRegionNoZone := command1.ArgSpecs.GetByName("region") == nil && + command1.ArgSpecs.GetByName("zone") == nil + c2NoRegionNoZone := command2.ArgSpecs.GetByName("region") == nil && + command2.ArgSpecs.GetByName("zone") == nil if !samePathLength { continue @@ -296,7 +327,15 @@ func testDifferentLocalizationForNamespaceError(commands *core.Commands) []error Command2: command2, ArgNames1: argNames1, ArgNames2: argNames2, - Checks: []bool{sameNamespace, c1HasRegionOnly, c2HasRegionOnly, c1HasZoneOnly, c2HasZoneOnly, c1NoRegionNoZone, c2NoRegionNoZone}, + Checks: []bool{ + sameNamespace, + c1HasRegionOnly, + c2HasRegionOnly, + c1HasZoneOnly, + c2HasZoneOnly, + c1NoRegionNoZone, + c2NoRegionNoZone, + }, }) } } diff --git a/internal/sentry/sentry.go b/internal/sentry/sentry.go index e55b39d88a..04c14b1975 100644 --- a/internal/sentry/sentry.go +++ b/internal/sentry/sentry.go @@ -125,10 +125,12 @@ func filterStackFrames(event *sentry.Event) { if frame.Module == "main" && strings.HasPrefix(frame.Function, "cleanup") { continue } - if frame.Module == "github.com/scaleway/scaleway-cli/v2/internal/sentry" && strings.HasPrefix(frame.Function, "RecoverPanicAndSendReport") { + if frame.Module == "github.com/scaleway/scaleway-cli/v2/internal/sentry" && + strings.HasPrefix(frame.Function, "RecoverPanicAndSendReport") { continue } - if frame.Module == "github.com/scaleway/scaleway-cli/v2/internal/sentry" && strings.HasPrefix(frame.Function, "logAndSentry") { + if frame.Module == "github.com/scaleway/scaleway-cli/v2/internal/sentry" && + strings.HasPrefix(frame.Function, "logAndSentry") { continue } frames = append(frames, frame) diff --git a/internal/tabwriter/tabwriter.go b/internal/tabwriter/tabwriter.go index e8927310ed..7613131652 100644 --- a/internal/tabwriter/tabwriter.go +++ b/internal/tabwriter/tabwriter.go @@ -219,7 +219,12 @@ const ( // (for correct-looking results, tabwidth must correspond // to the tab width in the viewer displaying the result) // flags formatting control -func (b *Writer) Init(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer { +func (b *Writer) Init( + output io.Writer, + minwidth, tabwidth, padding int, + padchar byte, + flags uint, +) *Writer { if minwidth < 0 || tabwidth < 0 || padding < 0 { panic("negative minwidth, tabwidth, or padding") } @@ -633,6 +638,11 @@ func (b *Writer) Write(buf []byte) (n int, err error) { // NewWriter allocates and initializes a new tabwriter.Writer. // The parameters are the same as for the Init function. -func NewWriter(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer { +func NewWriter( + output io.Writer, + minwidth, tabwidth, padding int, + padchar byte, + flags uint, +) *Writer { return new(Writer).Init(output, minwidth, tabwidth, padding, padchar, flags) } diff --git a/internal/tabwriter/tabwriter_test.go b/internal/tabwriter/tabwriter_test.go index 454fa0ff03..2f857b8ac5 100644 --- a/internal/tabwriter/tabwriter_test.go +++ b/internal/tabwriter/tabwriter_test.go @@ -46,7 +46,13 @@ func write(t *testing.T, testname string, w *tabwriter.Writer, src string) { t.Errorf("--- test: %s\n--- src:\n%q\n--- write error: %v\n", testname, src, err) } if written != len(src) { - t.Errorf("--- test: %s\n--- src:\n%q\n--- written = %d, len(src) = %d\n", testname, src, written, len(src)) + t.Errorf( + "--- test: %s\n--- src:\n%q\n--- written = %d, len(src) = %d\n", + testname, + src, + written, + len(src), + ) } } @@ -59,11 +65,24 @@ func verify(t *testing.T, testname string, w *tabwriter.Writer, b *buffer, src, res := b.String() if res != expected { - t.Errorf("--- test: %s\n--- src:\n%q\n--- found:\n%q\n--- expected:\n%q\n", testname, src, res, expected) + t.Errorf( + "--- test: %s\n--- src:\n%q\n--- found:\n%q\n--- expected:\n%q\n", + testname, + src, + res, + expected, + ) } } -func check(t *testing.T, testname string, minwidth, tabwidth, padding int, padchar byte, flags uint, src, expected string) { +func check( + t *testing.T, + testname string, + minwidth, tabwidth, padding int, + padchar byte, + flags uint, + src, expected string, +) { t.Helper() var b buffer b.init(1000) @@ -650,7 +669,17 @@ var tests = []struct { func Test(t *testing.T) { for _, e := range tests { - check(t, e.testname, e.minwidth, e.tabwidth, e.padding, e.padchar, e.flags, e.src, e.expected) + check( + t, + e.testname, + e.minwidth, + e.tabwidth, + e.padding, + e.padchar, + e.flags, + e.src, + e.expected, + ) } } @@ -702,7 +731,14 @@ func BenchmarkTable(b *testing.B) { b.Run("new", func(b *testing.B) { b.ReportAllocs() for range b.N { - w := tabwriter.NewWriter(io.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings + w := tabwriter.NewWriter( + io.Discard, + 4, + 4, + 1, + ' ', + 0, + ) // no particular reason for these settings // Write the line h times. for range h { w.Write(line) @@ -713,7 +749,14 @@ func BenchmarkTable(b *testing.B) { b.Run("reuse", func(b *testing.B) { b.ReportAllocs() - w := tabwriter.NewWriter(io.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings + w := tabwriter.NewWriter( + io.Discard, + 4, + 4, + 1, + ' ', + 0, + ) // no particular reason for these settings for range b.N { // Write the line h times. for range h { @@ -734,7 +777,14 @@ func BenchmarkPyramid(b *testing.B) { b.Run(strconv.Itoa(x), func(b *testing.B) { b.ReportAllocs() for range b.N { - w := tabwriter.NewWriter(io.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings + w := tabwriter.NewWriter( + io.Discard, + 4, + 4, + 1, + ' ', + 0, + ) // no particular reason for these settings // Write increasing prefixes of that line. for j := range x { w.Write(line[:j*2]) @@ -756,7 +806,14 @@ func BenchmarkRagged(b *testing.B) { b.Run(strconv.Itoa(h), func(b *testing.B) { b.ReportAllocs() for range b.N { - w := tabwriter.NewWriter(io.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings + w := tabwriter.NewWriter( + io.Discard, + 4, + 4, + 1, + ' ', + 0, + ) // no particular reason for these settings // Write the lines in turn h times. for j := range h { w.Write(lines[j%len(lines)]) @@ -784,7 +841,14 @@ lines func BenchmarkCode(b *testing.B) { b.ReportAllocs() for range b.N { - w := tabwriter.NewWriter(io.Discard, 4, 4, 1, ' ', 0) // no particular reason for these settings + w := tabwriter.NewWriter( + io.Discard, + 4, + 4, + 1, + ' ', + 0, + ) // no particular reason for these settings // The code is small, so it's reasonable for the tabwriter user // to write it all at once, or buffer the writes. w.Write([]byte(codeSnippet)) diff --git a/internal/tasks/logger.go b/internal/tasks/logger.go index 3d8355f2d7..e4c280cf00 100644 --- a/internal/tasks/logger.go +++ b/internal/tasks/logger.go @@ -43,7 +43,11 @@ func NewTasksLogger(ctx context.Context, mode LoggerMode) (*Logger, error) { status: make(chan *buildkit.SolveStatus), done: doneChan, } - display, err := progressui.NewDisplay(writer, progressui.DefaultMode, progressui.WithDesc("Running workflow", "")) + display, err := progressui.NewDisplay( + writer, + progressui.DefaultMode, + progressui.WithDesc("Running workflow", ""), + ) if err != nil { return nil, fmt.Errorf("failed to create display: %w", err) } diff --git a/internal/tasks/tasks.go b/internal/tasks/tasks.go index a8b413eb1e..fce9ed7ade 100644 --- a/internal/tasks/tasks.go +++ b/internal/tasks/tasks.go @@ -42,7 +42,11 @@ func (ts *Tasks) SetLoggerMode(mode LoggerMode) { ts.LoggerMode = mode } -func Add[TaskArg any, TaskReturn any](ts *Tasks, name string, taskFunc TaskFunc[TaskArg, TaskReturn]) { +func Add[TaskArg any, TaskReturn any]( + ts *Tasks, + name string, + taskFunc TaskFunc[TaskArg, TaskReturn], +) { var argValue TaskArg var returnValue TaskReturn argType := reflect.TypeOf(argValue) @@ -52,7 +56,13 @@ func Add[TaskArg any, TaskReturn any](ts *Tasks, name string, taskFunc TaskFunc[ if tasksAmount > 0 { lastTask := ts.tasks[tasksAmount-1] if argType != lastTask.returnType { - panic(fmt.Errorf("invalid task declared, wait for %s, previous task returns %s", argType.Name(), lastTask.returnType.Name())) + panic( + fmt.Errorf( + "invalid task declared, wait for %s, previous task returns %s", + argType.Name(), + lastTask.returnType.Name(), + ), + ) } } @@ -101,7 +111,9 @@ func (ts *Tasks) Cleanup(ctx context.Context, logger *Logger, failed int) { if len(task.cleanFunctions) != 0 { var err error for i, cleanUpFunc := range task.cleanFunctions { - loggerEntry := logger.AddEntry(fmt.Sprintf("Cleaning task %q %d/%d", task.Name, i+1, len(task.cleanFunctions))) + loggerEntry := logger.AddEntry( + fmt.Sprintf("Cleaning task %q %d/%d", task.Name, i+1, len(task.cleanFunctions)), + ) task.Logs = loggerEntry.Logs loggerEntry.Start() diff --git a/internal/tasks/tasks_test.go b/internal/tasks/tasks_test.go index 360389d46b..f1a77a3a1e 100644 --- a/internal/tasks/tasks_test.go +++ b/internal/tasks/tasks_test.go @@ -18,17 +18,25 @@ func TestGeneric(t *testing.T) { ts := tasks.Begin() ts.SetLoggerMode(tasks.PrinterModeQuiet) - tasks.Add(ts, "convert int to string", func(_ *tasks.Task, args int) (nextArgs string, err error) { - return strconv.Itoa(args), nil - }) - tasks.Add(ts, "convert string to int and divide by 4", func(_ *tasks.Task, args string) (nextArgs int, err error) { - i, err := strconv.ParseInt(args, 10, 32) - if err != nil { - return 0, err - } - - return int(i) / 4, nil - }) + tasks.Add( + ts, + "convert int to string", + func(_ *tasks.Task, args int) (nextArgs string, err error) { + return strconv.Itoa(args), nil + }, + ) + tasks.Add( + ts, + "convert string to int and divide by 4", + func(_ *tasks.Task, args string) (nextArgs int, err error) { + i, err := strconv.ParseInt(args, 10, 32) + if err != nil { + return 0, err + } + + return int(i) / 4, nil + }, + ) res, err := ts.Execute(t.Context(), 12) require.NoError(t, err) @@ -45,9 +53,13 @@ func TestInvalidGeneric(t *testing.T) { ts := tasks.Begin() ts.SetLoggerMode(tasks.PrinterModeQuiet) - tasks.Add(ts, "convert int to string", func(_ *tasks.Task, args int) (nextArgs string, err error) { - return strconv.Itoa(args), nil - }) + tasks.Add( + ts, + "convert int to string", + func(_ *tasks.Task, args int) (nextArgs string, err error) { + return strconv.Itoa(args), nil + }, + ) tasks.Add(ts, "divide by 4", func(_ *tasks.Task, args int) (nextArgs int, err error) { return args / 4, nil }) @@ -58,33 +70,45 @@ func TestCleanup(t *testing.T) { clean := 0 - tasks.Add(ts, "TaskFunc 1", func(task *tasks.Task, _ interface{}) (nextArgs interface{}, err error) { - task.AddToCleanUp(func(_ context.Context) error { - clean++ - - return nil - }) + tasks.Add( + ts, + "TaskFunc 1", + func(task *tasks.Task, _ interface{}) (nextArgs interface{}, err error) { + task.AddToCleanUp(func(_ context.Context) error { + clean++ - return nil, nil - }) - tasks.Add(ts, "TaskFunc 2", func(task *tasks.Task, _ interface{}) (nextArgs interface{}, err error) { - task.AddToCleanUp(func(_ context.Context) error { - clean++ - - return nil - }) - - return nil, nil - }) - tasks.Add(ts, "TaskFunc 3", func(task *tasks.Task, _ interface{}) (nextArgs interface{}, err error) { - task.AddToCleanUp(func(_ context.Context) error { - clean++ + return nil + }) - return nil - }) + return nil, nil + }, + ) + tasks.Add( + ts, + "TaskFunc 2", + func(task *tasks.Task, _ interface{}) (nextArgs interface{}, err error) { + task.AddToCleanUp(func(_ context.Context) error { + clean++ + + return nil + }) - return nil, errors.New("fail") - }) + return nil, nil + }, + ) + tasks.Add( + ts, + "TaskFunc 3", + func(task *tasks.Task, _ interface{}) (nextArgs interface{}, err error) { + task.AddToCleanUp(func(_ context.Context) error { + clean++ + + return nil + }) + + return nil, errors.New("fail") + }, + ) _, err := ts.Execute(t.Context(), nil) require.Error(t, err, "Execute should return error after cleanup") @@ -100,48 +124,60 @@ func TestCleanupOnContext(t *testing.T) { clean := 0 ctx := t.Context() - tasks.Add(ts, "TaskFunc 1", func(task *tasks.Task, _ interface{}) (nextArgs interface{}, err error) { - task.AddToCleanUp(func(_ context.Context) error { - clean++ - - return nil - }) - - return nil, nil - }) - tasks.Add(ts, "TaskFunc 2", func(task *tasks.Task, _ interface{}) (nextArgs interface{}, err error) { - task.AddToCleanUp(func(_ context.Context) error { - clean++ + tasks.Add( + ts, + "TaskFunc 1", + func(task *tasks.Task, _ interface{}) (nextArgs interface{}, err error) { + task.AddToCleanUp(func(_ context.Context) error { + clean++ - return nil - }) + return nil + }) - return nil, nil - }) - tasks.Add(ts, "TaskFunc 3", func(task *tasks.Task, _ interface{}) (nextArgs interface{}, err error) { - task.AddToCleanUp(func(_ context.Context) error { - clean++ - - return nil - }) - p, err := os.FindProcess(os.Getpid()) - if err != nil { - return nil, err - } - - // Interrupt tasks, as done with Ctrl-C - err = p.Signal(os.Interrupt) - if err != nil { - t.Fatal(err) - } + return nil, nil + }, + ) + tasks.Add( + ts, + "TaskFunc 2", + func(task *tasks.Task, _ interface{}) (nextArgs interface{}, err error) { + task.AddToCleanUp(func(_ context.Context) error { + clean++ + + return nil + }) - select { - case <-task.Ctx.Done(): - return nil, errors.New("interrupted") - case <-time.After(time.Second * 3): return nil, nil - } - }) + }, + ) + tasks.Add( + ts, + "TaskFunc 3", + func(task *tasks.Task, _ interface{}) (nextArgs interface{}, err error) { + task.AddToCleanUp(func(_ context.Context) error { + clean++ + + return nil + }) + p, err := os.FindProcess(os.Getpid()) + if err != nil { + return nil, err + } + + // Interrupt tasks, as done with Ctrl-C + err = p.Signal(os.Interrupt) + if err != nil { + t.Fatal(err) + } + + select { + case <-task.Ctx.Done(): + return nil, errors.New("interrupted") + case <-time.After(time.Second * 3): + return nil, nil + } + }, + ) _, err := ts.Execute(ctx, nil) require.Error(t, err, "context should have been interrupted") From f61770d32b0dddaeda2e964c3cd2c7af3791c9cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20L=C3=A9one?= Date: Tue, 1 Apr 2025 18:03:20 +0200 Subject: [PATCH 03/24] Fix --- .github/workflows/golangci-lint.yml | 2 +- .golangci.yml | 26 +------------------------- internal/editor/reflect.go | 2 +- 3 files changed, 3 insertions(+), 27 deletions(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 3dd3a9ebc6..8a3a37f479 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -9,7 +9,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: golangci-lint - uses: golangci/golangci-lint-action@v6 + uses: golangci/golangci-lint-action@v7 with: # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. version: latest diff --git a/.golangci.yml b/.golangci.yml index 18ba0990cb..6e62ffe0b7 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -13,6 +13,7 @@ formatters: - golines linters: + default: none # Run golangci-lint linters to see the list of all linters # Please keep them sorted alphabetically enable: @@ -25,7 +26,6 @@ linters: - decorder # check declaration order and count of types, constants, variables and functions [fast: true, auto-fix: false] - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) [fast: true, auto-fix: false] - durationcheck # check for two durations multiplied together [fast: false, auto-fix: false] - - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases [fast: false, auto-fix: false] - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted. [fast: false, auto-fix: false] - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. [fast: false, auto-fix: false] - exptostd # Detects functions from golang.org/x/exp/ that can be replaced by std functions. [auto-fix] @@ -38,7 +38,6 @@ linters: - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. [fast: true, auto-fix: false] - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. [fast: true, auto-fix: false] - goprintffuncname # Checks that printf-like functions are named with `f` at the end [fast: true, auto-fix: false] - - gosec #(gas): Inspects source code for security problems [fast: false, auto-fix: false] - govet #(vet, vetshadow): Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string [fast: false, auto-fix: false] - grouper # An analyzer to analyze expression groups. [fast: true, auto-fix: false] - importas # Enforces consistent import aliases [fast: false, auto-fix: false] @@ -63,7 +62,6 @@ linters: - revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. [fast: false, auto-fix: false] - rowserrcheck # checks whether Err of rows is checked successfully [fast: false, auto-fix: false] - sloglint # ensure consistent code style when using log/slog [fast: false, auto-fix: false] - - staticcheck - tagalign # check that struct tags are well aligned [fast: true, auto-fix: true] - testifylint # Checks usage of github.com/stretchr/testify. [fast: false, auto-fix: false] - testpackage # linter that makes you use a separate _test package [fast: true, auto-fix: false] @@ -78,28 +76,6 @@ linters: - whitespace # Tool for detection of leading and trailing whitespace [fast: true, auto-fix: true] - zerologlint # Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg` [fast: false, auto-fix: false] - disable: - - cyclop # checks function and package cyclomatic complexity [fast: false, auto-fix: false] - - depguard # Go linter that checks if package imports are in a list of acceptable packages [fast: true, auto-fix: false] - - dupl # Tool for code clone detection [fast: true, auto-fix: false] - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. [fast: false, auto-fix: false] - - exhaustive # check exhaustiveness of enum switch statements [fast: false, auto-fix: false] - - forcetypeassert # finds forced type assertions [fast: true, auto-fix: false] - - funlen # Tool for detection of long functions [fast: true, auto-fix: false] - - gochecknoglobals # check that no global variables exist [fast: true, auto-fix: false] - - gochecknoinits # Checks that no init functions are present in Go code [fast: true, auto-fix: false] - - gocognit # Computes and checks the cognitive complexity of functions [fast: true, auto-fix: false] - - godot # Check if comments end in a period [fast: true, auto-fix: true] - - godox # Tool for detection of FIXME, TODO and other comment keywords [fast: true, auto-fix: false] - - err113 # Golang linter to check the errors handling expressions [fast: false, auto-fix: false] - - lll # Reports long lines [fast: true, auto-fix: false] - - maintidx # maintidx measures the maintainability index of each function. [fast: true, auto-fix: false] - - nestif # Reports deeply nested if statements [fast: true, auto-fix: false] - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. [fast: false, auto-fix: false] - - varnamelen # checks that the length of a variable's name matches its scope [fast: false, auto-fix: false] - - wsl # Whitespace Linter - Forces you to use empty lines! [fast: true, auto-fix: false] - - settings: goconst: min-len: 5 diff --git a/internal/editor/reflect.go b/internal/editor/reflect.go index 053d206d50..4045f71262 100644 --- a/internal/editor/reflect.go +++ b/internal/editor/reflect.go @@ -111,7 +111,7 @@ func MapWithTag(includeFields ...string) ValueMapperOpt { // MapWithTag will map only fields that don't have one of these tags as json tag // -//nolint:deadcode,unused +//nolint:unused func mapWithoutTag(excludeFields ...string) ValueMapperOpt { return func(cfg *valueMapperConfig) { cfg.excludeFields = append(cfg.excludeFields, excludeFields...) From ab66efc5a14cab242aba3742424736afe5cc077d Mon Sep 17 00:00:00 2001 From: Scaleway Bot Date: Tue, 25 Mar 2025 18:28:26 +0100 Subject: [PATCH 04/24] feat(vpc_gw): enable CLI generation for v2 (#4612) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Rémy Léone --- docs/commands/interlink.md | 491 ++++++++ go.mod | 2 +- go.sum | 4 +- internal/namespaces/vpcgw/v2/vpcgw_cli.go | 1243 +++++++++++++++++++++ 4 files changed, 1737 insertions(+), 3 deletions(-) create mode 100644 docs/commands/interlink.md create mode 100644 internal/namespaces/vpcgw/v2/vpcgw_cli.go diff --git a/docs/commands/interlink.md b/docs/commands/interlink.md new file mode 100644 index 0000000000..57fb4e8658 --- /dev/null +++ b/docs/commands/interlink.md @@ -0,0 +1,491 @@ + +# Documentation for `scw interlink` +This API allows you to manage your InterLink services. + +- [Links commands](#links-commands) + - [Attach a routing policy](#attach-a-routing-policy) + - [Attach a VPC](#attach-a-vpc) + - [Create a link](#create-a-link) + - [Delete a link](#delete-a-link) + - [Detach a routing policy](#detach-a-routing-policy) + - [Detach a VPC](#detach-a-vpc) + - [Disable route propagation](#disable-route-propagation) + - [Enable route propagation](#enable-route-propagation) + - [Get a link](#get-a-link) + - [List links](#list-links) + - [Update a link](#update-a-link) +- [Partners commands](#partners-commands) + - [Get a partner](#get-a-partner) + - [List available partners](#list-available-partners) +- [PoP commands](#pop-commands) + - [Get a PoP](#get-a-pop) + - [List PoPs](#list-pops) +- [Routing policies commands](#routing-policies-commands) + - [Create a routing policy](#create-a-routing-policy) + - [Delete a routing policy](#delete-a-routing-policy) + - [Get routing policy](#get-routing-policy) + - [List routing policies](#list-routing-policies) + - [Update a routing policy](#update-a-routing-policy) + + +## Links commands + +Links commands. + + +### Attach a routing policy + +Attach a routing policy to an existing link. As all routes across the link are blocked by default, you must attach a routing policy to set IP prefix filters for allowed routes, facilitating traffic flow. + +**Usage:** + +``` +scw interlink link attach_policy [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| link-id | Required | ID of the link to attach a routing policy to | +| routing-policy-id | Required | ID of the routing policy to be attached | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### Attach a VPC + +Attach a VPC to an existing link. This facilitates communication between the resources in your Scaleway VPC, and your on-premises infrastructure. + +**Usage:** + +``` +scw interlink link attach_vpc [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| link-id | Required | ID of the link to attach VPC to | +| vpc-id | Required | ID of the VPC to attach | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### Create a link + +Create a link (InterLink connection) in a given PoP, specifying its various configuration details. For the moment only hosted links (faciliated by partners) are available, though in the future dedicated and shared links will also be possible. + +**Usage:** + +``` +scw interlink link create [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| project-id | | Project ID to use. If none is passed the default project ID will be used | +| name | Required | Name of the link | +| tags.{index} | | List of tags to apply to the link | +| pop-id | Required | PoP (location) where the link will be created | +| bandwidth-mbps | Required | Desired bandwidth for the link. Must be compatible with available link bandwidths and remaining bandwidth capacity of the port | +| dedicated | | If true, a dedicated link (1 link per port, dedicated to one customer) will be crated. It is not necessary to specify a `port_id` or `partner_id`. A new port will created and assigned to the link. Note that Scaleway has not yet enabled the creation of dedicated links, this field is reserved for future use. | +| port-id | | If set, a shared link (N links per port, one of which is this customer's port) will be created. As the customer, specify the ID of the port you already have for this link. Note that shared links are not currently available. Note that Scaleway has not yet enabled the creation of shared links, this field is reserved for future use. | +| partner-id | | If set, a hosted link (N links per port on a partner port) will be created. Specify the ID of the chosen partner, who already has a shareable port with available bandwidth. Note that this is currently the only type of link offered by Scaleway, and therefore this field must be set when creating a link. | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### Delete a link + +Delete an existing link, specified by its link ID. Note that as well as deleting the link here on the Scaleway side, it is also necessary to request deletion from the partner on their side. Only when this action has been carried out on both sides will the resource be completely deleted. + +**Usage:** + +``` +scw interlink link delete [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| link-id | Required | ID of the link to delete | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### Detach a routing policy + +Detach a routing policy from an existing link. Without a routing policy, all routes across the link are blocked by default. + +**Usage:** + +``` +scw interlink link detach_policy [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| link-id | Required | ID of the link to detach a routing policy from | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### Detach a VPC + +Detach a VPC from an existing link. + +**Usage:** + +``` +scw interlink link detach_vpc [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| link-id | Required | ID of the link to detach the VPC from | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### Disable route propagation + +Prevent any prefixes from being announced in the BGP session. Traffic will not be able to flow over the InterLink until route propagation is re-enabled. + +**Usage:** + +``` +scw interlink link disable_propagation [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| link-id | Required | ID of the link on which to disable route propagation | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### Enable route propagation + +Enable all allowed prefixes (defined in a routing policy) to be announced in the BGP session. This allows traffic to flow between the attached VPC and the on-premises infrastructure along the announced routes. Note that by default, even when route propagation is enabled, all routes are blocked. It is essential to attach a routing policy to define the ranges of routes to announce. + +**Usage:** + +``` +scw interlink link enable_propagation [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| link-id | Required | ID of the link on which to enable route propagation | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### Get a link + +Get a link (InterLink connection) for the given link ID. The response object includes information about the link's various configuration details. + +**Usage:** + +``` +scw interlink link get [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| link-id | Required | ID of the link to get | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### List links + +List all your links (InterLink connections). A number of filters are available, including Project ID, name, tags and status. + +**Usage:** + +``` +scw interlink link list [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| order-by | One of: `created_at_asc`, `created_at_desc`, `name_asc`, `name_desc`, `status_asc`, `status_desc` | Order in which to return results | +| project-id | | Project ID to filter for | +| name | | Link name to filter for | +| tags.{index} | | Tags to filter for | +| status | One of: `unknown_link_status`, `configuring`, `failed`, `requested`, `refused`, `expired`, `provisioning`, `active`, `limited_connectivity`, `all_down`, `deprovisioning`, `deleted`, `locked` | Link status to filter for | +| bgp-v4-status | One of: `unknown_bgp_status`, `up`, `down` | BGP IPv4 status to filter for | +| bgp-v6-status | One of: `unknown_bgp_status`, `up`, `down` | BGP IPv6 status to filter for | +| pop-id | | Filter for links attached to this PoP (via ports) | +| bandwidth-mbps | | Filter for link bandwidth (in Mbps) | +| partner-id | | Filter for links hosted by this partner | +| vpc-id | | Filter for links attached to this VPC | +| routing-policy-id | | Filter for links using this routing policy | +| pairing-key | | Filter for the link with this pairing_key | +| organization-id | | Organization ID to filter for | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw`, `all` | Region to target. If none is passed will use default region from the config | + + + +### Update a link + +Update an existing link, specified by its link ID. Only its name and tags can be updated. + +**Usage:** + +``` +scw interlink link update [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| link-id | Required | ID of the link to update | +| name | | Name of the link | +| tags.{index} | | List of tags to apply to the link | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +## Partners commands + +Partners commands. + + +### Get a partner + +Get a partner for the given partner IP. The response object includes information such as the partner's name, email address and portal URL. + +**Usage:** + +``` +scw interlink partner get [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| partner-id | Required | ID of partner to get | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### List available partners + +List all available partners. By default, the partners returned in the list are ordered by name in ascending order, though this can be modified via the `order_by` field. + +**Usage:** + +``` +scw interlink partner list [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| order-by | One of: `name_asc`, `name_desc` | Order in which to return results | +| pop-ids.{index} | | Filter for partners present (offering a port) in one of these PoPs | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw`, `all` | Region to target. If none is passed will use default region from the config | + + + +## PoP commands + +PoP commands. + + +### Get a PoP + +Get a PoP for the given PoP ID. The response object includes the PoP's name and information about its physical location. + +**Usage:** + +``` +scw interlink pop get [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| pop-id | Required | ID of PoP to get | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### List PoPs + +List all available PoPs (locations) for a given region. By default, the results are returned in ascending alphabetical order by name. + +**Usage:** + +``` +scw interlink pop list [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| order-by | One of: `name_asc`, `name_desc` | Order in which to return results | +| name | | PoP name to filter for | +| hosting-provider-name | | Hosting provider name to filter for | +| partner-id | | Filter for PoPs hosting an available shared port from this partner | +| link-bandwidth-mbps | | Filter for PoPs with a shared port allowing this bandwidth size. Note that we cannot guarantee that PoPs returned will have available capacity. | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw`, `all` | Region to target. If none is passed will use default region from the config | + + + +## Routing policies commands + +Routing policies commands. + + +### Create a routing policy + +Create a routing policy. Routing policies allow you to set IP prefix filters to define the incoming route announcements to accept from the peer, and the outgoing routes to announce to the peer. + +**Usage:** + +``` +scw interlink routing-policy create [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| project-id | | Project ID to use. If none is passed the default project ID will be used | +| name | Required | Name of the routing policy | +| tags.{index} | | List of tags to apply to the routing policy | +| prefix-filter-in.{index} | | IP prefixes to accept from the peer (ranges of route announcements to accept) | +| prefix-filter-out.{index} | | IP prefix filters to advertise to the peer (ranges of routes to advertise) | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### Delete a routing policy + +Delete an existing routing policy, specified by its routing policy ID. + +**Usage:** + +``` +scw interlink routing-policy delete [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| routing-policy-id | Required | ID of the routing policy to delete | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### Get routing policy + +Get a routing policy for the given routing policy ID. The response object gives information including the policy's name, tags and prefix filters. + +**Usage:** + +``` +scw interlink routing-policy get [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| routing-policy-id | Required | ID of the routing policy to get | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + +### List routing policies + +List all routing policies in a given region. A routing policy can be attached to one or multiple links (InterLink connections). + +**Usage:** + +``` +scw interlink routing-policy list [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| order-by | One of: `created_at_asc`, `created_at_desc`, `name_asc`, `name_desc` | Order in which to return results | +| project-id | | Project ID to filter for | +| name | | Routing policy name to filter for | +| tags.{index} | | Tags to filter for | +| organization-id | | Organization ID to filter for | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw`, `all` | Region to target. If none is passed will use default region from the config | + + + +### Update a routing policy + +Update an existing routing policy, specified by its routing policy ID. Its name, tags and incoming/outgoing prefix filters can be updated. + +**Usage:** + +``` +scw interlink routing-policy update [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| routing-policy-id | Required | ID of the routing policy to update | +| name | | Name of the routing policy | +| tags.{index} | | List of tags to apply to the routing policy | +| prefix-filter-in.{index} | | IP prefixes to accept from the peer (ranges of route announcements to accept) | +| prefix-filter-out.{index} | | IP prefix filters for routes to advertise to the peer (ranges of routes to advertise) | +| region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | + + + diff --git a/go.mod b/go.mod index 37281f747e..1b4f4baff1 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,7 @@ require ( github.com/mattn/go-isatty v0.0.20 github.com/moby/buildkit v0.13.2 github.com/opencontainers/go-digest v1.0.0 - github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250320154743-e4b083248f79 + github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250324094923-50c5f738c4d6 github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 github.com/spf13/cobra v1.9.1 github.com/spf13/pflag v1.0.6 diff --git a/go.sum b/go.sum index d95e8b2356..9ef594e52d 100644 --- a/go.sum +++ b/go.sum @@ -462,8 +462,8 @@ github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUz github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 h1:OkMGxebDjyw0ULyrTYWeN0UNCCkmCWfjPnIA2W6oviI= github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06/go.mod h1:+ePHsJ1keEjQtpvf9HHw0f4ZeJ0TLRsxhunSI2hYJSs= -github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250320154743-e4b083248f79 h1:6gWhYDQblqaIYxEYwJDkcJbvqnKmz6uHwrYcxOeMZ7s= -github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250320154743-e4b083248f79/go.mod h1:792k1RTU+5JeMXm35/e2Wgp71qPH/DmDoZrRc+EFZDk= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250324094923-50c5f738c4d6 h1:qbiYj4oaF8rke2GNsdCYrECYyqQsbCwrkjahT/9/I04= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250324094923-50c5f738c4d6/go.mod h1:792k1RTU+5JeMXm35/e2Wgp71qPH/DmDoZrRc+EFZDk= github.com/sclevine/spec v1.4.0 h1:z/Q9idDcay5m5irkZ28M7PtQM4aOISzOpj4bUPkDee8= github.com/sclevine/spec v1.4.0/go.mod h1:LvpgJaFyvQzRvc1kaDs0bulYwzC70PbiYjC4QnFHkOM= github.com/secure-systems-lab/go-securesystemslib v0.8.0 h1:mr5An6X45Kb2nddcFlbmfHkLguCE9laoZCUzEEpIZXA= diff --git a/internal/namespaces/vpcgw/v2/vpcgw_cli.go b/internal/namespaces/vpcgw/v2/vpcgw_cli.go new file mode 100644 index 0000000000..14f21cf803 --- /dev/null +++ b/internal/namespaces/vpcgw/v2/vpcgw_cli.go @@ -0,0 +1,1243 @@ +// This file was automatically generated. DO NOT EDIT. +// If you have any remark or suggestion do not hesitate to open an issue. + +package vpcgw + +import ( + "context" + "reflect" + + "github.com/scaleway/scaleway-cli/v2/core" + "github.com/scaleway/scaleway-sdk-go/api/vpcgw/v2" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +// always import dependencies +var ( + _ = scw.RegionFrPar +) + +func GetGeneratedCommands() *core.Commands { + return core.NewCommands( + vpcGwRoot(), + vpcGwGateway(), + vpcGwGatewayNetwork(), + vpcGwPatRule(), + vpcGwIP(), + vpcGwGatewayType(), + vpcGwGatewayList(), + vpcGwGatewayGet(), + vpcGwGatewayCreate(), + vpcGwGatewayUpdate(), + vpcGwGatewayDelete(), + vpcGwGatewayUpgrade(), + vpcGwGatewayNetworkList(), + vpcGwGatewayNetworkGet(), + vpcGwGatewayNetworkCreate(), + vpcGwGatewayNetworkUpdate(), + vpcGwGatewayNetworkDelete(), + vpcGwPatRuleList(), + vpcGwPatRuleGet(), + vpcGwPatRuleCreate(), + vpcGwPatRuleUpdate(), + vpcGwPatRuleSet(), + vpcGwPatRuleDelete(), + vpcGwGatewayTypeList(), + vpcGwIPList(), + vpcGwIPGet(), + vpcGwIPCreate(), + vpcGwIPUpdate(), + vpcGwIPDelete(), + vpcGwGatewayRefreshSSHKeys(), + ) +} +func vpcGwRoot() *core.Command { + return &core.Command{ + Short: `This API allows you to manage your Public Gateways`, + Long: `This API allows you to manage your Public Gateways.`, + Namespace: "vpc-gw", + } +} + +func vpcGwGateway() *core.Command { + return &core.Command{ + Short: `Public Gateway management`, + Long: `Public Gateways are building blocks for your infrastructure on Scaleway's shared public cloud. They provide a set of managed network services and features for Scaleway's Private Networks such NAT and PAT rules.`, + Namespace: "vpc-gw", + Resource: "gateway", + } +} + +func vpcGwGatewayNetwork() *core.Command { + return &core.Command{ + Short: `Gateway Networks management`, + Long: `A Gateway Network represents the connection of a Private Network to a Public Gateway.`, + Namespace: "vpc-gw", + Resource: "gateway-network", + } +} + +func vpcGwPatRule() *core.Command { + return &core.Command{ + Short: `PAT rules management`, + Long: `PAT (Port Address Translation) rules, aka static NAT rules, belong to a specified Public Gateway. They define the forwarding of a public port to a specific device on a Private Network, enabling enables ingress traffic from the public Internet to reach the correct device in the Private Network.`, + Namespace: "vpc-gw", + Resource: "pat-rule", + } +} + +func vpcGwIP() *core.Command { + return &core.Command{ + Short: `IP address management`, + Long: `Public, flexible IP addresses for Public Gateways, allowing the gateway to reach the public internet, as well as forward (masquerade) traffic from member devices of attached Private Networks.`, + Namespace: "vpc-gw", + Resource: "ip", + } +} + +func vpcGwGatewayType() *core.Command { + return &core.Command{ + Short: `Gateway types information`, + Long: `Public Gateways come in various shapes, sizes and prices, which are described by gateway types. They represent the different commercial offer types for Public Gateways available at Scaleway.`, + Namespace: "vpc-gw", + Resource: "gateway-type", + } +} + +func vpcGwGatewayList() *core.Command { + return &core.Command{ + Short: `List Public Gateways`, + Long: `List Public Gateways in a given Scaleway Organization or Project. By default, results are displayed in ascending order of creation date.`, + Namespace: "vpc-gw", + Resource: "gateway", + Verb: "list", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.ListGatewaysRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "order-by", + Short: `Order in which to return results`, + Required: false, + Deprecated: false, + Positional: false, + EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "type_asc", "type_desc", "status_asc", "status_desc"}, + }, + { + Name: "project-id", + Short: `Include only gateways in this Project`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "name", + Short: `Filter for gateways which have this search term in their name`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "tags.{index}", + Short: `Filter for gateways with these tags`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "types.{index}", + Short: `Filter for gateways of these types`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "status.{index}", + Short: `Filter for gateways with these status. Use ` + "`" + `unknown` + "`" + ` to include all statuses`, + Required: false, + Deprecated: false, + Positional: false, + EnumValues: []string{"unknown_status", "stopped", "allocating", "configuring", "running", "stopping", "failed", "deleting", "locked"}, + }, + { + Name: "private-network-ids.{index}", + Short: `Filter for gateways attached to these Private Networks`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "include-legacy", + Short: `Include also legacy gateways`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "organization-id", + Short: `Include only gateways in this Organization`, + Required: false, + Deprecated: false, + Positional: false, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.ListGatewaysRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + opts := []scw.RequestOption{scw.WithAllPages()} + if request.Zone == scw.Zone(core.AllLocalities) { + opts = append(opts, scw.WithZones(api.Zones()...)) + request.Zone = "" + } + resp, err := api.ListGateways(request, opts...) + if err != nil { + return nil, err + } + return resp.Gateways, nil + }, + } +} + +func vpcGwGatewayGet() *core.Command { + return &core.Command{ + Short: `Get a Public Gateway`, + Long: `Get details of a Public Gateway, specified by its gateway ID. The response object contains full details of the gateway, including its **name**, **type**, **status** and more.`, + Namespace: "vpc-gw", + Resource: "gateway", + Verb: "get", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.GetGatewayRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "gateway-id", + Short: `ID of the gateway to fetch`, + Required: true, + Deprecated: false, + Positional: true, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.GetGatewayRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.GetGateway(request) + }, + } +} + +func vpcGwGatewayCreate() *core.Command { + return &core.Command{ + Short: `Create a Public Gateway`, + Long: `Create a new Public Gateway in the specified Scaleway Project, defining its **name**, **type** and other configuration details such as whether to enable SSH bastion.`, + Namespace: "vpc-gw", + Resource: "gateway", + Verb: "create", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.CreateGatewayRequest{}), + ArgSpecs: core.ArgSpecs{ + core.ProjectIDArgSpec(), + { + Name: "name", + Short: `Name for the gateway`, + Required: false, + Deprecated: false, + Positional: false, + Default: core.RandomValueGenerator("gw"), + }, + { + Name: "tags.{index}", + Short: `Tags for the gateway`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "type", + Short: `Gateway type (commercial offer type)`, + Required: false, + Deprecated: false, + Positional: false, + Default: core.DefaultValueSetter("VPC-GW-S"), + }, + { + Name: "ip-id", + Short: `Existing IP address to attach to the gateway`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "enable-smtp", + Short: `Defines whether SMTP traffic should be allowed pass through the gateway`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "enable-bastion", + Short: `Defines whether SSH bastion should be enabled the gateway`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "bastion-port", + Short: `Port of the SSH bastion`, + Required: false, + Deprecated: false, + Positional: false, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.CreateGatewayRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.CreateGateway(request) + }, + } +} + +func vpcGwGatewayUpdate() *core.Command { + return &core.Command{ + Short: `Update a Public Gateway`, + Long: `Update the parameters of an existing Public Gateway, for example, its **name**, **tags**, **SSH bastion configuration**, and **DNS servers**.`, + Namespace: "vpc-gw", + Resource: "gateway", + Verb: "update", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.UpdateGatewayRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "gateway-id", + Short: `ID of the gateway to update`, + Required: true, + Deprecated: false, + Positional: true, + }, + { + Name: "name", + Short: `Name for the gateway`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "tags.{index}", + Short: `Tags for the gateway`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "enable-bastion", + Short: `Defines whether SSH bastion should be enabled the gateway`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "bastion-port", + Short: `Port of the SSH bastion`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "enable-smtp", + Short: `Defines whether SMTP traffic should be allowed to pass through the gateway`, + Required: false, + Deprecated: false, + Positional: false, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.UpdateGatewayRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.UpdateGateway(request) + }, + } +} + +func vpcGwGatewayDelete() *core.Command { + return &core.Command{ + Short: `Delete a Public Gateway`, + Long: `Delete an existing Public Gateway, specified by its gateway ID. This action is irreversible.`, + Namespace: "vpc-gw", + Resource: "gateway", + Verb: "delete", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.DeleteGatewayRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "gateway-id", + Short: `ID of the gateway to delete`, + Required: true, + Deprecated: false, + Positional: true, + }, + { + Name: "delete-ip", + Short: `Defines whether the PGW's IP should be deleted`, + Required: false, + Deprecated: false, + Positional: false, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.DeleteGatewayRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.DeleteGateway(request) + }, + } +} + +func vpcGwGatewayUpgrade() *core.Command { + return &core.Command{ + Short: `Upgrade a Public Gateway to the latest version and/or to a different commercial offer type`, + Long: `Upgrade a given Public Gateway to the newest software version or to a different commercial offer type. This applies the latest bugfixes and features to your Public Gateway. Note that gateway service will be interrupted during the update.`, + Namespace: "vpc-gw", + Resource: "gateway", + Verb: "upgrade", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.UpgradeGatewayRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "gateway-id", + Short: `ID of the gateway to upgrade`, + Required: true, + Deprecated: false, + Positional: true, + }, + { + Name: "type", + Short: `Gateway type (commercial offer)`, + Required: false, + Deprecated: false, + Positional: false, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.UpgradeGatewayRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.UpgradeGateway(request) + }, + } +} + +func vpcGwGatewayNetworkList() *core.Command { + return &core.Command{ + Short: `List Public Gateway connections to Private Networks`, + Long: `List the connections between Public Gateways and Private Networks (a connection = a GatewayNetwork). You can choose to filter by ` + "`" + `gateway-id` + "`" + ` to list all Private Networks attached to the specified Public Gateway, or by ` + "`" + `private_network_id` + "`" + ` to list all Public Gateways attached to the specified Private Network. Other query parameters are also available. The result is an array of GatewayNetwork objects, each giving details of the connection between a given Public Gateway and a given Private Network.`, + Namespace: "vpc-gw", + Resource: "gateway-network", + Verb: "list", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.ListGatewayNetworksRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "order-by", + Short: `Order in which to return results`, + Required: false, + Deprecated: false, + Positional: false, + EnumValues: []string{"created_at_asc", "created_at_desc", "status_asc", "status_desc"}, + }, + { + Name: "status.{index}", + Short: `Filter for GatewayNetworks with these status. Use ` + "`" + `unknown` + "`" + ` to include all statuses`, + Required: false, + Deprecated: false, + Positional: false, + EnumValues: []string{"unknown_status", "created", "attaching", "configuring", "ready", "detaching"}, + }, + { + Name: "gateway-ids.{index}", + Short: `Filter for GatewayNetworks connected to these gateways`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "private-network-ids.{index}", + Short: `Filter for GatewayNetworks connected to these Private Networks`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "masquerade-enabled", + Short: `Filter for GatewayNetworks with this ` + "`" + `enable_masquerade` + "`" + ` setting`, + Required: false, + Deprecated: false, + Positional: false, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.ListGatewayNetworksRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + opts := []scw.RequestOption{scw.WithAllPages()} + if request.Zone == scw.Zone(core.AllLocalities) { + opts = append(opts, scw.WithZones(api.Zones()...)) + request.Zone = "" + } + resp, err := api.ListGatewayNetworks(request, opts...) + if err != nil { + return nil, err + } + return resp.GatewayNetworks, nil + }, + } +} + +func vpcGwGatewayNetworkGet() *core.Command { + return &core.Command{ + Short: `Get a Public Gateway connection to a Private Network`, + Long: `Get details of a given connection between a Public Gateway and a Private Network (this connection = a GatewayNetwork), specified by its ` + "`" + `gateway_network_id` + "`" + `. The response object contains details of the connection including the IDs of the Public Gateway and Private Network, the dates the connection was created/updated and its configuration settings.`, + Namespace: "vpc-gw", + Resource: "gateway-network", + Verb: "get", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.GetGatewayNetworkRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "gateway-network-id", + Short: `ID of the GatewayNetwork to fetch`, + Required: true, + Deprecated: false, + Positional: true, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.GetGatewayNetworkRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.GetGatewayNetwork(request) + }, + } +} + +func vpcGwGatewayNetworkCreate() *core.Command { + return &core.Command{ + Short: `Attach a Public Gateway to a Private Network`, + Long: `Attach a specific Public Gateway to a specific Private Network (create a GatewayNetwork). You can configure parameters for the connection including whether to enable masquerade (dynamic NAT), and more.`, + Namespace: "vpc-gw", + Resource: "gateway-network", + Verb: "create", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.CreateGatewayNetworkRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "gateway-id", + Short: `Public Gateway to connect`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "private-network-id", + Short: `Private Network to connect`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "enable-masquerade", + Short: `Defines whether to enable masquerade (dynamic NAT) on the GatewayNetwork.`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "push-default-route", + Short: `Enabling the default route also enables masquerading`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "ipam-ip-id", + Short: `Use this IPAM-booked IP ID as the Gateway's IP in this Private Network`, + Required: false, + Deprecated: false, + Positional: false, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.CreateGatewayNetworkRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.CreateGatewayNetwork(request) + }, + } +} + +func vpcGwGatewayNetworkUpdate() *core.Command { + return &core.Command{ + Short: `Update a Public Gateway's connection to a Private Network`, + Long: `Update the configuration parameters of a connection between a given Public Gateway and Private Network (the connection = a GatewayNetwork). Updatable parameters include whether to enable traffic masquerade (dynamic NAT).`, + Namespace: "vpc-gw", + Resource: "gateway-network", + Verb: "update", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.UpdateGatewayNetworkRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "gateway-network-id", + Short: `ID of the GatewayNetwork to update`, + Required: true, + Deprecated: false, + Positional: true, + }, + { + Name: "enable-masquerade", + Short: `Defines whether to enable masquerade (dynamic NAT) on the GatewayNetwork.`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "push-default-route", + Short: `Enabling the default route also enables masquerading`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "ipam-ip-id", + Short: `Use this IPAM-booked IP ID as the Gateway's IP in this Private Network`, + Required: false, + Deprecated: false, + Positional: false, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.UpdateGatewayNetworkRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.UpdateGatewayNetwork(request) + }, + } +} + +func vpcGwGatewayNetworkDelete() *core.Command { + return &core.Command{ + Short: `Detach a Public Gateway from a Private Network`, + Long: `Detach a given Public Gateway from a given Private Network, i.e. delete a GatewayNetwork specified by a gateway_network_id.`, + Namespace: "vpc-gw", + Resource: "gateway-network", + Verb: "delete", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.DeleteGatewayNetworkRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "gateway-network-id", + Short: `ID of the GatewayNetwork to delete`, + Required: true, + Deprecated: false, + Positional: true, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.DeleteGatewayNetworkRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.DeleteGatewayNetwork(request) + }, + } +} + +func vpcGwPatRuleList() *core.Command { + return &core.Command{ + Short: `List PAT rules`, + Long: `List PAT rules. You can filter by gateway ID to list all PAT rules for a particular gateway, or filter for PAT rules targeting a specific IP address or using a specific protocol.`, + Namespace: "vpc-gw", + Resource: "pat-rule", + Verb: "list", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.ListPatRulesRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "order-by", + Short: `Order in which to return results`, + Required: false, + Deprecated: false, + Positional: false, + EnumValues: []string{"created_at_asc", "created_at_desc", "public_port_asc", "public_port_desc"}, + }, + { + Name: "gateway-ids.{index}", + Short: `Filter for PAT rules on these gateways`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "private-ips.{index}", + Short: `Filter for PAT rules targeting these private ips`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "protocol", + Short: `Filter for PAT rules with this protocol`, + Required: false, + Deprecated: false, + Positional: false, + EnumValues: []string{"unknown_protocol", "both", "tcp", "udp"}, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.ListPatRulesRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + opts := []scw.RequestOption{scw.WithAllPages()} + if request.Zone == scw.Zone(core.AllLocalities) { + opts = append(opts, scw.WithZones(api.Zones()...)) + request.Zone = "" + } + resp, err := api.ListPatRules(request, opts...) + if err != nil { + return nil, err + } + return resp.PatRules, nil + }, + } +} + +func vpcGwPatRuleGet() *core.Command { + return &core.Command{ + Short: `Get a PAT rule`, + Long: `Get a PAT rule, specified by its PAT rule ID. The response object gives full details of the PAT rule, including the Public Gateway it belongs to and the configuration settings in terms of public / private ports, private IP and protocol.`, + Namespace: "vpc-gw", + Resource: "pat-rule", + Verb: "get", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.GetPatRuleRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "pat-rule-id", + Short: `ID of the PAT rule to get`, + Required: true, + Deprecated: false, + Positional: true, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.GetPatRuleRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.GetPatRule(request) + }, + } +} + +func vpcGwPatRuleCreate() *core.Command { + return &core.Command{ + Short: `Create a PAT rule`, + Long: `Create a new PAT rule on a specified Public Gateway, defining the protocol to use, public port to listen on, and private port / IP address to map to.`, + Namespace: "vpc-gw", + Resource: "pat-rule", + Verb: "create", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.CreatePatRuleRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "gateway-id", + Short: `ID of the Gateway on which to create the rule`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "public-port", + Short: `Public port to listen on`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "private-ip", + Short: `Private IP to forward data to`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "private-port", + Short: `Private port to translate to`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "protocol", + Short: `Protocol the rule should apply to`, + Required: false, + Deprecated: false, + Positional: false, + EnumValues: []string{"unknown_protocol", "both", "tcp", "udp"}, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.CreatePatRuleRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.CreatePatRule(request) + }, + } +} + +func vpcGwPatRuleUpdate() *core.Command { + return &core.Command{ + Short: `Update a PAT rule`, + Long: `Update a PAT rule, specified by its PAT rule ID. Configuration settings including private/public port, private IP address and protocol can all be updated.`, + Namespace: "vpc-gw", + Resource: "pat-rule", + Verb: "update", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.UpdatePatRuleRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "pat-rule-id", + Short: `ID of the PAT rule to update`, + Required: true, + Deprecated: false, + Positional: true, + }, + { + Name: "public-port", + Short: `Public port to listen on`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "private-ip", + Short: `Private IP to forward data to`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "private-port", + Short: `Private port to translate to`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "protocol", + Short: `Protocol the rule should apply to`, + Required: false, + Deprecated: false, + Positional: false, + EnumValues: []string{"unknown_protocol", "both", "tcp", "udp"}, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.UpdatePatRuleRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.UpdatePatRule(request) + }, + } +} + +func vpcGwPatRuleSet() *core.Command { + return &core.Command{ + Short: `Set all PAT rules`, + Long: `Set a definitive list of PAT rules attached to a Public Gateway. Each rule is identified by its public port and protocol. This will sync the current PAT rule list on the gateway with the new list, creating, updating or deleting PAT rules accordingly.`, + Namespace: "vpc-gw", + Resource: "pat-rule", + Verb: "set", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.SetPatRulesRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "gateway-id", + Short: `ID of the gateway on which to set the PAT rules`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "pat-rules.{index}.public-port", + Short: `Public port to listen on`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "pat-rules.{index}.private-ip", + Short: `Private IP to forward data to`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "pat-rules.{index}.private-port", + Short: `Private port to translate to`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "pat-rules.{index}.protocol", + Short: `Protocol the rule should apply to`, + Required: false, + Deprecated: false, + Positional: false, + EnumValues: []string{"unknown_protocol", "both", "tcp", "udp"}, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.SetPatRulesRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.SetPatRules(request) + }, + } +} + +func vpcGwPatRuleDelete() *core.Command { + return &core.Command{ + Short: `Delete a PAT rule`, + Long: `Delete a PAT rule, identified by its PAT rule ID. This action is irreversible.`, + Namespace: "vpc-gw", + Resource: "pat-rule", + Verb: "delete", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.DeletePatRuleRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "pat-rule-id", + Short: `ID of the PAT rule to delete`, + Required: true, + Deprecated: false, + Positional: true, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.DeletePatRuleRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + e = api.DeletePatRule(request) + if e != nil { + return nil, e + } + return &core.SuccessResult{ + Resource: "pat-rule", + Verb: "delete", + }, nil + }, + } +} + +func vpcGwGatewayTypeList() *core.Command { + return &core.Command{ + Short: `List Public Gateway types`, + Long: `List the different Public Gateway commercial offer types available at Scaleway. The response is an array of objects describing the name and technical details of each available gateway type.`, + Namespace: "vpc-gw", + Resource: "gateway-type", + Verb: "list", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.ListGatewayTypesRequest{}), + ArgSpecs: core.ArgSpecs{ + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.ListGatewayTypesRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.ListGatewayTypes(request) + }, + } +} + +func vpcGwIPList() *core.Command { + return &core.Command{ + Short: `List IPs`, + Long: `List Public Gateway flexible IP addresses. A number of filter options are available for limiting results in the response.`, + Namespace: "vpc-gw", + Resource: "ip", + Verb: "list", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.ListIPsRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "order-by", + Short: `Order in which to return results`, + Required: false, + Deprecated: false, + Positional: false, + EnumValues: []string{"created_at_asc", "created_at_desc", "address_asc", "address_desc", "reverse_asc", "reverse_desc"}, + }, + { + Name: "project-id", + Short: `Filter for IP addresses in this Project`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "tags.{index}", + Short: `Filter for IP addresses with these tags`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "reverse", + Short: `Filter for IP addresses that have a reverse containing this string`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "is-free", + Short: `Filter based on whether the IP is attached to a gateway or not`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "organization-id", + Short: `Include only gateways in this Organization`, + Required: false, + Deprecated: false, + Positional: false, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.ListIPsRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + opts := []scw.RequestOption{scw.WithAllPages()} + if request.Zone == scw.Zone(core.AllLocalities) { + opts = append(opts, scw.WithZones(api.Zones()...)) + request.Zone = "" + } + resp, err := api.ListIPs(request, opts...) + if err != nil { + return nil, err + } + return resp.IPs, nil + }, + } +} + +func vpcGwIPGet() *core.Command { + return &core.Command{ + Short: `Get an IP`, + Long: `Get details of a Public Gateway flexible IP address, identified by its IP ID. The response object contains information including which (if any) Public Gateway using this IP address, the reverse and various other metadata.`, + Namespace: "vpc-gw", + Resource: "ip", + Verb: "get", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.GetIPRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "ip-id", + Short: `ID of the IP address to get`, + Required: true, + Deprecated: false, + Positional: true, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.GetIPRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.GetIP(request) + }, + } +} + +func vpcGwIPCreate() *core.Command { + return &core.Command{ + Short: `Reserve an IP`, + Long: `Create (reserve) a new flexible IP address that can be used for a Public Gateway in a specified Scaleway Project.`, + Namespace: "vpc-gw", + Resource: "ip", + Verb: "create", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.CreateIPRequest{}), + ArgSpecs: core.ArgSpecs{ + core.ProjectIDArgSpec(), + { + Name: "tags.{index}", + Short: `Tags to give to the IP address`, + Required: false, + Deprecated: false, + Positional: false, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.CreateIPRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.CreateIP(request) + }, + } +} + +func vpcGwIPUpdate() *core.Command { + return &core.Command{ + Short: `Update an IP`, + Long: `Update details of an existing flexible IP address, including its tags, reverse and the Public Gateway it is assigned to.`, + Namespace: "vpc-gw", + Resource: "ip", + Verb: "update", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.UpdateIPRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "ip-id", + Short: `ID of the IP address to update`, + Required: true, + Deprecated: false, + Positional: true, + }, + { + Name: "tags.{index}", + Short: `Tags to give to the IP address`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "reverse", + Short: `Reverse to set on the address. Empty string to unset`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "gateway-id", + Short: `Gateway to attach the IP address to. Empty string to detach`, + Required: false, + Deprecated: false, + Positional: false, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.UpdateIPRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.UpdateIP(request) + }, + } +} + +func vpcGwIPDelete() *core.Command { + return &core.Command{ + Short: `Delete an IP`, + Long: `Delete a flexible IP address from your account. This action is irreversible.`, + Namespace: "vpc-gw", + Resource: "ip", + Verb: "delete", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.DeleteIPRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "ip-id", + Short: `ID of the IP address to delete`, + Required: true, + Deprecated: false, + Positional: true, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.DeleteIPRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + e = api.DeleteIP(request) + if e != nil { + return nil, e + } + return &core.SuccessResult{ + Resource: "ip", + Verb: "delete", + }, nil + }, + } +} + +func vpcGwGatewayRefreshSSHKeys() *core.Command { + return &core.Command{ + Short: `Refresh a Public Gateway's SSH keys`, + Long: `Refresh the SSH keys of a given Public Gateway, specified by its gateway ID. This adds any new SSH keys in the gateway's Scaleway Project to the gateway itself.`, + Namespace: "vpc-gw", + Resource: "gateway", + Verb: "refresh-ssh-keys", + // Deprecated: false, + ArgsType: reflect.TypeOf(vpcgw.RefreshSSHKeysRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "gateway-id", + Short: `ID of the gateway to refresh SSH keys on`, + Required: true, + Deprecated: false, + Positional: true, + }, + core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + }, + Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { + request := args.(*vpcgw.RefreshSSHKeysRequest) + + client := core.ExtractClient(ctx) + api := vpcgw.NewAPI(client) + return api.RefreshSSHKeys(request) + }, + } +} From 3ba4b8a586db9e6c26fd4bcb431318f696ce32e7 Mon Sep 17 00:00:00 2001 From: Scaleway Bot Date: Wed, 26 Mar 2025 11:29:25 +0100 Subject: [PATCH 05/24] docs(iam): remove beta mentions (#4614) --- ...t-all-usage-iam-user-update-password-usage.golden | 2 +- ...t-all-usage-iam-user-update-username-usage.golden | 2 +- .../testdata/test-all-usage-iam-user-usage.golden | 4 ++-- docs/commands/iam.md | 12 ++++++------ internal/namespaces/iam/v1alpha1/iam_cli.go | 8 ++++---- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/cmd/scw/testdata/test-all-usage-iam-user-update-password-usage.golden b/cmd/scw/testdata/test-all-usage-iam-user-update-password-usage.golden index 4e300e8871..670a9d5d6f 100644 --- a/cmd/scw/testdata/test-all-usage-iam-user-update-password-usage.golden +++ b/cmd/scw/testdata/test-all-usage-iam-user-update-password-usage.golden @@ -1,6 +1,6 @@ 🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 🟥🟥🟥 STDERR️️ 🟥🟥🟥️ -Update an user's password. Private Beta feature. +Update an user's password. USAGE: scw iam user update-password [arg=value ...] diff --git a/cmd/scw/testdata/test-all-usage-iam-user-update-username-usage.golden b/cmd/scw/testdata/test-all-usage-iam-user-update-username-usage.golden index 9b017853c8..af351fab14 100644 --- a/cmd/scw/testdata/test-all-usage-iam-user-update-username-usage.golden +++ b/cmd/scw/testdata/test-all-usage-iam-user-update-username-usage.golden @@ -1,6 +1,6 @@ 🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 🟥🟥🟥 STDERR️️ 🟥🟥🟥️ -Update an user's username. Private Beta feature. +Update an user's username. USAGE: scw iam user update-username [arg=value ...] diff --git a/cmd/scw/testdata/test-all-usage-iam-user-usage.golden b/cmd/scw/testdata/test-all-usage-iam-user-usage.golden index ccd5b251b2..e48a99fe41 100644 --- a/cmd/scw/testdata/test-all-usage-iam-user-usage.golden +++ b/cmd/scw/testdata/test-all-usage-iam-user-usage.golden @@ -11,8 +11,8 @@ AVAILABLE COMMANDS: get Get a given user list List users of an Organization update Update a user - update-password Update an user's password. Private Beta feature. - update-username Update an user's username. Private Beta feature. + update-password Update an user's password. + update-username Update an user's username. FLAGS: -h, --help help for user diff --git a/docs/commands/iam.md b/docs/commands/iam.md index d205c2a42d..6551af92ed 100644 --- a/docs/commands/iam.md +++ b/docs/commands/iam.md @@ -58,8 +58,8 @@ This API allows you to manage Identity and Access Management (IAM) across your S - [Get a given user](#get-a-given-user) - [List users of an Organization](#list-users-of-an-organization) - [Update a user](#update-a-user) - - [Update an user's password. Private Beta feature.](#update-an-user's-password.-private-beta-feature.) - - [Update an user's username. Private Beta feature.](#update-an-user's-username.-private-beta-feature.) + - [Update an user's password.](#update-an-user's-password.) + - [Update an user's username.](#update-an-user's-username.) ## API keys management commands @@ -1160,9 +1160,9 @@ scw iam user update [arg=value ...] -### Update an user's password. Private Beta feature. +### Update an user's password. -Update an user's password. Private Beta feature. +Update an user's password. **Usage:** @@ -1180,9 +1180,9 @@ scw iam user update-password [arg=value ...] -### Update an user's username. Private Beta feature. +### Update an user's username. -Update an user's username. Private Beta feature. +Update an user's username. **Usage:** diff --git a/internal/namespaces/iam/v1alpha1/iam_cli.go b/internal/namespaces/iam/v1alpha1/iam_cli.go index 92b7ad706c..fd097cf291 100644 --- a/internal/namespaces/iam/v1alpha1/iam_cli.go +++ b/internal/namespaces/iam/v1alpha1/iam_cli.go @@ -764,8 +764,8 @@ func iamUserCreate() *core.Command { func iamUserUpdateUsername() *core.Command { return &core.Command{ - Short: `Update an user's username. Private Beta feature.`, - Long: `Update an user's username. Private Beta feature.`, + Short: `Update an user's username.`, + Long: `Update an user's username.`, Namespace: "iam", Resource: "user", Verb: "update-username", @@ -800,8 +800,8 @@ func iamUserUpdateUsername() *core.Command { func iamUserUpdatePassword() *core.Command { return &core.Command{ - Short: `Update an user's password. Private Beta feature.`, - Long: `Update an user's password. Private Beta feature.`, + Short: `Update an user's password.`, + Long: `Update an user's password.`, Namespace: "iam", Resource: "user", Verb: "update-password", From bf40b4ef2601eac6f6321246b0327d3802497041 Mon Sep 17 00:00:00 2001 From: Scaleway Bot Date: Wed, 26 Mar 2025 14:08:20 +0100 Subject: [PATCH 06/24] fix(vpc): fix capitalization (#4616) --- cmd/scw/testdata/test-all-usage-vpc-rule-usage.golden | 4 ++-- docs/commands/vpc.md | 6 +++--- go.mod | 2 +- go.sum | 4 ++-- internal/namespaces/vpc/v2/vpc_cli.go | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/cmd/scw/testdata/test-all-usage-vpc-rule-usage.golden b/cmd/scw/testdata/test-all-usage-vpc-rule-usage.golden index e65c32e5d0..5daacfa28c 100644 --- a/cmd/scw/testdata/test-all-usage-vpc-rule-usage.golden +++ b/cmd/scw/testdata/test-all-usage-vpc-rule-usage.golden @@ -1,12 +1,12 @@ 🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 🟥🟥🟥 STDERR️️ 🟥🟥🟥️ -Acl Rules. +ACL Rules. USAGE: scw vpc rule AVAILABLE COMMANDS: - get Get Acl Rules for VPC + get Get ACL Rules for VPC set Set VPC ACL rules FLAGS: diff --git a/docs/commands/vpc.md b/docs/commands/vpc.md index 4495ff381c..48321cc7f9 100644 --- a/docs/commands/vpc.md +++ b/docs/commands/vpc.md @@ -17,7 +17,7 @@ This API allows you to manage your Virtual Private Clouds (VPCs) and Private Net - [Return routes with associated next hop data](#return-routes-with-associated-next-hop-data) - [Update Route](#update-route) - [Rule management command](#rule-management-command) - - [Get Acl Rules for VPC](#get-acl-rules-for-vpc) + - [Get ACL Rules for VPC](#get-acl-rules-for-vpc) - [Set VPC ACL rules](#set-vpc-acl-rules) - [Subnet management command](#subnet-management-command) - [VPC management command](#vpc-management-command) @@ -313,10 +313,10 @@ scw vpc route update [arg=value ...] ## Rule management command -Acl Rules. +ACL Rules. -### Get Acl Rules for VPC +### Get ACL Rules for VPC Retrieve a list of ACL rules for a VPC, specified by its VPC ID. diff --git a/go.mod b/go.mod index 1b4f4baff1..9f8aa259cc 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,7 @@ require ( github.com/mattn/go-isatty v0.0.20 github.com/moby/buildkit v0.13.2 github.com/opencontainers/go-digest v1.0.0 - github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250324094923-50c5f738c4d6 + github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250326091623-c76ff7151d13 github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 github.com/spf13/cobra v1.9.1 github.com/spf13/pflag v1.0.6 diff --git a/go.sum b/go.sum index 9ef594e52d..93b108ab72 100644 --- a/go.sum +++ b/go.sum @@ -462,8 +462,8 @@ github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUz github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 h1:OkMGxebDjyw0ULyrTYWeN0UNCCkmCWfjPnIA2W6oviI= github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06/go.mod h1:+ePHsJ1keEjQtpvf9HHw0f4ZeJ0TLRsxhunSI2hYJSs= -github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250324094923-50c5f738c4d6 h1:qbiYj4oaF8rke2GNsdCYrECYyqQsbCwrkjahT/9/I04= -github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250324094923-50c5f738c4d6/go.mod h1:792k1RTU+5JeMXm35/e2Wgp71qPH/DmDoZrRc+EFZDk= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250326091623-c76ff7151d13 h1:GLd3G2hvNpzjMUYOdLO79M+jiicgXnaf8eCKK+nOHLY= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250326091623-c76ff7151d13/go.mod h1:792k1RTU+5JeMXm35/e2Wgp71qPH/DmDoZrRc+EFZDk= github.com/sclevine/spec v1.4.0 h1:z/Q9idDcay5m5irkZ28M7PtQM4aOISzOpj4bUPkDee8= github.com/sclevine/spec v1.4.0/go.mod h1:LvpgJaFyvQzRvc1kaDs0bulYwzC70PbiYjC4QnFHkOM= github.com/secure-systems-lab/go-securesystemslib v0.8.0 h1:mr5An6X45Kb2nddcFlbmfHkLguCE9laoZCUzEEpIZXA= diff --git a/internal/namespaces/vpc/v2/vpc_cli.go b/internal/namespaces/vpc/v2/vpc_cli.go index ee7f640af8..4f4e8377b7 100644 --- a/internal/namespaces/vpc/v2/vpc_cli.go +++ b/internal/namespaces/vpc/v2/vpc_cli.go @@ -99,7 +99,7 @@ func vpcRoute() *core.Command { func vpcRule() *core.Command { return &core.Command{ Short: `Rule management command`, - Long: `Acl Rules.`, + Long: `ACL Rules.`, Namespace: "vpc", Resource: "rule", } @@ -866,7 +866,7 @@ func vpcRouteDelete() *core.Command { func vpcRuleGet() *core.Command { return &core.Command{ - Short: `Get Acl Rules for VPC`, + Short: `Get ACL Rules for VPC`, Long: `Retrieve a list of ACL rules for a VPC, specified by its VPC ID.`, Namespace: "vpc", Resource: "rule", From ca778cf7e62ec1e473ec5c33741ca926b83d831d Mon Sep 17 00:00:00 2001 From: Yacine Fodil <105779815+yfodil@users.noreply.github.com> Date: Wed, 26 Mar 2025 16:09:57 +0100 Subject: [PATCH 07/24] feat(vpcgw) support v2 (#4615) --- ...sage-vpc-gw-gateway-create-usage#01.golden | 28 +++++++ ...sage-vpc-gw-gateway-delete-usage#01.golden | 20 +++++ ...l-usage-vpc-gw-gateway-get-usage#01.golden | 19 +++++ ...-usage-vpc-gw-gateway-list-usage#01.golden | 26 ++++++ ...-gw-gateway-network-create-usage#01.golden | 27 +++++++ ...-gw-gateway-network-delete-usage#01.golden | 21 +++++ ...vpc-gw-gateway-network-get-usage#01.golden | 19 +++++ ...pc-gw-gateway-network-list-usage#01.golden | 24 ++++++ ...w-gateway-network-list-usage.cassette.yaml | 35 ++++++++ ...-gw-gateway-network-update-usage#01.golden | 25 ++++++ ...age-vpc-gw-gateway-network-usage#01.golden | 24 ++++++ ...-usage-vpc-gw-gateway-network-usage.golden | 10 +-- ...w-gateway-refresh-ssh-keys-usage#01.golden | 19 +++++ ...e-vpc-gw-gateway-type-list-usage#01.golden | 18 +++++ ...-usage-vpc-gw-gateway-type-usage#01.golden | 20 +++++ ...all-usage-vpc-gw-gateway-type-usage.golden | 2 +- ...sage-vpc-gw-gateway-update-usage#01.golden | 25 ++++++ ...age-vpc-gw-gateway-upgrade-usage#01.golden | 20 +++++ ...t-all-usage-vpc-gw-gateway-usage#01.golden | 27 +++++++ ...test-all-usage-vpc-gw-gateway-usage.golden | 17 ++-- ...all-usage-vpc-gw-ip-create-usage#01.golden | 20 +++++ ...all-usage-vpc-gw-ip-delete-usage#01.golden | 19 +++++ ...st-all-usage-vpc-gw-ip-get-usage#01.golden | 19 +++++ ...t-all-usage-vpc-gw-ip-list-usage#01.golden | 24 ++++++ ...all-usage-vpc-gw-ip-update-usage#01.golden | 22 +++++ .../test-all-usage-vpc-gw-ip-usage#01.golden | 24 ++++++ .../test-all-usage-vpc-gw-ip-usage.golden | 10 +-- ...age-vpc-gw-pat-rule-create-usage#01.golden | 23 ++++++ ...age-vpc-gw-pat-rule-delete-usage#01.golden | 19 +++++ ...-usage-vpc-gw-pat-rule-get-usage#01.golden | 19 +++++ ...usage-vpc-gw-pat-rule-list-usage#01.golden | 22 +++++ ...-usage-vpc-gw-pat-rule-set-usage#01.golden | 23 ++++++ ...age-vpc-gw-pat-rule-update-usage#01.golden | 23 ++++++ ...-all-usage-vpc-gw-pat-rule-usage#01.golden | 25 ++++++ ...est-all-usage-vpc-gw-pat-rule-usage.golden | 12 +-- .../test-all-usage-vpc-gw-usage#01.golden | 26 ++++++ commands/commands.go | 2 + docs/commands/vpc-gw.md | 80 ++++++------------- internal/docgen/docgen.go | 13 +++ internal/namespaces/vpcgw/v1/custom.go | 12 +++ internal/namespaces/vpcgw/v2/custom.go | 29 +++++++ .../namespaces/vpcgw/v2/custom_gateway.go | 65 +++++++++++++++ .../vpcgw/v2/custom_gateway_network.go | 67 ++++++++++++++++ .../vpcgw/v2/custom_gateway_type.go | 23 ++++++ scripts/check-size.sh | 2 +- 45 files changed, 967 insertions(+), 82 deletions(-) create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-create-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-delete-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-get-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-list-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-create-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-delete-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-get-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-list-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-list-usage.cassette.yaml create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-update-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-refresh-ssh-keys-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-type-list-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-type-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-update-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-upgrade-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-gateway-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-ip-create-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-ip-delete-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-ip-get-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-ip-list-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-ip-update-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-ip-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-create-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-delete-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-get-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-list-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-set-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-update-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-usage#01.golden create mode 100644 cmd/scw/testdata/test-all-usage-vpc-gw-usage#01.golden create mode 100644 internal/namespaces/vpcgw/v2/custom.go create mode 100644 internal/namespaces/vpcgw/v2/custom_gateway.go create mode 100644 internal/namespaces/vpcgw/v2/custom_gateway_network.go create mode 100644 internal/namespaces/vpcgw/v2/custom_gateway_type.go diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-create-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-create-usage#01.golden new file mode 100644 index 0000000000..251e348adf --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-create-usage#01.golden @@ -0,0 +1,28 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Create a new Public Gateway in the specified Scaleway Project, defining its **name**, **type** and other configuration details such as whether to enable SSH bastion. + +USAGE: + scw vpc-gw gateway create [arg=value ...] + +ARGS: + [project-id] Project ID to use. If none is passed the default project ID will be used + [name=] Name for the gateway + [tags.{index}] Tags for the gateway + [type=VPC-GW-S] Gateway type (commercial offer type) + [upstream-dns-servers.{index}] Array of DNS server IP addresses to override the gateway's default recursive DNS servers + [ip-id] Existing IP address to attach to the gateway + [enable-smtp] Defines whether SMTP traffic should be allowed pass through the gateway + [enable-bastion] Defines whether SSH bastion should be enabled the gateway + [bastion-port] Port of the SSH bastion + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for create + -w, --wait wait until the gateway is ready + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-delete-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-delete-usage#01.golden new file mode 100644 index 0000000000..80fd2ba5cd --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-delete-usage#01.golden @@ -0,0 +1,20 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Delete an existing Public Gateway, specified by its gateway ID. This action is irreversible. + +USAGE: + scw vpc-gw gateway delete [arg=value ...] + +ARGS: + gateway-id ID of the gateway to delete + [cleanup-dhcp] Defines whether to clean up attached DHCP configurations (if any, and if not attached to another Gateway Network) + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for delete + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-get-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-get-usage#01.golden new file mode 100644 index 0000000000..8eb2a0de32 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-get-usage#01.golden @@ -0,0 +1,19 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Get details of a Public Gateway, specified by its gateway ID. The response object contains full details of the gateway, including its **name**, **type**, **status** and more. + +USAGE: + scw vpc-gw gateway get [arg=value ...] + +ARGS: + gateway-id ID of the gateway to fetch + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for get + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-list-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-list-usage#01.golden new file mode 100644 index 0000000000..9553ff5450 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-list-usage#01.golden @@ -0,0 +1,26 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +List Public Gateways in a given Scaleway Organization or Project. By default, results are displayed in ascending order of creation date. + +USAGE: + scw vpc-gw gateway list [arg=value ...] + +ARGS: + [order-by] Order in which to return results (created_at_asc | created_at_desc | name_asc | name_desc | type_asc | type_desc | status_asc | status_desc) + [project-id] Include only gateways in this Project + [name] Filter for gateways which have this search term in their name + [tags.{index}] Filter for gateways with these tags + [type] Filter for gateways of this type + [status] Filter for gateways with this current status. Use `unknown` to include all statuses (unknown | stopped | allocating | configuring | running | stopping | failed | deleting | deleted | locked) + [private-network-id] Filter for gateways attached to this Private nNetwork + [organization-id] Include only gateways in this Organization + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3 | all) + +FLAGS: + -h, --help help for list + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-create-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-create-usage#01.golden new file mode 100644 index 0000000000..26c6950759 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-create-usage#01.golden @@ -0,0 +1,27 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Attach a specific Public Gateway to a specific Private Network (create a GatewayNetwork). You can configure parameters for the connection including DHCP settings, whether to enable masquerade (dynamic NAT), and more. + +USAGE: + scw vpc-gw gateway-network create [arg=value ...] + +ARGS: + [gateway-id] Public Gateway to connect + [private-network-id] Private Network to connect + [enable-masquerade] Defines whether to enable masquerade (dynamic NAT) on the GatewayNetwork. + [enable-dhcp] Defines whether to enable DHCP on this Private Network. + [dhcp-id] ID of an existing DHCP configuration object to use for this GatewayNetwork + [address] Static IP address in CIDR format to to use without DHCP + [ipam-config.push-default-route] Enabling the default route also enables masquerading + [ipam-config.ipam-ip-id] Use this IPAM-booked IP ID as the Gateway's IP in this Private Network + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for create + -w, --wait wait until the gateway-network is ready + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-delete-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-delete-usage#01.golden new file mode 100644 index 0000000000..856af57a4f --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-delete-usage#01.golden @@ -0,0 +1,21 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Detach a given Public Gateway from a given Private Network, i.e. delete a GatewayNetwork specified by a gateway_network_id. + +USAGE: + scw vpc-gw gateway-network delete [arg=value ...] + +ARGS: + gateway-network-id ID of the GatewayNetwork to delete + [cleanup-dhcp] Defines whether to clean up attached DHCP configurations (if any, and if not attached to another Gateway Network) + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for delete + -w, --wait wait until the gateway-network is ready + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-get-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-get-usage#01.golden new file mode 100644 index 0000000000..3742a18b54 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-get-usage#01.golden @@ -0,0 +1,19 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Get details of a given connection between a Public Gateway and a Private Network (this connection = a GatewayNetwork), specified by its `gateway_network_id`. The response object contains details of the connection including the IDs of the Public Gateway and Private Network, the dates the connection was created/updated and its configuration settings. + +USAGE: + scw vpc-gw gateway-network get [arg=value ...] + +ARGS: + gateway-network-id ID of the GatewayNetwork to fetch + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for get + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-list-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-list-usage#01.golden new file mode 100644 index 0000000000..6552109ba1 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-list-usage#01.golden @@ -0,0 +1,24 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +List the connections between Public Gateways and Private Networks (a connection = a GatewayNetwork). You can choose to filter by `gateway-id` to list all Private Networks attached to the specified Public Gateway, or by `private_network_id` to list all Public Gateways attached to the specified Private Network. Other query parameters are also available. The result is an array of GatewayNetwork objects, each giving details of the connection between a given Public Gateway and a given Private Network. + +USAGE: + scw vpc-gw gateway-network list [arg=value ...] + +ARGS: + [order-by] Order in which to return results (created_at_asc | created_at_desc | status_asc | status_desc) + [gateway-id] Filter for GatewayNetworks connected to this gateway + [private-network-id] Filter for GatewayNetworks connected to this Private Network + [enable-masquerade] Filter for GatewayNetworks with this `enable_masquerade` setting + [dhcp-id] Filter for GatewayNetworks using this DHCP configuration + [status] Filter for GatewayNetworks with this current status this status. Use `unknown` to include all statuses (unknown | created | attaching | configuring | ready | detaching | deleted) + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3 | all) + +FLAGS: + -h, --help help for list + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-list-usage.cassette.yaml b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-list-usage.cassette.yaml new file mode 100644 index 0000000000..05228242b1 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-list-usage.cassette.yaml @@ -0,0 +1,35 @@ +--- +version: 1 +interactions: +- request: + body: '{"access_key":"SCWBDFF054RNNE8204AJ","secret_key":null,"description":"my-key","created_at":"2022-06-10T08:39:27.845066Z","updated_at":"2022-07-05T15:12:12.987880Z","expires_at":null,"default_project_id":"564aa517-68b0-4fd7-8c8c-d21c4bcdcbd5","editable":true,"creation_ip":"51.159.46.153","application_id":"531f5518-a0a5-44c2-b790-a9975505c89d"}' + form: {} + headers: + User-Agent: + - scaleway-sdk-go/v1.0.0-beta.7+dev (go1.20.4; darwin; amd64) cli-e2e-test + url: https://api.scaleway.com/iam/v1alpha1/api-keys/SCWXXXXXXXXXXXXXXXXX + method: GET + response: + body: '{"access_key":"SCWBDFF054RNNE8204AJ","secret_key":null,"description":"my-key","created_at":"2022-06-10T08:39:27.845066Z","updated_at":"2022-07-05T15:12:12.987880Z","expires_at":null,"default_project_id":"564aa517-68b0-4fd7-8c8c-d21c4bcdcbd5","editable":true,"creation_ip":"51.159.46.153","application_id":"531f5518-a0a5-44c2-b790-a9975505c89d"}' + headers: + Content-Length: + - "344" + Content-Security-Policy: + - default-src 'none'; frame-ancestors 'none' + Content-Type: + - application/json + Date: + - Wed, 14 Jun 2023 13:56:47 GMT + Server: + - Scaleway API-Gateway + Strict-Transport-Security: + - max-age=63072000 + X-Content-Type-Options: + - nosniff + X-Frame-Options: + - DENY + X-Request-Id: + - 8dedeae5-ec2d-4679-95c6-bc9e7089d96a + status: 200 OK + code: 200 + duration: "" diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-update-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-update-usage#01.golden new file mode 100644 index 0000000000..1930b685f2 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-update-usage#01.golden @@ -0,0 +1,25 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Update the configuration parameters of a connection between a given Public Gateway and Private Network (the connection = a GatewayNetwork). Updatable parameters include DHCP settings and whether to enable traffic masquerade (dynamic NAT). + +USAGE: + scw vpc-gw gateway-network update [arg=value ...] + +ARGS: + gateway-network-id ID of the GatewayNetwork to update + [enable-masquerade] Defines whether to enable masquerade (dynamic NAT) on the GatewayNetwork. + [enable-dhcp] Defines whether to enable DHCP on this Private Network. + [dhcp-id] ID of the new DHCP configuration object to use with this GatewayNetwork + [address] New static IP address + [ipam-config.push-default-route] Enabling the default route also enables masquerading + [ipam-config.ipam-ip-id] Use this IPAM-booked IP ID as the Gateway's IP in this Private Network + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for update + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-usage#01.golden new file mode 100644 index 0000000000..213fffe9c5 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-usage#01.golden @@ -0,0 +1,24 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +A Gateway Network represents the connection of a Private Network to a Public Gateway. It holds configuration options relative to this specific connection, such as the DHCP configuration. + +USAGE: + scw vpc-gw gateway-network + +AVAILABLE COMMANDS: + create-v2 Attach a Public Gateway to a Private Network + delete-v2 Detach a Public Gateway from a Private Network + get-v2 Get a Public Gateway connection to a Private Network + list-v2 List Public Gateway connections to Private Networks + update-v2 Update a Public Gateway's connection to a Private Network + +FLAGS: + -h, --help help for gateway-network + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use + +Use "scw vpc-gw gateway-network [command] --help" for more information about a command. diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-usage.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-usage.golden index 992d88bd96..213fffe9c5 100644 --- a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-usage.golden +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-network-usage.golden @@ -6,11 +6,11 @@ USAGE: scw vpc-gw gateway-network AVAILABLE COMMANDS: - create Attach a Public Gateway to a Private Network - delete Detach a Public Gateway from a Private Network - get Get a Public Gateway connection to a Private Network - list List Public Gateway connections to Private Networks - update Update a Public Gateway's connection to a Private Network + create-v2 Attach a Public Gateway to a Private Network + delete-v2 Detach a Public Gateway from a Private Network + get-v2 Get a Public Gateway connection to a Private Network + list-v2 List Public Gateway connections to Private Networks + update-v2 Update a Public Gateway's connection to a Private Network FLAGS: -h, --help help for gateway-network diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-refresh-ssh-keys-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-refresh-ssh-keys-usage#01.golden new file mode 100644 index 0000000000..033e5ae1a4 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-refresh-ssh-keys-usage#01.golden @@ -0,0 +1,19 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Refresh the SSH keys of a given Public Gateway, specified by its gateway ID. This adds any new SSH keys in the gateway's Scaleway Project to the gateway itself. + +USAGE: + scw vpc-gw gateway refresh-ssh-keys [arg=value ...] + +ARGS: + gateway-id ID of the gateway to refresh SSH keys on + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for refresh-ssh-keys + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-type-list-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-type-list-usage#01.golden new file mode 100644 index 0000000000..5f39215674 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-type-list-usage#01.golden @@ -0,0 +1,18 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +List the different Public Gateway commercial offer types available at Scaleway. The response is an array of objects describing the name and technical details of each available gateway type. + +USAGE: + scw vpc-gw gateway-type list [arg=value ...] + +ARGS: + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for list + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-type-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-type-usage#01.golden new file mode 100644 index 0000000000..7ddd06f0f0 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-type-usage#01.golden @@ -0,0 +1,20 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Public Gateways come in various shapes, sizes and prices, which are described by gateway types. They represent the different commercial offer types for Public Gateways available at Scaleway. + +USAGE: + scw vpc-gw gateway-type + +AVAILABLE COMMANDS: + list-v2 List Public Gateway types + +FLAGS: + -h, --help help for gateway-type + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use + +Use "scw vpc-gw gateway-type [command] --help" for more information about a command. diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-type-usage.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-type-usage.golden index 2fccb628db..7ddd06f0f0 100644 --- a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-type-usage.golden +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-type-usage.golden @@ -6,7 +6,7 @@ USAGE: scw vpc-gw gateway-type AVAILABLE COMMANDS: - list List Public Gateway types + list-v2 List Public Gateway types FLAGS: -h, --help help for gateway-type diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-update-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-update-usage#01.golden new file mode 100644 index 0000000000..bc3d5be403 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-update-usage#01.golden @@ -0,0 +1,25 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Update the parameters of an existing Public Gateway, for example, its **name**, **tags**, **SSH bastion configuration**, and **DNS servers**. + +USAGE: + scw vpc-gw gateway update [arg=value ...] + +ARGS: + gateway-id ID of the gateway to update + [name] Name for the gateway + [tags.{index}] Tags for the gateway + [upstream-dns-servers.{index}] Array of DNS server IP addresses to override the gateway's default recursive DNS servers + [enable-bastion] Defines whether SSH bastion should be enabled the gateway + [bastion-port] Port of the SSH bastion + [enable-smtp] Defines whether SMTP traffic should be allowed to pass through the gateway + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for update + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-upgrade-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-upgrade-usage#01.golden new file mode 100644 index 0000000000..52eec10c5b --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-upgrade-usage#01.golden @@ -0,0 +1,20 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Upgrade a given Public Gateway to the newest software version or to a different commercial offer type. This applies the latest bugfixes and features to your Public Gateway. Note that gateway service will be interrupted during the update. + +USAGE: + scw vpc-gw gateway upgrade [arg=value ...] + +ARGS: + gateway-id ID of the gateway to upgrade + [type] Gateway type (commercial offer) + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for upgrade + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-usage#01.golden new file mode 100644 index 0000000000..5e830ecae4 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-usage#01.golden @@ -0,0 +1,27 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Public Gateways are building blocks for your infrastructure on Scaleway's shared public cloud. They provide a set of managed network services and features for Scaleway's Private Networks such as DHCP, NAT and routing. + +USAGE: + scw vpc-gw gateway + +AVAILABLE COMMANDS: + create-v2 Create a Public Gateway + delete-v2 Delete a Public Gateway + get-v2 Get a Public Gateway + list-v2 List Public Gateways + migrate-to-v2 Put a Public Gateway in IPAM mode + refresh-ssh-keys-v2 Refresh a Public Gateway's SSH keys + update-v2 Update a Public Gateway + upgrade-v2 Upgrade a Public Gateway to the latest version and/or to a different commercial offer type + +FLAGS: + -h, --help help for gateway + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use + +Use "scw vpc-gw gateway [command] --help" for more information about a command. diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-usage.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-usage.golden index 556001fdba..5e830ecae4 100644 --- a/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-usage.golden +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-gateway-usage.golden @@ -6,15 +6,14 @@ USAGE: scw vpc-gw gateway AVAILABLE COMMANDS: - create Create a Public Gateway - delete Delete a Public Gateway - enable-ip-mobility Upgrade a Public Gateway to IP mobility - get Get a Public Gateway - list List Public Gateways - migrate-to-v2 Put a Public Gateway in IPAM mode - refresh-ssh-keys Refresh a Public Gateway's SSH keys - update Update a Public Gateway - upgrade Upgrade a Public Gateway to the latest version and/or to a different commercial offer type + create-v2 Create a Public Gateway + delete-v2 Delete a Public Gateway + get-v2 Get a Public Gateway + list-v2 List Public Gateways + migrate-to-v2 Put a Public Gateway in IPAM mode + refresh-ssh-keys-v2 Refresh a Public Gateway's SSH keys + update-v2 Update a Public Gateway + upgrade-v2 Upgrade a Public Gateway to the latest version and/or to a different commercial offer type FLAGS: -h, --help help for gateway diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-ip-create-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-create-usage#01.golden new file mode 100644 index 0000000000..0f19036b24 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-create-usage#01.golden @@ -0,0 +1,20 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Create (reserve) a new flexible IP address that can be used for a Public Gateway in a specified Scaleway Project. + +USAGE: + scw vpc-gw ip create [arg=value ...] + +ARGS: + [project-id] Project ID to use. If none is passed the default project ID will be used + [tags.{index}] Tags to give to the IP address + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for create + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-ip-delete-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-delete-usage#01.golden new file mode 100644 index 0000000000..bc955fcb9a --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-delete-usage#01.golden @@ -0,0 +1,19 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Delete a flexible IP address from your account. This action is irreversible. + +USAGE: + scw vpc-gw ip delete [arg=value ...] + +ARGS: + ip-id ID of the IP address to delete + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for delete + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-ip-get-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-get-usage#01.golden new file mode 100644 index 0000000000..754c0f5389 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-get-usage#01.golden @@ -0,0 +1,19 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Get details of a Public Gateway flexible IP address, identified by its IP ID. The response object contains information including which (if any) Public Gateway using this IP address, the reverse and various other metadata. + +USAGE: + scw vpc-gw ip get [arg=value ...] + +ARGS: + ip-id ID of the IP address to get + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for get + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-ip-list-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-list-usage#01.golden new file mode 100644 index 0000000000..15a34a0abe --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-list-usage#01.golden @@ -0,0 +1,24 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +List Public Gateway flexible IP addresses. A number of filter options are available for limiting results in the response. + +USAGE: + scw vpc-gw ip list [arg=value ...] + +ARGS: + [order-by] Order in which to return results (created_at_asc | created_at_desc | ip_asc | ip_desc | reverse_asc | reverse_desc) + [project-id] Filter for IP addresses in this Project + [tags.{index}] Filter for IP addresses with these tags + [reverse] Filter for IP addresses that have a reverse containing this string + [is-free] Filter based on whether the IP is attached to a gateway or not + [organization-id] Filter for IP addresses in this Organization + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3 | all) + +FLAGS: + -h, --help help for list + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-ip-update-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-update-usage#01.golden new file mode 100644 index 0000000000..d29d093a9a --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-update-usage#01.golden @@ -0,0 +1,22 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Update details of an existing flexible IP address, including its tags, reverse and the Public Gateway it is assigned to. + +USAGE: + scw vpc-gw ip update [arg=value ...] + +ARGS: + ip-id ID of the IP address to update + [tags.{index}] Tags to give to the IP address + [reverse] Reverse to set on the address. Empty string to unset + [gateway-id] Gateway to attach the IP address to. Empty string to detach + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for update + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-ip-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-usage#01.golden new file mode 100644 index 0000000000..3f59475df3 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-usage#01.golden @@ -0,0 +1,24 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Public, flexible IP addresses for Public Gateways, allowing the gateway to reach the public internet, as well as forward (masquerade) traffic from member devices of attached Private Networks. + +USAGE: + scw vpc-gw ip + +AVAILABLE COMMANDS: + create-v2 Reserve an IP + delete-v2 Delete an IP + get-v2 Get an IP + list-v2 List IPs + update-v2 Update an IP + +FLAGS: + -h, --help help for ip + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use + +Use "scw vpc-gw ip [command] --help" for more information about a command. diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-ip-usage.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-usage.golden index e59c5c4268..3f59475df3 100644 --- a/cmd/scw/testdata/test-all-usage-vpc-gw-ip-usage.golden +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-ip-usage.golden @@ -6,11 +6,11 @@ USAGE: scw vpc-gw ip AVAILABLE COMMANDS: - create Reserve an IP - delete Delete an IP - get Get an IP - list List IPs - update Update an IP + create-v2 Reserve an IP + delete-v2 Delete an IP + get-v2 Get an IP + list-v2 List IPs + update-v2 Update an IP FLAGS: -h, --help help for ip diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-create-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-create-usage#01.golden new file mode 100644 index 0000000000..7e310d00c2 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-create-usage#01.golden @@ -0,0 +1,23 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Create a new PAT rule on a specified Public Gateway, defining the protocol to use, public port to listen on, and private port / IP address to map to. + +USAGE: + scw vpc-gw pat-rule create [arg=value ...] + +ARGS: + [gateway-id] ID of the Gateway on which to create the rule + [public-port] Public port to listen on + [private-ip] Private IP to forward data to + [private-port] Private port to translate to + [protocol] Protocol the rule should apply to (unknown | both | tcp | udp) + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for create + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-delete-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-delete-usage#01.golden new file mode 100644 index 0000000000..bbeef41458 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-delete-usage#01.golden @@ -0,0 +1,19 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Delete a PAT rule, identified by its PAT rule ID. This action is irreversible. + +USAGE: + scw vpc-gw pat-rule delete [arg=value ...] + +ARGS: + pat-rule-id ID of the PAT rule to delete + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for delete + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-get-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-get-usage#01.golden new file mode 100644 index 0000000000..420d6dcfc0 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-get-usage#01.golden @@ -0,0 +1,19 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Get a PAT rule, specified by its PAT rule ID. The response object gives full details of the PAT rule, including the Public Gateway it belongs to and the configuration settings in terms of public / private ports, private IP and protocol. + +USAGE: + scw vpc-gw pat-rule get [arg=value ...] + +ARGS: + pat-rule-id ID of the PAT rule to get + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for get + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-list-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-list-usage#01.golden new file mode 100644 index 0000000000..3c3689ace0 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-list-usage#01.golden @@ -0,0 +1,22 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +List PAT rules. You can filter by gateway ID to list all PAT rules for a particular gateway, or filter for PAT rules targeting a specific IP address or using a specific protocol. + +USAGE: + scw vpc-gw pat-rule list [arg=value ...] + +ARGS: + [order-by] Order in which to return results (created_at_asc | created_at_desc | public_port_asc | public_port_desc) + [gateway-id] Filter for PAT rules on this Gateway + [private-ip] Filter for PAT rules targeting this private ip + [protocol] Filter for PAT rules with this protocol (unknown | both | tcp | udp) + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3 | all) + +FLAGS: + -h, --help help for list + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-set-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-set-usage#01.golden new file mode 100644 index 0000000000..001cecaaa1 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-set-usage#01.golden @@ -0,0 +1,23 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Set a definitive list of PAT rules attached to a Public Gateway. Each rule is identified by its public port and protocol. This will sync the current PAT rule list on the gateway with the new list, creating, updating or deleting PAT rules accordingly. + +USAGE: + scw vpc-gw pat-rule set [arg=value ...] + +ARGS: + [gateway-id] ID of the gateway on which to set the PAT rules + [pat-rules.{index}.public-port] Public port to listen on + [pat-rules.{index}.private-ip] Private IP to forward data to + [pat-rules.{index}.private-port] Private port to translate to + [pat-rules.{index}.protocol] Protocol the rule should apply to (unknown | both | tcp | udp) + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for set + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-update-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-update-usage#01.golden new file mode 100644 index 0000000000..3bccb1731b --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-update-usage#01.golden @@ -0,0 +1,23 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Update a PAT rule, specified by its PAT rule ID. Configuration settings including private/public port, private IP address and protocol can all be updated. + +USAGE: + scw vpc-gw pat-rule update [arg=value ...] + +ARGS: + pat-rule-id ID of the PAT rule to update + [public-port] Public port to listen on + [private-ip] Private IP to forward data to + [private-port] Private port to translate to + [protocol] Protocol the rule should apply to (unknown | both | tcp | udp) + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for update + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-usage#01.golden new file mode 100644 index 0000000000..e280ed5d60 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-usage#01.golden @@ -0,0 +1,25 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +PAT (Port Address Translation) rules, aka static NAT rules, belong to a specified Public Gateway. They define the forwarding of a public port to a specific device on a Private Network, enabling enables ingress traffic from the public Internet to reach the correct device in the Private Network. + +USAGE: + scw vpc-gw pat-rule + +AVAILABLE COMMANDS: + create-v2 Create a PAT rule + delete-v2 Delete a PAT rule + get-v2 Get a PAT rule + list-v2 List PAT rules + set-v2 Set all PAT rules + update-v2 Update a PAT rule + +FLAGS: + -h, --help help for pat-rule + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use + +Use "scw vpc-gw pat-rule [command] --help" for more information about a command. diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-usage.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-usage.golden index 240ae10fe9..e280ed5d60 100644 --- a/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-usage.golden +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-pat-rule-usage.golden @@ -6,12 +6,12 @@ USAGE: scw vpc-gw pat-rule AVAILABLE COMMANDS: - create Create a PAT rule - delete Delete a PAT rule - get Get a PAT rule - list List PAT rules - set Set all PAT rules - update Update a PAT rule + create-v2 Create a PAT rule + delete-v2 Delete a PAT rule + get-v2 Get a PAT rule + list-v2 List PAT rules + set-v2 Set all PAT rules + update-v2 Update a PAT rule FLAGS: -h, --help help for pat-rule diff --git a/cmd/scw/testdata/test-all-usage-vpc-gw-usage#01.golden b/cmd/scw/testdata/test-all-usage-vpc-gw-usage#01.golden new file mode 100644 index 0000000000..8e3272589e --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-vpc-gw-usage#01.golden @@ -0,0 +1,26 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +This API allows you to manage your Public Gateways. + +USAGE: + scw vpc-gw + +AVAILABLE COMMANDS: + dhcp DHCP configuration management + dhcp-entry DHCP entries management + gateway Public Gateway management + gateway-network Gateway Networks management + gateway-type Gateway types information + ip IP address management + pat-rule PAT rules management + +FLAGS: + -h, --help help for vpc-gw + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use + +Use "scw vpc-gw [command] --help" for more information about a command. diff --git a/commands/commands.go b/commands/commands.go index cb1d9ffd88..224f74c006 100644 --- a/commands/commands.go +++ b/commands/commands.go @@ -50,6 +50,7 @@ import ( versionNamespace "github.com/scaleway/scaleway-cli/v2/internal/namespaces/version" "github.com/scaleway/scaleway-cli/v2/internal/namespaces/vpc/v2" "github.com/scaleway/scaleway-cli/v2/internal/namespaces/vpcgw/v1" + vpcgwV2 "github.com/scaleway/scaleway-cli/v2/internal/namespaces/vpcgw/v2" "github.com/scaleway/scaleway-cli/v2/internal/namespaces/webhosting/v1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -91,6 +92,7 @@ func GetCommands() *core.Commands { container.GetCommands(), function.GetCommands(), vpcgw.GetCommands(), + vpcgwV2.GetCommands(), redis.GetCommands(), secret.GetCommands(), keymanager.GetCommands(), diff --git a/docs/commands/vpc-gw.md b/docs/commands/vpc-gw.md index b869b16464..351ff5e8c9 100644 --- a/docs/commands/vpc-gw.md +++ b/docs/commands/vpc-gw.md @@ -18,7 +18,6 @@ This API allows you to manage your Public Gateways. - [Public Gateway management](#public-gateway-management) - [Create a Public Gateway](#create-a-public-gateway) - [Delete a Public Gateway](#delete-a-public-gateway) - - [Upgrade a Public Gateway to IP mobility](#upgrade-a-public-gateway-to-ip-mobility) - [Get a Public Gateway](#get-a-public-gateway) - [List Public Gateways](#list-public-gateways) - [Put a Public Gateway in IPAM mode](#put-a-public-gateway-in-ipam-mode) @@ -320,7 +319,7 @@ scw vpc-gw dhcp-entry update [arg=value ...] ## Public Gateway management -Public Gateways are building blocks for your infrastructure on Scaleway's shared public cloud. They provide a set of managed network services and features for Scaleway's Private Networks such as DHCP, NAT and routing. +Public Gateways are building blocks for your infrastructure on Scaleway's shared public cloud. They provide a set of managed network services and features for Scaleway's Private Networks such NAT and PAT rules. ### Create a Public Gateway @@ -342,7 +341,6 @@ scw vpc-gw gateway create [arg=value ...] | name | Default: `` | Name for the gateway | | tags.{index} | | Tags for the gateway | | type | Default: `VPC-GW-S` | Gateway type (commercial offer type) | -| upstream-dns-servers.{index} | | Array of DNS server IP addresses to override the gateway's default recursive DNS servers | | ip-id | | Existing IP address to attach to the gateway | | enable-smtp | | Defines whether SMTP traffic should be allowed pass through the gateway | | enable-bastion | | Defines whether SSH bastion should be enabled the gateway | @@ -367,27 +365,7 @@ scw vpc-gw gateway delete [arg=value ...] | Name | | Description | |------|---|-------------| | gateway-id | Required | ID of the gateway to delete | -| cleanup-dhcp | | Defines whether to clean up attached DHCP configurations (if any, and if not attached to another Gateway Network) | -| zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3` | Zone to target. If none is passed will use default zone from the config | - - - -### Upgrade a Public Gateway to IP mobility - -Upgrade a Public Gateway to IP mobility (move from NAT IP to routed IP). This is idempotent: repeated calls after the first will return no error but have no effect. - -**Usage:** - -``` -scw vpc-gw gateway enable-ip-mobility [arg=value ...] -``` - - -**Args:** - -| Name | | Description | -|------|---|-------------| -| gateway-id | Required | ID of the gateway to upgrade to IP mobility | +| delete-ip | | Defines whether the PGW's IP should be deleted | | zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3` | Zone to target. If none is passed will use default zone from the config | @@ -431,9 +409,10 @@ scw vpc-gw gateway list [arg=value ...] | project-id | | Include only gateways in this Project | | name | | Filter for gateways which have this search term in their name | | tags.{index} | | Filter for gateways with these tags | -| type | | Filter for gateways of this type | -| status | One of: `unknown`, `stopped`, `allocating`, `configuring`, `running`, `stopping`, `failed`, `deleting`, `deleted`, `locked` | Filter for gateways with this current status. Use `unknown` to include all statuses | -| private-network-id | | Filter for gateways attached to this Private nNetwork | +| types.{index} | | Filter for gateways of these types | +| status.{index} | One of: `unknown_status`, `stopped`, `allocating`, `configuring`, `running`, `stopping`, `failed`, `deleting`, `locked` | Filter for gateways with these status. Use `unknown` to include all statuses | +| private-network-ids.{index} | | Filter for gateways attached to these Private Networks | +| include-legacy | | Include also legacy gateways | | organization-id | | Include only gateways in this Organization | | zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3`, `all` | Zone to target. If none is passed will use default zone from the config | @@ -497,7 +476,6 @@ scw vpc-gw gateway update [arg=value ...] | gateway-id | Required | ID of the gateway to update | | name | | Name for the gateway | | tags.{index} | | Tags for the gateway | -| upstream-dns-servers.{index} | | Array of DNS server IP addresses to override the gateway's default recursive DNS servers | | enable-bastion | | Defines whether SSH bastion should be enabled the gateway | | bastion-port | | Port of the SSH bastion | | enable-smtp | | Defines whether SMTP traffic should be allowed to pass through the gateway | @@ -528,12 +506,12 @@ scw vpc-gw gateway upgrade [arg=value ...] ## Gateway Networks management -A Gateway Network represents the connection of a Private Network to a Public Gateway. It holds configuration options relative to this specific connection, such as the DHCP configuration. +A Gateway Network represents the connection of a Private Network to a Public Gateway. ### Attach a Public Gateway to a Private Network -Attach a specific Public Gateway to a specific Private Network (create a GatewayNetwork). You can configure parameters for the connection including DHCP settings, whether to enable masquerade (dynamic NAT), and more. +Attach a specific Public Gateway to a specific Private Network (create a GatewayNetwork). You can configure parameters for the connection including whether to enable masquerade (dynamic NAT), and more. **Usage:** @@ -549,11 +527,8 @@ scw vpc-gw gateway-network create [arg=value ...] | gateway-id | | Public Gateway to connect | | private-network-id | | Private Network to connect | | enable-masquerade | | Defines whether to enable masquerade (dynamic NAT) on the GatewayNetwork. | -| enable-dhcp | | Defines whether to enable DHCP on this Private Network. | -| dhcp-id | | ID of an existing DHCP configuration object to use for this GatewayNetwork | -| address | | Static IP address in CIDR format to to use without DHCP | -| ipam-config.push-default-route | | Enabling the default route also enables masquerading | -| ipam-config.ipam-ip-id | | Use this IPAM-booked IP ID as the Gateway's IP in this Private Network | +| push-default-route | | Enabling the default route also enables masquerading | +| ipam-ip-id | | Use this IPAM-booked IP ID as the Gateway's IP in this Private Network | | zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3` | Zone to target. If none is passed will use default zone from the config | @@ -574,7 +549,6 @@ scw vpc-gw gateway-network delete [arg=value ...] | Name | | Description | |------|---|-------------| | gateway-network-id | Required | ID of the GatewayNetwork to delete | -| cleanup-dhcp | | Defines whether to clean up attached DHCP configurations (if any, and if not attached to another Gateway Network) | | zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3` | Zone to target. If none is passed will use default zone from the config | @@ -615,18 +589,17 @@ scw vpc-gw gateway-network list [arg=value ...] | Name | | Description | |------|---|-------------| | order-by | One of: `created_at_asc`, `created_at_desc`, `status_asc`, `status_desc` | Order in which to return results | -| gateway-id | | Filter for GatewayNetworks connected to this gateway | -| private-network-id | | Filter for GatewayNetworks connected to this Private Network | -| enable-masquerade | | Filter for GatewayNetworks with this `enable_masquerade` setting | -| dhcp-id | | Filter for GatewayNetworks using this DHCP configuration | -| status | One of: `unknown`, `created`, `attaching`, `configuring`, `ready`, `detaching`, `deleted` | Filter for GatewayNetworks with this current status this status. Use `unknown` to include all statuses | +| status.{index} | One of: `unknown_status`, `created`, `attaching`, `configuring`, `ready`, `detaching` | Filter for GatewayNetworks with these status. Use `unknown` to include all statuses | +| gateway-ids.{index} | | Filter for GatewayNetworks connected to these gateways | +| private-network-ids.{index} | | Filter for GatewayNetworks connected to these Private Networks | +| masquerade-enabled | | Filter for GatewayNetworks with this `enable_masquerade` setting | | zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3`, `all` | Zone to target. If none is passed will use default zone from the config | ### Update a Public Gateway's connection to a Private Network -Update the configuration parameters of a connection between a given Public Gateway and Private Network (the connection = a GatewayNetwork). Updatable parameters include DHCP settings and whether to enable traffic masquerade (dynamic NAT). +Update the configuration parameters of a connection between a given Public Gateway and Private Network (the connection = a GatewayNetwork). Updatable parameters include whether to enable traffic masquerade (dynamic NAT). **Usage:** @@ -641,11 +614,8 @@ scw vpc-gw gateway-network update [arg=value ...] |------|---|-------------| | gateway-network-id | Required | ID of the GatewayNetwork to update | | enable-masquerade | | Defines whether to enable masquerade (dynamic NAT) on the GatewayNetwork. | -| enable-dhcp | | Defines whether to enable DHCP on this Private Network. | -| dhcp-id | | ID of the new DHCP configuration object to use with this GatewayNetwork | -| address | | New static IP address | -| ipam-config.push-default-route | | Enabling the default route also enables masquerading | -| ipam-config.ipam-ip-id | | Use this IPAM-booked IP ID as the Gateway's IP in this Private Network | +| push-default-route | | Enabling the default route also enables masquerading | +| ipam-ip-id | | Use this IPAM-booked IP ID as the Gateway's IP in this Private Network | | zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3` | Zone to target. If none is passed will use default zone from the config | @@ -755,12 +725,12 @@ scw vpc-gw ip list [arg=value ...] | Name | | Description | |------|---|-------------| -| order-by | One of: `created_at_asc`, `created_at_desc`, `ip_asc`, `ip_desc`, `reverse_asc`, `reverse_desc` | Order in which to return results | +| order-by | One of: `created_at_asc`, `created_at_desc`, `address_asc`, `address_desc`, `reverse_asc`, `reverse_desc` | Order in which to return results | | project-id | | Filter for IP addresses in this Project | | tags.{index} | | Filter for IP addresses with these tags | | reverse | | Filter for IP addresses that have a reverse containing this string | | is-free | | Filter based on whether the IP is attached to a gateway or not | -| organization-id | | Filter for IP addresses in this Organization | +| organization-id | | Include only gateways in this Organization | | zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3`, `all` | Zone to target. If none is passed will use default zone from the config | @@ -812,7 +782,7 @@ scw vpc-gw pat-rule create [arg=value ...] | public-port | | Public port to listen on | | private-ip | | Private IP to forward data to | | private-port | | Private port to translate to | -| protocol | One of: `unknown`, `both`, `tcp`, `udp` | Protocol the rule should apply to | +| protocol | One of: `unknown_protocol`, `both`, `tcp`, `udp` | Protocol the rule should apply to | | zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3` | Zone to target. If none is passed will use default zone from the config | @@ -873,9 +843,9 @@ scw vpc-gw pat-rule list [arg=value ...] | Name | | Description | |------|---|-------------| | order-by | One of: `created_at_asc`, `created_at_desc`, `public_port_asc`, `public_port_desc` | Order in which to return results | -| gateway-id | | Filter for PAT rules on this Gateway | -| private-ip | | Filter for PAT rules targeting this private ip | -| protocol | One of: `unknown`, `both`, `tcp`, `udp` | Filter for PAT rules with this protocol | +| gateway-ids.{index} | | Filter for PAT rules on these gateways | +| private-ips.{index} | | Filter for PAT rules targeting these private ips | +| protocol | One of: `unknown_protocol`, `both`, `tcp`, `udp` | Filter for PAT rules with this protocol | | zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3`, `all` | Zone to target. If none is passed will use default zone from the config | @@ -899,7 +869,7 @@ scw vpc-gw pat-rule set [arg=value ...] | pat-rules.{index}.public-port | | Public port to listen on | | pat-rules.{index}.private-ip | | Private IP to forward data to | | pat-rules.{index}.private-port | | Private port to translate to | -| pat-rules.{index}.protocol | One of: `unknown`, `both`, `tcp`, `udp` | Protocol the rule should apply to | +| pat-rules.{index}.protocol | One of: `unknown_protocol`, `both`, `tcp`, `udp` | Protocol the rule should apply to | | zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3` | Zone to target. If none is passed will use default zone from the config | @@ -923,7 +893,7 @@ scw vpc-gw pat-rule update [arg=value ...] | public-port | | Public port to listen on | | private-ip | | Private IP to forward data to | | private-port | | Private port to translate to | -| protocol | One of: `unknown`, `both`, `tcp`, `udp` | Protocol the rule should apply to | +| protocol | One of: `unknown_protocol`, `both`, `tcp`, `udp` | Protocol the rule should apply to | | zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3` | Zone to target. If none is passed will use default zone from the config | diff --git a/internal/docgen/docgen.go b/internal/docgen/docgen.go index b187445462..82682b0aae 100644 --- a/internal/docgen/docgen.go +++ b/internal/docgen/docgen.go @@ -73,6 +73,19 @@ func GenerateDocs(commands *core.Commands, outDir string) error { resource.Verbs[c.Verb] = c } + // Fallback: if a resource has no Cmd defined, pick one verb as the fallback + for _, ns := range data.Namespaces { + for _, res := range ns.Resources { + if res.Cmd == nil && len(res.Verbs) > 0 { + for _, cmd := range res.Verbs { + res.Cmd = cmd + + break + } + } + } + } + for name, namespace := range data.Namespaces { fmt.Println("Generating namespace", name) namespaceDoc, err := renderNamespace(namespace) diff --git a/internal/namespaces/vpcgw/v1/custom.go b/internal/namespaces/vpcgw/v1/custom.go index 094c85073f..565d66ce09 100644 --- a/internal/namespaces/vpcgw/v1/custom.go +++ b/internal/namespaces/vpcgw/v1/custom.go @@ -8,6 +8,18 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + for _, cmd := range cmds.GetAll() { + if cmd.Resource == "" || cmd.Verb == "" { + continue + } + if cmd.Verb == "migrate-to-v2" { + continue + } + if cmd.Resource == "dhcp" || cmd.Resource == "dhcp-entry" { + continue + } + cmd.Hidden = true + } human.RegisterMarshalerFunc( vpcgw.GatewayNetworkStatus(""), diff --git a/internal/namespaces/vpcgw/v2/custom.go b/internal/namespaces/vpcgw/v2/custom.go new file mode 100644 index 0000000000..e69a727f42 --- /dev/null +++ b/internal/namespaces/vpcgw/v2/custom.go @@ -0,0 +1,29 @@ +package vpcgw + +import ( + "strings" + + "github.com/scaleway/scaleway-cli/v2/core" + "github.com/scaleway/scaleway-cli/v2/core/human" + "github.com/scaleway/scaleway-sdk-go/api/vpcgw/v2" +) + +func GetCommands() *core.Commands { + cmds := GetGeneratedCommands() + for _, cmd := range cmds.GetAll() { + if cmd.Verb != "" && !strings.HasSuffix(cmd.Verb, "-v2") { + cmd.Verb = strings.TrimSpace(cmd.Verb) + "-v2" + } + } + + human.RegisterMarshalerFunc(vpcgw.GatewayNetworkStatus(""), human.EnumMarshalFunc(gatewayNetworkStatusMarshalSpecs)) + human.RegisterMarshalerFunc(vpcgw.GatewayStatus(""), human.EnumMarshalFunc(gatewayStatusMarshalSpecs)) + human.RegisterMarshalerFunc(vpcgw.Gateway{}, gatewayMarshalerFunc) + + cmds.MustFind("vpc-gw", "gateway-type", "list").Override(vpcgwGatewayTypeListBuilder) + cmds.MustFind("vpc-gw", "gateway", "create").Override(gatewayCreateBuilder) + cmds.MustFind("vpc-gw", "gateway-network", "create").Override(gatewayNetworkCreateBuilder) + cmds.MustFind("vpc-gw", "gateway-network", "delete").Override(gatewayNetworkDeleteBuilder) + + return cmds +} diff --git a/internal/namespaces/vpcgw/v2/custom_gateway.go b/internal/namespaces/vpcgw/v2/custom_gateway.go new file mode 100644 index 0000000000..09c6eaaf2e --- /dev/null +++ b/internal/namespaces/vpcgw/v2/custom_gateway.go @@ -0,0 +1,65 @@ +package vpcgw + +import ( + "context" + "time" + + "github.com/fatih/color" + "github.com/scaleway/scaleway-cli/v2/core" + "github.com/scaleway/scaleway-cli/v2/core/human" + "github.com/scaleway/scaleway-sdk-go/api/vpcgw/v2" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +const ( + gatewayActionTimeout = 60 * time.Minute +) + +var gatewayStatusMarshalSpecs = human.EnumMarshalSpecs{ + vpcgw.GatewayStatusUnknownStatus: &human.EnumMarshalSpec{Attribute: color.Faint}, + vpcgw.GatewayStatusAllocating: &human.EnumMarshalSpec{Attribute: color.FgBlue}, + vpcgw.GatewayStatusConfiguring: &human.EnumMarshalSpec{Attribute: color.FgBlue}, + vpcgw.GatewayStatusDeleting: &human.EnumMarshalSpec{Attribute: color.FgBlue}, + vpcgw.GatewayStatusFailed: &human.EnumMarshalSpec{Attribute: color.FgRed}, + vpcgw.GatewayStatusRunning: &human.EnumMarshalSpec{Attribute: color.FgGreen}, + vpcgw.GatewayStatusStopped: &human.EnumMarshalSpec{Attribute: color.FgRed}, + vpcgw.GatewayStatusLocked: &human.EnumMarshalSpec{Attribute: color.FgRed}, + vpcgw.GatewayStatusStopping: &human.EnumMarshalSpec{Attribute: color.FgBlue}, +} + +func gatewayCreateBuilder(c *core.Command) *core.Command { + c.WaitFunc = func(ctx context.Context, _, respI interface{}) (interface{}, error) { + getResp := respI.(*vpcgw.Gateway) + api := vpcgw.NewAPI(core.ExtractClient(ctx)) + + return api.WaitForGateway(&vpcgw.WaitForGatewayRequest{ + GatewayID: getResp.ID, + Zone: getResp.Zone, + Timeout: scw.TimeDurationPtr(gatewayActionTimeout), + RetryInterval: core.DefaultRetryInterval, + }) + } + + return c +} + +func gatewayMarshalerFunc(i interface{}, opt *human.MarshalOpt) (string, error) { + type tmp vpcgw.Gateway + vpcgtw := tmp(i.(vpcgw.Gateway)) + opt.Sections = []*human.MarshalSection{ + { + FieldName: "IP", + Title: "IP", + }, + { + FieldName: "GatewayNetworks", + Title: "GatewayNetworks", + }, + } + str, err := human.Marshal(vpcgtw, opt) + if err != nil { + return "", err + } + + return str, nil +} diff --git a/internal/namespaces/vpcgw/v2/custom_gateway_network.go b/internal/namespaces/vpcgw/v2/custom_gateway_network.go new file mode 100644 index 0000000000..eca9acd002 --- /dev/null +++ b/internal/namespaces/vpcgw/v2/custom_gateway_network.go @@ -0,0 +1,67 @@ +package vpcgw + +import ( + "context" + "errors" + "net/http" + + "github.com/fatih/color" + "github.com/scaleway/scaleway-cli/v2/core" + "github.com/scaleway/scaleway-cli/v2/core/human" + "github.com/scaleway/scaleway-sdk-go/api/vpcgw/v2" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +var gatewayNetworkStatusMarshalSpecs = human.EnumMarshalSpecs{ + vpcgw.GatewayNetworkStatusAttaching: &human.EnumMarshalSpec{Attribute: color.FgBlue}, + vpcgw.GatewayNetworkStatusConfiguring: &human.EnumMarshalSpec{Attribute: color.FgBlue}, + vpcgw.GatewayNetworkStatusCreated: &human.EnumMarshalSpec{Attribute: color.FgGreen}, + vpcgw.GatewayNetworkStatusDetaching: &human.EnumMarshalSpec{Attribute: color.FgBlue}, + vpcgw.GatewayNetworkStatusReady: &human.EnumMarshalSpec{Attribute: color.FgGreen}, + vpcgw.GatewayNetworkStatusUnknownStatus: &human.EnumMarshalSpec{Attribute: color.Faint}, +} + +func gatewayNetworkCreateBuilder(c *core.Command) *core.Command { + c.WaitFunc = func(ctx context.Context, _, respI interface{}) (interface{}, error) { + getResp := respI.(*vpcgw.GatewayNetwork) + api := vpcgw.NewAPI(core.ExtractClient(ctx)) + + return api.WaitForGatewayNetwork(&vpcgw.WaitForGatewayNetworkRequest{ + GatewayNetworkID: getResp.ID, + Zone: getResp.Zone, + Timeout: scw.TimeDurationPtr(gatewayActionTimeout), + RetryInterval: core.DefaultRetryInterval, + }) + } + + return c +} + +func gatewayNetworkDeleteBuilder(c *core.Command) *core.Command { + c.WaitFunc = func(ctx context.Context, argsI, _ interface{}) (interface{}, error) { + getResp := argsI.(*vpcgw.DeleteGatewayNetworkRequest) + api := vpcgw.NewAPI(core.ExtractClient(ctx)) + gwNetwork, err := api.WaitForGatewayNetwork(&vpcgw.WaitForGatewayNetworkRequest{ + GatewayNetworkID: getResp.GatewayNetworkID, + Zone: getResp.Zone, + Timeout: scw.TimeDurationPtr(gatewayActionTimeout), + RetryInterval: core.DefaultRetryInterval, + }) + if err != nil { + notFoundError := &scw.ResourceNotFoundError{} + responseError := &scw.ResponseError{} + if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) { + return &core.SuccessResult{ + Resource: "gateway-network", + Verb: "delete", + }, nil + } + + return nil, err + } + + return gwNetwork, nil + } + + return c +} diff --git a/internal/namespaces/vpcgw/v2/custom_gateway_type.go b/internal/namespaces/vpcgw/v2/custom_gateway_type.go new file mode 100644 index 0000000000..73533e3fe9 --- /dev/null +++ b/internal/namespaces/vpcgw/v2/custom_gateway_type.go @@ -0,0 +1,23 @@ +package vpcgw + +import ( + "context" + + "github.com/scaleway/scaleway-cli/v2/core" + "github.com/scaleway/scaleway-sdk-go/api/vpcgw/v2" +) + +func vpcgwGatewayTypeListBuilder(c *core.Command) *core.Command { + c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + res, err := runner(ctx, argsI) + if err != nil { + return nil, err + } + + typesResponse := res.(*vpcgw.ListGatewayTypesResponse) + + return typesResponse.Types, nil + }) + + return c +} diff --git a/scripts/check-size.sh b/scripts/check-size.sh index 8cbc2cbb42..ac0730eeba 100755 --- a/scripts/check-size.sh +++ b/scripts/check-size.sh @@ -1,6 +1,6 @@ #/bin/env bash -MAX_BINARY_SIZE=50000000 +MAX_BINARY_SIZE=52000000 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" From 059580c54f20407627c64120b71552ba85b203f3 Mon Sep 17 00:00:00 2001 From: Mia-Cross Date: Wed, 26 Mar 2025 16:11:41 +0100 Subject: [PATCH 08/24] feat(instance): redirect to scw login when no credentials are provided (#4617) --- core/client.go | 5 ++--- internal/platform/terminal/terminal_client.go | 22 +++++++++++++++---- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/core/client.go b/core/client.go index e08c11cc06..c31aa9532b 100644 --- a/core/client.go +++ b/core/client.go @@ -1,7 +1,6 @@ package core import ( - "fmt" "net/http" "github.com/scaleway/scaleway-cli/v2/internal/platform" @@ -25,7 +24,7 @@ func createAnonymousClient(httpClient *http.Client, buildInfo *BuildInfo) (*scw. } func createClientError(err error) error { - credentialsHint := "You can get your credentials here: https://console.scaleway.com/iam/api-keys" + credentialsHint := "You can check your credentials here: https://console.scaleway.com/iam/api-keys" if clientError, isClientError := err.(*platform.ClientError); isClientError { err = &CliError{ @@ -35,5 +34,5 @@ func createClientError(err error) error { } } - return fmt.Errorf("failed to create client: %w", err) + return err } diff --git a/internal/platform/terminal/terminal_client.go b/internal/platform/terminal/terminal_client.go index b578e279a8..1e7fb0ee50 100644 --- a/internal/platform/terminal/terminal_client.go +++ b/internal/platform/terminal/terminal_client.go @@ -97,9 +97,9 @@ func errIsConfigFileNotFound(err error) bool { // configErrorDetails generate a detailed error message for an invalid client option. func configErrorDetails(configKey, varEnv string) string { // TODO: update the more info link - return fmt.Sprintf(`%s can be initialised using the command "scw init". + return fmt.Sprintf(`%s can be initialized using the command "scw init". -After initialisation, there are three ways to provide %s: +After initialization, there are three ways to provide %s: - with the Scaleway config file, in the %s key: %s; - with the %s environement variable; @@ -114,10 +114,25 @@ More info: https://github.com/scaleway/scaleway-sdk-go/tree/master/scw#scaleway- ) } +// noConfigErrorDetails prints a message prompting the user to run 'scw login' when both the access key +// and the secret key are missing. +func noConfigErrorDetails() string { + return `You can create a new API keypair using the command "scw login".` +} + // validateClient validate a client configuration and make sure all mandatory setting are present. // This function is only call for commands that require a valid client. func validateClient(client *scw.Client) error { - accessKey, _ := client.GetAccessKey() + accessKey, accessKeyExists := client.GetAccessKey() + secretKey, secretKeyExists := client.GetSecretKey() + + if !accessKeyExists && !secretKeyExists { + return &platform.ClientError{ + Err: errors.New("no credentials provided"), + Details: noConfigErrorDetails(), + } + } + if accessKey == "" { return &platform.ClientError{ Err: errors.New("access key is required"), @@ -134,7 +149,6 @@ func validateClient(client *scw.Client) error { } } - secretKey, _ := client.GetSecretKey() if secretKey == "" { return &platform.ClientError{ Err: errors.New("secret key is required"), From 35674038f14d333f5cf87a629824b7e2ad588cf2 Mon Sep 17 00:00:00 2001 From: Scaleway Bot Date: Wed, 26 Mar 2025 16:22:59 +0100 Subject: [PATCH 09/24] feat(interlink): add connection & revamp doc (#4618) --- ...ll-usage-interlink-connection-usage.golden | 15 ++++ ...l-usage-interlink-link-create-usage.golden | 9 ++- ...-all-usage-interlink-link-get-usage.golden | 2 +- ...all-usage-interlink-link-list-usage.golden | 4 +- ...test-all-usage-interlink-link-usage.golden | 2 +- ...-usage-interlink-partner-list-usage.golden | 2 +- ...t-all-usage-interlink-partner-usage.golden | 2 +- ...-all-usage-interlink-pop-list-usage.golden | 5 +- ...sage-interlink-routing-policy-usage.golden | 2 +- .../test-all-usage-interlink-usage.golden | 7 +- docs/commands/interlink.md | 55 +++++++++----- .../interlink/v1beta1/interlink_cli.go | 71 +++++++++++++------ 12 files changed, 118 insertions(+), 58 deletions(-) create mode 100644 cmd/scw/testdata/test-all-usage-interlink-connection-usage.golden diff --git a/cmd/scw/testdata/test-all-usage-interlink-connection-usage.golden b/cmd/scw/testdata/test-all-usage-interlink-connection-usage.golden new file mode 100644 index 0000000000..419c8f6f91 --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-interlink-connection-usage.golden @@ -0,0 +1,15 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Connection commands. + +USAGE: + scw interlink connection + +FLAGS: + -h, --help help for connection + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use diff --git a/cmd/scw/testdata/test-all-usage-interlink-link-create-usage.golden b/cmd/scw/testdata/test-all-usage-interlink-link-create-usage.golden index 6d0fa9dd98..9dcab473c9 100644 --- a/cmd/scw/testdata/test-all-usage-interlink-link-create-usage.golden +++ b/cmd/scw/testdata/test-all-usage-interlink-link-create-usage.golden @@ -1,6 +1,6 @@ 🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 🟥🟥🟥 STDERR️️ 🟥🟥🟥️ -Create a link (InterLink connection) in a given PoP, specifying its various configuration details. For the moment only hosted links (faciliated by partners) are available, though in the future dedicated and shared links will also be possible. +Create a link (InterLink session / logical InterLink resource) in a given PoP, specifying its various configuration details. Links can either be hosted (faciliated by partners' shared physical connections) or self-hosted (for users who have purchased a dedicated physical connection). USAGE: scw interlink link create [arg=value ...] @@ -10,10 +10,9 @@ ARGS: name Name of the link [tags.{index}] List of tags to apply to the link pop-id PoP (location) where the link will be created - bandwidth-mbps Desired bandwidth for the link. Must be compatible with available link bandwidths and remaining bandwidth capacity of the port - [dedicated] If true, a dedicated link (1 link per port, dedicated to one customer) will be crated. It is not necessary to specify a `port_id` or `partner_id`. A new port will created and assigned to the link. Note that Scaleway has not yet enabled the creation of dedicated links, this field is reserved for future use. - [port-id] If set, a shared link (N links per port, one of which is this customer's port) will be created. As the customer, specify the ID of the port you already have for this link. Note that shared links are not currently available. Note that Scaleway has not yet enabled the creation of shared links, this field is reserved for future use. - [partner-id] If set, a hosted link (N links per port on a partner port) will be created. Specify the ID of the chosen partner, who already has a shareable port with available bandwidth. Note that this is currently the only type of link offered by Scaleway, and therefore this field must be set when creating a link. + bandwidth-mbps Desired bandwidth for the link. Must be compatible with available link bandwidths and remaining bandwidth capacity of the connection + [connection-id] If set, creates a self-hosted link using this dedicated physical connection. As the customer, specify the ID of the physical connection you already have for this link. + [partner-id] If set, creates a hosted link on a partner's connection. Specify the ID of the chosen partner, who already has a shared connection with available bandwidth. [region=fr-par] Region to target. If none is passed will use default region from the config (fr-par | nl-ams | pl-waw) FLAGS: diff --git a/cmd/scw/testdata/test-all-usage-interlink-link-get-usage.golden b/cmd/scw/testdata/test-all-usage-interlink-link-get-usage.golden index e38a3affd4..963f731b41 100644 --- a/cmd/scw/testdata/test-all-usage-interlink-link-get-usage.golden +++ b/cmd/scw/testdata/test-all-usage-interlink-link-get-usage.golden @@ -1,6 +1,6 @@ 🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 🟥🟥🟥 STDERR️️ 🟥🟥🟥️ -Get a link (InterLink connection) for the given link ID. The response object includes information about the link's various configuration details. +Get a link (InterLink session / logical InterLink resource) for the given link ID. The response object includes information about the link's various configuration details. USAGE: scw interlink link get [arg=value ...] diff --git a/cmd/scw/testdata/test-all-usage-interlink-link-list-usage.golden b/cmd/scw/testdata/test-all-usage-interlink-link-list-usage.golden index cae69183e2..3066791845 100644 --- a/cmd/scw/testdata/test-all-usage-interlink-link-list-usage.golden +++ b/cmd/scw/testdata/test-all-usage-interlink-link-list-usage.golden @@ -13,12 +13,14 @@ ARGS: [status] Link status to filter for (unknown_link_status | configuring | failed | requested | refused | expired | provisioning | active | limited_connectivity | all_down | deprovisioning | deleted | locked) [bgp-v4-status] BGP IPv4 status to filter for (unknown_bgp_status | up | down) [bgp-v6-status] BGP IPv6 status to filter for (unknown_bgp_status | up | down) - [pop-id] Filter for links attached to this PoP (via ports) + [pop-id] Filter for links attached to this PoP (via connections) [bandwidth-mbps] Filter for link bandwidth (in Mbps) [partner-id] Filter for links hosted by this partner [vpc-id] Filter for links attached to this VPC [routing-policy-id] Filter for links using this routing policy [pairing-key] Filter for the link with this pairing_key + [kind] Filter for hosted or self-hosted links (hosted | self_hosted) + [connection-id] Filter for links self-hosted on this connection [organization-id] Organization ID to filter for [region=fr-par] Region to target. If none is passed will use default region from the config (fr-par | nl-ams | pl-waw | all) diff --git a/cmd/scw/testdata/test-all-usage-interlink-link-usage.golden b/cmd/scw/testdata/test-all-usage-interlink-link-usage.golden index 7b7b32fb78..e5f326be79 100644 --- a/cmd/scw/testdata/test-all-usage-interlink-link-usage.golden +++ b/cmd/scw/testdata/test-all-usage-interlink-link-usage.golden @@ -1,6 +1,6 @@ 🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 🟥🟥🟥 STDERR️️ 🟥🟥🟥️ -Links commands. +Link commands. USAGE: scw interlink link diff --git a/cmd/scw/testdata/test-all-usage-interlink-partner-list-usage.golden b/cmd/scw/testdata/test-all-usage-interlink-partner-list-usage.golden index 2cf7ea44c7..0c7cc52ac7 100644 --- a/cmd/scw/testdata/test-all-usage-interlink-partner-list-usage.golden +++ b/cmd/scw/testdata/test-all-usage-interlink-partner-list-usage.golden @@ -7,7 +7,7 @@ USAGE: ARGS: [order-by] Order in which to return results (name_asc | name_desc) - [pop-ids.{index}] Filter for partners present (offering a port) in one of these PoPs + [pop-ids.{index}] Filter for partners present (offering a connection) in one of these PoPs [region=fr-par] Region to target. If none is passed will use default region from the config (fr-par | nl-ams | pl-waw | all) FLAGS: diff --git a/cmd/scw/testdata/test-all-usage-interlink-partner-usage.golden b/cmd/scw/testdata/test-all-usage-interlink-partner-usage.golden index c7498aa01e..b30e8bf1d5 100644 --- a/cmd/scw/testdata/test-all-usage-interlink-partner-usage.golden +++ b/cmd/scw/testdata/test-all-usage-interlink-partner-usage.golden @@ -1,6 +1,6 @@ 🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 🟥🟥🟥 STDERR️️ 🟥🟥🟥️ -Partners commands. +Partner commands. USAGE: scw interlink partner diff --git a/cmd/scw/testdata/test-all-usage-interlink-pop-list-usage.golden b/cmd/scw/testdata/test-all-usage-interlink-pop-list-usage.golden index 1d593b2514..cebad1ddf7 100644 --- a/cmd/scw/testdata/test-all-usage-interlink-pop-list-usage.golden +++ b/cmd/scw/testdata/test-all-usage-interlink-pop-list-usage.golden @@ -9,8 +9,9 @@ ARGS: [order-by] Order in which to return results (name_asc | name_desc) [name] PoP name to filter for [hosting-provider-name] Hosting provider name to filter for - [partner-id] Filter for PoPs hosting an available shared port from this partner - [link-bandwidth-mbps] Filter for PoPs with a shared port allowing this bandwidth size. Note that we cannot guarantee that PoPs returned will have available capacity. + [partner-id] Filter for PoPs hosting an available shared connection from this partner + [link-bandwidth-mbps] Filter for PoPs with a shared connection allowing this bandwidth size. Note that we cannot guarantee that PoPs returned will have available capacity. + [dedicated-available] Filter for PoPs with a dedicated connection available for self-hosted links. [region=fr-par] Region to target. If none is passed will use default region from the config (fr-par | nl-ams | pl-waw | all) FLAGS: diff --git a/cmd/scw/testdata/test-all-usage-interlink-routing-policy-usage.golden b/cmd/scw/testdata/test-all-usage-interlink-routing-policy-usage.golden index 75081dc1a1..452be3b785 100644 --- a/cmd/scw/testdata/test-all-usage-interlink-routing-policy-usage.golden +++ b/cmd/scw/testdata/test-all-usage-interlink-routing-policy-usage.golden @@ -1,6 +1,6 @@ 🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 🟥🟥🟥 STDERR️️ 🟥🟥🟥️ -Routing policies commands. +Routing policy commands. USAGE: scw interlink routing-policy diff --git a/cmd/scw/testdata/test-all-usage-interlink-usage.golden b/cmd/scw/testdata/test-all-usage-interlink-usage.golden index 6b184368c1..c83df827ac 100644 --- a/cmd/scw/testdata/test-all-usage-interlink-usage.golden +++ b/cmd/scw/testdata/test-all-usage-interlink-usage.golden @@ -6,10 +6,11 @@ USAGE: scw interlink AVAILABLE COMMANDS: - link Links commands - partner Partners commands + connection Connection commands + link Link commands + partner Partner commands pop PoP commands - routing-policy Routing policies commands + routing-policy Routing policy commands FLAGS: -h, --help help for interlink diff --git a/docs/commands/interlink.md b/docs/commands/interlink.md index 57fb4e8658..fe0ed90d10 100644 --- a/docs/commands/interlink.md +++ b/docs/commands/interlink.md @@ -2,7 +2,8 @@ # Documentation for `scw interlink` This API allows you to manage your InterLink services. -- [Links commands](#links-commands) +- [Connection commands](#connection-commands) +- [Link commands](#link-commands) - [Attach a routing policy](#attach-a-routing-policy) - [Attach a VPC](#attach-a-vpc) - [Create a link](#create-a-link) @@ -14,13 +15,13 @@ This API allows you to manage your InterLink services. - [Get a link](#get-a-link) - [List links](#list-links) - [Update a link](#update-a-link) -- [Partners commands](#partners-commands) +- [Partner commands](#partner-commands) - [Get a partner](#get-a-partner) - [List available partners](#list-available-partners) - [PoP commands](#pop-commands) - [Get a PoP](#get-a-pop) - [List PoPs](#list-pops) -- [Routing policies commands](#routing-policies-commands) +- [Routing policy commands](#routing-policy-commands) - [Create a routing policy](#create-a-routing-policy) - [Delete a routing policy](#delete-a-routing-policy) - [Get routing policy](#get-routing-policy) @@ -28,9 +29,23 @@ This API allows you to manage your InterLink services. - [Update a routing policy](#update-a-routing-policy) -## Links commands +## Connection commands -Links commands. +Connection commands. + +Connection commands. + +**Usage:** + +``` +scw interlink connection +``` + + + +## Link commands + +Link commands. ### Attach a routing policy @@ -77,7 +92,7 @@ scw interlink link attach_vpc [arg=value ...] ### Create a link -Create a link (InterLink connection) in a given PoP, specifying its various configuration details. For the moment only hosted links (faciliated by partners) are available, though in the future dedicated and shared links will also be possible. +Create a link (InterLink session / logical InterLink resource) in a given PoP, specifying its various configuration details. Links can either be hosted (faciliated by partners' shared physical connections) or self-hosted (for users who have purchased a dedicated physical connection). **Usage:** @@ -94,10 +109,9 @@ scw interlink link create [arg=value ...] | name | Required | Name of the link | | tags.{index} | | List of tags to apply to the link | | pop-id | Required | PoP (location) where the link will be created | -| bandwidth-mbps | Required | Desired bandwidth for the link. Must be compatible with available link bandwidths and remaining bandwidth capacity of the port | -| dedicated | | If true, a dedicated link (1 link per port, dedicated to one customer) will be crated. It is not necessary to specify a `port_id` or `partner_id`. A new port will created and assigned to the link. Note that Scaleway has not yet enabled the creation of dedicated links, this field is reserved for future use. | -| port-id | | If set, a shared link (N links per port, one of which is this customer's port) will be created. As the customer, specify the ID of the port you already have for this link. Note that shared links are not currently available. Note that Scaleway has not yet enabled the creation of shared links, this field is reserved for future use. | -| partner-id | | If set, a hosted link (N links per port on a partner port) will be created. Specify the ID of the chosen partner, who already has a shareable port with available bandwidth. Note that this is currently the only type of link offered by Scaleway, and therefore this field must be set when creating a link. | +| bandwidth-mbps | Required | Desired bandwidth for the link. Must be compatible with available link bandwidths and remaining bandwidth capacity of the connection | +| connection-id | | If set, creates a self-hosted link using this dedicated physical connection. As the customer, specify the ID of the physical connection you already have for this link. | +| partner-id | | If set, creates a hosted link on a partner's connection. Specify the ID of the chosen partner, who already has a shared connection with available bandwidth. | | region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw` | Region to target. If none is passed will use default region from the config | @@ -204,7 +218,7 @@ scw interlink link enable_propagation [arg=value ...] ### Get a link -Get a link (InterLink connection) for the given link ID. The response object includes information about the link's various configuration details. +Get a link (InterLink session / logical InterLink resource) for the given link ID. The response object includes information about the link's various configuration details. **Usage:** @@ -244,12 +258,14 @@ scw interlink link list [arg=value ...] | status | One of: `unknown_link_status`, `configuring`, `failed`, `requested`, `refused`, `expired`, `provisioning`, `active`, `limited_connectivity`, `all_down`, `deprovisioning`, `deleted`, `locked` | Link status to filter for | | bgp-v4-status | One of: `unknown_bgp_status`, `up`, `down` | BGP IPv4 status to filter for | | bgp-v6-status | One of: `unknown_bgp_status`, `up`, `down` | BGP IPv6 status to filter for | -| pop-id | | Filter for links attached to this PoP (via ports) | +| pop-id | | Filter for links attached to this PoP (via connections) | | bandwidth-mbps | | Filter for link bandwidth (in Mbps) | | partner-id | | Filter for links hosted by this partner | | vpc-id | | Filter for links attached to this VPC | | routing-policy-id | | Filter for links using this routing policy | | pairing-key | | Filter for the link with this pairing_key | +| kind | One of: `hosted`, `self_hosted` | Filter for hosted or self-hosted links | +| connection-id | | Filter for links self-hosted on this connection | | organization-id | | Organization ID to filter for | | region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw`, `all` | Region to target. If none is passed will use default region from the config | @@ -277,9 +293,9 @@ scw interlink link update [arg=value ...] -## Partners commands +## Partner commands -Partners commands. +Partner commands. ### Get a partner @@ -318,7 +334,7 @@ scw interlink partner list [arg=value ...] | Name | | Description | |------|---|-------------| | order-by | One of: `name_asc`, `name_desc` | Order in which to return results | -| pop-ids.{index} | | Filter for partners present (offering a port) in one of these PoPs | +| pop-ids.{index} | | Filter for partners present (offering a connection) in one of these PoPs | | region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw`, `all` | Region to target. If none is passed will use default region from the config | @@ -366,15 +382,16 @@ scw interlink pop list [arg=value ...] | order-by | One of: `name_asc`, `name_desc` | Order in which to return results | | name | | PoP name to filter for | | hosting-provider-name | | Hosting provider name to filter for | -| partner-id | | Filter for PoPs hosting an available shared port from this partner | -| link-bandwidth-mbps | | Filter for PoPs with a shared port allowing this bandwidth size. Note that we cannot guarantee that PoPs returned will have available capacity. | +| partner-id | | Filter for PoPs hosting an available shared connection from this partner | +| link-bandwidth-mbps | | Filter for PoPs with a shared connection allowing this bandwidth size. Note that we cannot guarantee that PoPs returned will have available capacity. | +| dedicated-available | | Filter for PoPs with a dedicated connection available for self-hosted links. | | region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw`, `all` | Region to target. If none is passed will use default region from the config | -## Routing policies commands +## Routing policy commands -Routing policies commands. +Routing policy commands. ### Create a routing policy diff --git a/internal/namespaces/interlink/v1beta1/interlink_cli.go b/internal/namespaces/interlink/v1beta1/interlink_cli.go index 0a4b0f7bff..8c48218c73 100644 --- a/internal/namespaces/interlink/v1beta1/interlink_cli.go +++ b/internal/namespaces/interlink/v1beta1/interlink_cli.go @@ -22,6 +22,7 @@ func GetGeneratedCommands() *core.Commands { interlinkRoot(), interlinkPartner(), interlinkPop(), + interlinkConnection(), interlinkLink(), interlinkRoutingPolicy(), interlinkPartnerList(), @@ -57,8 +58,8 @@ func interlinkRoot() *core.Command { func interlinkPartner() *core.Command { return &core.Command{ - Short: `Partners commands`, - Long: `Partners commands.`, + Short: `Partner commands`, + Long: `Partner commands.`, Namespace: "interlink", Resource: "partner", } @@ -73,10 +74,19 @@ func interlinkPop() *core.Command { } } +func interlinkConnection() *core.Command { + return &core.Command{ + Short: `Connection commands`, + Long: `Connection commands.`, + Namespace: "interlink", + Resource: "connection", + } +} + func interlinkLink() *core.Command { return &core.Command{ - Short: `Links commands`, - Long: `Links commands.`, + Short: `Link commands`, + Long: `Link commands.`, Namespace: "interlink", Resource: "link", } @@ -84,8 +94,8 @@ func interlinkLink() *core.Command { func interlinkRoutingPolicy() *core.Command { return &core.Command{ - Short: `Routing policies commands`, - Long: `Routing policies commands.`, + Short: `Routing policy commands`, + Long: `Routing policy commands.`, Namespace: "interlink", Resource: "routing-policy", } @@ -111,7 +121,7 @@ func interlinkPartnerList() *core.Command { }, { Name: "pop-ids.{index}", - Short: `Filter for partners present (offering a port) in one of these PoPs`, + Short: `Filter for partners present (offering a connection) in one of these PoPs`, Required: false, Deprecated: false, Positional: false, @@ -207,14 +217,21 @@ func interlinkPopList() *core.Command { }, { Name: "partner-id", - Short: `Filter for PoPs hosting an available shared port from this partner`, + Short: `Filter for PoPs hosting an available shared connection from this partner`, Required: false, Deprecated: false, Positional: false, }, { Name: "link-bandwidth-mbps", - Short: `Filter for PoPs with a shared port allowing this bandwidth size. Note that we cannot guarantee that PoPs returned will have available capacity.`, + Short: `Filter for PoPs with a shared connection allowing this bandwidth size. Note that we cannot guarantee that PoPs returned will have available capacity.`, + Required: false, + Deprecated: false, + Positional: false, + }, + { + Name: "dedicated-available", + Short: `Filter for PoPs with a dedicated connection available for self-hosted links.`, Required: false, Deprecated: false, Positional: false, @@ -362,7 +379,7 @@ func interlinkLinkList() *core.Command { }, { Name: "pop-id", - Short: `Filter for links attached to this PoP (via ports)`, + Short: `Filter for links attached to this PoP (via connections)`, Required: false, Deprecated: false, Positional: false, @@ -402,6 +419,21 @@ func interlinkLinkList() *core.Command { Deprecated: false, Positional: false, }, + { + Name: "kind", + Short: `Filter for hosted or self-hosted links`, + Required: false, + Deprecated: false, + Positional: false, + EnumValues: []string{"hosted", "self_hosted"}, + }, + { + Name: "connection-id", + Short: `Filter for links self-hosted on this connection`, + Required: false, + Deprecated: false, + Positional: false, + }, { Name: "organization-id", Short: `Organization ID to filter for`, @@ -439,7 +471,7 @@ func interlinkLinkList() *core.Command { func interlinkLinkGet() *core.Command { return &core.Command{ Short: `Get a link`, - Long: `Get a link (InterLink connection) for the given link ID. The response object includes information about the link's various configuration details.`, + Long: `Get a link (InterLink session / logical InterLink resource) for the given link ID. The response object includes information about the link's various configuration details.`, Namespace: "interlink", Resource: "link", Verb: "get", @@ -469,7 +501,7 @@ func interlinkLinkGet() *core.Command { func interlinkLinkCreate() *core.Command { return &core.Command{ Short: `Create a link`, - Long: `Create a link (InterLink connection) in a given PoP, specifying its various configuration details. For the moment only hosted links (facilitated by partners) are available, though in the future dedicated and shared links will also be possible.`, + Long: `Create a link (InterLink session / logical InterLink resource) in a given PoP, specifying its various configuration details. Links can either be hosted (faciliated by partners' shared physical connections) or self-hosted (for users who have purchased a dedicated physical connection).`, Namespace: "interlink", Resource: "link", Verb: "create", @@ -500,28 +532,21 @@ func interlinkLinkCreate() *core.Command { }, { Name: "bandwidth-mbps", - Short: `Desired bandwidth for the link. Must be compatible with available link bandwidths and remaining bandwidth capacity of the port`, + Short: `Desired bandwidth for the link. Must be compatible with available link bandwidths and remaining bandwidth capacity of the connection`, Required: true, Deprecated: false, Positional: false, }, { - Name: "dedicated", - Short: `If true, a dedicated link (1 link per port, dedicated to one customer) will be crated. It is not necessary to specify a ` + "`" + `port_id` + "`" + ` or ` + "`" + `partner_id` + "`" + `. A new port will created and assigned to the link. Note that Scaleway has not yet enabled the creation of dedicated links, this field is reserved for future use.`, - Required: false, - Deprecated: false, - Positional: false, - }, - { - Name: "port-id", - Short: `If set, a shared link (N links per port, one of which is this customer's port) will be created. As the customer, specify the ID of the port you already have for this link. Note that shared links are not currently available. Note that Scaleway has not yet enabled the creation of shared links, this field is reserved for future use.`, + Name: "connection-id", + Short: `If set, creates a self-hosted link using this dedicated physical connection. As the customer, specify the ID of the physical connection you already have for this link.`, Required: false, Deprecated: false, Positional: false, }, { Name: "partner-id", - Short: `If set, a hosted link (N links per port on a partner port) will be created. Specify the ID of the chosen partner, who already has a shareable port with available bandwidth. Note that this is currently the only type of link offered by Scaleway, and therefore this field must be set when creating a link.`, + Short: `If set, creates a hosted link on a partner's connection. Specify the ID of the chosen partner, who already has a shared connection with available bandwidth.`, Required: false, Deprecated: false, Positional: false, From fce56b979c3b2eba8a323bed2e9c215e1eb27c15 Mon Sep 17 00:00:00 2001 From: Scaleway Bot Date: Fri, 28 Mar 2025 17:31:17 +0100 Subject: [PATCH 10/24] docs(iam): create user spec (#4619) --- cmd/scw/testdata/test-all-usage-iam-user-create-usage.golden | 2 +- docs/commands/iam.md | 2 +- go.mod | 2 +- go.sum | 4 ++-- internal/namespaces/iam/v1alpha1/iam_cli.go | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cmd/scw/testdata/test-all-usage-iam-user-create-usage.golden b/cmd/scw/testdata/test-all-usage-iam-user-create-usage.golden index edaf5b56f0..65f49567df 100644 --- a/cmd/scw/testdata/test-all-usage-iam-user-create-usage.golden +++ b/cmd/scw/testdata/test-all-usage-iam-user-create-usage.golden @@ -1,6 +1,6 @@ 🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 🟥🟥🟥 STDERR️️ 🟥🟥🟥️ -Create a new user. You must define the `organization_id` and the `email` in your request. +Create a new user. You must define the `organization_id` in your request. If you are adding a member, enter the member's details. If you are adding a guest, you must define the `email` and not add the member attribute. USAGE: scw iam user create [arg=value ...] diff --git a/docs/commands/iam.md b/docs/commands/iam.md index 6551af92ed..8496bc4d44 100644 --- a/docs/commands/iam.md +++ b/docs/commands/iam.md @@ -1045,7 +1045,7 @@ Users management commands. ### Create a new user -Create a new user. You must define the `organization_id` and the `email` in your request. +Create a new user. You must define the `organization_id` in your request. If you are adding a member, enter the member's details. If you are adding a guest, you must define the `email` and not add the member attribute. **Usage:** diff --git a/go.mod b/go.mod index 9f8aa259cc..0a2b6efad4 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,7 @@ require ( github.com/mattn/go-isatty v0.0.20 github.com/moby/buildkit v0.13.2 github.com/opencontainers/go-digest v1.0.0 - github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250326091623-c76ff7151d13 + github.com/scaleway/scaleway-sdk-go v1.0.0-beta.33.0.20250327145452-20e9e72214ed github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 github.com/spf13/cobra v1.9.1 github.com/spf13/pflag v1.0.6 diff --git a/go.sum b/go.sum index 93b108ab72..7f490ff82d 100644 --- a/go.sum +++ b/go.sum @@ -462,8 +462,8 @@ github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUz github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 h1:OkMGxebDjyw0ULyrTYWeN0UNCCkmCWfjPnIA2W6oviI= github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06/go.mod h1:+ePHsJ1keEjQtpvf9HHw0f4ZeJ0TLRsxhunSI2hYJSs= -github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250326091623-c76ff7151d13 h1:GLd3G2hvNpzjMUYOdLO79M+jiicgXnaf8eCKK+nOHLY= -github.com/scaleway/scaleway-sdk-go v1.0.0-beta.32.0.20250326091623-c76ff7151d13/go.mod h1:792k1RTU+5JeMXm35/e2Wgp71qPH/DmDoZrRc+EFZDk= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.33.0.20250327145452-20e9e72214ed h1:klCw4VdfiQ+nTqNoY8ymobNj0ZYs5oDQ9A6ilvndopg= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.33.0.20250327145452-20e9e72214ed/go.mod h1:792k1RTU+5JeMXm35/e2Wgp71qPH/DmDoZrRc+EFZDk= github.com/sclevine/spec v1.4.0 h1:z/Q9idDcay5m5irkZ28M7PtQM4aOISzOpj4bUPkDee8= github.com/sclevine/spec v1.4.0/go.mod h1:LvpgJaFyvQzRvc1kaDs0bulYwzC70PbiYjC4QnFHkOM= github.com/secure-systems-lab/go-securesystemslib v0.8.0 h1:mr5An6X45Kb2nddcFlbmfHkLguCE9laoZCUzEEpIZXA= diff --git a/internal/namespaces/iam/v1alpha1/iam_cli.go b/internal/namespaces/iam/v1alpha1/iam_cli.go index fd097cf291..dd2451e997 100644 --- a/internal/namespaces/iam/v1alpha1/iam_cli.go +++ b/internal/namespaces/iam/v1alpha1/iam_cli.go @@ -665,7 +665,7 @@ func iamUserDelete() *core.Command { func iamUserCreate() *core.Command { return &core.Command{ Short: `Create a new user`, - Long: `Create a new user. You must define the ` + "`" + `organization_id` + "`" + ` and the ` + "`" + `email` + "`" + ` in your request.`, + Long: `Create a new user. You must define the ` + "`" + `organization_id` + "`" + ` in your request. If you are adding a member, enter the member's details. If you are adding a guest, you must define the ` + "`" + `email` + "`" + ` and not add the member attribute.`, Namespace: "iam", Resource: "user", Verb: "create", From b3d2833b6a6ed625e357bd9f29e5083a8b405bdc Mon Sep 17 00:00:00 2001 From: SamyOubouaziz Date: Fri, 28 Mar 2025 17:31:40 +0100 Subject: [PATCH 11/24] fix(docs): update doc build workflow (#4541) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Rémy Léone --- .github/workflows/deploy-docs.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 8b0d3e3a0c..89c40e8c2d 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -31,8 +31,8 @@ jobs: docker run --rm -i -v ${PWD}/docs:/docs squidfunk/mkdocs-material build - name: Download and set up AWS CLI run: | - apt update - apt install curl unzip -y + sudo apt update + sudo apt install curl unzip -y curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" unzip awscliv2.zip ./aws/install From 6004edeac770b675e84d2970e67f2e83c50c269e Mon Sep 17 00:00:00 2001 From: Olivier Cano Date: Mon, 31 Mar 2025 09:54:57 +0200 Subject: [PATCH 12/24] feat(core): support positional args as dynamic args as well (#4621) Signed-off-by: Olivier Cano --- core/arg_specs.go | 1 + core/cobra_utils.go | 7 ++- core/cobra_utils_test.go | 133 ++++++++++++++++++++++++++++----------- 3 files changed, 103 insertions(+), 38 deletions(-) diff --git a/core/arg_specs.go b/core/arg_specs.go index d8ad143e90..402fc6c3b1 100644 --- a/core/arg_specs.go +++ b/core/arg_specs.go @@ -14,6 +14,7 @@ var AllLocalities = "all" type ArgSpecs []*ArgSpec +// GetPositionalArg returns the last positional argument from the arg specs. func (s ArgSpecs) GetPositionalArg() *ArgSpec { var positionalArg *ArgSpec for _, argSpec := range s { diff --git a/core/cobra_utils.go b/core/cobra_utils.go index 8b401c5c55..4a46d13192 100644 --- a/core/cobra_utils.go +++ b/core/cobra_utils.go @@ -45,8 +45,11 @@ func cobraRun(ctx context.Context, cmd *Command) func(*cobra.Command, []string) positionalArgSpec := cmd.ArgSpecs.GetPositionalArg() - // If this command has no positional argument we execute the run - if positionalArgSpec == nil { + // If this command has no positional argument or the positional arg is already passed, we execute the run + if positionalArgSpec == nil || rawArgs.Has(positionalArgSpec.Name) { + if positionalArgSpec != nil && rawArgs.Has(positionalArgSpec.Name) { + rawArgs = rawArgs.RemoveAllPositional() + } data, err := run(ctx, cobraCmd, cmd, rawArgs) if err != nil { return err diff --git a/core/cobra_utils_test.go b/core/cobra_utils_test.go index cbd5dc81c1..26199ddb86 100644 --- a/core/cobra_utils_test.go +++ b/core/cobra_utils_test.go @@ -17,6 +17,11 @@ type testType struct { Tag string } +type testTypeManyTags struct { + NameID string + Tags []string +} + type testDate struct { Date *time.Time } @@ -78,6 +83,45 @@ func testGetCommands() *core.Commands { return argsI, nil }, }, + &core.Command{ + Namespace: "test", + Resource: "many-positional", + ArgSpecs: core.ArgSpecs{ + { + Name: "name-id", + Positional: true, + }, + { + Name: "tag", + Positional: true, + }, + }, + AllowAnonymousClient: true, + ArgsType: reflect.TypeOf(testType{}), + Run: func(_ context.Context, argsI interface{}) (i interface{}, e error) { + return argsI, nil + }, + }, + &core.Command{ + Namespace: "test", + Resource: "many-multi-positional", + ArgSpecs: core.ArgSpecs{ + { + Name: "name-id", + Positional: true, + }, + { + Name: "tags", + Positional: true, + }, + }, + AcceptMultiplePositionalArgs: true, + AllowAnonymousClient: true, + ArgsType: reflect.TypeOf(testTypeManyTags{}), + Run: func(_ context.Context, argsI interface{}) (i interface{}, e error) { + return argsI, nil + }, + }, &core.Command{ Namespace: "test", Resource: "raw-args", @@ -200,42 +244,6 @@ func Test_PositionalArg(t *testing.T) { }), ), })) - - t.Run("Invalid1", core.Test(&core.TestConfig{ - Commands: testGetCommands(), - Cmd: "scw test positional name-id=plop tag=world", - Check: core.TestCheckCombine( - core.TestCheckExitCode(1), - core.TestCheckError(&core.CliError{ - Err: errors.New("a positional argument is required for this command"), - Hint: "Try running: scw test positional plop tag=world", - }), - ), - })) - - t.Run("Invalid2", core.Test(&core.TestConfig{ - Commands: testGetCommands(), - Cmd: "scw test positional tag=world name-id=plop", - Check: core.TestCheckCombine( - core.TestCheckExitCode(1), - core.TestCheckError(&core.CliError{ - Err: errors.New("a positional argument is required for this command"), - Hint: "Try running: scw test positional plop tag=world", - }), - ), - })) - - t.Run("Invalid3", core.Test(&core.TestConfig{ - Commands: testGetCommands(), - Cmd: "scw test positional plop name-id=plop", - Check: core.TestCheckCombine( - core.TestCheckExitCode(1), - core.TestCheckError(&core.CliError{ - Err: errors.New("a positional argument is required for this command"), - Hint: "Try running: scw test positional plop", - }), - ), - })) }) t.Run("simple", core.Test(&core.TestConfig{ @@ -244,6 +252,24 @@ func Test_PositionalArg(t *testing.T) { Check: core.TestCheckExitCode(0), })) + t.Run("simple2", core.Test(&core.TestConfig{ + Commands: testGetCommands(), + Cmd: "scw test positional name-id=plop tag=world", + Check: core.TestCheckExitCode(0), + })) + + t.Run("simple3", core.Test(&core.TestConfig{ + Commands: testGetCommands(), + Cmd: "scw test positional tag=world name-id=plop", + Check: core.TestCheckExitCode(0), + })) + + t.Run("simple4", core.Test(&core.TestConfig{ + Commands: testGetCommands(), + Cmd: "scw test positional plop name-id=plop", + Check: core.TestCheckExitCode(0), + })) + t.Run("full command", core.Test(&core.TestConfig{ Commands: testGetCommands(), Cmd: "scw test positional plop tag=world", @@ -276,6 +302,41 @@ func Test_PositionalArg(t *testing.T) { core.TestCheckGolden(), ), })) + + t.Run("many positional", core.Test(&core.TestConfig{ + Commands: testGetCommands(), + Cmd: "scw test many-positional tag1 name-id=plop", + Check: core.TestCheckExitCode(0), + })) + + t.Run("many positional", core.Test(&core.TestConfig{ + Commands: testGetCommands(), + Cmd: "scw test many-positional tag1 name-id=plop", + Check: core.TestCheckCombine( + core.TestCheckExitCode(0), + func(t *testing.T, ctx *core.CheckFuncCtx) { + t.Helper() + res := ctx.Result.(*testType) + assert.Equal(t, "plop", res.NameID) + assert.Equal(t, "tag1", res.Tag) + }, + ), + })) + + t.Run("many multi-positional", core.Test(&core.TestConfig{ + Commands: testGetCommands(), + Cmd: "scw test many-multi-positional pos1 pos2 name-id=plop", + Check: core.TestCheckCombine( + core.TestCheckExitCode(0), + func(t *testing.T, ctx *core.CheckFuncCtx) { + t.Helper() + res := ctx.Result.(*testTypeManyTags) + assert.Equal(t, "plop", res.NameID) + assert.Equal(t, "pos1", res.Tags[0]) + assert.Equal(t, "pos2", res.Tags[1]) + }, + ), + })) } func Test_MultiPositionalArg(t *testing.T) { From d404628287506f2af23fa65052edeff151c864c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20L=C3=A9one?= Date: Mon, 31 Mar 2025 11:53:46 +0200 Subject: [PATCH 13/24] docs: add section for command namespaces (#4620) Co-authored-by: Laure-di <62625835+Laure-di@users.noreply.github.com> --- cmd/scw/testdata/test-main-usage-usage.golden | 91 ++++++++++++------- internal/namespaces/account/v3/custom.go | 2 + .../applesilicon/v1alpha1/custom.go | 2 + .../namespaces/audit_trail/v1alpha1/custom.go | 2 + .../namespaces/autocomplete/autocomplete.go | 1 + internal/namespaces/baremetal/v1/custom.go | 2 + internal/namespaces/billing/v2beta1/custom.go | 2 + internal/namespaces/block/v1alpha1/custom.go | 2 + internal/namespaces/cockpit/v1/custom.go | 2 + .../namespaces/container/v1beta1/custom.go | 2 + internal/namespaces/dedibox/v1/custom.go | 2 + .../namespaces/documentdb/v1beta1/custom.go | 2 + internal/namespaces/domain/v2beta1/custom.go | 2 + .../edge_services/v1alpha1/custom.go | 2 + .../namespaces/flexibleip/v1alpha1/custom.go | 2 + .../namespaces/function/v1beta1/custom.go | 2 + internal/namespaces/help/custom.go | 1 + internal/namespaces/iam/v1alpha1/custom.go | 2 + .../namespaces/inference/v1beta1/custom.go | 2 + internal/namespaces/instance/v1/custom.go | 2 + .../namespaces/interlink/v1beta1/custom.go | 2 + internal/namespaces/iot/v1/custom.go | 2 + internal/namespaces/ipam/v1/custom.go | 2 + internal/namespaces/jobs/v1alpha1/custom.go | 2 + internal/namespaces/k8s/v1/custom.go | 3 + .../namespaces/key_manager/v1alpha1/custom.go | 2 + internal/namespaces/lb/v1/custom.go | 2 + internal/namespaces/marketplace/v2/custom.go | 2 + internal/namespaces/mnq/v1beta1/custom.go | 2 + .../namespaces/mongodb/v1alpha1/custom.go | 2 + .../namespaces/object/v1/custom_command.go | 1 + internal/namespaces/rdb/v1/custom.go | 2 + internal/namespaces/redis/v1/custom.go | 2 + internal/namespaces/registry/v1/custom.go | 3 + internal/namespaces/secret/v1beta1/custom.go | 2 + .../serverless_sqldb/v1alpha1/custom.go | 2 + internal/namespaces/tem/v1alpha1/custom.go | 6 +- internal/namespaces/vpc/v2/custom.go | 2 + internal/namespaces/vpcgw/v1/custom.go | 3 + internal/namespaces/vpcgw/v2/custom.go | 2 + internal/namespaces/webhosting/v1/custom.go | 2 + 41 files changed, 141 insertions(+), 34 deletions(-) diff --git a/cmd/scw/testdata/test-main-usage-usage.golden b/cmd/scw/testdata/test-main-usage-usage.golden index 6721a1c50d..760cd1059b 100644 --- a/cmd/scw/testdata/test-main-usage-usage.golden +++ b/cmd/scw/testdata/test-main-usage-usage.golden @@ -3,54 +3,79 @@ USAGE: scw -AVAILABLE COMMANDS: - account This API allows you to manage your Scaleway Projects +AI COMMANDS: + inference This API allows you to manage your Inference services + +BAREMETAL COMMANDS: apple-silicon Apple silicon API - audit-trail This API allows you to ensure accountability and security by recording events and changes performed within your Scaleway Organization. - autocomplete Autocomplete related commands baremetal Elastic Metal API - billing This API allows you to manage and query your Scaleway billing and consumption - block This API allows you to manage your Block Storage volumes - cockpit This API allows you to manage your Scaleway Cockpit, for storing and visualizing metrics and logs - container This API allows you to manage your Serverless Containers - dns This API allows you to manage your domains, DNS zones and records - document-db This API allows you to manage your Document Databases - edge-services Edge Services API fip This API allows you to manage your Elastic Metal servers' flexible public IP addresses - function Function as a Service API - help Get help about how the CLI works - iam This API allows you to manage Identity and Access Management (IAM) across your Scaleway Organizations, Projects and resources - inference This API allows you to manage your Inference services + +COMPUTE COMMANDS: instance This API allows you to manage your Instances - interlink This API allows you to manage your InterLink services - iot This API allows you to manage your IoT hubs and devices - ipam This API allows you to manage your Scaleway IP addresses with our IP Address Management tool - jobs This API allows you to manage your Serverless Jobs - k8s This API allows you to manage Kubernetes Kapsule and Kosmos clusters - keymanager Key Manager API - lb This API allows you to manage your Scaleway Load Balancer services marketplace This API allows you to find available images for use when launching a Scaleway Instance - mnq These APIs allow you to manage your Messaging and Queuing NATS, Queues and Topics and Events services + +CONFIGURATION COMMANDS: + alias Alias related commands + config Config file management + info Get info about current settings + init Initialize the config + login Login to scaleway + +CONTAINER COMMANDS: + k8s This API allows you to manage Kubernetes Kapsule and Kosmos clusters + registry This API allows you to manage your Container Registry resources + +COST COMMANDS: + billing This API allows you to manage and query your Scaleway billing and consumption + +DATABASE COMMANDS: + document-db This API allows you to manage your Document Databases mongodb This API allows you to manage your Managed Databases for MongoDB® - object Object-storage utils rdb This API allows you to manage your Managed Databases for PostgreSQL and MySQL redis This API allows you to manage your Managed Databases for Redis™ - registry This API allows you to manage your Container Registry resources sdb-sql This API allows you to manage your Serverless SQL Databases - secret Secret Manager API + +DOMAIN & WEBHOSTING COMMANDS: + dns This API allows you to manage your domains, DNS zones and records tem This API allows you to manage your Transactional Email services + webhosting This API allows you to manage your Web Hosting services + +INTEGRATION COMMANDS: + iot This API allows you to manage your IoT hubs and devices + mnq These APIs allow you to manage your Messaging and Queuing NATS, Queues and Topics and Events services + +MONITORING COMMANDS: + audit-trail This API allows you to ensure accountability and security by recording events and changes performed within your Scaleway Organization. + cockpit This API allows you to manage your Scaleway Cockpit, for storing and visualizing metrics and logs + +NETWORK COMMANDS: + edge-services Edge Services API + interlink This API allows you to manage your InterLink services + ipam This API allows you to manage your Scaleway IP addresses with our IP Address Management tool + lb This API allows you to manage your Scaleway Load Balancer services vpc This API allows you to manage your Virtual Private Clouds (VPCs) and Private Networks vpc-gw This API allows you to manage your Public Gateways - webhosting This API allows you to manage your Web Hosting services -CONFIGURATION COMMANDS: - alias Alias related commands - config Config file management - info Get info about current settings - init Initialize the config - login Login to scaleway +SECURITY COMMANDS: + account This API allows you to manage your Scaleway Projects + audit-trail This API allows you to ensure accountability and security by recording events and changes performed within your Scaleway Organization. + iam This API allows you to manage Identity and Access Management (IAM) across your Scaleway Organizations, Projects and resources + keymanager Key Manager API + secret Secret Manager API + +SERVERLESS COMMANDS: + container This API allows you to manage your Serverless Containers + function Function as a Service API + jobs This API allows you to manage your Serverless Jobs + +STORAGE COMMANDS: + block This API allows you to manage your Block Storage volumes + object Object-storage utils + registry This API allows you to manage your Container Registry resources UTILITY COMMANDS: + autocomplete Autocomplete related commands feedback Send feedback to the Scaleway CLI Team! help Get help about how the CLI works shell Start shell mode diff --git a/internal/namespaces/account/v3/custom.go b/internal/namespaces/account/v3/custom.go index 74eac729a2..3b15027fb2 100644 --- a/internal/namespaces/account/v3/custom.go +++ b/internal/namespaces/account/v3/custom.go @@ -7,5 +7,7 @@ import ( func GetCommands() *core.Commands { commands := GetGeneratedCommands() + commands.MustFind("account").Groups = []string{"security"} + return commands } diff --git a/internal/namespaces/applesilicon/v1alpha1/custom.go b/internal/namespaces/applesilicon/v1alpha1/custom.go index 8af1e66a59..f14972c6cf 100644 --- a/internal/namespaces/applesilicon/v1alpha1/custom.go +++ b/internal/namespaces/applesilicon/v1alpha1/custom.go @@ -14,6 +14,8 @@ func GetCommands() *core.Commands { serverWaitCommand(), )) + cmds.MustFind("apple-silicon").Groups = []string{"baremetal"} + human.RegisterMarshalerFunc(applesilicon.ServerTypeCPU{}, cpuMarshalerFunc) human.RegisterMarshalerFunc(applesilicon.ServerTypeDisk{}, diskMarshalerFunc) human.RegisterMarshalerFunc(applesilicon.ServerTypeMemory{}, memoryMarshalerFunc) diff --git a/internal/namespaces/audit_trail/v1alpha1/custom.go b/internal/namespaces/audit_trail/v1alpha1/custom.go index 9a958595ee..c891547727 100644 --- a/internal/namespaces/audit_trail/v1alpha1/custom.go +++ b/internal/namespaces/audit_trail/v1alpha1/custom.go @@ -7,6 +7,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("audit-trail").Groups = []string{"security", "monitoring"} + cmds.MustFind("audit-trail", "event", "list").Override(eventListBuilder) return cmds diff --git a/internal/namespaces/autocomplete/autocomplete.go b/internal/namespaces/autocomplete/autocomplete.go index 875928dd6c..4608766223 100644 --- a/internal/namespaces/autocomplete/autocomplete.go +++ b/internal/namespaces/autocomplete/autocomplete.go @@ -41,6 +41,7 @@ func autocompleteRootCommand() *core.Command { Short: `Autocomplete related commands`, Long: ``, Namespace: "autocomplete", + Groups: []string{"utility"}, } } diff --git a/internal/namespaces/baremetal/v1/custom.go b/internal/namespaces/baremetal/v1/custom.go index a35dee7d4d..2512b7ad31 100644 --- a/internal/namespaces/baremetal/v1/custom.go +++ b/internal/namespaces/baremetal/v1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("baremetal").Groups = []string{"baremetal"} + cmds.Merge(core.NewCommands( serverWaitCommand(), serverAddFlexibleIP(), diff --git a/internal/namespaces/billing/v2beta1/custom.go b/internal/namespaces/billing/v2beta1/custom.go index 4e3626fcc0..945d62633b 100644 --- a/internal/namespaces/billing/v2beta1/custom.go +++ b/internal/namespaces/billing/v2beta1/custom.go @@ -17,6 +17,8 @@ var invoiceTypeMarshalSpecs = human.EnumMarshalSpecs{ func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("billing").Groups = []string{"cost"} + human.RegisterMarshalerFunc( billing.DownloadInvoiceRequestFileType("pdf"), human.EnumMarshalFunc(invoiceTypeMarshalSpecs), diff --git a/internal/namespaces/block/v1alpha1/custom.go b/internal/namespaces/block/v1alpha1/custom.go index 644bacb99c..2130ecf0f4 100644 --- a/internal/namespaces/block/v1alpha1/custom.go +++ b/internal/namespaces/block/v1alpha1/custom.go @@ -45,6 +45,8 @@ var ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("block").Groups = []string{"storage"} + cmds.Add(volumeWaitCommand()) cmds.Add(snapshotWaitCommand()) diff --git a/internal/namespaces/cockpit/v1/custom.go b/internal/namespaces/cockpit/v1/custom.go index 41a64441df..03fe33bcd8 100644 --- a/internal/namespaces/cockpit/v1/custom.go +++ b/internal/namespaces/cockpit/v1/custom.go @@ -7,6 +7,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("cockpit").Groups = []string{"monitoring"} + cmds.MustFind("cockpit", "token", "get").Override(cockpitTokenGetBuilder) return cmds diff --git a/internal/namespaces/container/v1beta1/custom.go b/internal/namespaces/container/v1beta1/custom.go index dc20eee773..a4a80e7612 100644 --- a/internal/namespaces/container/v1beta1/custom.go +++ b/internal/namespaces/container/v1beta1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("container").Groups = []string{"serverless"} + human.RegisterMarshalerFunc( container.NamespaceStatus(""), human.EnumMarshalFunc(namespaceStatusMarshalSpecs), diff --git a/internal/namespaces/dedibox/v1/custom.go b/internal/namespaces/dedibox/v1/custom.go index ad36196b41..1252dc3ba1 100644 --- a/internal/namespaces/dedibox/v1/custom.go +++ b/internal/namespaces/dedibox/v1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("dedibox").Groups = []string{"baremetal"} + for _, commandPath := range [][]string{ {"dedibox", "server", "list"}, {"dedibox", "service", "list"}, diff --git a/internal/namespaces/documentdb/v1beta1/custom.go b/internal/namespaces/documentdb/v1beta1/custom.go index 336fb18b5c..3cf03751c0 100644 --- a/internal/namespaces/documentdb/v1beta1/custom.go +++ b/internal/namespaces/documentdb/v1beta1/custom.go @@ -59,6 +59,8 @@ var instanceStatusMarshalSpecs = human.EnumMarshalSpecs{ func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("document-db").Groups = []string{"database"} + human.RegisterMarshalerFunc( documentdb.InstanceStatus(""), human.EnumMarshalFunc(instanceStatusMarshalSpecs), diff --git a/internal/namespaces/domain/v2beta1/custom.go b/internal/namespaces/domain/v2beta1/custom.go index 66388f943a..a757a839e0 100644 --- a/internal/namespaces/domain/v2beta1/custom.go +++ b/internal/namespaces/domain/v2beta1/custom.go @@ -38,6 +38,8 @@ const defaultTTL = "3600" func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("dns").Groups = []string{"Domain & WebHosting"} + cmds.Merge(core.NewCommands( dnsRecordAddCommand(), dnsRecordSetCommand(), diff --git a/internal/namespaces/edge_services/v1alpha1/custom.go b/internal/namespaces/edge_services/v1alpha1/custom.go index b3fdfbaf73..9fa7f7d58c 100644 --- a/internal/namespaces/edge_services/v1alpha1/custom.go +++ b/internal/namespaces/edge_services/v1alpha1/custom.go @@ -5,5 +5,7 @@ import "github.com/scaleway/scaleway-cli/v2/core" func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("edge-services").Groups = []string{"network"} + return cmds } diff --git a/internal/namespaces/flexibleip/v1alpha1/custom.go b/internal/namespaces/flexibleip/v1alpha1/custom.go index 816532d759..7b0dab1a93 100644 --- a/internal/namespaces/flexibleip/v1alpha1/custom.go +++ b/internal/namespaces/flexibleip/v1alpha1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("fip").Groups = []string{"baremetal"} + human.RegisterMarshalerFunc( fip.FlexibleIPStatus(""), human.EnumMarshalFunc(ipStatusMarshalSpecs), diff --git a/internal/namespaces/function/v1beta1/custom.go b/internal/namespaces/function/v1beta1/custom.go index 2d8d67b7da..c0e3ec852c 100644 --- a/internal/namespaces/function/v1beta1/custom.go +++ b/internal/namespaces/function/v1beta1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("function").Groups = []string{"serverless"} + human.RegisterMarshalerFunc( function.NamespaceStatus(""), human.EnumMarshalFunc(namespaceStatusMarshalSpecs), diff --git a/internal/namespaces/help/custom.go b/internal/namespaces/help/custom.go index a6560c7f51..fb8fe41f6b 100644 --- a/internal/namespaces/help/custom.go +++ b/internal/namespaces/help/custom.go @@ -20,6 +20,7 @@ func helpRoot() *core.Command { Short: "Get help about how the CLI works", Namespace: "help", AllowAnonymousClient: true, + Groups: []string{"utility"}, } } diff --git a/internal/namespaces/iam/v1alpha1/custom.go b/internal/namespaces/iam/v1alpha1/custom.go index 449107bf86..1057ed3c50 100644 --- a/internal/namespaces/iam/v1alpha1/custom.go +++ b/internal/namespaces/iam/v1alpha1/custom.go @@ -26,6 +26,8 @@ var logActionMarshalSpecs = human.EnumMarshalSpecs{ func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("iam").Groups = []string{"security"} + human.RegisterMarshalerFunc(iam.LogAction(""), human.EnumMarshalFunc(logActionMarshalSpecs)) cmds.Merge(core.NewCommands( diff --git a/internal/namespaces/inference/v1beta1/custom.go b/internal/namespaces/inference/v1beta1/custom.go index 5981e5f6b9..a1944b2b52 100644 --- a/internal/namespaces/inference/v1beta1/custom.go +++ b/internal/namespaces/inference/v1beta1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("inference").Groups = []string{"ai"} + human.RegisterMarshalerFunc( inference.DeploymentStatus(""), human.EnumMarshalFunc(deployementStateMarshalSpecs), diff --git a/internal/namespaces/instance/v1/custom.go b/internal/namespaces/instance/v1/custom.go index f50b96de6e..b988f9328b 100644 --- a/internal/namespaces/instance/v1/custom.go +++ b/internal/namespaces/instance/v1/custom.go @@ -47,6 +47,8 @@ func GetCommands() *core.Commands { human.RegisterMarshalerFunc([]*instance.Server{}, serversMarshalerFunc) human.RegisterMarshalerFunc(instance.Bootscript{}, bootscriptMarshalerFunc) + cmds.MustFind("instance").Groups = []string{"compute"} + cmds.MustFind("instance", "server", "list").Override(serverListBuilder) cmds.MustFind("instance", "server", "update").Override(serverUpdateBuilder) cmds.MustFind("instance", "server", "get").Override(serverGetBuilder) diff --git a/internal/namespaces/interlink/v1beta1/custom.go b/internal/namespaces/interlink/v1beta1/custom.go index e1fe31bed9..601e0f5420 100644 --- a/internal/namespaces/interlink/v1beta1/custom.go +++ b/internal/namespaces/interlink/v1beta1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("interlink").Groups = []string{"network"} + human.RegisterMarshalerFunc( interlink.BgpStatus(""), human.EnumMarshalFunc(bgpStatusMarshalSpecs), diff --git a/internal/namespaces/iot/v1/custom.go b/internal/namespaces/iot/v1/custom.go index 618a4c5d81..66a99e6306 100644 --- a/internal/namespaces/iot/v1/custom.go +++ b/internal/namespaces/iot/v1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("iot").Groups = []string{"integration"} + human.RegisterMarshalerFunc(iot.HubStatus(""), human.EnumMarshalFunc(hubStatusMarshalSpecs)) human.RegisterMarshalerFunc( iot.DeviceMessageFiltersRulePolicy(""), diff --git a/internal/namespaces/ipam/v1/custom.go b/internal/namespaces/ipam/v1/custom.go index c0814cbf61..b8fe437492 100644 --- a/internal/namespaces/ipam/v1/custom.go +++ b/internal/namespaces/ipam/v1/custom.go @@ -5,5 +5,7 @@ import "github.com/scaleway/scaleway-cli/v2/core" func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("ipam").Groups = []string{"network"} + return cmds } diff --git a/internal/namespaces/jobs/v1alpha1/custom.go b/internal/namespaces/jobs/v1alpha1/custom.go index 2a52670d55..45376623f9 100644 --- a/internal/namespaces/jobs/v1alpha1/custom.go +++ b/internal/namespaces/jobs/v1alpha1/custom.go @@ -20,6 +20,8 @@ var jobRunStateMarshalSpecs = human.EnumMarshalSpecs{ func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("jobs").Groups = []string{"serverless"} + human.RegisterMarshalerFunc( jobs.JobRunState(""), human.EnumMarshalFunc(jobRunStateMarshalSpecs), diff --git a/internal/namespaces/k8s/v1/custom.go b/internal/namespaces/k8s/v1/custom.go index 6412024509..ce110eecfc 100644 --- a/internal/namespaces/k8s/v1/custom.go +++ b/internal/namespaces/k8s/v1/custom.go @@ -14,6 +14,9 @@ import ( // - Apply handwritten overrides (of Command.Run) func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + + cmds.MustFind("k8s").Groups = []string{"container"} + cmds.Merge(core.NewCommands( k8sExecCredentialCommand(), k8sKubeconfigCommand(), diff --git a/internal/namespaces/key_manager/v1alpha1/custom.go b/internal/namespaces/key_manager/v1alpha1/custom.go index 32642c9b25..9482a885e6 100644 --- a/internal/namespaces/key_manager/v1alpha1/custom.go +++ b/internal/namespaces/key_manager/v1alpha1/custom.go @@ -11,6 +11,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("keymanager").Groups = []string{"security"} + cmds.MustFind("keymanager", "key", "decrypt").Override(cipherDecrypt) cmds.MustFind("keymanager", "key", "encrypt").Override(plaintextEncrypt) diff --git a/internal/namespaces/lb/v1/custom.go b/internal/namespaces/lb/v1/custom.go index 6e16dec0ba..22384ea6ae 100644 --- a/internal/namespaces/lb/v1/custom.go +++ b/internal/namespaces/lb/v1/custom.go @@ -42,6 +42,8 @@ func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("lb").Groups = []string{"network"} + cmds.Add( lbWaitCommand(), ) diff --git a/internal/namespaces/marketplace/v2/custom.go b/internal/namespaces/marketplace/v2/custom.go index 1b8a5f09df..07c2fe55b4 100644 --- a/internal/namespaces/marketplace/v2/custom.go +++ b/internal/namespaces/marketplace/v2/custom.go @@ -16,5 +16,7 @@ func GetCommands() *core.Commands { // Update commands with custom implementation of fields updateCommands(marketplaceCommands) + marketplaceCommands.MustFind("marketplace").Groups = []string{"compute"} + return marketplaceCommands } diff --git a/internal/namespaces/mnq/v1beta1/custom.go b/internal/namespaces/mnq/v1beta1/custom.go index 2507cf428e..9bf035e76d 100644 --- a/internal/namespaces/mnq/v1beta1/custom.go +++ b/internal/namespaces/mnq/v1beta1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("mnq").Groups = []string{"integration"} + human.RegisterMarshalerFunc( mnq.SnsInfoStatus(""), human.EnumMarshalFunc(mnqSqsInfoStatusMarshalSpecs), diff --git a/internal/namespaces/mongodb/v1alpha1/custom.go b/internal/namespaces/mongodb/v1alpha1/custom.go index 2b9c6cce41..102837d9ea 100644 --- a/internal/namespaces/mongodb/v1alpha1/custom.go +++ b/internal/namespaces/mongodb/v1alpha1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("mongodb").Groups = []string{"database"} + human.RegisterMarshalerFunc( mongodb.SnapshotStatus(""), human.EnumMarshalFunc(snapshotStatusMarshalSpecs), diff --git a/internal/namespaces/object/v1/custom_command.go b/internal/namespaces/object/v1/custom_command.go index 5942d6e2a9..dd719d9491 100644 --- a/internal/namespaces/object/v1/custom_command.go +++ b/internal/namespaces/object/v1/custom_command.go @@ -8,6 +8,7 @@ func objectRoot() *core.Command { return &core.Command{ Short: `Object-storage utils`, Namespace: "object", + Groups: []string{"storage"}, } } diff --git a/internal/namespaces/rdb/v1/custom.go b/internal/namespaces/rdb/v1/custom.go index 7f8182181b..6226f7dc9b 100644 --- a/internal/namespaces/rdb/v1/custom.go +++ b/internal/namespaces/rdb/v1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("rdb").Groups = []string{"database"} + human.RegisterMarshalerFunc(rdb.Instance{}, instanceMarshalerFunc) human.RegisterMarshalerFunc(rdb.BackupSchedule{}, backupScheduleMarshalerFunc) human.RegisterMarshalerFunc(backupDownloadResult{}, backupResultMarshallerFunc) diff --git a/internal/namespaces/redis/v1/custom.go b/internal/namespaces/redis/v1/custom.go index 87f4f23988..f3579a3221 100644 --- a/internal/namespaces/redis/v1/custom.go +++ b/internal/namespaces/redis/v1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("redis").Groups = []string{"database"} + human.RegisterMarshalerFunc(redis.Cluster{}, redisClusterGetMarshalerFunc) cmds.Merge(core.NewCommands(clusterWaitCommand())) diff --git a/internal/namespaces/registry/v1/custom.go b/internal/namespaces/registry/v1/custom.go index 3947064eec..b9932a13b0 100644 --- a/internal/namespaces/registry/v1/custom.go +++ b/internal/namespaces/registry/v1/custom.go @@ -14,6 +14,9 @@ import ( // - Apply handwritten overrides (of Command.Run) func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + + cmds.MustFind("registry").Groups = []string{"container", "storage"} + cmds.Merge(core.NewCommands( registryLoginCommand(), registryLogoutCommand(), diff --git a/internal/namespaces/secret/v1beta1/custom.go b/internal/namespaces/secret/v1beta1/custom.go index a03ea0b04d..a71939edbf 100644 --- a/internal/namespaces/secret/v1beta1/custom.go +++ b/internal/namespaces/secret/v1beta1/custom.go @@ -14,6 +14,8 @@ type customAccessSecretVersionRequest struct { func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("secret").Groups = []string{"security"} + cmds.MustFind("secret", "version", "create").Override(secretVersionCreateBuilder) cmds.MustFind("secret", "version", "access").Override(secretVersionAccessBuilder) diff --git a/internal/namespaces/serverless_sqldb/v1alpha1/custom.go b/internal/namespaces/serverless_sqldb/v1alpha1/custom.go index fa9c807c3f..0e3cad9688 100644 --- a/internal/namespaces/serverless_sqldb/v1alpha1/custom.go +++ b/internal/namespaces/serverless_sqldb/v1alpha1/custom.go @@ -51,6 +51,8 @@ var ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("sdb-sql").Groups = []string{"database"} + human.RegisterMarshalerFunc( serverless_sqldb.DatabaseStatus(""), human.EnumMarshalFunc(sdbSQLDatabaseStatusMarshalSpecs), diff --git a/internal/namespaces/tem/v1alpha1/custom.go b/internal/namespaces/tem/v1alpha1/custom.go index b6ba6ef2d0..5c04ed42b0 100644 --- a/internal/namespaces/tem/v1alpha1/custom.go +++ b/internal/namespaces/tem/v1alpha1/custom.go @@ -9,11 +9,15 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("tem").Groups = []string{"Domain & WebHosting"} + human.RegisterMarshalerFunc( tem.DomainStatus(""), human.EnumMarshalFunc(domainStatusMarshalSpecs), ) - human.RegisterMarshalerFunc(tem.EmailStatus(""), human.EnumMarshalFunc(emailStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + tem.EmailStatus(""), + human.EnumMarshalFunc(emailStatusMarshalSpecs)) cmds.MustFind("tem", "domain", "get").Override(domainGetBuilder) diff --git a/internal/namespaces/vpc/v2/custom.go b/internal/namespaces/vpc/v2/custom.go index d6dc93ec3c..59803fcacb 100644 --- a/internal/namespaces/vpc/v2/custom.go +++ b/internal/namespaces/vpc/v2/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("vpc").Groups = []string{"network"} + cmds.Remove("vpc", "post") cmds.MustFind("vpc", "private-network", "get").Override(privateNetworkGetBuilder) human.RegisterMarshalerFunc(vpc.PrivateNetwork{}, privateNetworkMarshalerFunc) diff --git a/internal/namespaces/vpcgw/v1/custom.go b/internal/namespaces/vpcgw/v1/custom.go index 565d66ce09..c9f4b6b22f 100644 --- a/internal/namespaces/vpcgw/v1/custom.go +++ b/internal/namespaces/vpcgw/v1/custom.go @@ -8,6 +8,9 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + + cmds.MustFind("vpc-gw").Groups = []string{"network"} + for _, cmd := range cmds.GetAll() { if cmd.Resource == "" || cmd.Verb == "" { continue diff --git a/internal/namespaces/vpcgw/v2/custom.go b/internal/namespaces/vpcgw/v2/custom.go index e69a727f42..e467ec28c7 100644 --- a/internal/namespaces/vpcgw/v2/custom.go +++ b/internal/namespaces/vpcgw/v2/custom.go @@ -16,6 +16,8 @@ func GetCommands() *core.Commands { } } + cmds.MustFind("vpc-gw").Groups = []string{"network"} + human.RegisterMarshalerFunc(vpcgw.GatewayNetworkStatus(""), human.EnumMarshalFunc(gatewayNetworkStatusMarshalSpecs)) human.RegisterMarshalerFunc(vpcgw.GatewayStatus(""), human.EnumMarshalFunc(gatewayStatusMarshalSpecs)) human.RegisterMarshalerFunc(vpcgw.Gateway{}, gatewayMarshalerFunc) diff --git a/internal/namespaces/webhosting/v1/custom.go b/internal/namespaces/webhosting/v1/custom.go index 96a89334b6..9b84d44bad 100644 --- a/internal/namespaces/webhosting/v1/custom.go +++ b/internal/namespaces/webhosting/v1/custom.go @@ -9,6 +9,8 @@ import ( func GetCommands() *core.Commands { cmds := GetGeneratedCommands() + cmds.MustFind("webhosting").Groups = []string{"Domain & WebHosting"} + human.RegisterMarshalerFunc( webhosting.HostingStatus(""), human.EnumMarshalFunc(hostingStatusMarshalSpecs), From 3b5a26bbc02370d6dab1efab908f99216321996d Mon Sep 17 00:00:00 2001 From: Olivier Cano Date: Mon, 31 Mar 2025 20:06:09 +0200 Subject: [PATCH 14/24] chore(lb): update cassette on attach/detach private network (#4623) Signed-off-by: Olivier Cano --- go.mod | 2 +- go.sum | 4 ++-- .../test-list-lb-private-network-simple.cassette.yaml | 4 ++-- .../testdata/test-get-private-network-multiple.cassette.yaml | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/go.mod b/go.mod index 0a2b6efad4..16d5a03dc0 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,7 @@ require ( github.com/mattn/go-isatty v0.0.20 github.com/moby/buildkit v0.13.2 github.com/opencontainers/go-digest v1.0.0 - github.com/scaleway/scaleway-sdk-go v1.0.0-beta.33.0.20250327145452-20e9e72214ed + github.com/scaleway/scaleway-sdk-go v1.0.0-beta.33.0.20250331103057-9ba2b07cedf3 github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 github.com/spf13/cobra v1.9.1 github.com/spf13/pflag v1.0.6 diff --git a/go.sum b/go.sum index 7f490ff82d..b1990f700a 100644 --- a/go.sum +++ b/go.sum @@ -462,8 +462,8 @@ github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUz github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 h1:OkMGxebDjyw0ULyrTYWeN0UNCCkmCWfjPnIA2W6oviI= github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06/go.mod h1:+ePHsJ1keEjQtpvf9HHw0f4ZeJ0TLRsxhunSI2hYJSs= -github.com/scaleway/scaleway-sdk-go v1.0.0-beta.33.0.20250327145452-20e9e72214ed h1:klCw4VdfiQ+nTqNoY8ymobNj0ZYs5oDQ9A6ilvndopg= -github.com/scaleway/scaleway-sdk-go v1.0.0-beta.33.0.20250327145452-20e9e72214ed/go.mod h1:792k1RTU+5JeMXm35/e2Wgp71qPH/DmDoZrRc+EFZDk= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.33.0.20250331103057-9ba2b07cedf3 h1:KNur0AcnbYdoNWt4octc3EgBbwADaDNMZh9yZj5m2Z8= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.33.0.20250331103057-9ba2b07cedf3/go.mod h1:792k1RTU+5JeMXm35/e2Wgp71qPH/DmDoZrRc+EFZDk= github.com/sclevine/spec v1.4.0 h1:z/Q9idDcay5m5irkZ28M7PtQM4aOISzOpj4bUPkDee8= github.com/sclevine/spec v1.4.0/go.mod h1:LvpgJaFyvQzRvc1kaDs0bulYwzC70PbiYjC4QnFHkOM= github.com/secure-systems-lab/go-securesystemslib v0.8.0 h1:mr5An6X45Kb2nddcFlbmfHkLguCE9laoZCUzEEpIZXA= diff --git a/internal/namespaces/lb/v1/testdata/test-list-lb-private-network-simple.cassette.yaml b/internal/namespaces/lb/v1/testdata/test-list-lb-private-network-simple.cassette.yaml index f02d158b0f..f32cf15138 100644 --- a/internal/namespaces/lb/v1/testdata/test-list-lb-private-network-simple.cassette.yaml +++ b/internal/namespaces/lb/v1/testdata/test-list-lb-private-network-simple.cassette.yaml @@ -287,7 +287,7 @@ interactions: - application/json User-Agent: - scaleway-sdk-go/v1.0.0-beta.7+dev (go1.23.4; darwin; amd64) cli-e2e-test - url: https://api.scaleway.com/lb/v1/zones/fr-par-1/lbs/7a0c3a08-e13a-46f8-b0a2-1423625bb0ef/private-networks/f6dd3849-441c-4dae-988a-93a673ad72d7/attach + url: https://api.scaleway.com/lb/v1/zones/fr-par-1/lbs/7a0c3a08-e13a-46f8-b0a2-1423625bb0ef/attach-private-network method: POST response: body: '{"lb":{"id":"7a0c3a08-e13a-46f8-b0a2-1423625bb0ef", "name":"cli-test", @@ -391,7 +391,7 @@ interactions: - application/json User-Agent: - scaleway-sdk-go/v1.0.0-beta.7+dev (go1.23.4; darwin; amd64) cli-e2e-test - url: https://api.scaleway.com/lb/v1/zones/fr-par-1/lbs/7a0c3a08-e13a-46f8-b0a2-1423625bb0ef/private-networks/f6dd3849-441c-4dae-988a-93a673ad72d7/detach + url: https://api.scaleway.com/lb/v1/zones/fr-par-1/lbs/7a0c3a08-e13a-46f8-b0a2-1423625bb0ef/detach-private-network method: POST response: body: "" diff --git a/internal/namespaces/vpc/v2/testdata/test-get-private-network-multiple.cassette.yaml b/internal/namespaces/vpc/v2/testdata/test-get-private-network-multiple.cassette.yaml index 145669a018..5fb96042f4 100644 --- a/internal/namespaces/vpc/v2/testdata/test-get-private-network-multiple.cassette.yaml +++ b/internal/namespaces/vpc/v2/testdata/test-get-private-network-multiple.cassette.yaml @@ -1721,7 +1721,7 @@ interactions: - application/json User-Agent: - scaleway-sdk-go/v1.0.0-beta.7+dev (go1.23.4; darwin; arm64) cli-e2e-test - url: https://api.scaleway.com/lb/v1/zones/fr-par-1/lbs/f072f5f0-2237-4f33-80aa-6d6ea7a763ad/private-networks/82e2935f-1e06-46cb-83a9-ad664aedd289/attach + url: https://api.scaleway.com/lb/v1/zones/fr-par-1/lbs/f072f5f0-2237-4f33-80aa-6d6ea7a763ad/attach-private-network method: POST response: body: '{"lb":{"id":"f072f5f0-2237-4f33-80aa-6d6ea7a763ad","name":"cli-test","description":"cli-test","status":"ready","instances":[{"id":"a1715e84-5bbf-45ff-826b-5840fbe3b816","status":"ready","ip_address":"","created_at":"2025-01-30T16:55:01.596231Z","updated_at":"2025-01-30T17:00:14.260850Z","region":"fr-par","zone":"fr-par-1"}],"organization_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","ip":[{"id":"41a54fa2-b025-4455-ad9f-66e8dc0cd99c","ip_address":"51.159.9.201","organization_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","project_id":"ee7bd9e1-9cbd-4724-b2f4-19e50f3cf38b","lb_id":"f072f5f0-2237-4f33-80aa-6d6ea7a763ad","reverse":"51-159-9-201.lb.fr-par.scw.cloud","tags":[],"region":"fr-par","zone":"fr-par-1"}],"tags":[],"frontend_count":0,"backend_count":0,"type":"lb-s","subscriber":null,"ssl_compatibility_level":"ssl_compatibility_level_intermediate","created_at":"2025-01-30T17:00:11.424424Z","updated_at":"2025-01-30T17:00:15.872226Z","private_network_count":1,"route_count":0,"region":"fr-par","zone":"fr-par-1"},"private_network_id":"82e2935f-1e06-46cb-83a9-ad664aedd289","status":"pending","created_at":"2025-01-30T17:00:16.309513576Z","updated_at":"2025-01-30T17:00:16.309513576Z","dhcp_config":{"ip_id":null},"ipam_ids":[]}' @@ -3434,7 +3434,7 @@ interactions: - application/json User-Agent: - scaleway-sdk-go/v1.0.0-beta.7+dev (go1.23.4; darwin; arm64) cli-e2e-test - url: https://api.scaleway.com/lb/v1/zones/fr-par-1/lbs/f072f5f0-2237-4f33-80aa-6d6ea7a763ad/private-networks/82e2935f-1e06-46cb-83a9-ad664aedd289/detach + url: https://api.scaleway.com/lb/v1/zones/fr-par-1/lbs/f072f5f0-2237-4f33-80aa-6d6ea7a763ad/detach-private-network method: POST response: body: "" From efb9d6e27d1a71d5e5e02d79d04bc7b535fb88a4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Apr 2025 09:40:26 +0200 Subject: [PATCH 15/24] chore(deps): bump github.com/aws/aws-sdk-go-v2/service/s3 from 1.78.2 to 1.79.0 (#4626) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 4 +--- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 16d5a03dc0..490cf2414a 100644 --- a/go.mod +++ b/go.mod @@ -2,11 +2,9 @@ module github.com/scaleway/scaleway-cli/v2 go 1.24 -toolchain go1.24.0 - require ( github.com/aws/aws-sdk-go-v2 v1.36.3 - github.com/aws/aws-sdk-go-v2/service/s3 v1.78.2 + github.com/aws/aws-sdk-go-v2/service/s3 v1.79.0 github.com/buildpacks/pack v0.34.2 github.com/c-bata/go-prompt v0.2.6 github.com/charmbracelet/bubbletea v1.3.4 diff --git a/go.sum b/go.sum index b1990f700a..b3c7bd4a7d 100644 --- a/go.sum +++ b/go.sum @@ -90,8 +90,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.15 h1:dM9/92u2 github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.15/go.mod h1:SwFBy2vjtA0vZbjjaFtfN045boopadnoVPhu4Fv66vY= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.18.15 h1:moLQUoVq91LiqT1nbvzDukyqAlCv89ZmwaHw/ZFlFZg= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.18.15/go.mod h1:ZH34PJUc8ApjBIfgQCFvkWcUDBtl/WTD+uiYHjd8igA= -github.com/aws/aws-sdk-go-v2/service/s3 v1.78.2 h1:jIiopHEV22b4yQP2q36Y0OmwLbsxNWdWwfZRR5QRRO4= -github.com/aws/aws-sdk-go-v2/service/s3 v1.78.2/go.mod h1:U5SNqwhXB3Xe6F47kXvWihPl/ilGaEDe8HD/50Z9wxc= +github.com/aws/aws-sdk-go-v2/service/s3 v1.79.0 h1:OIw2nryEApESTYI5deCZGcq4Gvz8DBAt4tJlNyg3v5o= +github.com/aws/aws-sdk-go-v2/service/s3 v1.79.0/go.mod h1:U5SNqwhXB3Xe6F47kXvWihPl/ilGaEDe8HD/50Z9wxc= github.com/aws/aws-sdk-go-v2/service/sso v1.20.2 h1:XOPfar83RIRPEzfihnp+U6udOveKZJvPQ76SKWrLRHc= github.com/aws/aws-sdk-go-v2/service/sso v1.20.2/go.mod h1:Vv9Xyk1KMHXrR3vNQe8W5LMFdTjSeWk0gBZBzvf3Qa0= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.23.2 h1:pi0Skl6mNl2w8qWZXcdOyg197Zsf4G97U7Sso9JXGZE= From b3083e67894d419a7b257b532e9d53e3aa92742b Mon Sep 17 00:00:00 2001 From: Olivier Cano Date: Tue, 1 Apr 2025 14:57:59 +0200 Subject: [PATCH 16/24] fix(arg-spec): revert multi positional arg definition (#4627) Signed-off-by: Olivier Cano --- core/arg_specs.go | 3 +- core/cobra_utils_test.go | 79 ---------------------------------------- 2 files changed, 2 insertions(+), 80 deletions(-) diff --git a/core/arg_specs.go b/core/arg_specs.go index 402fc6c3b1..96331d1596 100644 --- a/core/arg_specs.go +++ b/core/arg_specs.go @@ -14,7 +14,8 @@ var AllLocalities = "all" type ArgSpecs []*ArgSpec -// GetPositionalArg returns the last positional argument from the arg specs. +// GetPositionalArg if exist returns the positional argument from the arg specs. +// Panics when more than one positional arg is found. func (s ArgSpecs) GetPositionalArg() *ArgSpec { var positionalArg *ArgSpec for _, argSpec := range s { diff --git a/core/cobra_utils_test.go b/core/cobra_utils_test.go index 26199ddb86..d91f39d1ad 100644 --- a/core/cobra_utils_test.go +++ b/core/cobra_utils_test.go @@ -17,11 +17,6 @@ type testType struct { Tag string } -type testTypeManyTags struct { - NameID string - Tags []string -} - type testDate struct { Date *time.Time } @@ -83,45 +78,6 @@ func testGetCommands() *core.Commands { return argsI, nil }, }, - &core.Command{ - Namespace: "test", - Resource: "many-positional", - ArgSpecs: core.ArgSpecs{ - { - Name: "name-id", - Positional: true, - }, - { - Name: "tag", - Positional: true, - }, - }, - AllowAnonymousClient: true, - ArgsType: reflect.TypeOf(testType{}), - Run: func(_ context.Context, argsI interface{}) (i interface{}, e error) { - return argsI, nil - }, - }, - &core.Command{ - Namespace: "test", - Resource: "many-multi-positional", - ArgSpecs: core.ArgSpecs{ - { - Name: "name-id", - Positional: true, - }, - { - Name: "tags", - Positional: true, - }, - }, - AcceptMultiplePositionalArgs: true, - AllowAnonymousClient: true, - ArgsType: reflect.TypeOf(testTypeManyTags{}), - Run: func(_ context.Context, argsI interface{}) (i interface{}, e error) { - return argsI, nil - }, - }, &core.Command{ Namespace: "test", Resource: "raw-args", @@ -302,41 +258,6 @@ func Test_PositionalArg(t *testing.T) { core.TestCheckGolden(), ), })) - - t.Run("many positional", core.Test(&core.TestConfig{ - Commands: testGetCommands(), - Cmd: "scw test many-positional tag1 name-id=plop", - Check: core.TestCheckExitCode(0), - })) - - t.Run("many positional", core.Test(&core.TestConfig{ - Commands: testGetCommands(), - Cmd: "scw test many-positional tag1 name-id=plop", - Check: core.TestCheckCombine( - core.TestCheckExitCode(0), - func(t *testing.T, ctx *core.CheckFuncCtx) { - t.Helper() - res := ctx.Result.(*testType) - assert.Equal(t, "plop", res.NameID) - assert.Equal(t, "tag1", res.Tag) - }, - ), - })) - - t.Run("many multi-positional", core.Test(&core.TestConfig{ - Commands: testGetCommands(), - Cmd: "scw test many-multi-positional pos1 pos2 name-id=plop", - Check: core.TestCheckCombine( - core.TestCheckExitCode(0), - func(t *testing.T, ctx *core.CheckFuncCtx) { - t.Helper() - res := ctx.Result.(*testTypeManyTags) - assert.Equal(t, "plop", res.NameID) - assert.Equal(t, "pos1", res.Tags[0]) - assert.Equal(t, "pos2", res.Tags[1]) - }, - ), - })) } func Test_MultiPositionalArg(t *testing.T) { From be2e88ebd39b48141729dc97f42855a31f2d82bc Mon Sep 17 00:00:00 2001 From: Olivier Cano Date: Tue, 1 Apr 2025 17:01:38 +0200 Subject: [PATCH 17/24] fix(go.mod): set go minor version (#4629) --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 490cf2414a..2c0ea429d9 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/scaleway/scaleway-cli/v2 -go 1.24 +go 1.24.0 require ( github.com/aws/aws-sdk-go-v2 v1.36.3 From a0c21c07324489f1168fd02cc69ddcf815fa28a8 Mon Sep 17 00:00:00 2001 From: SamyOubouaziz Date: Wed, 2 Apr 2025 10:44:05 +0200 Subject: [PATCH 18/24] fix(docs): downgrade awscli version for docs workflow (#4630) --- .github/workflows/deploy-docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 89c40e8c2d..9289ca5baf 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -33,7 +33,7 @@ jobs: run: | sudo apt update sudo apt install curl unzip -y - curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" + curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64-2.22.20.zip" -o "awscliv2.zip" unzip awscliv2.zip ./aws/install From b85d792c555be39dcb022bbb62dc576399cd047c Mon Sep 17 00:00:00 2001 From: Mia-Cross Date: Wed, 2 Apr 2025 14:28:42 +0200 Subject: [PATCH 19/24] feat(instance): add fetch-keys to ssh commands (#4622) Co-authored-by: Benedikt Rollik --- ...usage-instance-ssh-fetch-keys-usage.golden | 24 +++++ ...-usage-instance-ssh-list-keys-usage.golden | 2 +- .../test-all-usage-instance-ssh-usage.golden | 1 + docs/commands/instance.md | 27 ++++- internal/namespaces/instance/v1/custom.go | 1 + .../namespaces/instance/v1/custom_ssh_key.go | 101 +++++++++++++++++- 6 files changed, 153 insertions(+), 3 deletions(-) create mode 100644 cmd/scw/testdata/test-all-usage-instance-ssh-fetch-keys-usage.golden diff --git a/cmd/scw/testdata/test-all-usage-instance-ssh-fetch-keys-usage.golden b/cmd/scw/testdata/test-all-usage-instance-ssh-fetch-keys-usage.golden new file mode 100644 index 0000000000..83580018ed --- /dev/null +++ b/cmd/scw/testdata/test-all-usage-instance-ssh-fetch-keys-usage.golden @@ -0,0 +1,24 @@ +🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲 +🟥🟥🟥 STDERR️️ 🟥🟥🟥️ +Keys registered via the Scaleway Console will be propagated to the selected servers. +The command 'ssh -t -l scw-fetch-ssh-keys --upgrade' will be run on the servers matching the zone and project filters. +Keep in mind that you need to be able to connect to your server with another key than the one you want to add. +Keep in mind that SSH keys are scoped by project. + +USAGE: + scw instance ssh fetch-keys [arg=value ...] + +ARGS: + [project-id] Fetch the keys on all servers in the given Project + [username=root] Username used for the SSH connection + [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | fr-par-3 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) + +FLAGS: + -h, --help help for fetch-keys + +GLOBAL FLAGS: + -c, --config string The path to the config file + -D, --debug Enable debug mode + -o, --output string Output format: json or human, see 'scw help output' for more info (default "human") + -p, --profile string The config profile to use + --web open console page for the current ressource diff --git a/cmd/scw/testdata/test-all-usage-instance-ssh-list-keys-usage.golden b/cmd/scw/testdata/test-all-usage-instance-ssh-list-keys-usage.golden index fe750509a7..6b7b6d8748 100644 --- a/cmd/scw/testdata/test-all-usage-instance-ssh-list-keys-usage.golden +++ b/cmd/scw/testdata/test-all-usage-instance-ssh-list-keys-usage.golden @@ -8,7 +8,7 @@ USAGE: scw instance ssh list-keys [arg=value ...] ARGS: - server-id Server to add your key to + server-id Server which keys are to be listed [zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | fr-par-3 | nl-ams-1 | nl-ams-2 | nl-ams-3 | pl-waw-1 | pl-waw-2 | pl-waw-3) FLAGS: diff --git a/cmd/scw/testdata/test-all-usage-instance-ssh-usage.golden b/cmd/scw/testdata/test-all-usage-instance-ssh-usage.golden index bf0c84a931..f0d732d3e4 100644 --- a/cmd/scw/testdata/test-all-usage-instance-ssh-usage.golden +++ b/cmd/scw/testdata/test-all-usage-instance-ssh-usage.golden @@ -9,6 +9,7 @@ USAGE: UTILITY COMMANDS: add-key Add a public key to a server + fetch-keys Fetch SSH keys from the console and install them on multiple servers list-keys List manually added public keys remove-key Remove a manually added public key from a server diff --git a/docs/commands/instance.md b/docs/commands/instance.md index 200100232f..96ac79e4c9 100644 --- a/docs/commands/instance.md +++ b/docs/commands/instance.md @@ -87,6 +87,7 @@ This API allows you to manage your Instances. - [Wait for snapshot to reach a stable state](#wait-for-snapshot-to-reach-a-stable-state) - [SSH Utilities](#ssh-utilities) - [Add a public key to a server](#add-a-public-key-to-a-server) + - [Fetch SSH keys from the console and install them on multiple servers](#fetch-ssh-keys-from-the-console-and-install-them-on-multiple-servers) - [Install a ssh config with all your servers as host It generate hosts for instance servers, baremetal, apple-silicon and bastions](#install-a-ssh-config-with-all-your-servers-as-host it-generate-hosts-for-instance-servers,-baremetal,-apple-silicon-and-bastions) @@ -2769,6 +2770,30 @@ scw instance ssh add-key [arg=value ...] +### Fetch SSH keys from the console and install them on multiple servers + +Keys registered via the Scaleway Console will be propagated to the selected servers. +The command 'ssh -t -l scw-fetch-ssh-keys --upgrade' will be run on the servers matching the zone and project filters. +Keep in mind that you need to be able to connect to your server with another key than the one you want to add. +Keep in mind that SSH keys are scoped by project. + +**Usage:** + +``` +scw instance ssh fetch-keys [arg=value ...] +``` + + +**Args:** + +| Name | | Description | +|------|---|-------------| +| project-id | | Fetch the keys on all servers in the given Project | +| username | Default: `root` | Username used for the SSH connection | +| zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `fr-par-3`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3` | Zone to target. If none is passed will use default zone from the config | + + + ### Install a ssh config with all your servers as host It generate hosts for instance servers, baremetal, apple-silicon and bastions @@ -2807,7 +2832,7 @@ scw instance ssh list-keys [arg=value ...] | Name | | Description | |------|---|-------------| -| server-id | Required | Server to add your key to | +| server-id | Required | Server which keys are to be listed | | zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `fr-par-3`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3` | Zone to target. If none is passed will use default zone from the config | diff --git a/internal/namespaces/instance/v1/custom.go b/internal/namespaces/instance/v1/custom.go index b988f9328b..f1c9bb3701 100644 --- a/internal/namespaces/instance/v1/custom.go +++ b/internal/namespaces/instance/v1/custom.go @@ -230,6 +230,7 @@ func GetCommands() *core.Commands { instanceSSH(), sshAddKeyCommand(), sshConfigInstallCommand(), + sshFetchKeysCommand(), sshListKeysCommand(), sshRemoveKeyCommand(), instanceServerGetRdpPassword(), diff --git a/internal/namespaces/instance/v1/custom_ssh_key.go b/internal/namespaces/instance/v1/custom_ssh_key.go index 48503281c9..35cd83fa8f 100644 --- a/internal/namespaces/instance/v1/custom_ssh_key.go +++ b/internal/namespaces/instance/v1/custom_ssh_key.go @@ -7,11 +7,13 @@ import ( "errors" "fmt" "hash/crc32" + "os/exec" "reflect" "strings" "github.com/scaleway/scaleway-cli/v2/core" "github.com/scaleway/scaleway-cli/v2/core/human" + "github.com/scaleway/scaleway-cli/v2/internal/interactive" "github.com/scaleway/scaleway-sdk-go/api/instance/v1" "github.com/scaleway/scaleway-sdk-go/scw" ) @@ -132,6 +134,103 @@ Lookup /root/.ssh/authorized_keys on your server for more information`, } } +type sshFetchKeysRequest struct { + Zone scw.Zone + ProjectID string + Username string +} + +func sshFetchKeysCommand() *core.Command { + return &core.Command{ + Namespace: "instance", + Resource: "ssh", + Verb: "fetch-keys", + Groups: []string{"utility"}, + Short: "Fetch SSH keys from the console and install them on multiple servers", + Long: `Keys registered via the Scaleway Console will be propagated to the selected servers. +The command 'ssh -t -l scw-fetch-ssh-keys --upgrade' will be run on the servers matching the zone and project filters. +Keep in mind that you need to be able to connect to your server with another key than the one you want to add. +Keep in mind that SSH keys are scoped by project.`, + ArgsType: reflect.TypeOf(sshFetchKeysRequest{}), + ArgSpecs: core.ArgSpecs{ + { + Name: "project-id", + Short: "Fetch the keys on all servers in the given Project", + Required: false, + }, + { + Name: "username", + Short: "Username used for the SSH connection", + Default: core.DefaultValueSetter("root"), + }, + core.ZoneArgSpec(((*instance.API)(nil)).Zones()...), + }, + Run: func(ctx context.Context, argsI interface{}) (interface{}, error) { + args := argsI.(*sshFetchKeysRequest) + api := instance.NewAPI(core.ExtractClient(ctx)) + + listServersRequest := &instance.ListServersRequest{ + Zone: args.Zone, + } + if args.ProjectID != "" { + listServersRequest.Project = &args.ProjectID + } + servers, err := api.ListServers(listServersRequest, scw.WithAllPages(), scw.WithContext(ctx)) + if err != nil { + return nil, fmt.Errorf("failed to fetch servers: %w", err) + } + + for i, server := range servers.Servers { + msg := fmt.Sprintf("Loading SSH keys on server %q", server.Name) + if i == 0 { + _, _ = interactive.Println(">", msg) + } else { + _, _ = interactive.Println("\n>", msg) + } + + if server.State != instance.ServerStateRunning { + _, _ = interactive.Printf("Failed: server %q is not running", server.Name) + + continue + } + + if len(server.PublicIPs) == 0 { + _, _ = interactive.Printf("Failed: server %q has no public IP", server.Name) + + continue + } + + for _, publicIP := range server.PublicIPs { + sshArgs := []string{ + publicIP.Address.String(), + "-t", + "-l", args.Username, + "/usr/sbin/scw-fetch-ssh-keys", + "--upgrade", + } + + sshCmd := exec.Command("ssh", sshArgs...) + + _, _ = interactive.Println(sshCmd) + + exitCode, err := core.ExecCmd(ctx, sshCmd) + if err != nil || exitCode != 0 { + if err != nil { + _, _ = interactive.Println("Failed:", err) + } else { + _, _ = interactive.Println("Failed: ssh command failed with exit code", exitCode) + } + } else { + _, _ = interactive.Println("Success") + } + } + } + + return &core.SuccessResult{Empty: true}, nil + }, + } +} + type sshListKeysRequest struct { Zone scw.Zone ServerID string @@ -151,7 +250,7 @@ Lookup /root/.ssh/authorized_keys on your server for more information`, ArgSpecs: core.ArgSpecs{ { Name: "server-id", - Short: "Server to add your key to", + Short: "Server which keys are to be listed", Positional: true, Required: true, }, From 8d719c6b6ff92f540a3a2098fe5ebb438b3cc61e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20L=C3=A9one?= Date: Thu, 27 Mar 2025 17:33:30 +0100 Subject: [PATCH 20/24] FIx linters --- internal/namespaces/billing/v2beta1/custom.go | 1 + internal/namespaces/iam/v1alpha1/iam_cli.go | 10 +++++----- internal/namespaces/vpc/v2/vpc_cli.go | 4 ++-- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/internal/namespaces/billing/v2beta1/custom.go b/internal/namespaces/billing/v2beta1/custom.go index 945d62633b..4e65eb6a09 100644 --- a/internal/namespaces/billing/v2beta1/custom.go +++ b/internal/namespaces/billing/v2beta1/custom.go @@ -23,6 +23,7 @@ func GetCommands() *core.Commands { billing.DownloadInvoiceRequestFileType("pdf"), human.EnumMarshalFunc(invoiceTypeMarshalSpecs), ) + cmds.MustFind("billing", "invoice", "download").Override(invoiceDownloadBuilder) cmds.MustFind("billing", "invoice", "export").Override(invoiceExportBuilder) diff --git a/internal/namespaces/iam/v1alpha1/iam_cli.go b/internal/namespaces/iam/v1alpha1/iam_cli.go index dd2451e997..92b7ad706c 100644 --- a/internal/namespaces/iam/v1alpha1/iam_cli.go +++ b/internal/namespaces/iam/v1alpha1/iam_cli.go @@ -665,7 +665,7 @@ func iamUserDelete() *core.Command { func iamUserCreate() *core.Command { return &core.Command{ Short: `Create a new user`, - Long: `Create a new user. You must define the ` + "`" + `organization_id` + "`" + ` in your request. If you are adding a member, enter the member's details. If you are adding a guest, you must define the ` + "`" + `email` + "`" + ` and not add the member attribute.`, + Long: `Create a new user. You must define the ` + "`" + `organization_id` + "`" + ` and the ` + "`" + `email` + "`" + ` in your request.`, Namespace: "iam", Resource: "user", Verb: "create", @@ -764,8 +764,8 @@ func iamUserCreate() *core.Command { func iamUserUpdateUsername() *core.Command { return &core.Command{ - Short: `Update an user's username.`, - Long: `Update an user's username.`, + Short: `Update an user's username. Private Beta feature.`, + Long: `Update an user's username. Private Beta feature.`, Namespace: "iam", Resource: "user", Verb: "update-username", @@ -800,8 +800,8 @@ func iamUserUpdateUsername() *core.Command { func iamUserUpdatePassword() *core.Command { return &core.Command{ - Short: `Update an user's password.`, - Long: `Update an user's password.`, + Short: `Update an user's password. Private Beta feature.`, + Long: `Update an user's password. Private Beta feature.`, Namespace: "iam", Resource: "user", Verb: "update-password", diff --git a/internal/namespaces/vpc/v2/vpc_cli.go b/internal/namespaces/vpc/v2/vpc_cli.go index 4f4e8377b7..ee7f640af8 100644 --- a/internal/namespaces/vpc/v2/vpc_cli.go +++ b/internal/namespaces/vpc/v2/vpc_cli.go @@ -99,7 +99,7 @@ func vpcRoute() *core.Command { func vpcRule() *core.Command { return &core.Command{ Short: `Rule management command`, - Long: `ACL Rules.`, + Long: `Acl Rules.`, Namespace: "vpc", Resource: "rule", } @@ -866,7 +866,7 @@ func vpcRouteDelete() *core.Command { func vpcRuleGet() *core.Command { return &core.Command{ - Short: `Get ACL Rules for VPC`, + Short: `Get Acl Rules for VPC`, Long: `Retrieve a list of ACL rules for a VPC, specified by its VPC ID.`, Namespace: "vpc", Resource: "rule", From 8baf06cf6e355963c1c4af91934c54e38ba7f492 Mon Sep 17 00:00:00 2001 From: Laure-di Date: Thu, 3 Apr 2025 19:56:34 +0200 Subject: [PATCH 21/24] delete .DS_Store --- .DS_Store | Bin 8196 -> 0 bytes cmd/.DS_Store | Bin 6148 -> 0 bytes cmd/scw-wasm-tester/human.go | 3 +- cmd/scw-wasm-tester/main.go | 3 +- cmd/scw-wasm-tester/slices.go | 3 +- cmd/scw-wasm/main.go | 7 +- cmd/scw-wasm/run.go | 2 +- cmd/scw/.DS_Store | Bin 6148 -> 0 bytes core/shell_disabled.go | 13 +- internal/.DS_Store | Bin 6148 -> 0 bytes internal/gotty/resize_windows.go | 1 + internal/jshelpers/arrays.go | 5 +- internal/jshelpers/async.go | 1 + internal/jshelpers/function.go | 18 +- internal/jshelpers/objects.go | 1 + internal/jshelpers/scalar.go | 1 + .../namespaces/instance/v1/custom_ssh_key.go | 6 +- .../interlink/v1beta1/interlink_cli.go | 2 +- internal/namespaces/vpcgw/v2/custom.go | 12 +- .../vpcgw/v2/custom_gateway_network.go | 3 +- .../vpcgw/v2/custom_gateway_type.go | 18 +- internal/namespaces/vpcgw/v2/vpcgw_cli.go | 325 ++++++++++++++++-- internal/wasm/autocomplete.go | 12 +- internal/wasm/output.go | 3 +- internal/wasm/roundtrip.go | 8 +- internal/wasm/run.go | 12 +- 26 files changed, 385 insertions(+), 74 deletions(-) delete mode 100644 .DS_Store delete mode 100644 cmd/.DS_Store delete mode 100644 cmd/scw/.DS_Store delete mode 100644 internal/.DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 8f95adcb51e2ed5771ae21cc3c4726ccb0825f81..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8196 zcmeHMJ%|%Q6n?WwxD8i$;?D)I*+K+S#E4*}#3TMy2gbriFh9rLX*L^^I}fW%<8hKg zZIpEOA}AIj3U;Da7GfoOjg5jRdX0tn%}3srj%RGn*p{{`6?5w9 zL6}rwN(`aX;rC=XY|hx0wmO}JPA6fIg{e@4LPwsb!b#+`wWC$QDiBpb*6uFtL)BiS z3a{VGfnR6gkr+S7=S$U~B=h%X_M~r~cz!f)EG`xt(2n?oWt>*o3{UWsyGbH z!<85w#rcr9A^D`hXHMOnVu*`4xEl6y9v>!7?ry(SJXk*G5FZhPpP&-(YaH8IP8|Za z@o?O+wbG7Tj}>+rI-*FUND1)!RFP-RM(=a4h(4Zy8gy=kkZIf1xERji^UCGUqUI2pi?ca>Zlb$4B5@&J`tVCCUJd;{ zt-Jpzb-fKfJs;+Nq4x7_gxR2wGpFOoSe$PC2 zCYP@}&L6_vB4KeKu*+y3Z=nWkk*fSYI8QFTjf>$t9>4h7-3yVqIG;boabC_x_56)c z6KXWTt`2r#Rp`hBSPevQPE(yq^1+gMAB5)NjD|;XK16o_hWoP!b(-XJecS_=o^c=N z;Qi|K_l3#j=y86I>t1{U?r&zLrgcD=Fa`JnpifO1E& zm4!U6?)v=G!)IpQ*7bbV&Jn3@o?l-MPy4HWcKJhgbKg6)xde?y1*iZOpaN9jUn_u~ ztyY~ma-{-PfC_vlpx=iKS1f^@qkTHC*a!gB-*_`T+bjXh8UU8S&Jht5}YboD(;vm{5}4j(E0mNyU*X6`%sg3XFU^(f)r8|7QL_CUHjvsKB36 zAdTy$p5c|Ew+>!Tdu@i_!ru+GR*uD5G0<8uHrk3WdUaW!kuQOrqtOvJI*>mCstb(@ H{DuN=-H0pe diff --git a/cmd/scw-wasm-tester/human.go b/cmd/scw-wasm-tester/human.go index 174a230f53..65e2aef843 100644 --- a/cmd/scw-wasm-tester/human.go +++ b/cmd/scw-wasm-tester/human.go @@ -3,11 +3,10 @@ package main import ( - "syscall/js" - "github.com/hashicorp/go-version" "github.com/scaleway/scaleway-cli/v2/core" "github.com/scaleway/scaleway-cli/v2/core/human" + "syscall/js" ) func wasmTestMarshalBuildInfo(_ js.Value, _ []js.Value) any { diff --git a/cmd/scw-wasm-tester/main.go b/cmd/scw-wasm-tester/main.go index 977b1b5f11..ae2ce25869 100644 --- a/cmd/scw-wasm-tester/main.go +++ b/cmd/scw-wasm-tester/main.go @@ -3,9 +3,8 @@ package main import ( - "syscall/js" - "github.com/scaleway/scaleway-cli/v2/internal/jshelpers" + "syscall/js" ) type jsFunction func(js.Value, []js.Value) any diff --git a/cmd/scw-wasm-tester/slices.go b/cmd/scw-wasm-tester/slices.go index cc81265559..0913f21eb7 100644 --- a/cmd/scw-wasm-tester/slices.go +++ b/cmd/scw-wasm-tester/slices.go @@ -3,9 +3,8 @@ package main import ( - "syscall/js" - "github.com/scaleway/scaleway-cli/v2/internal/jshelpers" + "syscall/js" ) func wasmTestFromSlice(_ js.Value, _ []js.Value) any { diff --git a/cmd/scw-wasm/main.go b/cmd/scw-wasm/main.go index 86bc57fb2c..08dcaf92a8 100644 --- a/cmd/scw-wasm/main.go +++ b/cmd/scw-wasm/main.go @@ -5,12 +5,12 @@ package main import ( "runtime" "runtime/debug" - "syscall/js" "github.com/hashicorp/go-version" "github.com/scaleway/scaleway-cli/v2/core" "github.com/scaleway/scaleway-cli/v2/internal/jshelpers" "github.com/scaleway/scaleway-cli/v2/internal/wasm" + "syscall/js" ) var ( @@ -62,7 +62,10 @@ func main() { if args.targetObject != "" { cliPackage := js.ValueOf(map[string]any{}) cliPackage.Set("run", js.FuncOf(jshelpers.AsPromise(wasm.RunWithBuildInfo(buildInfo)))) - cliPackage.Set("complete", js.FuncOf(jshelpers.AsPromise(wasm.AutocompleteWithBuildInfo(buildInfo)))) + cliPackage.Set( + "complete", + js.FuncOf(jshelpers.AsPromise(wasm.AutocompleteWithBuildInfo(buildInfo))), + ) cliPackage.Set("configureOutput", js.FuncOf(jshelpers.AsPromise(wasm.ConfigureOutput))) cliPackage.Set("stop", js.FuncOf(jshelpers.AsyncJsFunc(stop))) js.Global().Set(args.targetObject, cliPackage) diff --git a/cmd/scw-wasm/run.go b/cmd/scw-wasm/run.go index 88bc39a698..9e0ca513fd 100644 --- a/cmd/scw-wasm/run.go +++ b/cmd/scw-wasm/run.go @@ -4,11 +4,11 @@ package main import ( "fmt" - "syscall/js" "github.com/scaleway/scaleway-cli/v2/core" "github.com/scaleway/scaleway-cli/v2/internal/jshelpers" "github.com/scaleway/scaleway-cli/v2/internal/wasm" + "syscall/js" ) func wasmRun(this js.Value, args []js.Value) (any, error) { diff --git a/cmd/scw/.DS_Store b/cmd/scw/.DS_Store deleted file mode 100644 index 439e4a7457d537f7e2b039f43217e23abb54bc34..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKJ5B>J5S@V(E73%vq4X8@21~SDAS+Rmun3Ao8!13qAA*JpA#n-BDX4k#A!3CK z8W2J=lKsY>kG)S?+e1V=yX$MBDG^m@f-FiwWV&cNaOVk-HAhbix~0YHy6y^z{^FGE zy~3WaXp8>S{x661MmK!?@=)?w4{f_#4NI}To!>w1o}W(3e*L%nHaB&*UvvJ7R3X7Y zFc1s`1Hr(LFn~K-q&hN;J{SlFf`L5)ay}$9!NxHg>d}EtO8}reqg9|wEg><J5S^Js&?0wSO9wOq|?Pf|eA)*RRkVP2~nI1Ha+<6RS&9S47mb9h|+6^T7i&L`q zW4gw!8{PGO|J%#yeBCykY#!@iqu`*v5K)_++b zWk@g(3_I5vP=J diff --git a/internal/gotty/resize_windows.go b/internal/gotty/resize_windows.go index dfbc3eba57..7944591e9c 100644 --- a/internal/gotty/resize_windows.go +++ b/internal/gotty/resize_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package gotty diff --git a/internal/jshelpers/arrays.go b/internal/jshelpers/arrays.go index 0883b32b2c..c4d5f25e97 100644 --- a/internal/jshelpers/arrays.go +++ b/internal/jshelpers/arrays.go @@ -5,12 +5,11 @@ package jshelpers import ( "fmt" "reflect" + "syscall/js" ) -var ( - jsArray = js.Global().Get("Array") -) +var jsArray = js.Global().Get("Array") func asSlice(typ reflect.Type, value js.Value) (any, error) { if !value.InstanceOf(jsArray) { diff --git a/internal/jshelpers/async.go b/internal/jshelpers/async.go index a8572cbdc0..57071c7590 100644 --- a/internal/jshelpers/async.go +++ b/internal/jshelpers/async.go @@ -5,6 +5,7 @@ package jshelpers import ( "fmt" "runtime/debug" + "syscall/js" ) diff --git a/internal/jshelpers/function.go b/internal/jshelpers/function.go index 480e0a7e8f..2d1f6b9c95 100644 --- a/internal/jshelpers/function.go +++ b/internal/jshelpers/function.go @@ -5,12 +5,11 @@ package jshelpers import ( "fmt" "reflect" + "syscall/js" ) -var ( - goErrorInterface = reflect.TypeOf((*error)(nil)).Elem() -) +var goErrorInterface = reflect.TypeOf((*error)(nil)).Elem() func jsValue(val any) js.Value { valType := reflect.TypeOf(val) @@ -56,14 +55,23 @@ func AsPromise(goFunc any) JsFunc { return AsyncJsFunc(func(this js.Value, args []js.Value) (any, error) { if len(args) != len(goFuncArgs) { - return nil, fmt.Errorf("invalid number of arguments, expected %d, got %d", len(goFuncArgs), len(args)) + return nil, fmt.Errorf( + "invalid number of arguments, expected %d, got %d", + len(goFuncArgs), + len(args), + ) } argValues := make([]reflect.Value, len(goFuncArgs)) for i, argType := range goFuncArgs { arg, err := goValue(argType, args[i]) if err != nil { - return nil, fmt.Errorf("invalid argument at index %d, expected type %s: %w", i, argType.String(), err) + return nil, fmt.Errorf( + "invalid argument at index %d, expected type %s: %w", + i, + argType.String(), + err, + ) } argValues[i] = reflect.ValueOf(arg) } diff --git a/internal/jshelpers/objects.go b/internal/jshelpers/objects.go index 8841c9192e..7377b80e00 100644 --- a/internal/jshelpers/objects.go +++ b/internal/jshelpers/objects.go @@ -5,6 +5,7 @@ package jshelpers import ( "fmt" "reflect" + "syscall/js" ) diff --git a/internal/jshelpers/scalar.go b/internal/jshelpers/scalar.go index 99c3cd00c9..d129c3d539 100644 --- a/internal/jshelpers/scalar.go +++ b/internal/jshelpers/scalar.go @@ -5,6 +5,7 @@ package jshelpers import ( "fmt" "math" + "syscall/js" ) diff --git a/internal/namespaces/instance/v1/custom_ssh_key.go b/internal/namespaces/instance/v1/custom_ssh_key.go index 35cd83fa8f..8340d60265 100644 --- a/internal/namespaces/instance/v1/custom_ssh_key.go +++ b/internal/namespaces/instance/v1/custom_ssh_key.go @@ -175,7 +175,11 @@ Keep in mind that SSH keys are scoped by project.`, if args.ProjectID != "" { listServersRequest.Project = &args.ProjectID } - servers, err := api.ListServers(listServersRequest, scw.WithAllPages(), scw.WithContext(ctx)) + servers, err := api.ListServers( + listServersRequest, + scw.WithAllPages(), + scw.WithContext(ctx), + ) if err != nil { return nil, fmt.Errorf("failed to fetch servers: %w", err) } diff --git a/internal/namespaces/interlink/v1beta1/interlink_cli.go b/internal/namespaces/interlink/v1beta1/interlink_cli.go index 8c48218c73..53bc791c87 100644 --- a/internal/namespaces/interlink/v1beta1/interlink_cli.go +++ b/internal/namespaces/interlink/v1beta1/interlink_cli.go @@ -501,7 +501,7 @@ func interlinkLinkGet() *core.Command { func interlinkLinkCreate() *core.Command { return &core.Command{ Short: `Create a link`, - Long: `Create a link (InterLink session / logical InterLink resource) in a given PoP, specifying its various configuration details. Links can either be hosted (faciliated by partners' shared physical connections) or self-hosted (for users who have purchased a dedicated physical connection).`, + Long: `Create a link (InterLink session / logical InterLink resource) in a given PoP, specifying its various configuration details. Links can either be hosted (facilitated by partners' shared physical connections) or self-hosted (for users who have purchased a dedicated physical connection).`, Namespace: "interlink", Resource: "link", Verb: "create", diff --git a/internal/namespaces/vpcgw/v2/custom.go b/internal/namespaces/vpcgw/v2/custom.go index e467ec28c7..e69d18518a 100644 --- a/internal/namespaces/vpcgw/v2/custom.go +++ b/internal/namespaces/vpcgw/v2/custom.go @@ -18,9 +18,15 @@ func GetCommands() *core.Commands { cmds.MustFind("vpc-gw").Groups = []string{"network"} - human.RegisterMarshalerFunc(vpcgw.GatewayNetworkStatus(""), human.EnumMarshalFunc(gatewayNetworkStatusMarshalSpecs)) - human.RegisterMarshalerFunc(vpcgw.GatewayStatus(""), human.EnumMarshalFunc(gatewayStatusMarshalSpecs)) - human.RegisterMarshalerFunc(vpcgw.Gateway{}, gatewayMarshalerFunc) + human.RegisterMarshalerFunc( + vpcgw.GatewayNetworkStatus(""), + human.EnumMarshalFunc(gatewayNetworkStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + vpcgw.GatewayStatus(""), + human.EnumMarshalFunc(gatewayStatusMarshalSpecs)) + human.RegisterMarshalerFunc( + vpcgw.Gateway{}, + gatewayMarshalerFunc) cmds.MustFind("vpc-gw", "gateway-type", "list").Override(vpcgwGatewayTypeListBuilder) cmds.MustFind("vpc-gw", "gateway", "create").Override(gatewayCreateBuilder) diff --git a/internal/namespaces/vpcgw/v2/custom_gateway_network.go b/internal/namespaces/vpcgw/v2/custom_gateway_network.go index eca9acd002..6e31b1bece 100644 --- a/internal/namespaces/vpcgw/v2/custom_gateway_network.go +++ b/internal/namespaces/vpcgw/v2/custom_gateway_network.go @@ -50,7 +50,8 @@ func gatewayNetworkDeleteBuilder(c *core.Command) *core.Command { if err != nil { notFoundError := &scw.ResourceNotFoundError{} responseError := &scw.ResponseError{} - if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) { + if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || + errors.As(err, ¬FoundError) { return &core.SuccessResult{ Resource: "gateway-network", Verb: "delete", diff --git a/internal/namespaces/vpcgw/v2/custom_gateway_type.go b/internal/namespaces/vpcgw/v2/custom_gateway_type.go index 73533e3fe9..3eb44f3999 100644 --- a/internal/namespaces/vpcgw/v2/custom_gateway_type.go +++ b/internal/namespaces/vpcgw/v2/custom_gateway_type.go @@ -8,16 +8,18 @@ import ( ) func vpcgwGatewayTypeListBuilder(c *core.Command) *core.Command { - c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { - res, err := runner(ctx, argsI) - if err != nil { - return nil, err - } + c.AddInterceptors( + func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) { + res, err := runner(ctx, argsI) + if err != nil { + return nil, err + } - typesResponse := res.(*vpcgw.ListGatewayTypesResponse) + typesResponse := res.(*vpcgw.ListGatewayTypesResponse) - return typesResponse.Types, nil - }) + return typesResponse.Types, nil + }, + ) return c } diff --git a/internal/namespaces/vpcgw/v2/vpcgw_cli.go b/internal/namespaces/vpcgw/v2/vpcgw_cli.go index 14f21cf803..adbedc60ea 100644 --- a/internal/namespaces/vpcgw/v2/vpcgw_cli.go +++ b/internal/namespaces/vpcgw/v2/vpcgw_cli.go @@ -51,6 +51,7 @@ func GetGeneratedCommands() *core.Commands { vpcGwGatewayRefreshSSHKeys(), ) } + func vpcGwRoot() *core.Command { return &core.Command{ Short: `This API allows you to manage your Public Gateways`, @@ -120,7 +121,16 @@ func vpcGwGatewayList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "name_asc", "name_desc", "type_asc", "type_desc", "status_asc", "status_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "name_asc", + "name_desc", + "type_asc", + "type_desc", + "status_asc", + "status_desc", + }, }, { Name: "project-id", @@ -156,7 +166,17 @@ func vpcGwGatewayList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_status", "stopped", "allocating", "configuring", "running", "stopping", "failed", "deleting", "locked"}, + EnumValues: []string{ + "unknown_status", + "stopped", + "allocating", + "configuring", + "running", + "stopping", + "failed", + "deleting", + "locked", + }, }, { Name: "private-network-ids.{index}", @@ -179,7 +199,16 @@ func vpcGwGatewayList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities)), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.ListGatewaysRequest) @@ -195,6 +224,7 @@ func vpcGwGatewayList() *core.Command { if err != nil { return nil, err } + return resp.Gateways, nil }, } @@ -217,13 +247,22 @@ func vpcGwGatewayGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.GetGatewayRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.GetGateway(request) }, } @@ -291,13 +330,22 @@ func vpcGwGatewayCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.CreateGatewayRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.CreateGateway(request) }, } @@ -355,13 +403,22 @@ func vpcGwGatewayUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.UpdateGatewayRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.UpdateGateway(request) }, } @@ -391,13 +448,22 @@ func vpcGwGatewayDelete() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.DeleteGatewayRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.DeleteGateway(request) }, } @@ -427,13 +493,22 @@ func vpcGwGatewayUpgrade() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.UpgradeGatewayRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.UpgradeGateway(request) }, } @@ -455,7 +530,12 @@ func vpcGwGatewayNetworkList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "status_asc", "status_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "status_asc", + "status_desc", + }, }, { Name: "status.{index}", @@ -463,7 +543,14 @@ func vpcGwGatewayNetworkList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"unknown_status", "created", "attaching", "configuring", "ready", "detaching"}, + EnumValues: []string{ + "unknown_status", + "created", + "attaching", + "configuring", + "ready", + "detaching", + }, }, { Name: "gateway-ids.{index}", @@ -486,7 +573,16 @@ func vpcGwGatewayNetworkList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities)), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.ListGatewayNetworksRequest) @@ -502,6 +598,7 @@ func vpcGwGatewayNetworkList() *core.Command { if err != nil { return nil, err } + return resp.GatewayNetworks, nil }, } @@ -524,13 +621,22 @@ func vpcGwGatewayNetworkGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.GetGatewayNetworkRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.GetGatewayNetwork(request) }, } @@ -581,13 +687,22 @@ func vpcGwGatewayNetworkCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.CreateGatewayNetworkRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.CreateGatewayNetwork(request) }, } @@ -631,13 +746,22 @@ func vpcGwGatewayNetworkUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.UpdateGatewayNetworkRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.UpdateGatewayNetwork(request) }, } @@ -660,13 +784,22 @@ func vpcGwGatewayNetworkDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.DeleteGatewayNetworkRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.DeleteGatewayNetwork(request) }, } @@ -688,7 +821,12 @@ func vpcGwPatRuleList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "public_port_asc", "public_port_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "public_port_asc", + "public_port_desc", + }, }, { Name: "gateway-ids.{index}", @@ -712,7 +850,16 @@ func vpcGwPatRuleList() *core.Command { Positional: false, EnumValues: []string{"unknown_protocol", "both", "tcp", "udp"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities)), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.ListPatRulesRequest) @@ -728,6 +875,7 @@ func vpcGwPatRuleList() *core.Command { if err != nil { return nil, err } + return resp.PatRules, nil }, } @@ -750,13 +898,22 @@ func vpcGwPatRuleGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.GetPatRuleRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.GetPatRule(request) }, } @@ -808,13 +965,22 @@ func vpcGwPatRuleCreate() *core.Command { Positional: false, EnumValues: []string{"unknown_protocol", "both", "tcp", "udp"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.CreatePatRuleRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.CreatePatRule(request) }, } @@ -866,13 +1032,22 @@ func vpcGwPatRuleUpdate() *core.Command { Positional: false, EnumValues: []string{"unknown_protocol", "both", "tcp", "udp"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.UpdatePatRuleRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.UpdatePatRule(request) }, } @@ -924,13 +1099,22 @@ func vpcGwPatRuleSet() *core.Command { Positional: false, EnumValues: []string{"unknown_protocol", "both", "tcp", "udp"}, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.SetPatRulesRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.SetPatRules(request) }, } @@ -953,7 +1137,15 @@ func vpcGwPatRuleDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.DeletePatRuleRequest) @@ -964,6 +1156,7 @@ func vpcGwPatRuleDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "pat-rule", Verb: "delete", @@ -982,13 +1175,22 @@ func vpcGwGatewayTypeList() *core.Command { // Deprecated: false, ArgsType: reflect.TypeOf(vpcgw.ListGatewayTypesRequest{}), ArgSpecs: core.ArgSpecs{ - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.ListGatewayTypesRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.ListGatewayTypes(request) }, } @@ -1010,7 +1212,14 @@ func vpcGwIPList() *core.Command { Required: false, Deprecated: false, Positional: false, - EnumValues: []string{"created_at_asc", "created_at_desc", "address_asc", "address_desc", "reverse_asc", "reverse_desc"}, + EnumValues: []string{ + "created_at_asc", + "created_at_desc", + "address_asc", + "address_desc", + "reverse_asc", + "reverse_desc", + }, }, { Name: "project-id", @@ -1047,7 +1256,16 @@ func vpcGwIPList() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3, scw.Zone(core.AllLocalities)), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities)), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.ListIPsRequest) @@ -1063,6 +1281,7 @@ func vpcGwIPList() *core.Command { if err != nil { return nil, err } + return resp.IPs, nil }, } @@ -1085,13 +1304,23 @@ func vpcGwIPGet() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3, + scw.Zone(core.AllLocalities)), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.GetIPRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.GetIP(request) }, } @@ -1115,13 +1344,22 @@ func vpcGwIPCreate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.CreateIPRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.CreateIP(request) }, } @@ -1165,13 +1403,22 @@ func vpcGwIPUpdate() *core.Command { Deprecated: false, Positional: false, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.UpdateIPRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.UpdateIP(request) }, } @@ -1194,7 +1441,15 @@ func vpcGwIPDelete() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.DeleteIPRequest) @@ -1205,6 +1460,7 @@ func vpcGwIPDelete() *core.Command { if e != nil { return nil, e } + return &core.SuccessResult{ Resource: "ip", Verb: "delete", @@ -1230,13 +1486,22 @@ func vpcGwGatewayRefreshSSHKeys() *core.Command { Deprecated: false, Positional: true, }, - core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1, scw.ZoneNlAms2, scw.ZoneNlAms3, scw.ZonePlWaw1, scw.ZonePlWaw2, scw.ZonePlWaw3), + core.ZoneArgSpec( + scw.ZoneFrPar1, + scw.ZoneFrPar2, + scw.ZoneNlAms1, + scw.ZoneNlAms2, + scw.ZoneNlAms3, + scw.ZonePlWaw1, + scw.ZonePlWaw2, + scw.ZonePlWaw3), }, Run: func(ctx context.Context, args interface{}) (i interface{}, e error) { request := args.(*vpcgw.RefreshSSHKeysRequest) client := core.ExtractClient(ctx) api := vpcgw.NewAPI(client) + return api.RefreshSSHKeys(request) }, } diff --git a/internal/wasm/autocomplete.go b/internal/wasm/autocomplete.go index f422eac198..3cf2838002 100644 --- a/internal/wasm/autocomplete.go +++ b/internal/wasm/autocomplete.go @@ -23,7 +23,13 @@ func Autocomplete(buildInfo *core.BuildInfo, cfg *AutoCompleteConfig) ([]string, words := append(cfg.LeftWords, cfg.SelectedWord) words = append(words, cfg.RightWords...) - completeCommand := []string{"autocomplete", "complete", "zsh", strconv.FormatInt(indexToComplete, 10), "scw"} + completeCommand := []string{ + "autocomplete", + "complete", + "zsh", + strconv.FormatInt(indexToComplete, 10), + "scw", + } completeCommand = append(completeCommand, words...) @@ -43,7 +49,9 @@ func Autocomplete(buildInfo *core.BuildInfo, cfg *AutoCompleteConfig) ([]string, return suggestions, nil } -func AutocompleteWithBuildInfo(buildInfo *core.BuildInfo) func(cfg *AutoCompleteConfig) ([]string, error) { +func AutocompleteWithBuildInfo( + buildInfo *core.BuildInfo, +) func(cfg *AutoCompleteConfig) ([]string, error) { return func(cfg *AutoCompleteConfig) ([]string, error) { return Autocomplete(buildInfo, cfg) } diff --git a/internal/wasm/output.go b/internal/wasm/output.go index eb11906637..a10f2120e6 100644 --- a/internal/wasm/output.go +++ b/internal/wasm/output.go @@ -12,8 +12,7 @@ type ConfigureOutputConfig struct { Color bool `js:"color"` } -type ConfigureOutputResponse struct { -} +type ConfigureOutputResponse struct{} func ConfigureOutput(cfg *ConfigureOutputConfig) (*ConfigureOutputResponse, error) { terminal.Width = cfg.Width diff --git a/internal/wasm/roundtrip.go b/internal/wasm/roundtrip.go index 9c5fbda42e..557392c729 100644 --- a/internal/wasm/roundtrip.go +++ b/internal/wasm/roundtrip.go @@ -14,9 +14,9 @@ import ( "io" "net/http" "strconv" - "syscall/js" - _ "unsafe" + + "syscall/js" ) var uint8Array = js.Global().Get("Uint8Array") @@ -171,12 +171,10 @@ func (r *arrayReader) Close() error { return nil } -type Transport struct { -} +type Transport struct{} // RoundTrip implements the RoundTripper interface using the WHATWG Fetch API. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { - ac := js.Global().Get("AbortController") if !ac.IsUndefined() { // Some browsers that support WASM don't necessarily support diff --git a/internal/wasm/run.go b/internal/wasm/run.go index 3f962a3a5c..d67d01cbcd 100644 --- a/internal/wasm/run.go +++ b/internal/wasm/run.go @@ -34,7 +34,13 @@ type RunResponse struct { ExitCode int `js:"exitCode"` } -func runCommand(buildInfo *core.BuildInfo, cfg *RunConfig, args []string, stdout io.Writer, stderr io.Writer) int { +func runCommand( + buildInfo *core.BuildInfo, + cfg *RunConfig, + args []string, + stdout io.Writer, + stderr io.Writer, +) int { exitCode, _, _ := core.Bootstrap(&core.BootstrapConfig{ Args: args, Commands: getCommands(), @@ -72,7 +78,9 @@ func Run(buildInfo *core.BuildInfo, cfg *RunConfig, args []string) (*RunResponse }, nil } -func RunWithBuildInfo(buildInfo *core.BuildInfo) func(config *RunConfig, args []string) (*RunResponse, error) { +func RunWithBuildInfo( + buildInfo *core.BuildInfo, +) func(config *RunConfig, args []string) (*RunResponse, error) { return func(config *RunConfig, args []string) (*RunResponse, error) { return Run(buildInfo, config, args) } From 9974b0ca5a5bcea6242b3749393d35e04681718b Mon Sep 17 00:00:00 2001 From: Laure-di Date: Fri, 4 Apr 2025 00:55:06 +0200 Subject: [PATCH 22/24] generate doc --- docs/commands/document-db.md | 2 +- docs/commands/function.md | 10 +++++----- docs/commands/iam.md | 18 +++++++++--------- docs/commands/inference.md | 6 +++--- docs/commands/interlink.md | 2 +- docs/commands/iot.md | 2 +- docs/commands/rdb.md | 2 +- docs/commands/redis.md | 2 +- docs/commands/vpc-gw.md | 2 +- docs/commands/vpc.md | 6 +++--- 10 files changed, 26 insertions(+), 26 deletions(-) diff --git a/docs/commands/document-db.md b/docs/commands/document-db.md index abd10bb3b3..0a4ef5c1ab 100644 --- a/docs/commands/document-db.md +++ b/docs/commands/document-db.md @@ -965,7 +965,7 @@ scw document-db setting delete [arg=value ...] ### Set Database Instance advanced settings -Update an advanced setting for a Database Instance. Settings added upon database engine initalization can only be defined once, and cannot, therefore, be updated. +Update an advanced setting for a Database Instance. Settings added upon database engine initialization can only be defined once, and cannot, therefore, be updated. **Usage:** diff --git a/docs/commands/function.md b/docs/commands/function.md index 688554328c..674e86bae4 100644 --- a/docs/commands/function.md +++ b/docs/commands/function.md @@ -264,7 +264,7 @@ scw function domain list [arg=value ...] | Name | | Description | |------|---|-------------| | order-by | One of: `created_at_asc`, `created_at_desc`, `hostname_asc`, `hostname_desc` | Order of the domains | -| function-id | | UUID of the function the domain is assoicated with | +| function-id | | UUID of the function the domain is associated with | | region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw`, `all` | Region to target. If none is passed will use default region from the config | @@ -292,7 +292,7 @@ scw function function create [arg=value ...] | name | Default: `` | Name of the function to create | | namespace-id | | UUID of the namespace the function will be created in | | environment-variables.{key} | | Environment variables of the function | -| min-scale | | Minumum number of instances to scale the function to | +| min-scale | | Minimum number of instances to scale the function to | | max-scale | | Maximum number of instances to scale the function to | | runtime | One of: `unknown_runtime`, `golang`, `python`, `python3`, `node8`, `node10`, `node14`, `node16`, `node17`, `python37`, `python38`, `python39`, `python310`, `go113`, `go117`, `go118`, `node18`, `rust165`, `go119`, `python311`, `php82`, `node19`, `go120`, `node20`, `go121`, `node22`, `python312`, `php83`, `go122`, `rust179`, `go123`, `go124`, `python313`, `rust185`, `php84` | Runtime to use with the function | | memory-limit | | Memory limit of the function in MB | @@ -428,7 +428,7 @@ scw function function list [arg=value ...] | namespace-id | | UUID of the namespace the function belongs to | | name | | Name of the function | | project-id | | UUID of the Project the function belongs to | -| organization-id | | UUID of the Organziation the function belongs to | +| organization-id | | UUID of the Organization the function belongs to | | region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw`, `all` | Region to target. If none is passed will use default region from the config | @@ -450,7 +450,7 @@ scw function function update [arg=value ...] |------|---|-------------| | function-id | Required | UUID of the function to update | | environment-variables.{key} | | Environment variables of the function to update | -| min-scale | | Minumum number of instances to scale the function to | +| min-scale | | Minimum number of instances to scale the function to | | max-scale | | Maximum number of instances to scale the function to | | runtime | One of: `unknown_runtime`, `golang`, `python`, `python3`, `node8`, `node10`, `node14`, `node16`, `node17`, `python37`, `python38`, `python39`, `python310`, `go113`, `go117`, `go118`, `node18`, `rust165`, `go119`, `python311`, `php82`, `node19`, `go120`, `node20`, `go121`, `node22`, `python312`, `php83`, `go122`, `rust179`, `go123`, `go124`, `python313`, `rust185`, `php84` | Runtime to use with the function | | memory-limit | | Memory limit of the function in MB | @@ -694,7 +694,7 @@ scw function token list [arg=value ...] | Name | | Description | |------|---|-------------| | order-by | One of: `created_at_asc`, `created_at_desc` | Sort order for the tokens | -| function-id | | UUID of the function the token is assoicated with | +| function-id | | UUID of the function the token is associated with | | namespace-id | | UUID of the namespace the token is associated with | | region | Default: `fr-par`
One of: `fr-par`, `nl-ams`, `pl-waw`, `all` | Region to target. If none is passed will use default region from the config | diff --git a/docs/commands/iam.md b/docs/commands/iam.md index 8496bc4d44..a8ecb4550a 100644 --- a/docs/commands/iam.md +++ b/docs/commands/iam.md @@ -58,8 +58,8 @@ This API allows you to manage Identity and Access Management (IAM) across your S - [Get a given user](#get-a-given-user) - [List users of an Organization](#list-users-of-an-organization) - [Update a user](#update-a-user) - - [Update an user's password.](#update-an-user's-password.) - - [Update an user's username.](#update-an-user's-username.) + - [Update an user's password. Private Beta feature.](#update-an-user's-password.-private-beta-feature.) + - [Update an user's username. Private Beta feature.](#update-an-user's-username.-private-beta-feature.) ## API keys management commands @@ -121,7 +121,7 @@ scw iam api-key delete SCW00000000000 ### Get an API key -Retrive information about an API key, specified by the `access_key` parameter. The API key's details, including either the `user_id` or `application_id` of its bearer are returned in the response. Note that the string value for the `secret_key` is nullable, and therefore is not displayed in the response. The `secret_key` value is only displayed upon API key creation. +Retrieve information about an API key, specified by the `access_key` parameter. The API key's details, including either the `user_id` or `application_id` of its bearer are returned in the response. Note that the string value for the `secret_key` is nullable, and therefore is not displayed in the response. The `secret_key` value is only displayed upon API key creation. **Usage:** @@ -409,7 +409,7 @@ scw iam group delete 11111111-1111-1111-1111-111111111111 ### Get a group -Retrive information about a given group, specified by the `group_id` parameter. The group's full details, including `user_ids` and `application_ids` are returned in the response. +Retrieve information about a given group, specified by the `group_id` parameter. The group's full details, including `user_ids` and `application_ids` are returned in the response. **Usage:** @@ -1045,7 +1045,7 @@ Users management commands. ### Create a new user -Create a new user. You must define the `organization_id` in your request. If you are adding a member, enter the member's details. If you are adding a guest, you must define the `email` and not add the member attribute. +Create a new user. You must define the `organization_id` and the `email` in your request. **Usage:** @@ -1160,9 +1160,9 @@ scw iam user update [arg=value ...] -### Update an user's password. +### Update an user's password. Private Beta feature. -Update an user's password. +Update an user's password. Private Beta feature. **Usage:** @@ -1180,9 +1180,9 @@ scw iam user update-password [arg=value ...] -### Update an user's username. +### Update an user's username. Private Beta feature. -Update an user's username. +Update an user's username. Private Beta feature. **Usage:** diff --git a/docs/commands/inference.md b/docs/commands/inference.md index fad2419622..7c02208d56 100644 --- a/docs/commands/inference.md +++ b/docs/commands/inference.md @@ -4,7 +4,7 @@ This API allows you to manage your Inference services. - [Access Control List (ACL) management commands](#access-control-list-(acl)-management-commands) - [Add new ACLs](#add-new-acls) - - [Delete an exising ACL](#delete-an-exising-acl) + - [Delete an existing ACL](#delete-an-existing-acl) - [List your ACLs](#list-your-acls) - [Set new ACL](#set-new-acl) - [Deployment commands](#deployment-commands) @@ -52,9 +52,9 @@ scw inference acl add [arg=value ...] -### Delete an exising ACL +### Delete an existing ACL -Delete an exising ACL. +Delete an existing ACL. **Usage:** diff --git a/docs/commands/interlink.md b/docs/commands/interlink.md index fe0ed90d10..d458d19b8c 100644 --- a/docs/commands/interlink.md +++ b/docs/commands/interlink.md @@ -92,7 +92,7 @@ scw interlink link attach_vpc [arg=value ...] ### Create a link -Create a link (InterLink session / logical InterLink resource) in a given PoP, specifying its various configuration details. Links can either be hosted (faciliated by partners' shared physical connections) or self-hosted (for users who have purchased a dedicated physical connection). +Create a link (InterLink session / logical InterLink resource) in a given PoP, specifying its various configuration details. Links can either be hosted (facilitated by partners' shared physical connections) or self-hosted (for users who have purchased a dedicated physical connection). **Usage:** diff --git a/docs/commands/iot.md b/docs/commands/iot.md index 918c813ba6..d8b2a05ecb 100644 --- a/docs/commands/iot.md +++ b/docs/commands/iot.md @@ -209,7 +209,7 @@ scw iot device list [arg=value ...] | order-by | One of: `name_asc`, `name_desc`, `status_asc`, `status_desc`, `hub_id_asc`, `hub_id_desc`, `created_at_asc`, `created_at_desc`, `updated_at_asc`, `updated_at_desc`, `allow_insecure_asc`, `allow_insecure_desc` | Ordering of requested devices | | name | | Name to filter for, only devices with this name will be returned | | hub-id | | Hub ID to filter for, only devices attached to this Hub will be returned | -| allow-insecure | | Defines wheter to filter the allow_insecure flag | +| allow-insecure | | Defines whether to filter the allow_insecure flag | | status | One of: `unknown`, `error`, `enabled`, `disabled` | Device status (enabled, disabled, etc.) | | region | Default: `fr-par`
One of: `fr-par`, `all` | Region to target. If none is passed will use default region from the config | diff --git a/docs/commands/rdb.md b/docs/commands/rdb.md index 3c9aafe9c2..319c25310d 100644 --- a/docs/commands/rdb.md +++ b/docs/commands/rdb.md @@ -1400,7 +1400,7 @@ scw rdb setting delete [arg=value ...] ### Set Database Instance advanced settings -Update an advanced setting for a Database Instance. Settings added upon database engine initalization can only be defined once, and cannot, therefore, be updated. +Update an advanced setting for a Database Instance. Settings added upon database engine initialization can only be defined once, and cannot, therefore, be updated. **Usage:** diff --git a/docs/commands/redis.md b/docs/commands/redis.md index 87195630c3..10ce5b3185 100644 --- a/docs/commands/redis.md +++ b/docs/commands/redis.md @@ -557,7 +557,7 @@ scw redis setting delete [arg=value ...] ### Set advanced settings -Update an advanced setting for a Redis™ Database Instance (Redis™ cluster). Settings added upon database engine initalization can only be defined once, and cannot, therefore, be updated. +Update an advanced setting for a Redis™ Database Instance (Redis™ cluster). Settings added upon database engine initialization can only be defined once, and cannot, therefore, be updated. **Usage:** diff --git a/docs/commands/vpc-gw.md b/docs/commands/vpc-gw.md index 351ff5e8c9..489a870cd2 100644 --- a/docs/commands/vpc-gw.md +++ b/docs/commands/vpc-gw.md @@ -706,7 +706,7 @@ scw vpc-gw ip get [arg=value ...] | Name | | Description | |------|---|-------------| | ip-id | Required | ID of the IP address to get | -| zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3` | Zone to target. If none is passed will use default zone from the config | +| zone | Default: `fr-par-1`
One of: `fr-par-1`, `fr-par-2`, `nl-ams-1`, `nl-ams-2`, `nl-ams-3`, `pl-waw-1`, `pl-waw-2`, `pl-waw-3`, `all` | Zone to target. If none is passed will use default zone from the config | diff --git a/docs/commands/vpc.md b/docs/commands/vpc.md index 48321cc7f9..4495ff381c 100644 --- a/docs/commands/vpc.md +++ b/docs/commands/vpc.md @@ -17,7 +17,7 @@ This API allows you to manage your Virtual Private Clouds (VPCs) and Private Net - [Return routes with associated next hop data](#return-routes-with-associated-next-hop-data) - [Update Route](#update-route) - [Rule management command](#rule-management-command) - - [Get ACL Rules for VPC](#get-acl-rules-for-vpc) + - [Get Acl Rules for VPC](#get-acl-rules-for-vpc) - [Set VPC ACL rules](#set-vpc-acl-rules) - [Subnet management command](#subnet-management-command) - [VPC management command](#vpc-management-command) @@ -313,10 +313,10 @@ scw vpc route update [arg=value ...] ## Rule management command -ACL Rules. +Acl Rules. -### Get ACL Rules for VPC +### Get Acl Rules for VPC Retrieve a list of ACL rules for a VPC, specified by its VPC ID. From 05a52f0685eece11d3b2587862deb22a7ab320d2 Mon Sep 17 00:00:00 2001 From: Laure-di Date: Fri, 4 Apr 2025 11:04:11 +0200 Subject: [PATCH 23/24] fix regex issue --- core/testing_recorder.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/core/testing_recorder.go b/core/testing_recorder.go index e2a7dc7ac6..5935eabf4a 100644 --- a/core/testing_recorder.go +++ b/core/testing_recorder.go @@ -18,12 +18,14 @@ import ( func cassetteRequestFilter(i *cassette.Interaction) error { delete(i.Request.Headers, "x-auth-token") delete(i.Request.Headers, "X-Auth-Token") - i.URL = regexp.MustCompile("organization_id=[0-9a-f-]{36}"). - ReplaceAllString(i.URL, "organization_id=11111111-1111-1111-1111-111111111111") - i.URL = regexp.MustCompile(`api\.scaleway\.com/account/v1/tokens/[0-9a-f-]{36}`). - ReplaceAllString(i.URL, "api.scaleway.com/account/v1/tokens/11111111-1111-1111-1111-111111111111") - i.URL = regexp.MustCompile(`^api\.scaleway\.com/iam/v1alpha1/api-keys/SCW[0-9A-Z]{17}`). - ReplaceAllString(i.URL, "api.scaleway.com/iam/v1alpha1/api-keys/SCWXXXXXXXXXXXXXXXXX") + + orgIDRegex := regexp.MustCompile("organization_id=[0-9a-f-]{36}") + tokenRegex := regexp.MustCompile(`api\.scaleway\.com/account/v1/tokens/[0-9a-f-]{36}`) + apiKeyRegex := regexp.MustCompile(`^api\.scaleway\.com/iam/v1alpha1/api-keys/SCW[0-9A-Z]{17}`) + + i.URL = orgIDRegex.ReplaceAllString(i.URL, "organization_id=11111111-1111-1111-1111-111111111111") + i.URL = tokenRegex.ReplaceAllString(i.URL, "api.scaleway.com/account/v1/tokens/11111111-1111-1111-1111-111111111111") + i.URL = apiKeyRegex.ReplaceAllString(i.URL, "api.scaleway.com/iam/v1alpha1/api-keys/SCWXXXXXXXXXXXXXXXXX") return nil } From 14e6312df1b3de0d3b64591cfd31a0b62c346ced Mon Sep 17 00:00:00 2001 From: Laure-di Date: Fri, 4 Apr 2025 11:26:51 +0200 Subject: [PATCH 24/24] fix linter --- core/testing_recorder.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/core/testing_recorder.go b/core/testing_recorder.go index 5935eabf4a..b734e2a2d7 100644 --- a/core/testing_recorder.go +++ b/core/testing_recorder.go @@ -23,9 +23,15 @@ func cassetteRequestFilter(i *cassette.Interaction) error { tokenRegex := regexp.MustCompile(`api\.scaleway\.com/account/v1/tokens/[0-9a-f-]{36}`) apiKeyRegex := regexp.MustCompile(`^api\.scaleway\.com/iam/v1alpha1/api-keys/SCW[0-9A-Z]{17}`) - i.URL = orgIDRegex.ReplaceAllString(i.URL, "organization_id=11111111-1111-1111-1111-111111111111") - i.URL = tokenRegex.ReplaceAllString(i.URL, "api.scaleway.com/account/v1/tokens/11111111-1111-1111-1111-111111111111") - i.URL = apiKeyRegex.ReplaceAllString(i.URL, "api.scaleway.com/iam/v1alpha1/api-keys/SCWXXXXXXXXXXXXXXXXX") + i.URL = orgIDRegex.ReplaceAllString( + i.URL, + "organization_id=11111111-1111-1111-1111-111111111111") + i.URL = tokenRegex.ReplaceAllString( + i.URL, + "api.scaleway.com/account/v1/tokens/11111111-1111-1111-1111-111111111111") + i.URL = apiKeyRegex.ReplaceAllString( + i.URL, + "api.scaleway.com/iam/v1alpha1/api-keys/SCWXXXXXXXXXXXXXXXXX") return nil }