From d3ab00ba7b8bbddd1f9d9f0d0d0ba04fbf2e7d7d Mon Sep 17 00:00:00 2001 From: xescugc Date: Tue, 23 Jun 2026 11:22:04 +0200 Subject: [PATCH 1/2] feat(CLI-1): transform repo into Go installer shim Replace all CLI source code with a thin installer binary that auto-downloads the correct platform-specific pre-built cy binary from GitHub Releases on first run. What remains: - main.go: shim that downloads + caches + exec's real cy binary - go.mod: stdlib only, no external dependencies - scripts/cy-wrapper.sh: docker toolkit wrapper (unchanged) - LICENSE, README.md What was removed: - All CLI source (cmd/, internal/, printer/, config/, interpolator/) - All generated code (client/models/, client/client/) - All build tooling (Makefile, goreleaser, swagger, compose) - All tests (e2e/, pkg/testcfg/) - All dev config (golangci, changie, flake.nix) The real CLI source now lives in the BE repo (youdeploy-http-api/cli/). This repo will be synced from the BE on each release. go install github.com/cycloidio/cycloid-cli@latest installs the shim. On first run: cy organizations list downloads the real binary and exec's it. --- .changie.yaml | 107 -- .env.sample | 4 - .envrc | 11 - .gitignore | 32 +- .golangci.yml | 45 - .pre-commit-config.yaml | 19 - .rgignore | 3 - AGENTS.md | 245 ----- CHANGELOG.md | 208 ---- CLAUDE.md | 238 ----- CONTRIBUTING.md | 40 - DEVELOPING_TIPS.md | 252 ----- Makefile | 162 --- README.md | 49 +- changelog/releases/.gitkeep | 0 changelog/releases/0.md | 45 - changelog/releases/v3.1.47.md | 14 - changelog/releases/v3.2.44.md | 13 - changelog/releases/v3.3.26.md | 10 - changelog/releases/v4.0.11.md | 10 - changelog/releases/v4.0.133.md | 13 - changelog/releases/v4.0.162.md | 13 - changelog/releases/v4.0.17.md | 10 - changelog/releases/v4.0.178.md | 10 - changelog/releases/v4.0.20.md | 10 - changelog/releases/v4.0.290.md | 13 - changelog/releases/v4.0.295.md | 13 - changelog/releases/v4.0.340.md | 20 - changelog/releases/v5.0.20.md | 10 - changelog/releases/v5.0.34.md | 10 - changelog/releases/v5.0.49.md | 15 - changelog/releases/v5.0.66.md | 33 - changelog/releases/v5.1.134.md | 89 -- changelog/releases/v5.1.144.md | 10 - changelog/releases/v5.1.151.md | 18 - changelog/releases/v5.1.153.md | 13 - changelog/releases/v5.1.9.md | 10 - changelog/releases/v6.10.24.md | 10 - changelog/releases/v6.10.25.md | 10 - changelog/releases/v6.10.8.md | 40 - changelog/releases/v6.2.112.md | 10 - changelog/releases/v6.2.43.md | 43 - changelog/releases/v6.2.62.md | 34 - changelog/releases/v6.3.3.md | 13 - changelog/releases/v6.4.1.md | 13 - changelog/releases/v6.7.16.md | 14 - changelog/releases/v6.7.2.md | 24 - changelog/releases/v6.7.3.md | 14 - changelog/releases/v6.7.38.md | 10 - changelog/releases/v6.7.48.md | 14 - changelog/releases/v6.7.57.md | 13 - changelog/releases/v6.8.23.md | 40 - changelog/releases/v6.9.9.md | 34 - changelog/unreleased/.gitkeep | 0 client/models/a_w_s_cloud_watch_logs.go | 160 --- .../a_w_s_infrastructure_resource_bucket.go | 10 - ..._s_infrastructure_resource_d_b_instance.go | 10 - ...astructure_resource_elasticache_cluster.go | 10 - .../a_w_s_infrastructure_resource_image.go | 10 - .../a_w_s_infrastructure_resource_instance.go | 10 - ...nfrastructure_resource_load_balancer_v1.go | 10 - ...nfrastructure_resource_load_balancer_v2.go | 10 - ..._infrastructure_resource_security_group.go | 10 - .../a_w_s_infrastructure_resource_snapshot.go | 10 - .../a_w_s_infrastructure_resource_subnet.go | 10 - .../a_w_s_infrastructure_resource_v_p_c.go | 10 - .../a_w_s_infrastructure_resource_volume.go | 10 - ..._s_infrastructure_resources_aggregation.go | 970 ------------------ client/models/a_w_s_remote_t_f_state.go | 255 ----- client/models/a_w_s_storage.go | 251 ----- client/models/api_key.go | 296 ------ client/models/app_configuration.go | 79 -- client/models/app_version.go | 122 --- client/models/appearance.go | 463 --------- client/models/authentication.go | 176 ---- client/models/authentication_azure_a_d.go | 186 ---- client/models/authentication_config.go | 181 ---- client/models/authentication_git_hub.go | 235 ----- client/models/authentication_google.go | 174 ---- client/models/authentication_local.go | 160 --- client/models/authentication_o_id_c.go | 326 ------ client/models/authentication_s_a_m_l.go | 206 ---- client/models/azure_cost_export.go | 164 --- client/models/azure_remote_t_f_state.go | 200 ---- client/models/azure_storage.go | 199 ---- client/models/bare_credential.go | 249 ----- client/models/build.go | 156 --- client/models/build_inputs_outputs.go | 204 ---- client/models/build_summary.go | 139 --- client/models/c_i_version.go | 26 - client/models/can_do_input.go | 87 -- client/models/can_do_output.go | 73 -- client/models/check_report.go | 173 ---- client/models/clear_task_cache.go | 70 -- client/models/cloud_account.go | 322 ------ client/models/cloud_account_detail.go | 265 ----- client/models/cloud_account_simple.go | 151 --- .../models/cloud_cost_management_account.go | 476 --------- client/models/cloud_cost_management_bucket.go | 206 ---- .../models/cloud_cost_management_dashboard.go | 319 ------ .../cloud_cost_management_filter_values.go | 92 -- .../models/cloud_cost_management_histogram.go | 183 ---- .../cloud_cost_management_linked_account.go | 129 --- ...t_management_project_provider_resources.go | 155 --- ...cloud_cost_management_project_resources.go | 166 --- ...loud_cost_management_projects_dashboard.go | 175 ---- .../cloud_cost_management_provider_details.go | 175 ---- .../models/cloud_cost_management_providers.go | 116 --- .../cloud_cost_management_tag_mapping.go | 143 --- client/models/cloud_provider.go | 266 ----- .../cloud_provider_a_w_s_configuration.go | 159 --- .../cloud_provider_azure_configuration.go | 199 ---- client/models/cloud_provider_configuration.go | 134 --- .../cloud_provider_g_c_p_configuration.go | 190 ---- ...provider_vm_ware_v_sphere_configuration.go | 190 ---- client/models/component.go | 579 ----------- client/models/component_simple.go | 388 ------- client/models/config_file.go | 88 -- client/models/config_repository.go | 234 ----- client/models/configure_component.go | 167 --- client/models/cost_estimation_component.go | 217 ---- .../models/cost_estimation_component_state.go | 121 --- .../cost_estimation_resource_estimate.go | 215 ---- client/models/cost_estimation_result.go | 155 --- client/models/country.go | 92 -- .../models/create_or_update_subscription.go | 147 --- client/models/credential.go | 462 --------- client/models/credential_in_use.go | 269 ----- client/models/credential_raw.go | 155 --- client/models/credential_simple.go | 405 -------- client/models/elasticsearch_logs.go | 501 --------- client/models/ensure_plan.go | 173 ---- client/models/environment.go | 600 ----------- client/models/environment_simple.go | 134 --- client/models/environment_type.go | 234 ----- client/models/environment_variable_item.go | 229 ----- client/models/error_details_item.go | 90 -- client/models/error_payload.go | 135 --- client/models/event.go | 377 ------- client/models/events_actions_and_entities.go | 87 -- client/models/events_count.go | 109 -- client/models/external_backend.go | 480 --------- .../models/external_backend_configuration.go | 200 ---- client/models/filters.go | 10 - client/models/form_entity.go | 346 ------- client/models/form_group.go | 176 ---- client/models/form_section.go | 150 --- client/models/form_use_case.go | 147 --- client/models/form_variables.go | 49 - client/models/forms_file_v3.go | 147 --- client/models/forms_validation.go | 69 -- client/models/forms_validation_result.go | 133 --- client/models/forms_values_ref.go | 70 -- client/models/g_c_p_cost_storage.go | 173 ---- client/models/g_c_p_remote_t_f_state.go | 176 ---- client/models/g_c_p_storage.go | 178 ---- client/models/general_status.go | 208 ---- client/models/get_plan.go | 204 ---- client/models/git_lab_http_storage.go | 160 --- client/models/group_config.go | 76 -- client/models/http_storage.go | 160 --- client/models/in_use_component.go | 85 -- client/models/in_use_config_repository.go | 102 -- client/models/in_use_environment.go | 85 -- client/models/in_use_external_backend.go | 270 ----- client/models/in_use_project.go | 102 -- .../models/in_use_service_catalog_source.go | 102 -- client/models/infra_import.go | 250 ----- client/models/infra_import_preset.go | 87 -- client/models/infra_import_resource.go | 70 -- client/models/infra_import_resource_body.go | 225 ---- client/models/infra_import_resources_body.go | 213 ---- .../infra_policies_validation_result.go | 269 ----- .../infra_policies_validation_result_item.go | 120 --- client/models/infra_policy.go | 343 ------- client/models/infrastructure.go | 133 --- client/models/infrastructure_config.go | 10 - client/models/infrastructure_graph.go | 204 ---- client/models/infrastructure_graph_edge.go | 121 --- client/models/infrastructure_graph_node.go | 170 --- ...frastructure_resources_aggregation_item.go | 70 -- client/models/inventory_output.go | 107 -- client/models/inventory_resource.go | 414 -------- client/models/inventory_resource_label.go | 136 --- client/models/job.go | 435 -------- client/models/job_input.go | 172 ---- client/models/job_output.go | 87 -- client/models/k_p_i.go | 435 -------- client/models/licence.go | 248 ----- client/models/log_source.go | 75 -- client/models/log_source_entry.go | 114 -- client/models/member_assignation.go | 85 -- client/models/member_org.go | 573 ----------- client/models/member_team.go | 316 ------ client/models/metadata_field.go | 87 -- client/models/migrate_component.go | 146 --- .../new_a_w_s_marketplace_user_account.go | 255 ----- client/models/new_and_configured_component.go | 253 ----- client/models/new_api_key.go | 193 ---- client/models/new_appearance.go | 388 ------- client/models/new_cloud_account.go | 177 ---- client/models/new_cloud_account_credential.go | 263 ----- .../new_cloud_account_with_credentials.go | 334 ------ .../new_cloud_cost_management_account.go | 150 --- client/models/new_component.go | 175 ---- client/models/new_config_repository.go | 186 ---- client/models/new_credential.go | 271 ----- client/models/new_environment.go | 258 ----- client/models/new_environment_type.go | 132 --- client/models/new_event.go | 343 ------- client/models/new_external_backend.go | 409 -------- client/models/new_infra_import.go | 600 ----------- client/models/new_infra_import_component.go | 137 --- .../new_infra_import_external_backend.go | 211 ---- client/models/new_infra_import_project.go | 142 --- client/models/new_infra_policy.go | 218 ---- client/models/new_inventory_resource.go | 186 ---- client/models/new_k_p_i.go | 247 ----- client/models/new_licence.go | 70 -- client/models/new_member_invitation.go | 107 -- client/models/new_o_auth_user.go | 269 ----- client/models/new_organization.go | 105 -- client/models/new_pipeline.go | 94 -- client/models/new_plugin.go | 70 -- client/models/new_plugin_install.go | 70 -- client/models/new_plugin_manager.go | 95 -- client/models/new_plugin_registry.go | 92 -- client/models/new_plugin_version.go | 70 -- client/models/new_project.go | 188 ---- client/models/new_role.go | 192 ---- client/models/new_rule.go | 123 --- client/models/new_service_catalog.go | 370 ------- .../new_service_catalog_from_template.go | 203 ---- client/models/new_service_catalog_source.go | 209 ---- client/models/new_subscription.go | 85 -- client/models/new_team.go | 145 --- client/models/new_team_member_assignation.go | 78 -- client/models/new_user_account.go | 253 ----- client/models/new_watch_rule.go | 253 ----- client/models/new_watch_rule_filter.go | 87 -- client/models/notification.go | 205 ---- client/models/notification_settings.go | 124 --- client/models/on_failure_plan.go | 173 ---- client/models/on_success_plan.go | 173 ---- client/models/organization.go | 605 ----------- client/models/organization_messages.go | 47 - client/models/organization_naming_rules.go | 173 ---- client/models/page_concourse.go | 102 -- client/models/pagination.go | 117 --- client/models/pagination_a_w_s.go | 68 -- client/models/pagination_concourse.go | 171 --- client/models/pending_member_invitation.go | 75 -- client/models/pin_comment.go | 70 -- client/models/pipeline.go | 511 --------- client/models/pipeline_diff.go | 205 ---- client/models/pipeline_diff_record.go | 87 -- client/models/pipeline_diffs.go | 339 ------ client/models/pipeline_status.go | 184 ---- client/models/pipeline_variables.go | 90 -- client/models/plan.go | 695 ------------- client/models/plan_config.go | 291 ------ client/models/plugin.go | 356 ------- client/models/plugin_install.go | 296 ------ .../models/plugin_install_deployment_log.go | 92 -- client/models/plugin_install_runtime_log.go | 114 -- client/models/plugin_logs.go | 199 ---- client/models/plugin_manager.go | 263 ----- client/models/plugin_registry.go | 228 ---- client/models/plugin_relation.go | 87 -- client/models/plugin_version.go | 235 ----- client/models/plugin_version_log.go | 92 -- client/models/plugin_widget.go | 141 --- client/models/plugin_widget_data.go | 70 -- client/models/policy.go | 167 --- client/models/preparation.go | 170 --- client/models/project.go | 438 -------- client/models/project_environment.go | 508 --------- client/models/project_simple.go | 291 ------ client/models/public_build_input.go | 121 --- client/models/public_build_output.go | 87 -- client/models/public_plan.go | 87 -- client/models/put_plan.go | 198 ---- client/models/resource.go | 176 ---- client/models/resource_version.go | 181 ---- client/models/role.go | 287 ------ client/models/rule.go | 145 --- client/models/s_c_config.go | 132 --- client/models/s_c_config_custom_config.go | 149 --- client/models/s_c_config_form_data.go | 99 -- client/models/s_c_config_path_config.go | 87 -- client/models/s_c_config_path_dest_config.go | 104 -- client/models/s_c_config_pipeline_config.go | 173 ---- client/models/s_c_config_tech_config.go | 71 -- client/models/s_c_optional_template_config.go | 50 - client/models/s_c_template_config.go | 166 --- client/models/service_catalog.go | 741 ------------- client/models/service_catalog_changes.go | 416 -------- client/models/service_catalog_config.go | 397 ------- client/models/service_catalog_configs.go | 71 -- ..._catalog_dependencies_validation_result.go | 87 -- client/models/service_catalog_dependency.go | 52 - client/models/service_catalog_source.go | 455 -------- .../models/service_catalog_source_version.go | 259 ----- client/models/service_catalog_technology.go | 52 - client/models/simple_member_org.go | 212 ---- client/models/simple_team.go | 241 ----- client/models/stack_use_case.go | 130 --- client/models/state.go | 144 --- client/models/state_lock.go | 64 -- client/models/state_resource.go | 180 ---- client/models/state_resource_instances.go | 52 - client/models/subscription.go | 179 ---- client/models/subscription_plan.go | 107 -- client/models/summary.go | 204 ---- client/models/swift_remote_t_f_state.go | 222 ---- client/models/swift_storage.go | 224 ---- client/models/tag.go | 107 -- client/models/task_config.go | 200 ---- client/models/task_input_config.go | 73 -- client/models/task_plan.go | 227 ---- client/models/task_run_config.go | 76 -- client/models/team.go | 417 -------- client/models/terraform_h_c_l_config.go | 70 -- client/models/terraform_image.go | 71 -- client/models/terraform_json_config.go | 69 -- client/models/terraform_json_diagram.go | 10 - client/models/terraform_plan_input.go | 70 -- client/models/terraform_provider.go | 148 --- client/models/terraform_provider_resource.go | 282 ----- .../terraform_provider_resource_attributes.go | 55 - .../terraform_provider_resource_simple.go | 265 ----- client/models/terraform_provider_simple.go | 131 --- client/models/terraform_validation_result.go | 70 -- client/models/test_connection_credential.go | 187 ---- .../test_external_backend_connection_input.go | 302 ------ client/models/timeout_plan.go | 173 ---- client/models/try_plan.go | 173 ---- client/models/update_api_key.go | 85 -- client/models/update_cloud_account.go | 115 --- client/models/update_cloud_account_finops.go | 194 ---- .../update_cloud_cost_management_account.go | 119 --- ...te_cloud_cost_management_linked_account.go | 70 -- ...pdate_cloud_cost_management_tag_mapping.go | 64 -- client/models/update_component.go | 78 -- client/models/update_config_repository.go | 156 --- client/models/update_credential.go | 269 ----- client/models/update_environment.go | 228 ---- client/models/update_environment_type.go | 102 -- client/models/update_external_backend.go | 438 -------- client/models/update_infra_policy.go | 208 ---- client/models/update_organization.go | 93 -- client/models/update_organization_messages.go | 47 - .../update_organization_naming_rules.go | 173 ---- client/models/update_pipeline.go | 64 -- client/models/update_plugin.go | 70 -- client/models/update_plugin_install.go | 92 -- client/models/update_plugin_manager.go | 106 -- client/models/update_plugin_registry.go | 70 -- client/models/update_project.go | 229 ----- client/models/update_service_catalog.go | 101 -- .../models/update_service_catalog_source.go | 129 --- client/models/update_team.go | 147 --- client/models/update_user_account.go | 461 --------- client/models/update_user_account_email.go | 92 -- client/models/update_watch_rule.go | 169 --- client/models/user.go | 287 ------ client/models/user_account.go | 419 -------- client/models/user_account_email.go | 129 --- client/models/user_email.go | 75 -- client/models/user_guide.go | 10 - client/models/user_login.go | 132 --- client/models/user_o_auth.go | 120 --- client/models/user_password_reset_req.go | 75 -- client/models/user_password_reset_update.go | 102 -- client/models/user_session.go | 155 --- client/models/v_mware_vsphere.go | 158 --- client/models/version_config.go | 55 - client/models/versioned_resource_type.go | 180 ---- client/models/watch_rule.go | 321 ------ client/models/watch_rule_filter.go | 143 --- client/models/worker.go | 195 ---- client/version | 1 - cmd/cycloid/apikey/cmd.go | 26 - cmd/cycloid/apikey/create.go | 105 -- cmd/cycloid/apikey/delete.go | 77 -- cmd/cycloid/apikey/get.go | 84 -- cmd/cycloid/apikey/list.go | 46 - .../beta/bootstrap_first_org/bootstrap.go | 83 -- cmd/cycloid/beta/bootstrap_first_org/cmd.go | 42 - cmd/cycloid/beta/cmd.go | 23 - cmd/cycloid/beta/config/cmd.go | 15 - cmd/cycloid/beta/config/interpolate.go | 75 -- cmd/cycloid/catalogrepositories/cmd.go | 26 - cmd/cycloid/catalogrepositories/create.go | 150 --- cmd/cycloid/catalogrepositories/delete.go | 73 -- cmd/cycloid/catalogrepositories/get.go | 78 -- cmd/cycloid/catalogrepositories/list.go | 45 - cmd/cycloid/catalogrepositories/refresh.go | 72 -- cmd/cycloid/catalogrepositories/update.go | 91 -- cmd/cycloid/cloudaccounts/cmd.go | 55 - cmd/cycloid/cloudaccounts/cmd_test.go | 69 -- cmd/cycloid/cloudaccounts/create.go | 137 --- cmd/cycloid/cloudaccounts/credential.go | 90 -- cmd/cycloid/cloudaccounts/delete.go | 42 - cmd/cycloid/cloudaccounts/get.go | 49 - cmd/cycloid/cloudaccounts/list.go | 36 - cmd/cycloid/cloudaccounts/update.go | 97 -- cmd/cycloid/common/console_url.go | 27 - cmd/cycloid/common/console_url_test.go | 20 - cmd/cycloid/common/flags.go | 49 - cmd/cycloid/common/formsUtils.go | 35 - cmd/cycloid/common/helpers.go | 262 ----- cmd/cycloid/common/helpers_test.go | 113 -- cmd/cycloid/completion.go | 49 - cmd/cycloid/components/cmd.go | 70 -- cmd/cycloid/components/config.go | 20 - cmd/cycloid/components/config_get.go | 36 - cmd/cycloid/components/create.go | 132 --- cmd/cycloid/components/delete.go | 80 -- cmd/cycloid/components/get.go | 82 -- cmd/cycloid/components/list.go | 48 - cmd/cycloid/components/migrate.go | 72 -- cmd/cycloid/components/update.go | 133 --- cmd/cycloid/configrepositories/cmd.go | 24 - cmd/cycloid/configrepositories/create.go | 111 -- cmd/cycloid/configrepositories/delete.go | 73 -- cmd/cycloid/configrepositories/get.go | 78 -- cmd/cycloid/configrepositories/list.go | 45 - cmd/cycloid/configrepositories/update.go | 76 -- cmd/cycloid/credentials/cmd.go | 28 - cmd/cycloid/credentials/common.go | 11 - cmd/cycloid/credentials/create.go | 276 ----- cmd/cycloid/credentials/create_test.go | 87 -- cmd/cycloid/credentials/delete.go | 85 -- cmd/cycloid/credentials/get.go | 114 -- cmd/cycloid/credentials/list.go | 48 - cmd/cycloid/credentials/raw.go | 202 ---- cmd/cycloid/credentials/update.go | 243 ----- cmd/cycloid/environments/cmd.go | 29 - cmd/cycloid/environments/create.go | 52 - cmd/cycloid/environments/delete.go | 72 -- cmd/cycloid/environments/get.go | 90 -- cmd/cycloid/environments/link.go | 101 -- cmd/cycloid/environments/list.go | 61 -- cmd/cycloid/environments/update.go | 51 - cmd/cycloid/environments/utils.go | 212 ---- cmd/cycloid/environmenttypes/cmd.go | 29 - cmd/cycloid/environmenttypes/cmd_test.go | 68 -- cmd/cycloid/environmenttypes/create.go | 144 --- cmd/cycloid/environmenttypes/list.go | 128 --- cmd/cycloid/events/cmd.go | 22 - cmd/cycloid/events/list.go | 69 -- cmd/cycloid/events/send.go | 108 -- cmd/cycloid/externalbackends/cmd.go | 23 - cmd/cycloid/externalbackends/common.go | 71 -- cmd/cycloid/externalbackends/create.go | 143 --- cmd/cycloid/externalbackends/create_events.go | 56 - .../externalbackends/create_infra_view.go | 126 --- cmd/cycloid/externalbackends/create_logs.go | 127 --- cmd/cycloid/externalbackends/delete.go | 44 - cmd/cycloid/externalbackends/get.go | 27 - cmd/cycloid/externalbackends/list.go | 49 - cmd/cycloid/externalbackends/update.go | 29 - cmd/cycloid/get.go | 11 - cmd/cycloid/internal/version.go | 43 - cmd/cycloid/kpis/cmd.go | 20 - cmd/cycloid/kpis/common.go | 43 - cmd/cycloid/kpis/create.go | 87 -- cmd/cycloid/kpis/delete.go | 53 - cmd/cycloid/kpis/list.go | 58 -- cmd/cycloid/login/list.go | 52 - cmd/cycloid/login/login.go | 73 -- cmd/cycloid/members/cmd.go | 34 - cmd/cycloid/members/delete.go | 71 -- cmd/cycloid/members/get.go | 82 -- cmd/cycloid/members/invite.go | 52 - cmd/cycloid/members/list-invites.go | 46 - cmd/cycloid/members/list.go | 52 - cmd/cycloid/members/update.go | 52 - .../middleware/catalog_repositories.go | 150 --- .../middleware/catalog_repositories_test.go | 32 - cmd/cycloid/middleware/component_pipelines.go | 141 --- .../middleware/component_pipelines_jobs.go | 64 -- .../component_pipelines_jobs_builds.go | 179 ---- .../component_pipelines_jobs_builds_test.go | 23 - .../component_pipelines_jobs_test.go | 19 - .../middleware/component_pipelines_test.go | 144 --- cmd/cycloid/middleware/config_repositories.go | 99 -- .../middleware/config_repositories_test.go | 24 - cmd/cycloid/middleware/cost_estimation.go | 28 - cmd/cycloid/middleware/credentials.go | 117 --- cmd/cycloid/middleware/credentials_test.go | 43 - cmd/cycloid/middleware/cycloid.go | 35 - cmd/cycloid/middleware/cycloid_test.go | 24 - cmd/cycloid/middleware/debug.go | 80 -- .../middleware/environment_pipelines.go | 21 - .../middleware/environment_pipelines_test.go | 16 - cmd/cycloid/middleware/errors.go | 63 -- cmd/cycloid/middleware/errors_test.go | 78 -- cmd/cycloid/middleware/event.go | 65 -- cmd/cycloid/middleware/event_test.go | 23 - cmd/cycloid/middleware/external_backends.go | 122 --- .../middleware/external_backends_test.go | 16 - cmd/cycloid/middleware/generic_client.go | 245 ----- cmd/cycloid/middleware/generic_client_test.go | 63 -- cmd/cycloid/middleware/http_client.go | 156 --- cmd/cycloid/middleware/http_client_test.go | 27 - cmd/cycloid/middleware/init_first_org.go | 135 --- cmd/cycloid/middleware/init_first_org_test.go | 47 - cmd/cycloid/middleware/inventory.go | 84 -- cmd/cycloid/middleware/lhs_filter.go | 46 - .../middleware/lhs_filter_discovery_test.go | 301 ------ cmd/cycloid/middleware/middleware.go | 300 ------ cmd/cycloid/middleware/middleware_test.go | 45 - ...atalog_repository_refresh_versions_test.go | 200 ---- .../offline/generic_client_decode_test.go | 65 -- .../middleware/offline/lhs_filter_test.go | 138 --- cmd/cycloid/middleware/organization.go | 129 --- .../middleware/organization_api_key.go | 78 -- .../middleware/organization_api_key_test.go | 37 - .../middleware/organization_cloud_accounts.go | 82 -- .../organization_cloud_accounts_test.go | 86 -- .../middleware/organization_components.go | 176 ---- .../organization_components_test.go | 142 --- .../organization_environment_types.go | 73 -- .../organization_environment_types_test.go | 73 -- .../middleware/organization_environments.go | 104 -- cmd/cycloid/middleware/organization_forms.go | 72 -- .../middleware/organization_forms_test.go | 38 - .../middleware/organization_licence.go | 31 - .../middleware/organization_licence_test.go | 42 - .../middleware/organization_members.go | 106 -- .../middleware/organization_members_test.go | 37 - cmd/cycloid/middleware/organization_oidc.go | 209 ---- .../middleware/organization_pipelines.go | 37 - .../middleware/organization_pipelines_test.go | 36 - .../organization_project_environment_test.go | 87 -- .../middleware/organization_projects.go | 121 --- .../middleware/organization_projects_test.go | 61 -- cmd/cycloid/middleware/organization_roles.go | 106 -- .../middleware/organization_roles_test.go | 46 - .../middleware/organization_subscriptions.go | 51 - .../middleware/organization_team_members.go | 76 -- .../organization_team_members_test.go | 40 - cmd/cycloid/middleware/organization_teams.go | 129 --- .../middleware/organization_teams_test.go | 40 - cmd/cycloid/middleware/organization_test.go | 47 - cmd/cycloid/middleware/pagination.go | 72 -- cmd/cycloid/middleware/plugins.go | 492 --------- cmd/cycloid/middleware/plugins_test.go | 317 ------ cmd/cycloid/middleware/project_kpi.go | 98 -- cmd/cycloid/middleware/project_pipelines.go | 21 - .../middleware/project_pipelines_test.go | 28 - cmd/cycloid/middleware/query_encode.go | 98 -- cmd/cycloid/middleware/sanitize.go | 87 -- cmd/cycloid/middleware/sanitize_test.go | 119 --- cmd/cycloid/middleware/stacks.go | 271 ----- cmd/cycloid/middleware/stacks_test.go | 227 ---- cmd/cycloid/middleware/user.go | 101 -- cmd/cycloid/middleware/user_test.go | 17 - cmd/cycloid/middleware/utils.go | 84 -- cmd/cycloid/middleware/utils_test.go | 83 -- cmd/cycloid/oidc/cmd.go | 27 - cmd/cycloid/oidc/integration/cmd.go | 22 - cmd/cycloid/oidc/integration/get.go | 55 - cmd/cycloid/oidc/integration/set.go | 225 ---- cmd/cycloid/oidc/mappings/cmd.go | 22 - cmd/cycloid/oidc/mappings/create.go | 53 - cmd/cycloid/oidc/mappings/delete.go | 46 - cmd/cycloid/oidc/mappings/list.go | 46 - cmd/cycloid/oidc/settings/cmd.go | 20 - cmd/cycloid/oidc/settings/get.go | 45 - cmd/cycloid/oidc/settings/set.go | 101 -- cmd/cycloid/organizations/cmd.go | 32 - cmd/cycloid/organizations/create.go | 97 -- cmd/cycloid/organizations/create_children.go | 45 - cmd/cycloid/organizations/delete.go | 53 - cmd/cycloid/organizations/get.go | 68 -- cmd/cycloid/organizations/licence/activate.go | 53 - cmd/cycloid/organizations/licence/cmd.go | 17 - cmd/cycloid/organizations/licence/get.go | 43 - cmd/cycloid/organizations/list-children.go | 38 - cmd/cycloid/organizations/list-workers.go | 35 - cmd/cycloid/organizations/list.go | 35 - cmd/cycloid/organizations/subscription.go | 17 - .../subscription_create_or_update.go | 85 -- cmd/cycloid/organizations/update.go | 49 - cmd/cycloid/output/cmd.go | 92 -- cmd/cycloid/pipelines/build_cmd.go | 32 - cmd/cycloid/pipelines/build_get.go | 59 -- cmd/cycloid/pipelines/build_list.go | 53 - cmd/cycloid/pipelines/build_logs.go | 106 -- cmd/cycloid/pipelines/build_trigger.go | 162 --- cmd/cycloid/pipelines/jobs_cmd.go | 66 -- cmd/cycloid/pipelines/jobs_get.go | 50 - cmd/cycloid/pipelines/jobs_list.go | 47 - cmd/cycloid/pipelines/jobs_logs.go | 210 ---- cmd/cycloid/pipelines/jobs_pause.go | 49 - cmd/cycloid/pipelines/jobs_unpause.go | 49 - .../pipelines/pipeline_clear_task_cache.go | 55 - cmd/cycloid/pipelines/pipeline_cmd.go | 77 -- cmd/cycloid/pipelines/pipeline_diff.go | 67 -- cmd/cycloid/pipelines/pipeline_get.go | 47 - cmd/cycloid/pipelines/pipeline_last_used.go | 119 --- cmd/cycloid/pipelines/pipeline_list.go | 46 - cmd/cycloid/pipelines/pipeline_pause.go | 43 - cmd/cycloid/pipelines/pipeline_synced.go | 43 - cmd/cycloid/pipelines/pipeline_unpause.go | 43 - cmd/cycloid/pipelines/pipeline_update.go | 70 -- cmd/cycloid/plugins/cmd.go | 78 -- cmd/cycloid/plugins/component/cmd.go | 22 - cmd/cycloid/plugins/component/list.go | 56 - cmd/cycloid/plugins/component/relation_set.go | 69 -- cmd/cycloid/plugins/component/widget/cmd.go | 19 - cmd/cycloid/plugins/component/widget/list.go | 56 - cmd/cycloid/plugins/component/widget/query.go | 65 -- cmd/cycloid/plugins/get.go | 43 - cmd/cycloid/plugins/list.go | 37 - cmd/cycloid/plugins/logs.go | 112 -- cmd/cycloid/plugins/manager/accept.go | 47 - cmd/cycloid/plugins/manager/cmd.go | 21 - cmd/cycloid/plugins/manager/create.go | 82 -- cmd/cycloid/plugins/manager/delete.go | 49 - cmd/cycloid/plugins/manager/get.go | 43 - cmd/cycloid/plugins/manager/list.go | 36 - cmd/cycloid/plugins/manager/reject.go | 25 - cmd/cycloid/plugins/registry/cmd.go | 25 - cmd/cycloid/plugins/registry/create.go | 84 -- cmd/cycloid/plugins/registry/delete.go | 49 - cmd/cycloid/plugins/registry/get.go | 44 - cmd/cycloid/plugins/registry/list.go | 36 - cmd/cycloid/plugins/registry/plugin/cmd.go | 25 - cmd/cycloid/plugins/registry/plugin/create.go | 77 -- cmd/cycloid/plugins/registry/plugin/delete.go | 47 - cmd/cycloid/plugins/registry/plugin/get.go | 72 -- cmd/cycloid/plugins/registry/plugin/list.go | 43 - cmd/cycloid/plugins/registry/plugin/update.go | 56 - .../plugins/registry/plugin/version/cmd.go | 22 - .../plugins/registry/plugin/version/delete.go | 50 - .../plugins/registry/plugin/version/get.go | 50 - .../registry/plugin/version/helpers.go | 41 - .../registry/plugin/version/install.go | 112 -- .../plugins/registry/plugin/version/list.go | 45 - .../plugins/registry/plugin/version/logs.go | 50 - .../registry/plugin/version/publish.go | 75 -- .../plugins/registry/plugin/version/retry.go | 50 - cmd/cycloid/plugins/registry/update.go | 51 - cmd/cycloid/plugins/uninstall.go | 49 - cmd/cycloid/plugins/upgrade.go | 60 -- cmd/cycloid/plugins/widget/cmd.go | 19 - cmd/cycloid/plugins/widget/list.go | 44 - cmd/cycloid/plugins/widget/query.go | 62 -- cmd/cycloid/projects/cmd.go | 26 - cmd/cycloid/projects/create.go | 133 --- cmd/cycloid/projects/delete.go | 77 -- cmd/cycloid/projects/get.go | 75 -- cmd/cycloid/projects/list-env.go | 41 - cmd/cycloid/projects/list.go | 43 - cmd/cycloid/projects/update.go | 107 -- cmd/cycloid/roles/cmd.go | 34 - cmd/cycloid/roles/cmd_test.go | 40 - cmd/cycloid/roles/common.go | 92 -- cmd/cycloid/roles/create.go | 49 - cmd/cycloid/roles/delete.go | 56 - cmd/cycloid/roles/get.go | 88 -- cmd/cycloid/roles/list.go | 49 - cmd/cycloid/roles/update.go | 37 - cmd/cycloid/stacks/cmd.go | 27 - cmd/cycloid/stacks/create.go | 107 -- cmd/cycloid/stacks/forms.go | 22 - cmd/cycloid/stacks/forms_validate.go | 92 -- cmd/cycloid/stacks/get.go | 43 - cmd/cycloid/stacks/get_config.go | 69 -- cmd/cycloid/stacks/list.go | 84 -- cmd/cycloid/stacks/update.go | 86 -- cmd/cycloid/status.go | 61 -- cmd/cycloid/teams/cmd.go | 63 -- cmd/cycloid/teams/create.go | 96 -- cmd/cycloid/teams/delete.go | 47 - cmd/cycloid/teams/get.go | 52 - cmd/cycloid/teams/list.go | 69 -- cmd/cycloid/teams/members.go | 18 - cmd/cycloid/teams/members_assign.go | 61 -- cmd/cycloid/teams/members_get.go | 70 -- cmd/cycloid/teams/members_list.go | 55 - cmd/cycloid/teams/members_unassign.go | 60 -- cmd/cycloid/teams/update.go | 78 -- cmd/cycloid/teams/utils.go | 52 - cmd/cycloid/terracost/cmd.go | 20 - cmd/cycloid/terracost/common.go | 11 - cmd/cycloid/terracost/estimate.go | 46 - cmd/cycloid/uri/cmd.go | 19 - cmd/cycloid/uri/expand.go | 101 -- cmd/cycloid/uri/expand_test.go | 75 -- cmd/cycloid/uri/get.go | 47 - cmd/cycloid/uri/interpolate.go | 171 --- cmd/cycloid/version.go | 32 - cmd/cycloid/version_integration_test.go | 49 - cmd/root.go | 187 ---- compose.yml | 536 ---------- config/config.go | 81 -- docker/auth/htpasswd | 2 - docs/adding-a-command.md | 374 ------- docs/architecture.md | 220 ---- docs/middleware-refactor.md | 119 --- docs/pipeline-build-watch-output.md | 108 -- docs/testing.md | 307 ------ e2e/api_keys_test.go | 184 ---- e2e/catalog_repositories_test.go | 195 ---- e2e/components_test.go | 482 --------- e2e/config_repositories_test.go | 107 -- e2e/creds_test.go | 190 ---- e2e/e2e.go | 3 - e2e/e2e_test.go | 44 - e2e/env_var_test.go | 26 - e2e/environments_test.go | 251 ----- e2e/events_test.go | 42 - e2e/external_backends_test.go | 101 -- e2e/helpers_test.go | 275 ----- e2e/kpis_test.go | 170 --- e2e/licence_test.go | 95 -- e2e/login_test.go | 35 - e2e/members_test.go | 147 --- e2e/oidc_test.go | 207 ---- e2e/organizations_test.go | 175 ---- e2e/pipelines_test.go | 309 ------ e2e/plugin_setup_test.go | 66 -- e2e/plugins_test.go | 586 ----------- e2e/projects_test.go | 323 ------ e2e/roles_test.go | 98 -- e2e/stacks_test.go | 439 -------- e2e/teams_test.go | 160 --- e2e/terracost_test.go | 35 - e2e/uri_test.go | 260 ----- flake.lock | 61 -- flake.nix | 37 - go.mod | 89 -- go.sum | 226 ---- internal/buildwatch/events.go | 46 - internal/buildwatch/format.go | 235 ----- internal/buildwatch/stream.go | 113 -- internal/buildwatch/stream_test.go | 92 -- internal/buildwatch/theme.go | 35 - internal/buildwatch/watch.go | 398 ------- internal/buildwatch/watch_test.go | 300 ------ internal/custommodels/stacks.go | 10 - internal/cyargs/api_key.go | 101 -- internal/cyargs/bootstrap.go | 70 -- internal/cyargs/cloud_accounts.go | 84 -- internal/cyargs/common.go | 492 --------- internal/cyargs/common_test.go | 89 -- internal/cyargs/component.go | 119 --- .../cyargs/config_catalog_repositories.go | 152 --- internal/cyargs/credentials.go | 350 ------- internal/cyargs/environment_types.go | 48 - internal/cyargs/environments.go | 169 --- internal/cyargs/file.go | 79 -- internal/cyargs/flags.go | 27 - internal/cyargs/global_flags.go | 39 - internal/cyargs/licence.go | 95 -- internal/cyargs/members.go | 110 -- internal/cyargs/oidc.go | 264 ----- internal/cyargs/organizations.go | 190 ---- internal/cyargs/pipelines_jobs_build.go | 258 ----- internal/cyargs/plugins.go | 491 --------- internal/cyargs/repositories.go | 51 - internal/cyargs/stackforms_input.go | 287 ------ internal/cyargs/stackforms_input_test.go | 215 ---- internal/cyargs/stacks.go | 484 --------- internal/cyargs/stacks_test.go | 183 ---- internal/cyargs/teams.go | 336 ------ internal/cyout/errors.go | 130 --- internal/cyout/errors_test.go | 166 --- internal/cyout/print.go | 47 - internal/cyout/register.go | 40 - internal/ptr/ptr.go | 13 - internal/testcfg/config.go | 384 ------- internal/testcfg/helpers.go | 45 - internal/utils/utils.go | 32 - internal/version/info.go | 15 - interpolator/docs.go | 39 - interpolator/formatters/docs.go | 32 - interpolator/formatters/interface.go | 38 - interpolator/formatters/interface_test.go | 126 --- .../formatters/json/json_formatter.go | 94 -- .../formatters/json/json_formatter_test.go | 93 -- .../formatters/yaml/yaml_formatter.go | 67 -- .../yaml/yaml_formatter_options_test.go | 44 - .../formatters/yaml/yaml_formatter_test.go | 132 --- interpolator/parsers/fileparser.go | 37 - interpolator/parsers/fileparser_test.go | 58 -- interpolator/resolvers/httpresolver/error.go | 1 - .../resolvers/httpresolver/httpresolver.go | 93 -- .../resolvers/httpresolver/interpolate.go | 32 - interpolator/resolvers/httpresolver/types.go | 34 - interpolator/resolvers/interface.go | 8 - .../resolvers/mockresolver/mockresolver.go | 98 -- interpolator/resolvers/query.go | 54 - interpolator/resolvers/query_test.go | 43 - interpolator/resources/reference.go | 70 -- interpolator/resources/reference_test.go | 71 -- interpolator/transformers/docs.go | 19 - interpolator/transformers/transformers.go | 60 -- main.go | 185 +++- pkg/testcfg/bootstrap.go | 86 -- pkg/testcfg/config.go | 393 ------- pkg/testcfg/helpers.go | 45 - pkg/testcfg/plugins.go | 130 --- printer/factory/factory.go | 99 -- printer/factory/factory_test.go | 34 - printer/field/printer.go | 91 -- printer/http_error.go | 30 - printer/http_error_test.go | 31 - printer/jq/printer.go | 66 -- printer/json/printer.go | 63 -- printer/json/printer_test.go | 103 -- printer/options.go | 31 - printer/printer.go | 34 - printer/table/printer.go | 616 ----------- printer/table/printer_test.go | 460 --------- printer/yaml/printer.go | 25 - printer/yaml/printer_test.go | 42 - scripts/ci-tests.sh | 23 - test.json | 3 - 824 files changed, 205 insertions(+), 103358 deletions(-) delete mode 100644 .changie.yaml delete mode 100644 .env.sample delete mode 100644 .envrc delete mode 100644 .golangci.yml delete mode 100644 .pre-commit-config.yaml delete mode 100644 .rgignore delete mode 100644 AGENTS.md delete mode 100644 CHANGELOG.md delete mode 100644 CLAUDE.md delete mode 100644 CONTRIBUTING.md delete mode 100644 DEVELOPING_TIPS.md delete mode 100644 Makefile delete mode 100644 changelog/releases/.gitkeep delete mode 100644 changelog/releases/0.md delete mode 100644 changelog/releases/v3.1.47.md delete mode 100644 changelog/releases/v3.2.44.md delete mode 100644 changelog/releases/v3.3.26.md delete mode 100644 changelog/releases/v4.0.11.md delete mode 100644 changelog/releases/v4.0.133.md delete mode 100644 changelog/releases/v4.0.162.md delete mode 100644 changelog/releases/v4.0.17.md delete mode 100644 changelog/releases/v4.0.178.md delete mode 100644 changelog/releases/v4.0.20.md delete mode 100644 changelog/releases/v4.0.290.md delete mode 100644 changelog/releases/v4.0.295.md delete mode 100644 changelog/releases/v4.0.340.md delete mode 100644 changelog/releases/v5.0.20.md delete mode 100644 changelog/releases/v5.0.34.md delete mode 100644 changelog/releases/v5.0.49.md delete mode 100644 changelog/releases/v5.0.66.md delete mode 100644 changelog/releases/v5.1.134.md delete mode 100644 changelog/releases/v5.1.144.md delete mode 100644 changelog/releases/v5.1.151.md delete mode 100644 changelog/releases/v5.1.153.md delete mode 100644 changelog/releases/v5.1.9.md delete mode 100644 changelog/releases/v6.10.24.md delete mode 100644 changelog/releases/v6.10.25.md delete mode 100644 changelog/releases/v6.10.8.md delete mode 100644 changelog/releases/v6.2.112.md delete mode 100644 changelog/releases/v6.2.43.md delete mode 100644 changelog/releases/v6.2.62.md delete mode 100644 changelog/releases/v6.3.3.md delete mode 100644 changelog/releases/v6.4.1.md delete mode 100644 changelog/releases/v6.7.16.md delete mode 100644 changelog/releases/v6.7.2.md delete mode 100644 changelog/releases/v6.7.3.md delete mode 100644 changelog/releases/v6.7.38.md delete mode 100644 changelog/releases/v6.7.48.md delete mode 100644 changelog/releases/v6.7.57.md delete mode 100644 changelog/releases/v6.8.23.md delete mode 100644 changelog/releases/v6.9.9.md delete mode 100644 changelog/unreleased/.gitkeep delete mode 100644 client/models/a_w_s_cloud_watch_logs.go delete mode 100644 client/models/a_w_s_infrastructure_resource_bucket.go delete mode 100644 client/models/a_w_s_infrastructure_resource_d_b_instance.go delete mode 100644 client/models/a_w_s_infrastructure_resource_elasticache_cluster.go delete mode 100644 client/models/a_w_s_infrastructure_resource_image.go delete mode 100644 client/models/a_w_s_infrastructure_resource_instance.go delete mode 100644 client/models/a_w_s_infrastructure_resource_load_balancer_v1.go delete mode 100644 client/models/a_w_s_infrastructure_resource_load_balancer_v2.go delete mode 100644 client/models/a_w_s_infrastructure_resource_security_group.go delete mode 100644 client/models/a_w_s_infrastructure_resource_snapshot.go delete mode 100644 client/models/a_w_s_infrastructure_resource_subnet.go delete mode 100644 client/models/a_w_s_infrastructure_resource_v_p_c.go delete mode 100644 client/models/a_w_s_infrastructure_resource_volume.go delete mode 100644 client/models/a_w_s_infrastructure_resources_aggregation.go delete mode 100644 client/models/a_w_s_remote_t_f_state.go delete mode 100644 client/models/a_w_s_storage.go delete mode 100644 client/models/api_key.go delete mode 100644 client/models/app_configuration.go delete mode 100644 client/models/app_version.go delete mode 100644 client/models/appearance.go delete mode 100644 client/models/authentication.go delete mode 100644 client/models/authentication_azure_a_d.go delete mode 100644 client/models/authentication_config.go delete mode 100644 client/models/authentication_git_hub.go delete mode 100644 client/models/authentication_google.go delete mode 100644 client/models/authentication_local.go delete mode 100644 client/models/authentication_o_id_c.go delete mode 100644 client/models/authentication_s_a_m_l.go delete mode 100644 client/models/azure_cost_export.go delete mode 100644 client/models/azure_remote_t_f_state.go delete mode 100644 client/models/azure_storage.go delete mode 100644 client/models/bare_credential.go delete mode 100644 client/models/build.go delete mode 100644 client/models/build_inputs_outputs.go delete mode 100644 client/models/build_summary.go delete mode 100644 client/models/c_i_version.go delete mode 100644 client/models/can_do_input.go delete mode 100644 client/models/can_do_output.go delete mode 100644 client/models/check_report.go delete mode 100644 client/models/clear_task_cache.go delete mode 100644 client/models/cloud_account.go delete mode 100644 client/models/cloud_account_detail.go delete mode 100644 client/models/cloud_account_simple.go delete mode 100644 client/models/cloud_cost_management_account.go delete mode 100644 client/models/cloud_cost_management_bucket.go delete mode 100644 client/models/cloud_cost_management_dashboard.go delete mode 100644 client/models/cloud_cost_management_filter_values.go delete mode 100644 client/models/cloud_cost_management_histogram.go delete mode 100644 client/models/cloud_cost_management_linked_account.go delete mode 100644 client/models/cloud_cost_management_project_provider_resources.go delete mode 100644 client/models/cloud_cost_management_project_resources.go delete mode 100644 client/models/cloud_cost_management_projects_dashboard.go delete mode 100644 client/models/cloud_cost_management_provider_details.go delete mode 100644 client/models/cloud_cost_management_providers.go delete mode 100644 client/models/cloud_cost_management_tag_mapping.go delete mode 100644 client/models/cloud_provider.go delete mode 100644 client/models/cloud_provider_a_w_s_configuration.go delete mode 100644 client/models/cloud_provider_azure_configuration.go delete mode 100644 client/models/cloud_provider_configuration.go delete mode 100644 client/models/cloud_provider_g_c_p_configuration.go delete mode 100644 client/models/cloud_provider_vm_ware_v_sphere_configuration.go delete mode 100644 client/models/component.go delete mode 100644 client/models/component_simple.go delete mode 100644 client/models/config_file.go delete mode 100644 client/models/config_repository.go delete mode 100644 client/models/configure_component.go delete mode 100644 client/models/cost_estimation_component.go delete mode 100644 client/models/cost_estimation_component_state.go delete mode 100644 client/models/cost_estimation_resource_estimate.go delete mode 100644 client/models/cost_estimation_result.go delete mode 100644 client/models/country.go delete mode 100644 client/models/create_or_update_subscription.go delete mode 100644 client/models/credential.go delete mode 100644 client/models/credential_in_use.go delete mode 100644 client/models/credential_raw.go delete mode 100644 client/models/credential_simple.go delete mode 100644 client/models/elasticsearch_logs.go delete mode 100644 client/models/ensure_plan.go delete mode 100644 client/models/environment.go delete mode 100644 client/models/environment_simple.go delete mode 100644 client/models/environment_type.go delete mode 100644 client/models/environment_variable_item.go delete mode 100644 client/models/error_details_item.go delete mode 100644 client/models/error_payload.go delete mode 100644 client/models/event.go delete mode 100644 client/models/events_actions_and_entities.go delete mode 100644 client/models/events_count.go delete mode 100644 client/models/external_backend.go delete mode 100644 client/models/external_backend_configuration.go delete mode 100644 client/models/filters.go delete mode 100644 client/models/form_entity.go delete mode 100644 client/models/form_group.go delete mode 100644 client/models/form_section.go delete mode 100644 client/models/form_use_case.go delete mode 100644 client/models/form_variables.go delete mode 100644 client/models/forms_file_v3.go delete mode 100644 client/models/forms_validation.go delete mode 100644 client/models/forms_validation_result.go delete mode 100644 client/models/forms_values_ref.go delete mode 100644 client/models/g_c_p_cost_storage.go delete mode 100644 client/models/g_c_p_remote_t_f_state.go delete mode 100644 client/models/g_c_p_storage.go delete mode 100644 client/models/general_status.go delete mode 100644 client/models/get_plan.go delete mode 100644 client/models/git_lab_http_storage.go delete mode 100644 client/models/group_config.go delete mode 100644 client/models/http_storage.go delete mode 100644 client/models/in_use_component.go delete mode 100644 client/models/in_use_config_repository.go delete mode 100644 client/models/in_use_environment.go delete mode 100644 client/models/in_use_external_backend.go delete mode 100644 client/models/in_use_project.go delete mode 100644 client/models/in_use_service_catalog_source.go delete mode 100644 client/models/infra_import.go delete mode 100644 client/models/infra_import_preset.go delete mode 100644 client/models/infra_import_resource.go delete mode 100644 client/models/infra_import_resource_body.go delete mode 100644 client/models/infra_import_resources_body.go delete mode 100644 client/models/infra_policies_validation_result.go delete mode 100644 client/models/infra_policies_validation_result_item.go delete mode 100644 client/models/infra_policy.go delete mode 100644 client/models/infrastructure.go delete mode 100644 client/models/infrastructure_config.go delete mode 100644 client/models/infrastructure_graph.go delete mode 100644 client/models/infrastructure_graph_edge.go delete mode 100644 client/models/infrastructure_graph_node.go delete mode 100644 client/models/infrastructure_resources_aggregation_item.go delete mode 100644 client/models/inventory_output.go delete mode 100644 client/models/inventory_resource.go delete mode 100644 client/models/inventory_resource_label.go delete mode 100644 client/models/job.go delete mode 100644 client/models/job_input.go delete mode 100644 client/models/job_output.go delete mode 100644 client/models/k_p_i.go delete mode 100644 client/models/licence.go delete mode 100644 client/models/log_source.go delete mode 100644 client/models/log_source_entry.go delete mode 100644 client/models/member_assignation.go delete mode 100644 client/models/member_org.go delete mode 100644 client/models/member_team.go delete mode 100644 client/models/metadata_field.go delete mode 100644 client/models/migrate_component.go delete mode 100644 client/models/new_a_w_s_marketplace_user_account.go delete mode 100644 client/models/new_and_configured_component.go delete mode 100644 client/models/new_api_key.go delete mode 100644 client/models/new_appearance.go delete mode 100644 client/models/new_cloud_account.go delete mode 100644 client/models/new_cloud_account_credential.go delete mode 100644 client/models/new_cloud_account_with_credentials.go delete mode 100644 client/models/new_cloud_cost_management_account.go delete mode 100644 client/models/new_component.go delete mode 100644 client/models/new_config_repository.go delete mode 100644 client/models/new_credential.go delete mode 100644 client/models/new_environment.go delete mode 100644 client/models/new_environment_type.go delete mode 100644 client/models/new_event.go delete mode 100644 client/models/new_external_backend.go delete mode 100644 client/models/new_infra_import.go delete mode 100644 client/models/new_infra_import_component.go delete mode 100644 client/models/new_infra_import_external_backend.go delete mode 100644 client/models/new_infra_import_project.go delete mode 100644 client/models/new_infra_policy.go delete mode 100644 client/models/new_inventory_resource.go delete mode 100644 client/models/new_k_p_i.go delete mode 100644 client/models/new_licence.go delete mode 100644 client/models/new_member_invitation.go delete mode 100644 client/models/new_o_auth_user.go delete mode 100644 client/models/new_organization.go delete mode 100644 client/models/new_pipeline.go delete mode 100644 client/models/new_plugin.go delete mode 100644 client/models/new_plugin_install.go delete mode 100644 client/models/new_plugin_manager.go delete mode 100644 client/models/new_plugin_registry.go delete mode 100644 client/models/new_plugin_version.go delete mode 100644 client/models/new_project.go delete mode 100644 client/models/new_role.go delete mode 100644 client/models/new_rule.go delete mode 100644 client/models/new_service_catalog.go delete mode 100644 client/models/new_service_catalog_from_template.go delete mode 100644 client/models/new_service_catalog_source.go delete mode 100644 client/models/new_subscription.go delete mode 100644 client/models/new_team.go delete mode 100644 client/models/new_team_member_assignation.go delete mode 100644 client/models/new_user_account.go delete mode 100644 client/models/new_watch_rule.go delete mode 100644 client/models/new_watch_rule_filter.go delete mode 100644 client/models/notification.go delete mode 100644 client/models/notification_settings.go delete mode 100644 client/models/on_failure_plan.go delete mode 100644 client/models/on_success_plan.go delete mode 100644 client/models/organization.go delete mode 100644 client/models/organization_messages.go delete mode 100644 client/models/organization_naming_rules.go delete mode 100644 client/models/page_concourse.go delete mode 100644 client/models/pagination.go delete mode 100644 client/models/pagination_a_w_s.go delete mode 100644 client/models/pagination_concourse.go delete mode 100644 client/models/pending_member_invitation.go delete mode 100644 client/models/pin_comment.go delete mode 100644 client/models/pipeline.go delete mode 100644 client/models/pipeline_diff.go delete mode 100644 client/models/pipeline_diff_record.go delete mode 100644 client/models/pipeline_diffs.go delete mode 100644 client/models/pipeline_status.go delete mode 100644 client/models/pipeline_variables.go delete mode 100644 client/models/plan.go delete mode 100644 client/models/plan_config.go delete mode 100644 client/models/plugin.go delete mode 100644 client/models/plugin_install.go delete mode 100644 client/models/plugin_install_deployment_log.go delete mode 100644 client/models/plugin_install_runtime_log.go delete mode 100644 client/models/plugin_logs.go delete mode 100644 client/models/plugin_manager.go delete mode 100644 client/models/plugin_registry.go delete mode 100644 client/models/plugin_relation.go delete mode 100644 client/models/plugin_version.go delete mode 100644 client/models/plugin_version_log.go delete mode 100644 client/models/plugin_widget.go delete mode 100644 client/models/plugin_widget_data.go delete mode 100644 client/models/policy.go delete mode 100644 client/models/preparation.go delete mode 100644 client/models/project.go delete mode 100644 client/models/project_environment.go delete mode 100644 client/models/project_simple.go delete mode 100644 client/models/public_build_input.go delete mode 100644 client/models/public_build_output.go delete mode 100644 client/models/public_plan.go delete mode 100644 client/models/put_plan.go delete mode 100644 client/models/resource.go delete mode 100644 client/models/resource_version.go delete mode 100644 client/models/role.go delete mode 100644 client/models/rule.go delete mode 100644 client/models/s_c_config.go delete mode 100644 client/models/s_c_config_custom_config.go delete mode 100644 client/models/s_c_config_form_data.go delete mode 100644 client/models/s_c_config_path_config.go delete mode 100644 client/models/s_c_config_path_dest_config.go delete mode 100644 client/models/s_c_config_pipeline_config.go delete mode 100644 client/models/s_c_config_tech_config.go delete mode 100644 client/models/s_c_optional_template_config.go delete mode 100644 client/models/s_c_template_config.go delete mode 100644 client/models/service_catalog.go delete mode 100644 client/models/service_catalog_changes.go delete mode 100644 client/models/service_catalog_config.go delete mode 100644 client/models/service_catalog_configs.go delete mode 100644 client/models/service_catalog_dependencies_validation_result.go delete mode 100644 client/models/service_catalog_dependency.go delete mode 100644 client/models/service_catalog_source.go delete mode 100644 client/models/service_catalog_source_version.go delete mode 100644 client/models/service_catalog_technology.go delete mode 100644 client/models/simple_member_org.go delete mode 100644 client/models/simple_team.go delete mode 100644 client/models/stack_use_case.go delete mode 100644 client/models/state.go delete mode 100644 client/models/state_lock.go delete mode 100644 client/models/state_resource.go delete mode 100644 client/models/state_resource_instances.go delete mode 100644 client/models/subscription.go delete mode 100644 client/models/subscription_plan.go delete mode 100644 client/models/summary.go delete mode 100644 client/models/swift_remote_t_f_state.go delete mode 100644 client/models/swift_storage.go delete mode 100644 client/models/tag.go delete mode 100644 client/models/task_config.go delete mode 100644 client/models/task_input_config.go delete mode 100644 client/models/task_plan.go delete mode 100644 client/models/task_run_config.go delete mode 100644 client/models/team.go delete mode 100644 client/models/terraform_h_c_l_config.go delete mode 100644 client/models/terraform_image.go delete mode 100644 client/models/terraform_json_config.go delete mode 100644 client/models/terraform_json_diagram.go delete mode 100644 client/models/terraform_plan_input.go delete mode 100644 client/models/terraform_provider.go delete mode 100644 client/models/terraform_provider_resource.go delete mode 100644 client/models/terraform_provider_resource_attributes.go delete mode 100644 client/models/terraform_provider_resource_simple.go delete mode 100644 client/models/terraform_provider_simple.go delete mode 100644 client/models/terraform_validation_result.go delete mode 100644 client/models/test_connection_credential.go delete mode 100644 client/models/test_external_backend_connection_input.go delete mode 100644 client/models/timeout_plan.go delete mode 100644 client/models/try_plan.go delete mode 100644 client/models/update_api_key.go delete mode 100644 client/models/update_cloud_account.go delete mode 100644 client/models/update_cloud_account_finops.go delete mode 100644 client/models/update_cloud_cost_management_account.go delete mode 100644 client/models/update_cloud_cost_management_linked_account.go delete mode 100644 client/models/update_cloud_cost_management_tag_mapping.go delete mode 100644 client/models/update_component.go delete mode 100644 client/models/update_config_repository.go delete mode 100644 client/models/update_credential.go delete mode 100644 client/models/update_environment.go delete mode 100644 client/models/update_environment_type.go delete mode 100644 client/models/update_external_backend.go delete mode 100644 client/models/update_infra_policy.go delete mode 100644 client/models/update_organization.go delete mode 100644 client/models/update_organization_messages.go delete mode 100644 client/models/update_organization_naming_rules.go delete mode 100644 client/models/update_pipeline.go delete mode 100644 client/models/update_plugin.go delete mode 100644 client/models/update_plugin_install.go delete mode 100644 client/models/update_plugin_manager.go delete mode 100644 client/models/update_plugin_registry.go delete mode 100644 client/models/update_project.go delete mode 100644 client/models/update_service_catalog.go delete mode 100644 client/models/update_service_catalog_source.go delete mode 100644 client/models/update_team.go delete mode 100644 client/models/update_user_account.go delete mode 100644 client/models/update_user_account_email.go delete mode 100644 client/models/update_watch_rule.go delete mode 100644 client/models/user.go delete mode 100644 client/models/user_account.go delete mode 100644 client/models/user_account_email.go delete mode 100644 client/models/user_email.go delete mode 100644 client/models/user_guide.go delete mode 100644 client/models/user_login.go delete mode 100644 client/models/user_o_auth.go delete mode 100644 client/models/user_password_reset_req.go delete mode 100644 client/models/user_password_reset_update.go delete mode 100644 client/models/user_session.go delete mode 100644 client/models/v_mware_vsphere.go delete mode 100644 client/models/version_config.go delete mode 100644 client/models/versioned_resource_type.go delete mode 100644 client/models/watch_rule.go delete mode 100644 client/models/watch_rule_filter.go delete mode 100644 client/models/worker.go delete mode 100644 client/version delete mode 100644 cmd/cycloid/apikey/cmd.go delete mode 100644 cmd/cycloid/apikey/create.go delete mode 100644 cmd/cycloid/apikey/delete.go delete mode 100644 cmd/cycloid/apikey/get.go delete mode 100644 cmd/cycloid/apikey/list.go delete mode 100644 cmd/cycloid/beta/bootstrap_first_org/bootstrap.go delete mode 100644 cmd/cycloid/beta/bootstrap_first_org/cmd.go delete mode 100644 cmd/cycloid/beta/cmd.go delete mode 100644 cmd/cycloid/beta/config/cmd.go delete mode 100644 cmd/cycloid/beta/config/interpolate.go delete mode 100644 cmd/cycloid/catalogrepositories/cmd.go delete mode 100644 cmd/cycloid/catalogrepositories/create.go delete mode 100644 cmd/cycloid/catalogrepositories/delete.go delete mode 100644 cmd/cycloid/catalogrepositories/get.go delete mode 100644 cmd/cycloid/catalogrepositories/list.go delete mode 100644 cmd/cycloid/catalogrepositories/refresh.go delete mode 100644 cmd/cycloid/catalogrepositories/update.go delete mode 100644 cmd/cycloid/cloudaccounts/cmd.go delete mode 100644 cmd/cycloid/cloudaccounts/cmd_test.go delete mode 100644 cmd/cycloid/cloudaccounts/create.go delete mode 100644 cmd/cycloid/cloudaccounts/credential.go delete mode 100644 cmd/cycloid/cloudaccounts/delete.go delete mode 100644 cmd/cycloid/cloudaccounts/get.go delete mode 100644 cmd/cycloid/cloudaccounts/list.go delete mode 100644 cmd/cycloid/cloudaccounts/update.go delete mode 100644 cmd/cycloid/common/console_url.go delete mode 100644 cmd/cycloid/common/console_url_test.go delete mode 100644 cmd/cycloid/common/flags.go delete mode 100644 cmd/cycloid/common/formsUtils.go delete mode 100644 cmd/cycloid/common/helpers.go delete mode 100644 cmd/cycloid/common/helpers_test.go delete mode 100644 cmd/cycloid/completion.go delete mode 100644 cmd/cycloid/components/cmd.go delete mode 100644 cmd/cycloid/components/config.go delete mode 100644 cmd/cycloid/components/config_get.go delete mode 100644 cmd/cycloid/components/create.go delete mode 100644 cmd/cycloid/components/delete.go delete mode 100644 cmd/cycloid/components/get.go delete mode 100644 cmd/cycloid/components/list.go delete mode 100644 cmd/cycloid/components/migrate.go delete mode 100644 cmd/cycloid/components/update.go delete mode 100644 cmd/cycloid/configrepositories/cmd.go delete mode 100644 cmd/cycloid/configrepositories/create.go delete mode 100644 cmd/cycloid/configrepositories/delete.go delete mode 100644 cmd/cycloid/configrepositories/get.go delete mode 100644 cmd/cycloid/configrepositories/list.go delete mode 100644 cmd/cycloid/configrepositories/update.go delete mode 100644 cmd/cycloid/credentials/cmd.go delete mode 100644 cmd/cycloid/credentials/common.go delete mode 100644 cmd/cycloid/credentials/create.go delete mode 100644 cmd/cycloid/credentials/create_test.go delete mode 100644 cmd/cycloid/credentials/delete.go delete mode 100644 cmd/cycloid/credentials/get.go delete mode 100644 cmd/cycloid/credentials/list.go delete mode 100644 cmd/cycloid/credentials/raw.go delete mode 100644 cmd/cycloid/credentials/update.go delete mode 100644 cmd/cycloid/environments/cmd.go delete mode 100644 cmd/cycloid/environments/create.go delete mode 100644 cmd/cycloid/environments/delete.go delete mode 100644 cmd/cycloid/environments/get.go delete mode 100644 cmd/cycloid/environments/link.go delete mode 100644 cmd/cycloid/environments/list.go delete mode 100644 cmd/cycloid/environments/update.go delete mode 100644 cmd/cycloid/environments/utils.go delete mode 100644 cmd/cycloid/environmenttypes/cmd.go delete mode 100644 cmd/cycloid/environmenttypes/cmd_test.go delete mode 100644 cmd/cycloid/environmenttypes/create.go delete mode 100644 cmd/cycloid/environmenttypes/list.go delete mode 100644 cmd/cycloid/events/cmd.go delete mode 100644 cmd/cycloid/events/list.go delete mode 100644 cmd/cycloid/events/send.go delete mode 100644 cmd/cycloid/externalbackends/cmd.go delete mode 100644 cmd/cycloid/externalbackends/common.go delete mode 100644 cmd/cycloid/externalbackends/create.go delete mode 100644 cmd/cycloid/externalbackends/create_events.go delete mode 100644 cmd/cycloid/externalbackends/create_infra_view.go delete mode 100644 cmd/cycloid/externalbackends/create_logs.go delete mode 100644 cmd/cycloid/externalbackends/delete.go delete mode 100644 cmd/cycloid/externalbackends/get.go delete mode 100644 cmd/cycloid/externalbackends/list.go delete mode 100644 cmd/cycloid/externalbackends/update.go delete mode 100644 cmd/cycloid/get.go delete mode 100644 cmd/cycloid/internal/version.go delete mode 100644 cmd/cycloid/kpis/cmd.go delete mode 100644 cmd/cycloid/kpis/common.go delete mode 100644 cmd/cycloid/kpis/create.go delete mode 100644 cmd/cycloid/kpis/delete.go delete mode 100644 cmd/cycloid/kpis/list.go delete mode 100644 cmd/cycloid/login/list.go delete mode 100644 cmd/cycloid/login/login.go delete mode 100644 cmd/cycloid/members/cmd.go delete mode 100644 cmd/cycloid/members/delete.go delete mode 100644 cmd/cycloid/members/get.go delete mode 100644 cmd/cycloid/members/invite.go delete mode 100644 cmd/cycloid/members/list-invites.go delete mode 100644 cmd/cycloid/members/list.go delete mode 100644 cmd/cycloid/members/update.go delete mode 100644 cmd/cycloid/middleware/catalog_repositories.go delete mode 100644 cmd/cycloid/middleware/catalog_repositories_test.go delete mode 100644 cmd/cycloid/middleware/component_pipelines.go delete mode 100644 cmd/cycloid/middleware/component_pipelines_jobs.go delete mode 100644 cmd/cycloid/middleware/component_pipelines_jobs_builds.go delete mode 100644 cmd/cycloid/middleware/component_pipelines_jobs_builds_test.go delete mode 100644 cmd/cycloid/middleware/component_pipelines_jobs_test.go delete mode 100644 cmd/cycloid/middleware/component_pipelines_test.go delete mode 100644 cmd/cycloid/middleware/config_repositories.go delete mode 100644 cmd/cycloid/middleware/config_repositories_test.go delete mode 100644 cmd/cycloid/middleware/cost_estimation.go delete mode 100644 cmd/cycloid/middleware/credentials.go delete mode 100644 cmd/cycloid/middleware/credentials_test.go delete mode 100644 cmd/cycloid/middleware/cycloid.go delete mode 100644 cmd/cycloid/middleware/cycloid_test.go delete mode 100644 cmd/cycloid/middleware/debug.go delete mode 100644 cmd/cycloid/middleware/environment_pipelines.go delete mode 100644 cmd/cycloid/middleware/environment_pipelines_test.go delete mode 100644 cmd/cycloid/middleware/errors.go delete mode 100644 cmd/cycloid/middleware/errors_test.go delete mode 100644 cmd/cycloid/middleware/event.go delete mode 100644 cmd/cycloid/middleware/event_test.go delete mode 100644 cmd/cycloid/middleware/external_backends.go delete mode 100644 cmd/cycloid/middleware/external_backends_test.go delete mode 100644 cmd/cycloid/middleware/generic_client.go delete mode 100644 cmd/cycloid/middleware/generic_client_test.go delete mode 100644 cmd/cycloid/middleware/http_client.go delete mode 100644 cmd/cycloid/middleware/http_client_test.go delete mode 100644 cmd/cycloid/middleware/init_first_org.go delete mode 100644 cmd/cycloid/middleware/init_first_org_test.go delete mode 100644 cmd/cycloid/middleware/inventory.go delete mode 100644 cmd/cycloid/middleware/lhs_filter.go delete mode 100644 cmd/cycloid/middleware/lhs_filter_discovery_test.go delete mode 100644 cmd/cycloid/middleware/middleware.go delete mode 100644 cmd/cycloid/middleware/middleware_test.go delete mode 100644 cmd/cycloid/middleware/offline/catalog_repository_refresh_versions_test.go delete mode 100644 cmd/cycloid/middleware/offline/generic_client_decode_test.go delete mode 100644 cmd/cycloid/middleware/offline/lhs_filter_test.go delete mode 100644 cmd/cycloid/middleware/organization.go delete mode 100644 cmd/cycloid/middleware/organization_api_key.go delete mode 100644 cmd/cycloid/middleware/organization_api_key_test.go delete mode 100644 cmd/cycloid/middleware/organization_cloud_accounts.go delete mode 100644 cmd/cycloid/middleware/organization_cloud_accounts_test.go delete mode 100644 cmd/cycloid/middleware/organization_components.go delete mode 100644 cmd/cycloid/middleware/organization_components_test.go delete mode 100644 cmd/cycloid/middleware/organization_environment_types.go delete mode 100644 cmd/cycloid/middleware/organization_environment_types_test.go delete mode 100644 cmd/cycloid/middleware/organization_environments.go delete mode 100644 cmd/cycloid/middleware/organization_forms.go delete mode 100644 cmd/cycloid/middleware/organization_forms_test.go delete mode 100644 cmd/cycloid/middleware/organization_licence.go delete mode 100644 cmd/cycloid/middleware/organization_licence_test.go delete mode 100644 cmd/cycloid/middleware/organization_members.go delete mode 100644 cmd/cycloid/middleware/organization_members_test.go delete mode 100644 cmd/cycloid/middleware/organization_oidc.go delete mode 100644 cmd/cycloid/middleware/organization_pipelines.go delete mode 100644 cmd/cycloid/middleware/organization_pipelines_test.go delete mode 100644 cmd/cycloid/middleware/organization_project_environment_test.go delete mode 100644 cmd/cycloid/middleware/organization_projects.go delete mode 100644 cmd/cycloid/middleware/organization_projects_test.go delete mode 100644 cmd/cycloid/middleware/organization_roles.go delete mode 100644 cmd/cycloid/middleware/organization_roles_test.go delete mode 100644 cmd/cycloid/middleware/organization_subscriptions.go delete mode 100644 cmd/cycloid/middleware/organization_team_members.go delete mode 100644 cmd/cycloid/middleware/organization_team_members_test.go delete mode 100644 cmd/cycloid/middleware/organization_teams.go delete mode 100644 cmd/cycloid/middleware/organization_teams_test.go delete mode 100644 cmd/cycloid/middleware/organization_test.go delete mode 100644 cmd/cycloid/middleware/pagination.go delete mode 100644 cmd/cycloid/middleware/plugins.go delete mode 100644 cmd/cycloid/middleware/plugins_test.go delete mode 100644 cmd/cycloid/middleware/project_kpi.go delete mode 100644 cmd/cycloid/middleware/project_pipelines.go delete mode 100644 cmd/cycloid/middleware/project_pipelines_test.go delete mode 100644 cmd/cycloid/middleware/query_encode.go delete mode 100644 cmd/cycloid/middleware/sanitize.go delete mode 100644 cmd/cycloid/middleware/sanitize_test.go delete mode 100644 cmd/cycloid/middleware/stacks.go delete mode 100644 cmd/cycloid/middleware/stacks_test.go delete mode 100644 cmd/cycloid/middleware/user.go delete mode 100644 cmd/cycloid/middleware/user_test.go delete mode 100644 cmd/cycloid/middleware/utils.go delete mode 100644 cmd/cycloid/middleware/utils_test.go delete mode 100644 cmd/cycloid/oidc/cmd.go delete mode 100644 cmd/cycloid/oidc/integration/cmd.go delete mode 100644 cmd/cycloid/oidc/integration/get.go delete mode 100644 cmd/cycloid/oidc/integration/set.go delete mode 100644 cmd/cycloid/oidc/mappings/cmd.go delete mode 100644 cmd/cycloid/oidc/mappings/create.go delete mode 100644 cmd/cycloid/oidc/mappings/delete.go delete mode 100644 cmd/cycloid/oidc/mappings/list.go delete mode 100644 cmd/cycloid/oidc/settings/cmd.go delete mode 100644 cmd/cycloid/oidc/settings/get.go delete mode 100644 cmd/cycloid/oidc/settings/set.go delete mode 100644 cmd/cycloid/organizations/cmd.go delete mode 100644 cmd/cycloid/organizations/create.go delete mode 100644 cmd/cycloid/organizations/create_children.go delete mode 100644 cmd/cycloid/organizations/delete.go delete mode 100644 cmd/cycloid/organizations/get.go delete mode 100644 cmd/cycloid/organizations/licence/activate.go delete mode 100644 cmd/cycloid/organizations/licence/cmd.go delete mode 100644 cmd/cycloid/organizations/licence/get.go delete mode 100644 cmd/cycloid/organizations/list-children.go delete mode 100644 cmd/cycloid/organizations/list-workers.go delete mode 100644 cmd/cycloid/organizations/list.go delete mode 100644 cmd/cycloid/organizations/subscription.go delete mode 100644 cmd/cycloid/organizations/subscription_create_or_update.go delete mode 100644 cmd/cycloid/organizations/update.go delete mode 100644 cmd/cycloid/output/cmd.go delete mode 100644 cmd/cycloid/pipelines/build_cmd.go delete mode 100644 cmd/cycloid/pipelines/build_get.go delete mode 100644 cmd/cycloid/pipelines/build_list.go delete mode 100644 cmd/cycloid/pipelines/build_logs.go delete mode 100644 cmd/cycloid/pipelines/build_trigger.go delete mode 100644 cmd/cycloid/pipelines/jobs_cmd.go delete mode 100644 cmd/cycloid/pipelines/jobs_get.go delete mode 100644 cmd/cycloid/pipelines/jobs_list.go delete mode 100644 cmd/cycloid/pipelines/jobs_logs.go delete mode 100644 cmd/cycloid/pipelines/jobs_pause.go delete mode 100644 cmd/cycloid/pipelines/jobs_unpause.go delete mode 100644 cmd/cycloid/pipelines/pipeline_clear_task_cache.go delete mode 100644 cmd/cycloid/pipelines/pipeline_cmd.go delete mode 100644 cmd/cycloid/pipelines/pipeline_diff.go delete mode 100644 cmd/cycloid/pipelines/pipeline_get.go delete mode 100644 cmd/cycloid/pipelines/pipeline_last_used.go delete mode 100644 cmd/cycloid/pipelines/pipeline_list.go delete mode 100644 cmd/cycloid/pipelines/pipeline_pause.go delete mode 100644 cmd/cycloid/pipelines/pipeline_synced.go delete mode 100644 cmd/cycloid/pipelines/pipeline_unpause.go delete mode 100644 cmd/cycloid/pipelines/pipeline_update.go delete mode 100644 cmd/cycloid/plugins/cmd.go delete mode 100644 cmd/cycloid/plugins/component/cmd.go delete mode 100644 cmd/cycloid/plugins/component/list.go delete mode 100644 cmd/cycloid/plugins/component/relation_set.go delete mode 100644 cmd/cycloid/plugins/component/widget/cmd.go delete mode 100644 cmd/cycloid/plugins/component/widget/list.go delete mode 100644 cmd/cycloid/plugins/component/widget/query.go delete mode 100644 cmd/cycloid/plugins/get.go delete mode 100644 cmd/cycloid/plugins/list.go delete mode 100644 cmd/cycloid/plugins/logs.go delete mode 100644 cmd/cycloid/plugins/manager/accept.go delete mode 100644 cmd/cycloid/plugins/manager/cmd.go delete mode 100644 cmd/cycloid/plugins/manager/create.go delete mode 100644 cmd/cycloid/plugins/manager/delete.go delete mode 100644 cmd/cycloid/plugins/manager/get.go delete mode 100644 cmd/cycloid/plugins/manager/list.go delete mode 100644 cmd/cycloid/plugins/manager/reject.go delete mode 100644 cmd/cycloid/plugins/registry/cmd.go delete mode 100644 cmd/cycloid/plugins/registry/create.go delete mode 100644 cmd/cycloid/plugins/registry/delete.go delete mode 100644 cmd/cycloid/plugins/registry/get.go delete mode 100644 cmd/cycloid/plugins/registry/list.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/cmd.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/create.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/delete.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/get.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/list.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/update.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/version/cmd.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/version/delete.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/version/get.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/version/helpers.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/version/install.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/version/list.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/version/logs.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/version/publish.go delete mode 100644 cmd/cycloid/plugins/registry/plugin/version/retry.go delete mode 100644 cmd/cycloid/plugins/registry/update.go delete mode 100644 cmd/cycloid/plugins/uninstall.go delete mode 100644 cmd/cycloid/plugins/upgrade.go delete mode 100644 cmd/cycloid/plugins/widget/cmd.go delete mode 100644 cmd/cycloid/plugins/widget/list.go delete mode 100644 cmd/cycloid/plugins/widget/query.go delete mode 100644 cmd/cycloid/projects/cmd.go delete mode 100644 cmd/cycloid/projects/create.go delete mode 100644 cmd/cycloid/projects/delete.go delete mode 100644 cmd/cycloid/projects/get.go delete mode 100644 cmd/cycloid/projects/list-env.go delete mode 100644 cmd/cycloid/projects/list.go delete mode 100644 cmd/cycloid/projects/update.go delete mode 100644 cmd/cycloid/roles/cmd.go delete mode 100644 cmd/cycloid/roles/cmd_test.go delete mode 100644 cmd/cycloid/roles/common.go delete mode 100644 cmd/cycloid/roles/create.go delete mode 100644 cmd/cycloid/roles/delete.go delete mode 100644 cmd/cycloid/roles/get.go delete mode 100644 cmd/cycloid/roles/list.go delete mode 100644 cmd/cycloid/roles/update.go delete mode 100644 cmd/cycloid/stacks/cmd.go delete mode 100644 cmd/cycloid/stacks/create.go delete mode 100644 cmd/cycloid/stacks/forms.go delete mode 100644 cmd/cycloid/stacks/forms_validate.go delete mode 100644 cmd/cycloid/stacks/get.go delete mode 100644 cmd/cycloid/stacks/get_config.go delete mode 100644 cmd/cycloid/stacks/list.go delete mode 100644 cmd/cycloid/stacks/update.go delete mode 100644 cmd/cycloid/status.go delete mode 100644 cmd/cycloid/teams/cmd.go delete mode 100644 cmd/cycloid/teams/create.go delete mode 100644 cmd/cycloid/teams/delete.go delete mode 100644 cmd/cycloid/teams/get.go delete mode 100644 cmd/cycloid/teams/list.go delete mode 100644 cmd/cycloid/teams/members.go delete mode 100644 cmd/cycloid/teams/members_assign.go delete mode 100644 cmd/cycloid/teams/members_get.go delete mode 100644 cmd/cycloid/teams/members_list.go delete mode 100644 cmd/cycloid/teams/members_unassign.go delete mode 100644 cmd/cycloid/teams/update.go delete mode 100644 cmd/cycloid/teams/utils.go delete mode 100644 cmd/cycloid/terracost/cmd.go delete mode 100644 cmd/cycloid/terracost/common.go delete mode 100644 cmd/cycloid/terracost/estimate.go delete mode 100644 cmd/cycloid/uri/cmd.go delete mode 100644 cmd/cycloid/uri/expand.go delete mode 100644 cmd/cycloid/uri/expand_test.go delete mode 100644 cmd/cycloid/uri/get.go delete mode 100644 cmd/cycloid/uri/interpolate.go delete mode 100644 cmd/cycloid/version.go delete mode 100644 cmd/cycloid/version_integration_test.go delete mode 100644 cmd/root.go delete mode 100644 compose.yml delete mode 100644 config/config.go delete mode 100644 docker/auth/htpasswd delete mode 100644 docs/adding-a-command.md delete mode 100644 docs/architecture.md delete mode 100644 docs/middleware-refactor.md delete mode 100644 docs/pipeline-build-watch-output.md delete mode 100644 docs/testing.md delete mode 100644 e2e/api_keys_test.go delete mode 100644 e2e/catalog_repositories_test.go delete mode 100644 e2e/components_test.go delete mode 100644 e2e/config_repositories_test.go delete mode 100644 e2e/creds_test.go delete mode 100644 e2e/e2e.go delete mode 100644 e2e/e2e_test.go delete mode 100644 e2e/env_var_test.go delete mode 100644 e2e/environments_test.go delete mode 100644 e2e/events_test.go delete mode 100644 e2e/external_backends_test.go delete mode 100644 e2e/helpers_test.go delete mode 100644 e2e/kpis_test.go delete mode 100644 e2e/licence_test.go delete mode 100644 e2e/login_test.go delete mode 100644 e2e/members_test.go delete mode 100644 e2e/oidc_test.go delete mode 100644 e2e/organizations_test.go delete mode 100644 e2e/pipelines_test.go delete mode 100644 e2e/plugin_setup_test.go delete mode 100644 e2e/plugins_test.go delete mode 100644 e2e/projects_test.go delete mode 100644 e2e/roles_test.go delete mode 100644 e2e/stacks_test.go delete mode 100644 e2e/teams_test.go delete mode 100644 e2e/terracost_test.go delete mode 100644 e2e/uri_test.go delete mode 100644 flake.lock delete mode 100644 flake.nix delete mode 100644 go.sum delete mode 100644 internal/buildwatch/events.go delete mode 100644 internal/buildwatch/format.go delete mode 100644 internal/buildwatch/stream.go delete mode 100644 internal/buildwatch/stream_test.go delete mode 100644 internal/buildwatch/theme.go delete mode 100644 internal/buildwatch/watch.go delete mode 100644 internal/buildwatch/watch_test.go delete mode 100644 internal/custommodels/stacks.go delete mode 100644 internal/cyargs/api_key.go delete mode 100644 internal/cyargs/bootstrap.go delete mode 100644 internal/cyargs/cloud_accounts.go delete mode 100644 internal/cyargs/common.go delete mode 100644 internal/cyargs/common_test.go delete mode 100644 internal/cyargs/component.go delete mode 100644 internal/cyargs/config_catalog_repositories.go delete mode 100644 internal/cyargs/credentials.go delete mode 100644 internal/cyargs/environment_types.go delete mode 100644 internal/cyargs/environments.go delete mode 100644 internal/cyargs/file.go delete mode 100644 internal/cyargs/flags.go delete mode 100644 internal/cyargs/global_flags.go delete mode 100644 internal/cyargs/licence.go delete mode 100644 internal/cyargs/members.go delete mode 100644 internal/cyargs/oidc.go delete mode 100644 internal/cyargs/organizations.go delete mode 100644 internal/cyargs/pipelines_jobs_build.go delete mode 100644 internal/cyargs/plugins.go delete mode 100644 internal/cyargs/repositories.go delete mode 100644 internal/cyargs/stackforms_input.go delete mode 100644 internal/cyargs/stackforms_input_test.go delete mode 100644 internal/cyargs/stacks.go delete mode 100644 internal/cyargs/stacks_test.go delete mode 100644 internal/cyargs/teams.go delete mode 100644 internal/cyout/errors.go delete mode 100644 internal/cyout/errors_test.go delete mode 100644 internal/cyout/print.go delete mode 100644 internal/cyout/register.go delete mode 100644 internal/ptr/ptr.go delete mode 100644 internal/testcfg/config.go delete mode 100644 internal/testcfg/helpers.go delete mode 100644 internal/utils/utils.go delete mode 100644 internal/version/info.go delete mode 100644 interpolator/docs.go delete mode 100644 interpolator/formatters/docs.go delete mode 100644 interpolator/formatters/interface.go delete mode 100644 interpolator/formatters/interface_test.go delete mode 100644 interpolator/formatters/json/json_formatter.go delete mode 100644 interpolator/formatters/json/json_formatter_test.go delete mode 100644 interpolator/formatters/yaml/yaml_formatter.go delete mode 100644 interpolator/formatters/yaml/yaml_formatter_options_test.go delete mode 100644 interpolator/formatters/yaml/yaml_formatter_test.go delete mode 100644 interpolator/parsers/fileparser.go delete mode 100644 interpolator/parsers/fileparser_test.go delete mode 100644 interpolator/resolvers/httpresolver/error.go delete mode 100644 interpolator/resolvers/httpresolver/httpresolver.go delete mode 100644 interpolator/resolvers/httpresolver/interpolate.go delete mode 100644 interpolator/resolvers/httpresolver/types.go delete mode 100644 interpolator/resolvers/interface.go delete mode 100644 interpolator/resolvers/mockresolver/mockresolver.go delete mode 100644 interpolator/resolvers/query.go delete mode 100644 interpolator/resolvers/query_test.go delete mode 100644 interpolator/resources/reference.go delete mode 100644 interpolator/resources/reference_test.go delete mode 100644 interpolator/transformers/docs.go delete mode 100644 interpolator/transformers/transformers.go delete mode 100644 pkg/testcfg/bootstrap.go delete mode 100644 pkg/testcfg/config.go delete mode 100644 pkg/testcfg/helpers.go delete mode 100644 pkg/testcfg/plugins.go delete mode 100644 printer/factory/factory.go delete mode 100644 printer/factory/factory_test.go delete mode 100644 printer/field/printer.go delete mode 100644 printer/http_error.go delete mode 100644 printer/http_error_test.go delete mode 100644 printer/jq/printer.go delete mode 100644 printer/json/printer.go delete mode 100644 printer/json/printer_test.go delete mode 100644 printer/options.go delete mode 100644 printer/printer.go delete mode 100644 printer/table/printer.go delete mode 100644 printer/table/printer_test.go delete mode 100644 printer/yaml/printer.go delete mode 100644 printer/yaml/printer_test.go delete mode 100755 scripts/ci-tests.sh delete mode 100644 test.json diff --git a/.changie.yaml b/.changie.yaml deleted file mode 100644 index 1390a2198..000000000 --- a/.changie.yaml +++ /dev/null @@ -1,107 +0,0 @@ -# Changie docs -# https://changie.dev/config -# -# Advanced formatting/logic docs -# https://masterminds.github.io/sprig -changesDir: changelog/releases -unreleasedDir: ../unreleased -headerPath: ../header.tpl.md -versionHeaderPath: "" -versionFooterPath: "" -changelogPath: CHANGELOG.md -versionExt: md -componentFormat: "### {{.Component}}" -versionFormat: | - ## [{{.Version}}] _{{.Time.Format "2006-01-02"}}_ -headerFormat: | - Cycloid CLI changelog: -kindFormat: "**{{.Kind}}**" -changeFormat: | - - {{.Body}} ([CLI#{{.Custom.PR}}]) - {{if ne .Custom.DETAILS "" -}} - *{{.Custom.DETAILS}}* - {{- end -}} -footerFormat: | - {{- range (customs .Changes "PR" | uniq) }} - [CLI#{{.}}]: https://github.com/cycloidio/cycloid-cli/pull/{{.}} - {{- end}} -components: - - API Keys - - Authentication - - Budget - - CLI - - Cloud Cost Management - - Concourse - - Config Repo - - Credentials - - Dashboard - - Environments - - Events - - InfraImport - - InfraPolicies - - InfraView - - Inventory - - Invitations - - KPI - - Licence - - Logs - - Members - - Monitoring - - MSP - - Notifications - - Organizations - - Pipeline Designer - - Pipeline view - - Pipelines Overview - - Profile-User-SalesForce - - Project - - Quota - - Roles - - Service Catalog - - StackCraft - - StackForms - - Start&Stop Env - - Status Page - - Teams - - TerraCost - - Workers - - Other - -kinds: - - label: ADDED - - label: BREAKING - - label: CHANGED - - label: DEPRECATED - - label: FIXED - - label: INTERNAL - - label: REMOVED - - label: SECURITY - -# --[Notes]-- -# -# :: key & label :: -# Doesn't print out both key and label in the cmd line -# so you'll need to prepend the label with the key. -# -# :: optional :: -# Contrary to the docs, int is not optional. So if you -# want to make something optional, you need string. -# -# :: order :: -# We cannot dictate the order for custom properties, -# it's also not clear what logic is used to order them. -# -# :: DETAILS :: -# If your command line goes funky after typing then just -# press enter and finish writing in your IDE instead. -custom: - - key: TYPE - type: enum - enumOptions: - - CLI - - key: PR - type: int - minInt: 1 - - key: DETAILS - label: DETAILS - for public release, should be approx 1-2 sentences (user impact), optional. - type: string diff --git a/.env.sample b/.env.sample deleted file mode 100644 index 4d7c894ae..000000000 --- a/.env.sample +++ /dev/null @@ -1,4 +0,0 @@ -export ACCESS_KEY=cy://org/cycloid/credentials/scaleway_cycloid_automation_admin?key=.raw.raw.access_key -export SECRET_ACCESS=cy://org/cycloid/credentials/scaleway_cycloid_automation_admin?key=.raw.raw.secret_key -export SCW_REGION=fr-par -export API_LICENCE_KEY=cy://org/cycloid/credentials/scaleway-cycloid-backend?key=.raw.raw.licence_key diff --git a/.envrc b/.envrc deleted file mode 100644 index 77c1c5477..000000000 --- a/.envrc +++ /dev/null @@ -1,11 +0,0 @@ -dotenv_if_exists .env -dotenv_if_exists .api_key - -if has nix; then - watch_file flake.nix - use flake . -Lv --log-format raw - - if [ -f ../.envrc ]; then - source_env ../.envrc - fi -fi diff --git a/.gitignore b/.gitignore index 1ce57c642..d142b1750 100644 --- a/.gitignore +++ b/.gitignore @@ -1,38 +1,10 @@ .env -.api_key - -# Binaries for programs and plugins *.exe -*.exe~ -*.dll -*.so -*.dylib -cycloid-cli -cy-* - -# Test binary, built with `go test -c` *.test -swagger.yml - -# Output of the go coverage tool, specifically when used with LiteIDE *.out - -# Dependency directories (remove the comment below to include it) -# vendor/ - -plugins/ +cycloid-cli cy -./gen -pkged.go - -# Intellij +cy-* .idea/ -gst - -# direnv .direnv - -# Local tooling artifacts .claude/ -.gitnexus/ - diff --git a/.golangci.yml b/.golangci.yml deleted file mode 100644 index b43460fc0..000000000 --- a/.golangci.yml +++ /dev/null @@ -1,45 +0,0 @@ -version: "2" -run: - concurrency: 4 - go: "1.24" -linters: - default: none - enable: - - ineffassign - - misspell - - staticcheck - - unconvert - - unused - settings: - misspell: - locale: US - ignore-rules: - - licence - - licences - - utilisation - - cancelled - staticcheck: - checks: - - -SA1019 - - -SA5012 - - all - exclusions: - generated: lax - presets: - - comments - - common-false-positives - - legacy - - std-error-handling - paths: - - third_party$ - - builtin$ - - examples$ -formatters: - enable: - - goimports - exclusions: - generated: lax - paths: - - third_party$ - - builtin$ - - examples$ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml deleted file mode 100644 index 3d62d069b..000000000 --- a/.pre-commit-config.yaml +++ /dev/null @@ -1,19 +0,0 @@ -repos: -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v6.0.0 - hooks: - - id: check-yaml - - id: end-of-file-fixer - - id: trailing-whitespace - - id: detect-private-key - - id: no-commit-to-branch - args: [--branch, develop, --branch, master] - - id: check-shebang-scripts-are-executable -- repo: local - hooks: - - id: format-and-lint - name: Format and Lint - entry: make format lint - language: system - pass_filenames: false - stages: [pre-commit] diff --git a/.rgignore b/.rgignore deleted file mode 100644 index ea1e43897..000000000 --- a/.rgignore +++ /dev/null @@ -1,3 +0,0 @@ -# This file is there to set ignore in ripgrep search -# this won't affect git -client/** diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index 50890d6e8..000000000 --- a/AGENTS.md +++ /dev/null @@ -1,245 +0,0 @@ -# AGENTS.md - -This file mirrors `CLAUDE.md` for LLM agents that use the AGENTS.md convention. Keep in sync when updating either file. - ---- - -# CLAUDE.md - -This file is auto-loaded by Claude Code on every invocation. See also `AGENTS.md` (kept identical, for non-Claude LLM agents). - -## Commands - -```bash -# Build -make build # build all platform binaries -go build -o cy . # quick local build - -# Test (requires local backend) -make be-reset # start backend via docker compose -go test ./... # run all tests -make test # same -make be-stop # stop backend - -# Run a specific test -go test ./e2e/... -run TestProjects -go test ./cmd/cycloid/middleware/... -run TestGetProject - -# Lint & format -make lint # golangci-lint + shellcheck -make format # gci + goimports + shfmt - -# Client regeneration (when swagger.yaml changes) -make client-generate # regenerates ./client/ from swagger.yaml - -# Changelog -make new-changelog-entry # add unreleased changelog entry (uses changie via docker) -``` - -## Architecture - -``` -cmd/cycloid//*.go → cmd/cycloid/middleware/ → GenericRequest() - (cobra commands) (Middleware interface) (generic_client.go) -``` - -### Key packages - -- **`client/models/`** — Auto-generated go-swagger models from `swagger.yaml`. Never edit manually. Regenerate with `make client-generate`. -- **`client/client/`** — Intentionally NOT used. The generated operations package was removed in the middleware refactor. Use `GenericRequest` instead. -- **`cmd/cycloid/middleware/`** — The `Middleware` interface (`middleware.go`) makes HTTP calls via `GenericRequest` (`generic_client.go`). Each feature gets its own file (e.g., `organization_projects.go`). -- **`cmd/cycloid//`** — Cobra command definitions. Each feature directory has: `cmd.go` (registers subcommands), plus one file per verb (`list.go`, `get.go`, `create.go`, `update.go`, `delete.go`), and `common.go` for shared logic. -- **`internal/cyargs/`** — All shared flag definitions and completion functions. Every flag used by multiple commands must be declared here. -- **`printer/`** — Output formatting. Use `printer.SmartPrint(p, obj, err, errStr, opts, writer)` — success to `cmd.OutOrStdout()`, errors to `cmd.OutOrStderr()`. -- **`e2e/`** — End-to-end tests that run real CLI commands against a live backend. - -## Hard Rules - -These are invariants that LLM agents and new contributors must not violate: - -1. **NEVER edit `client/models/`** — auto-generated. Run `make client-generate` to update. -2. **NEVER import or use `client/client/`** — deprecated. Use `GenericRequest` in middleware methods. -3. **NEVER call `NewMiddleware` outside a cobra `RunE` function** — not at package init, not in tests directly. -4. **ALWAYS parse ALL flags via `cyargs.Get*` BEFORE calling `common.NewAPI()` and `NewMiddleware()`** — `GenericRequest` reads `verbosity` from Viper at call time; unparsed flags produce stale values. -5. **ALWAYS add shared flags to `internal/cyargs/`** — never inline a flag used by more than one command. -6. **ALWAYS use `printer.SmartPrint`** — errors go to `OutOrStderr()`, results go to `OutOrStdout()`. -7. **E2E tests require a running backend** (`make be-start`). Never run e2e in parallel. -8. **Run `make format && make lint` after every code change.** -9. **Ship tests with every feature** — in the same change, add or extend coverage for what you introduce: new or changed middleware in `cmd/cycloid/middleware/*_test.go` (or focused unit tests where appropriate), and user-facing CLI behavior in `e2e/*_test.go` when that resource already has e2e tests. Do not land behavior-only changes without tests. - -## `GenericRequest` pattern - -`GenericRequest` handles auth, JSON marshaling, and `{"data":...}` envelope unwrapping. Pass `&result` directly — do not wrap in a `struct{ Data *X }`. - -```go -// Standard middleware method pattern: -func (m *middleware) GetProject(org, project string) (*models.Project, *http.Response, error) { - var result *models.Project - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} -``` - -`Request` fields: `Method`, `Organization` (*string, for auth), `NoAuth` (bool), `Route` ([]string), `Query` (struct with `url` tags), `LHSFilters` ([]LHSFilter, see below), `Headers` (map), `Accept` (*string), `Body` (any, JSON-marshalled). - -## LHS filters - -The Cycloid API supports LHS bracket filters on `List` routes: `attribute[condition]=value`. The condition is typically `eq`, `rlike`, `gt`, `lt`, etc. - -**Rule: all new `List` middleware methods must accept `filters ...LHSFilter` as their last parameter.** - -`LHSFilter` is defined in `cmd/cycloid/middleware/lhs_filter.go`: - -```go -type LHSFilter struct { - Attribute string - Condition string - Value string -} -``` - -Pass filters via the `LHSFilters` field of `Request`. Brackets are kept literal (not percent-encoded) so the API receives `name[eq]=my-project`, not `name%5Beq%5D=my-project`. Regex metacharacters in values (`?`, `*`, `+`, etc.) are also preserved. - -```go -// Example: list projects filtered by name prefix -func (m *middleware) ListProjects(org string, filters ...LHSFilter) ([]*models.Project, *http.Response, error) { - var result []*models.Project - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects"}, - LHSFilters: filters, - }, &result) - ... -} - -// Caller usage: -projects, _, err := m.ListProjects(org, middleware.LHSFilter{ - Attribute: "name", - Condition: "rlike", - Value: "proj.*", -}) -``` - -Offline (no-backend) unit tests for LHS filter encoding live in `cmd/cycloid/middleware/offline/lhs_filter_test.go`. - -### Return type conventions - -| Verb | Return | -|------|--------| -| Get / Create | `(*models.X, *http.Response, error)` | -| List | `([]*models.X, *http.Response, error)` | -| Delete / void | `(*http.Response, error)` | - -Always return the `*http.Response` so callers can inspect status codes. Assign `_` if unused. - -## Command pattern - -```go -func getProject(cmd *cobra.Command, args []string) error { - // Step 1: ALL flags first - org, err := cyargs.GetOrg(cmd) - if err != nil { return err } - project, err := cyargs.GetProject(cmd) - if err != nil { return err } - output, err := cmd.Flags().GetString("output") - if err != nil { return errors.Wrap(err, "unable to get output flag") } - - // Step 2: printer - p, err := factory.GetPrinter(output) - if err != nil { return errors.Wrap(err, "unable to get printer") } - - // Step 3: API + middleware - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // Step 4: call + print - result, _, err := m.GetProject(org, project) - if err != nil { - return printer.SmartPrint(p, nil, err, "unable to get project", printer.Options{}, cmd.OutOrStderr()) - } - return printer.SmartPrint(p, result, nil, "", printer.Options{}, cmd.OutOrStdout()) -} -``` - -## `cyargs` flags - -All shared flag definitions live in `internal/cyargs/`. Pattern: - -```go -func AddWidgetFlag(cmd *cobra.Command) { - cmd.Flags().String("widget", "", "Widget canonical") - _ = cmd.RegisterFlagCompletionFunc("widget", widgetCompletion) -} - -func GetWidget(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("widget") -} -``` - -Register in the command constructor (`NewGetX()`), never inside `RunE`. - -## Testing - -- **Tests ship with the feature** (see Hard Rule 9): middleware and command changes should include tests in the same PR; extend existing `e2e/*_test.go` files when the resource is already covered there. -- **Middleware tests** (`cmd/cycloid/middleware/*_test.go`): `TestMain` calls `testcfg.NewConfig("middleware")`. Fixtures: `config.Project`, `config.Environment`, `config.Component`, `config.ConfigRepo`, `config.CatalogRepo`. -- **E2E tests** (`e2e/*_test.go`): `executeCommand(args)` runs the real CLI. Same `testcfg` setup. -- E2E tests are **not parallel** (backend git writes are not concurrent-safe). -- `CY_TEST_VERBOSITY=debug` → full HTTP request/response logs. Auth header redacted to `Bearer ***XXXXX` (last 5 chars). - -## Config & auth - -`common.NewAPI()` resolves config from flags → env vars → config file. Token priority: `--api-key` → `CY_API_KEY` → `CY_API_TOKEN` → per-org token in config file. - -## Deeper docs - -- `@docs/architecture.md` — HTTP layer, Request struct, auth flow, error taxonomy -- `@docs/pipeline-build-watch-output.md` — `pipeline build trigger --watch` human SSE output; how to disable or remove -- `@docs/adding-a-command.md` — full walkthrough with working example -- `@docs/testing.md` — middleware + e2e test patterns, testcfg deep-dive -- `@docs/middleware-refactor.md` — what changed and why, migration reference - - -# GitNexus — Code Intelligence - -This project is indexed by GitNexus as **cycloid-cli** (11392 symbols, 69497 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. - -> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first. - -## When GitNexus is Available - -- Before modifying a symbol, prefer running `gitnexus_impact({target: "symbolName", direction: "upstream"})` to understand callers and blast radius. -- Before committing, consider running `gitnexus_detect_changes()` to verify the affected scope matches expectations. -- If impact analysis returns HIGH or CRITICAL risk, surface it to the user before proceeding. -- When exploring unfamiliar code, prefer `gitnexus_query({query: "concept"})` over grepping — it returns process-grouped results ranked by relevance. -- For full context on a specific symbol — callers, callees, execution flows — use `gitnexus_context({name: "symbolName"})`. -- Prefer `gitnexus_rename` over find-and-replace for symbol renames — it understands the call graph. - -## Resources - -| Resource | Use for | -|----------|---------| -| `gitnexus://repo/cycloid-cli/context` | Codebase overview, check index freshness | -| `gitnexus://repo/cycloid-cli/clusters` | All functional areas | -| `gitnexus://repo/cycloid-cli/processes` | All execution flows | -| `gitnexus://repo/cycloid-cli/process/{name}` | Step-by-step execution trace | - -## CLI - -| Task | Read this skill file | -|------|---------------------| -| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` | -| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` | -| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` | -| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` | -| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` | -| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` | - - diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 57b6ddff1..000000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,208 +0,0 @@ -## [Unreleased] - -- **ADDED** - - `cy catalog-repository create` and `cy catalog-repository update` now accept a `--refresh` flag. - When set, a synchronous version re-index (`GET .../versions/refresh?sync_presence=true`) is triggered - immediately after the create or update succeeds, making all branches and tags resolvable without - waiting for the background cron (~10 min). This fixes the branch-stack presence race. - ([CLI-128](https://linear.app/cycloid/issue/CLI-128)) - - ## [v3.1.3] _2022-06-17_ - - **CHANGED** - - Update client to version v3.1.3 - ([PR #140](https://github.com/cycloidio/cycloid-cli/pull/140)) - ## [v1.0.97] _2022-06-13_ - - **CHANGED** - - Update client to version v1.0.97 - ([PR #137](https://github.com/cycloidio/cycloid-cli/pull/137)) -## [v1.0.89] _2022-03-08_ -- **CHANGED** - - Update client to version v1.0.89 - ([PR #130](https://github.com/cycloidio/cycloid-cli/pull/130)) - - Add the ability to specify canonical for credential create - ([PR #130](https://github.com/cycloidio/cycloid-cli/pull/130)) - - Add new field-file flag to custom credential create - ([PR #130](https://github.com/cycloidio/cycloid-cli/pull/130)) - -## [v1.0.88] _2022-02-10_ -- **CHANGED** - - Update client to version v1.0.88 - ([PR #125](https://github.com/cycloidio/cycloid-cli/pull/125)) - - cy-wrapper: Now use Cycloid URL instead of Github to avoid API request limits - ([PR #126](https://github.com/cycloidio/cycloid-cli/pull/126)) - - cy-wrapper: provide debug mode using CY_DEBUG env var - ([PR #127](https://github.com/cycloidio/cycloid-cli/pull/127)) - - cy-wrapper: CY_WAIT_NETWORK now default to false - ([PR #127](https://github.com/cycloidio/cycloid-cli/pull/127)) - - cy-wrapper: CY_VERSION can be enforced to a specific version - ([PR #127](https://github.com/cycloidio/cycloid-cli/pull/127)) - - cy-wrapper: Reduce the default number of retries and provide new CY_DOWNLOAD_RETRIES variable - ([PR #127](https://github.com/cycloidio/cycloid-cli/pull/127)) - - cy-wrapper: Error handling when CY_RELEASES_URL is not reachable or incorrect - ([PR #127](https://github.com/cycloidio/cycloid-cli/pull/127)) - -## [v1.0.86] _2022-01-04_ -- **CHANGED** - - Update client to version v1.0.86 - ([PR #122](https://github.com/cycloidio/cycloid-cli/pull/122)) - -## [v1.0.85] _2021-12-08_ -- **CHANGED** - - Update client to version v1.0.85 - ([PR #120](https://github.com/cycloidio/cycloid-cli/pull/120)) - -## [v1.0.84] _2021-11-10_ -- **CHANGED** - - Update client to version 1.0.84 - ([PR #115](https://github.com/cycloidio/cycloid-cli/pull/115)) -- **ADDED** - - Adding new pipeline synced command - ([PR #111](https://github.com/cycloidio/cycloid-cli/pull/111)) - - CY wrapper, add more retry on and wait for network - ([PR #110](https://github.com/cycloidio/cycloid-cli/pull/110)) - -## [v1.0.82] _2021-10-04_ -- **ADDED** - - Adding cycloid dev readme and local e2e make targets - ([PR #112](https://github.com/cycloidio/cycloid-cli/pull/105)) - -- **CHANGED** - - Update client to version 1.0.82 - ([PR #105](https://github.com/cycloidio/cycloid-cli/pull/105)) - - Changed makefile to allow better use of targets for the cli automatic bump - ([PR #112](https://github.com/cycloidio/cycloid-cli/pull/105)) - -- **FIXED** - - Fix error in help of delete-env command - ([PR #105](https://github.com/cycloidio/cycloid-cli/pull/105)) - -## [v1.0.76] _2021-07-08_ -- **CHANGED** - - Update client to version 1.0.76 - ([PR #101](https://github.com/cycloidio/cycloid-cli/pull/101)) - - Update client to version 1.0.72 - ([PR #99](https://github.com/cycloidio/cycloid-cli/pull/99)) - -- **BREAKING** - - Switching to API KEY login only - ([PR #79](https://github.com/cycloidio/cycloid-cli/pull/79)) - -## [v1.0.64] _2021-03-23_ -- **CHANGED** - - Update to version 1.0.64 - ([PR #92](https://github.com/cycloidio/cycloid-cli/pull/92)) - -- **BREAKING** - - Remove create api key command - ([PR #92](https://github.com/cycloidio/cycloid-cli/pull/92)) - -- **FIXED** - - Fix wrong list function execution in `members list-invites` - ([PR #94](https://github.com/cycloidio/cycloid-cli/pull/94)) - -## [v1.0.61] _2021-03-15_ -- **ADDED** - - Adding better error details display - ([PR #76](https://github.com/cycloidio/cycloid-cli/pull/76)) - - Adding organizations `list-children` command - ([PR #76](https://github.com/cycloidio/cycloid-cli/pull/76)) - -- **CHANGED** - - Update to version 1.0.61 - ([PR #84](https://github.com/cycloidio/cycloid-cli/pull/84)) - - wrapper: change behavior to look for the closest lower version - ([PR #85](https://github.com/cycloidio/cycloid-cli/pull/85)) - -- **REMOVED** - - Remove deprecated KPIs `list-avaiable` command - ([PR #84](https://github.com/cycloidio/cycloid-cli/pull/84)) - -## [v1.0.58] _2021-02-05_ -- **ADDED** - - Adding new kpis command - ([PR #81](https://github.com/cycloidio/cycloid-cli/pull/81)) - - Adding new list-invites command - ([PR #72](https://github.com/cycloidio/cycloid-cli/pull/72)) - - `gen-doc` subcommand - ([PR #61](https://github.com/cycloidio/cycloid-cli/pull/61)) - - `--insecure` flag to allow TLS verification skipping - ([Issue #70](https://github.com/cycloidio/cycloid-cli/issues/70)) - - Adding all missing creds type into the CLI (GCP, AWS, ...) - ([PR #74](https://github.com/cycloidio/cycloid-cli/pull/74)) - -## [v1.0.53] _2020-12-01_ -- **CHANGED** - - Update to version 1.0.53 - ([PR #62](https://github.com/cycloidio/cycloid-cli/pull/62)) - - Wrapper now fallback to RC version before trying the dev one - ([PR #62](https://github.com/cycloidio/cycloid-cli/pull/62)) - - Add pipeline list command to list all pipeline in an organization - ([PR #62](https://github.com/cycloidio/cycloid-cli/pull/62)) - -## [v1.0.51] _2020-11-12_ -- **CHANGED** - - Update to version 1.0.51 - ([PR #52](https://github.com/cycloidio/cycloid-cli/pull/52)) - -## [v1.0.50] _2020-11-04_ -- **ADDED** - - Add organization create/delete - ([PR #51](https://github.com/cycloidio/cycloid-cli/pull/51)) - - `api-keys` commands - ([PR #57](https://github.com/cycloidio/cycloid-cli/pull/57)) - -- **CHANGED** - - `login` method to allow login using API key - ([PR #57](https://github.com/cycloidio/cycloid-cli/pull/57)) - -## [v1.0.49] _2020-11-02_ -- **ADDED** - - Add validate-form command - ([PR #35](https://github.com/cycloidio/cycloid-cli/pull/35)) - - Bump CLI version - ([PR #35](https://github.com/cycloidio/cycloid-cli/pull/35)) - - printer /helpers for each command - ([PR #25](https://github.com/cycloidio/cycloid-cli/pull/25)) - - `login list` subcommand - ([PR #24](https://github.com/cycloidio/cycloid-cli/pull/24)) - - support for child org login - ([PR #37](https://github.com/cycloidio/cycloid-cli/pull/37)) - - status endpoint implementation - ([PR #42](https://github.com/cycloidio/cycloid-cli/pull/42)) - - bash/zsh auto-complete - ([PR #47](https://github.com/cycloidio/cycloid-cli/pull/47)) - -## [v1.0.47] _2020-09-21_ -- **ADDED** - - Printer with support for `json`, `yaml` and `table` format - ([PR #4](https://github.com/cycloidio/cycloid-cli/pull/4)) - - First iteration of login command - ([PR #9](https://github.com/cycloidio/cycloid-cli/pull/9)) - -- **CHANGED** - - Second iteration of login command : allow multiple orgs login - :warning: the signature of common.ClientCredentials has changed - ([PR #15](https://github.com/cycloidio/cycloid-cli/pull/15)) - -- **DEPRECATED** - -- **REMOVED** - -- **FIXED** - -- **SECURITY** - -## [1.0.46] _2020-09-20_ -- **ADDED** - - First changelog template - ([PR #0](https://github.com/cycloidio/cycloid-cli/pull/0)) - -- **CHANGED** - -- **DEPRECATED** - -- **REMOVED** - -- **FIXED** - -- **SECURITY** diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index c392ccd9a..000000000 --- a/CLAUDE.md +++ /dev/null @@ -1,238 +0,0 @@ -# CLAUDE.md - -This file is auto-loaded by Claude Code on every invocation. See also `AGENTS.md` (kept identical, for non-Claude LLM agents). - -## Commands - -```bash -# Build -make build # build all platform binaries -go build -o cy . # quick local build - -# Test (requires local backend) -make be-reset # start backend via docker compose -go test ./... # run all tests -make test # same -make be-stop # stop backend - -# Run a specific test -go test ./e2e/... -run TestProjects -go test ./cmd/cycloid/middleware/... -run TestGetProject - -# Lint & format -make lint # golangci-lint + shellcheck -make format # gci + goimports + shfmt - -# Client regeneration (when swagger.yaml changes) -make client-generate # regenerates ./client/ from swagger.yaml - -# Changelog -make new-changelog-entry # add unreleased changelog entry (uses changie via docker) -``` - -## Architecture - -``` -cmd/cycloid//*.go → cmd/cycloid/middleware/ → GenericRequest() - (cobra commands) (Middleware interface) (generic_client.go) -``` - -### Key packages - -- **`client/models/`** — Auto-generated go-swagger models from `swagger.yaml`. Never edit manually. Regenerate with `make client-generate`. -- **`client/client/`** — Intentionally NOT used. The generated operations package was removed in the middleware refactor. Use `GenericRequest` instead. -- **`cmd/cycloid/middleware/`** — The `Middleware` interface (`middleware.go`) makes HTTP calls via `GenericRequest` (`generic_client.go`). Each feature gets its own file (e.g., `organization_projects.go`). -- **`cmd/cycloid//`** — Cobra command definitions. Each feature directory has: `cmd.go` (registers subcommands), plus one file per verb (`list.go`, `get.go`, `create.go`, `update.go`, `delete.go`), and `common.go` for shared logic. -- **`internal/cyargs/`** — All shared flag definitions and completion functions. Every flag used by multiple commands must be declared here. -- **`printer/`** — Output formatting. Use `cyout.PrintWithOptions(cmd, obj, err, errMsg, opts)` — routes errors to `cmd.ErrOrStderr()`, results to `cmd.OutOrStdout()`. Direct `printer.SmartPrint` calls are legacy; migrate on touch. -- **`internal/cyout/`** — One-liner print helpers (`cyout.Print`, `cyout.PrintWithOptions`) and `cyout.RegisterModel` for `--output` shell completion. -- **`e2e/`** — End-to-end tests that run real CLI commands against a live backend. - -## Hard Rules - -These are invariants that LLM agents and new contributors must not violate: - -1. **NEVER edit `client/models/`** — auto-generated. Run `make client-generate` to update. -2. **NEVER import or use `client/client/`** — deprecated. Use `GenericRequest` in middleware methods. -3. **NEVER call `NewMiddleware` outside a cobra `RunE` function** — not at package init, not in tests directly. -4. **ALWAYS parse ALL flags via `cyargs.Get*` BEFORE calling `common.NewAPI()` and `NewMiddleware()`** — `GenericRequest` reads `verbosity` from Viper at call time; unparsed flags produce stale values. -5. **ALWAYS add shared flags to `internal/cyargs/`** — never inline a flag used by more than one command. -6. **ALWAYS use `cyout.PrintWithOptions` (or `cyout.Print`)** — errors go to `ErrOrStderr()`, results go to `OutOrStdout()`. Do not call `printer.SmartPrint` directly in new code. -7. **E2E tests require a running backend** (`make be-start`). Never run e2e in parallel. -8. **Run `make format && make lint` after every code change.** -9. **Ship tests with every feature** — in the same change, add or extend coverage for what you introduce: new or changed middleware in `cmd/cycloid/middleware/*_test.go` (or focused unit tests where appropriate), and user-facing CLI behavior in `e2e/*_test.go` when that resource already has e2e tests. Do not land behavior-only changes without tests. - -## `GenericRequest` pattern - -`GenericRequest` handles auth, JSON marshaling, and `{"data":...}` envelope unwrapping. Pass `&result` directly — do not wrap in a `struct{ Data *X }`. - -```go -// Standard middleware method pattern: -func (m *middleware) GetProject(org, project string) (*models.Project, *http.Response, error) { - var result *models.Project - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} -``` - -`Request` fields: `Method`, `Organization` (*string, for auth), `NoAuth` (bool), `Route` ([]string), `Query` (struct with `url` tags), `LHSFilters` ([]LHSFilter, see below), `Headers` (map), `Accept` (*string), `Body` (any, JSON-marshalled). - -## LHS filters - -The Cycloid API supports LHS bracket filters on `List` routes: `attribute[condition]=value`. The condition is typically `eq`, `rlike`, `gt`, `lt`, etc. - -**Rule: all new `List` middleware methods must accept `filters ...LHSFilter` as their last parameter.** - -`LHSFilter` is defined in `cmd/cycloid/middleware/lhs_filter.go`: - -```go -type LHSFilter struct { - Attribute string - Condition string - Value string -} -``` - -Pass filters via the `LHSFilters` field of `Request`. Brackets are kept literal (not percent-encoded) so the API receives `name[eq]=my-project`, not `name%5Beq%5D=my-project`. Regex metacharacters in values (`?`, `*`, `+`, etc.) are also preserved. - -```go -// Example: list projects filtered by name prefix -func (m *middleware) ListProjects(org string, filters ...LHSFilter) ([]*models.Project, *http.Response, error) { - var result []*models.Project - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects"}, - LHSFilters: filters, - }, &result) - ... -} - -// Caller usage: -projects, _, err := m.ListProjects(org, middleware.LHSFilter{ - Attribute: "name", - Condition: "rlike", - Value: "proj.*", -}) -``` - -Offline (no-backend) unit tests for LHS filter encoding live in `cmd/cycloid/middleware/offline/lhs_filter_test.go`. - -### Return type conventions - -| Verb | Return | -|------|--------| -| Get / Create | `(*models.X, *http.Response, error)` | -| List | `([]*models.X, *http.Response, error)` | -| Delete / void | `(*http.Response, error)` | - -Always return the `*http.Response` so callers can inspect status codes. Assign `_` if unused. - -## Command pattern - -```go -var projectTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "Description", "Owner.Username"}, - Identifier: "Canonical", -} - -func getProject(cmd *cobra.Command, args []string) error { - // Step 1: ALL flags first - org, err := cyargs.GetOrg(cmd) - if err != nil { return err } - project, err := cyargs.GetProject(cmd) - if err != nil { return err } - - // Step 2: API + middleware - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // Step 3: call + print (cyout handles printer selection and error routing) - result, _, err := m.GetProject(org, project) - return cyout.PrintWithOptions(cmd, result, err, "unable to get project", projectTableOptions) -} -``` - -`cyout.PrintWithOptions` handles everything: reads `--output`, picks the printer, routes errors to stderr and results to stdout. For commands with no column customisation, use `cyout.Print(cmd, obj, err, errMsg)`. - -## `cyargs` flags - -All shared flag definitions live in `internal/cyargs/`. Pattern: - -```go -func AddWidgetFlag(cmd *cobra.Command) { - cmd.Flags().String("widget", "", "Widget canonical") - _ = cmd.RegisterFlagCompletionFunc("widget", widgetCompletion) -} - -func GetWidget(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("widget") -} -``` - -Register in the command constructor (`NewGetX()`), never inside `RunE`. - -## Testing - -- **Tests ship with the feature** (see Hard Rule 9): middleware and command changes should include tests in the same PR; extend existing `e2e/*_test.go` files when the resource is already covered there. -- **Middleware tests** (`cmd/cycloid/middleware/*_test.go`): `TestMain` calls `testcfg.NewConfig("middleware")`. Fixtures: `config.Project`, `config.Environment`, `config.Component`, `config.ConfigRepo`, `config.CatalogRepo`. -- **E2E tests** (`e2e/*_test.go`): `executeCommand(args)` runs the real CLI. Same `testcfg` setup. -- E2E tests are **not parallel** (backend git writes are not concurrent-safe). -- `CY_TEST_VERBOSITY=debug` → full HTTP request/response logs. Auth header redacted to `Bearer ***XXXXX` (last 5 chars). - -## Config & auth - -`common.NewAPI()` resolves config from flags → env vars → config file. Token priority: `--api-key` → `CY_API_KEY` → `CY_API_TOKEN` → per-org token in config file. - -## Deeper docs - -- `@docs/architecture.md` — HTTP layer, Request struct, auth flow, error taxonomy -- `@docs/pipeline-build-watch-output.md` — `pipeline build trigger --watch` human SSE output; how to disable or remove -- `@docs/adding-a-command.md` — full walkthrough with working example -- `@docs/testing.md` — middleware + e2e test patterns, testcfg deep-dive -- `@docs/middleware-refactor.md` — what changed and why, migration reference - - -# GitNexus — Code Intelligence - -This project is indexed by GitNexus as **cycloid-cli** (11392 symbols, 69497 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. - -> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first. - -## When GitNexus is Available - -- Before modifying a symbol, prefer running `gitnexus_impact({target: "symbolName", direction: "upstream"})` to understand callers and blast radius. -- Before committing, consider running `gitnexus_detect_changes()` to verify the affected scope matches expectations. -- If impact analysis returns HIGH or CRITICAL risk, surface it to the user before proceeding. -- When exploring unfamiliar code, prefer `gitnexus_query({query: "concept"})` over grepping — it returns process-grouped results ranked by relevance. -- For full context on a specific symbol — callers, callees, execution flows — use `gitnexus_context({name: "symbolName"})`. -- Prefer `gitnexus_rename` over find-and-replace for symbol renames — it understands the call graph. - -## Resources - -| Resource | Use for | -|----------|---------| -| `gitnexus://repo/cycloid-cli/context` | Codebase overview, check index freshness | -| `gitnexus://repo/cycloid-cli/clusters` | All functional areas | -| `gitnexus://repo/cycloid-cli/processes` | All execution flows | -| `gitnexus://repo/cycloid-cli/process/{name}` | Step-by-step execution trace | - -## CLI - -| Task | Read this skill file | -|------|---------------------| -| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` | -| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` | -| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` | -| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` | -| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` | -| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` | - - diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index d6c07f3f5..000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,40 +0,0 @@ -# Contributing - -## Adding a feature or command - -See [`docs/adding-a-command.md`](docs/adding-a-command.md) for a full walkthrough including middleware methods, cobra commands, flags, and tests. - -## Running tests - -See [`docs/testing.md`](docs/testing.md) for setup, environment variables, and test patterns. - -Quick start: - -```bash -make be-start # start the local backend -go test ./... # run all tests -make be-stop -``` - -## Code style - -```bash -make format # gci + goimports + shfmt -make lint # golangci-lint + shellcheck -``` - -Always run both before submitting a PR. - -## Changelog - -Each PR should include a changelog entry: - -```bash -make new-changelog-entry -``` - -This runs `changie` via docker and creates a file in `changelog/unreleased/`. - -## Architecture overview - -See [`docs/architecture.md`](docs/architecture.md) and [`CLAUDE.md`](CLAUDE.md). diff --git a/DEVELOPING_TIPS.md b/DEVELOPING_TIPS.md deleted file mode 100644 index f33832efc..000000000 --- a/DEVELOPING_TIPS.md +++ /dev/null @@ -1,252 +0,0 @@ -# Cycloid Developer Tips - -> [!NOTE] **ARCHIVED** — Key content has been extracted into `docs/` (see `docs/adding-a-command.md`, `docs/testing.md`, `docs/architecture.md`). This file is kept for internal release process reference only (Concourse CI links, version tagging process) and requires access to private Cycloid repositories. - -> [!NOTE] These are internal notes meant for cycloid developers only since they -> require access to private git repositories. - -This file gives some tips to how to test, change or upgrade cli, for cycloid developers. - -The cli pipeline is available in the [cycloid-stacks](https://github.com/cycloidio/cycloid-stacks/tree/stacks/cycloid-cli) and the prod and staging cli can be checked [here](https://console.cycloid.io/organizations/cycloid/projects/cycloid-cli). - -## Prepare a CLI update - -Right now, the CLI release process and version is tied to the backend release. -This will be changed once the CLI codebase will be merged in the backend, until then, -we will have to make do. - -So the release process is as follows: -- The backend is merged and release in staging/production -- An automatic PR is made with the client update on [this component](https://console.cycloid.io/organizations/cycloid/projects/cycloid-cli/environments/automatic_bump/components/apibump/overview) -- The automatic PR will contain the client update and write the version in the - [`./client/version`](./client/version) file. - -> [!WARNING] -> The version tagging will occur when the PR with the updated client version with -> the updated [`./client/version`](./client/version) file will be merged on develop -> -> This means that every feature PR merged after this one will not be integrated -> in the release - -- Once the Client update PR merged, the version is tagged the pipeline on - [this component must go to completion on the release job](https://console.cycloid.io/organizations/cycloid/projects/cycloid-cli/environments/staging/components/develop/overview) -- To release in prod, use the [`merge-develop-to-master`](https://console.cycloid.io/organizations/cycloid/projects/cycloid-cli/environments/prod/components/master/pipelines/cycloid-cli-prod-master/jobs/merge-develop-to-master/builds/465851136#all) button on the prod pipeline. -- Then the release process will test, build and release on github. - -So we advise the following workflow: - -1. Until a client version update occurs, you can merge any feature PR on develop -2. Once the client PR update is created, and if you need to develop fixes and logic - linked to that client update, create a branch from the client update PR. - (basically treating the client update PR as the new develop) -3. Once you are done with all the changes linked to this version and the test passes, - you can merge the client update PR and proceed to release in production. - -If you need to create the PR update yourself manually to anticipate a version not release yet, -you can generate the client update using the `make client-generate` target. - -### Make a manual client update - -- Download the correct `swagger.yml` and put it at the repository's root at `./swagger.yml` -- Use `make client-generate` -- Wait for the backend release and add the correct version in `./client/version` - -Ping devops if you have any questions or doubt on the release process. - -## Add a new commands to the cli - -To add a new command you can start by verifying the api endpoint to implement in the [API docs](https://docs.cycloid.io/api/index.html). - -While you can follow this guide, I advise you to look up other implemented routes. - -### Implement the middleware method - -1. Ensure your client is up to date, if the backend version is not release yet, - see [the above section](#make-a-manual-client-update) - -2. Define the method that implements the endpoint in the middleware - - 1. Create the method in the middleware interface [here](./cmd/cycloid/middleware/middleware.go) - The naming convention of the function should reflect the naming on the API. - If you have a getComponent route on the API, the middleware should be a GetComponent function. - -> [!NOTE] -> Only exception, if a GET route list resources, we rename it to ListResource -> so the `getComponents` should be named `ListComponents`. - - 2. The function should accept all required parameters as argument in function. - a. Optional argument should be a pointer, a nil value means absent value. - b. Required values must be plain values - c. If a request has a body, use `body.Validate(strfmt.Default)` - - 3. Implement the API call either: - a. By using the generated client parameters, look any other implemented - like [getProject](./cmd/cycloid/middleware/organization_projects.go) - b. If the route can't be implemented using the client, use `net/http`. - - 4. All route should return either some data and error, or just an error: - a. Delete methods -> `return error` - b. Create/Get methods -> `return (*models.object, error)` - c. List methods -> `return ([]*models.object, error)` - - 5. Do not validate payload, it has generated too much issues in the past. - -#### Middleware testing - -Add in the middleware package a basic happy path test to ensure -that given correct parameters, the API responds. - -This is meant mostly to detect any API dift or issues. This way it will enable -developper to differenciate more easily server and client issues. - -Testing setup is done on the [TestMain function](./cmd/cycloid/middleware/middleware_test.go) -that will use the [testcfg package](./pkg/testcfg/config.go) to initialize -the backend, provision the required tools and give you all the required context -for testing (api key, org, api url, basic stuff like project/env/component, config -and catalog repo, etc...). - -Lookup how existing test are made and follow the same logic. - -### Implement the actual CLI command - -Now you need to define the cobra command at `cmd/cycloid//` so that -the method previously defined can be used in the cli. - - Each feature is structured as follows: - -```tree -./cmd/cycloid// -./cmd/cycloid//cmd.go # list and combine all the subcommands -./cmd/cycloid//get.go # each command has its own file -./cmd/cycloid//create.go -./cmd/cycloid//update.go -./cmd/cycloid//list.go -./cmd/cycloid//common.go # add common logic specific to this series of commands -``` - A feature can have subcommands in that case structure it like this: - -```tree -./cmd/cycloid// -./cmd/cycloid//cmd.go # list and combine all the subcommands -./cmd/cycloid//get.go # each command has its own file -./cmd/cycloid//create.go -./cmd/cycloid//update.go -./cmd/cycloid//list.go -./cmd/cycloid//sub_command.go # add your subcommand here, it must behave like the cmd.go file -./cmd/cycloid//sub_command_get.go # prefix all sub sub_command with the sub_command name -./cmd/cycloid//sub_command_create.go -./cmd/cycloid//common.go # add common logic specific to this series of commands -``` - -Command convention is as follow: - -`cy ` - -Example for components: -```bash -cy component create -cy component update -cy component get -cy component list -``` - -You should start by adding the type of command to the set of list of -available commands in `cmd.go` - -Then create a new file on this folder, where you will specify the method -that will return the cobra command that defines the cli command to implement -with the flags possible to use. - -Finally you define a method that will be run by this cobra command that will -take as argument the multiple flags and pass them to the middleware -interface method that you previsouly created. - -#### Implementation directives - -Use and implemant **all flags, arguments and completion definitions and functions** -in the [cyargs package](./internal/cyargs), each flag must be declared and its value -must be retrieved using a function in the cyargs package. - -Only if a flag is declared on only one specific command you can declare them locally. - -Look up how flags and completion are implemented for example [the component flag](./internal/cyargs/component.go). - -The command should: -1. Retrieve all flag -2. Process any pre-requisite (file read, default values management, etc...) -3. Do the action against the API. -4. Use the [printer](./printer/printer.go) to print the output of the API to the console - a. If no error, with valid payload => output on stdout using `cmd.OutOrStdout()` - b. If any error, print error and details on stderr using `cmd.OutOrStderr()` - -This about the UX for the command line: -- Add the completion -- Try to infer values as much as you can (use env vars, context, fetching existing values) -- Make action idempotent as much as possible -- Implement upsert (like `cy component create --update`) - -### Testing commands - -To test commands, do it in the [e2e test packages](./e2e/e2e_test.go). It has -all the required function an context for testing the command directly. - -It also uses the [testcfg package](./pkg/testcfg/config.go) to initialize -the backend, provision the required tools and give you all the required context -for testing (api key, org, api url, basic stuff like project/env/component, config -and catalog repo, etc...). - -Add tests for your command, what you should be testing: -- All basic happy path -- Test that all arguments, flags and env var works to configure your action -- Test that the output match expectations -- Try to test and catch edge cases - -As usual, look up other test commands for examples. - -Tests in CI are not executed in parallel due to some backend issues with concurrency -around git. - -### Add a changelog - -Once your changes are done, add a changelog to it: - -``` -make new-changelog-entry -``` - -## CLI local testing - -### Requirements - -To perform local test you need: -- Access to the Cycloid console on `cycloid` via the API -- A valid API key on `CY_SAAS_API_KEY` - -To start the test, login to docker to pull the backend image: - -```bash -make docker-login docker-pull -``` - -Start the local backend: - -```bash -make be-start -``` - -You can start the tests using `go test ./...` or - -```bash -make test -``` - -You can cleanup the backend with: - -```bash -make be-stop -``` - -And reset it (stop + start): -```bash -make be-reset -``` diff --git a/Makefile b/Makefile deleted file mode 100644 index f5e50dd13..000000000 --- a/Makefile +++ /dev/null @@ -1,162 +0,0 @@ -ifeq ($(GOCACHE),) - GOCACHE := $(HOME)/.cache/go-build -endif - -ifneq (, $(shell which go)) - GOCACHE := $(shell go env GOCACHE) -endif - -SHELL := /bin/sh -REPO_NAME ?= cycloid-cli -MAKEFILE_DIR := $(dir $(realpath $(lastword $(MAKEFILE_LIST)))) - -# IMAGE BUILD -BINARY ?= cy -# VERSION example v1.0.47 -VERSION ?= $(shell cat client/version) -REVISION ?= $(shell git rev-parse --short HEAD 2> /dev/null || echo 'unknown') -BRANCH ?= $(shell git rev-parse --abbrev-ref HEAD 2> /dev/null || echo 'unknown') -BUILD_ORIGIN ?= $(USER)@$(shell hostname -f) -BUILD_DATE ?= $(shell date --utc -Iseconds) -DOCKER_COMPOSE ?= $(shell docker compose --help >/dev/null 2>&1 && echo "docker compose" || echo "docker-compose") -REPO_PATH ?= github.com/cycloidio/cycloid-cli - -# GO -# Setup the -ldflags build option for go here, interpolate the variable values -GO_BUILD_FLAGS ?= -trimpath -GO_LDFLAGS ?= -ldflags \ - "-s -w\ - -X $(REPO_PATH)/internal/version.Version=$(VERSION)\ - -X $(REPO_PATH)/internal/version.Revision=$(REVISION)\ - -X $(REPO_PATH)/internal/version.Branch=$(BRANCH)\ - -X $(REPO_PATH)/internal/version.BuildOrigin=$(BUILD_ORIGIN)\ - -X $(REPO_PATH)/internal/version.BuildDate=$(BUILD_DATE)" - -# SWAGGER -SWAGGER_FILE ?= "swagger.yml" -SWAGGER_GENERATE = swagger generate client \ - --spec=$(SWAGGER_FILE) \ - --default-produces="application/vnd.cycloid.io.v1+json" \ - --target=./client \ - --name=api - --include .env --include .api_key - -.PHONY: help -help: ## Show this help - @grep -F -h "##" $(MAKEFILE_LIST) | grep -F -v fgrep | sed -e 's/:.*##/:##/' | column -t -s '##' - -.PHONY: print-version -print-version: - echo $$BACKEND_TAG - -.PHONY: install -install: .env .git/hooks/pre-commit ## install all pre-requisites - -.PHONY: .env -.env: ## generate the .env files with the required secrets for this repo - @rm .env || true - @CY_API_KEY=$${CY_SAAS_API_KEY?A valid API key to the cycloid org in our saas is required for this target. It must be provided via the CY_SAAS_API_KEY} \ - CY_API_URL=https://http-api.cycloid.io \ - CY_ORG=cycloid \ - cy uri interpolate .env.sample > .env - -source-env: ## source the local env to use cycloid - while read line; do export $$line; done < .api_key - -.PHONY: build -build: ## Build all the binaries - GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build $(GO_BUILD_FLAGS) -o $(BINARY) $(GO_LDFLAGS) $(REPO_PATH) - GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build $(GO_BUILD_FLAGS) -o $(BINARY)-linux-amd64 $(GO_LDFLAGS) $(REPO_PATH) - GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build $(GO_BUILD_FLAGS) -o $(BINARY)-linux-arm64 $(GO_LDFLAGS) $(REPO_PATH) - GO111MODULE=on CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build $(GO_BUILD_FLAGS) -o $(BINARY)-windows-amd64 $(GO_LDFLAGS) $(REPO_PATH) - GO111MODULE=on CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build $(GO_BUILD_FLAGS) -o $(BINARY)-darwin-arm64 $(GO_LDFLAGS) $(REPO_PATH) - GO111MODULE=on CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build $(GO_BUILD_FLAGS) -o $(BINARY)-darwin-amd64 $(GO_LDFLAGS) $(REPO_PATH) - -.PHONY: clean -clean: test-clean - @rm -f .env - go clean - -.PHONY: test test-clean -test: ## Run end to end tests - go test ./... - -test-clean: ## Clean test cache - go clean -testcache - -.PHONY: client-delete client-generate client-generate-from-docs -client-delete: ## Resets old client folder - rm -rf ./client && mkdir -p client - -client-generate: client-delete ## Generate client from file at SWAGGER_FILE path - # Used in CI, do not use docker compose here. - echo "Creating swagger files"; \ - $(SWAGGER_GENERATE) - @# Discard the generated HTTP client package — we only keep models. - @find ./client -mindepth 1 -maxdepth 1 ! -name 'models' ! -name 'version' -exec rm -rf {} + - @export SWAGGER_VERSION=$$(python3 -c 'import yaml, sys; y = yaml.safe_load(sys.stdin); print(y["info"]["version"])' < swagger.yml); \ - if [ -z "$$SWAGGER_VERSION" ]; then echo "Unable to read version from swagger"; exit 1; fi; \ - echo $$SWAGGER_VERSION > client/version; \ - go mod tidy - -client-generate-from-docs: client-delete ## Generates client using docker and swagger from docs (version -> latest-api) - @wget -O swagger.yml https://docs.cycloid.io/api/swagger.yml - @export SWAGGER_VERSION=$$(python3 -c 'import yaml, sys; y = yaml.safe_load(sys.stdin); print(y["info"]["version"])' < swagger.yml); \ - if [ -z "$$SWAGGER_VERSION" ]; then echo "Unable to read version from swagger"; exit 1; fi; \ - echo $$SWAGGER_VERSION > client/version; \ - make client-generate && \ - echo "Please run the following git commands:"; \ - echo "git add client" && \ - echo "git commit -m 'Bump swagger client to version $$SWAGGER_VERSION'" - -.PHONY: docker-login docker-pull -docker-login: .env - echo "$(SECRET_ACCESS)" | docker login rg.fr-par.scw.cloud/cycloidio/cycloid-backend -u $(ACCESS_KEY) --password-stdin - -docker-pull: .env - docker compose pull - -.PHONY: be-start be-stop be-reset -be-start: ## start the local backend - $(DOCKER_COMPOSE) up -dV - -be-stop: ## stop the local backend - $(DOCKER_COMPOSE) down -v - -be-reset: be-stop be-start ## reset the backend - -be-db-connect: ## Connect to the local mysql - $(DOCKER_COMPOSE) exec -it database mysql -uroot -pyoudeploy youdeploy - -.PHONY: new-changelog-entry -new-changelog-entry: ## Create a new entry for unreleased element - @docker run --rm -it -v $(CURDIR):/cycloid-cli -w /cycloid-cli cycloid/cycloid-toolkit:latest changie new - -.PHONY: lint lint-go lint-sh -lint: lint-go lint-sh - -lint-sh: - @find . -type f -name '*.sh' -exec shellcheck -f gcc {} \; - -lint-go: ## Lint the source code - @golangci-lint run -v - -.PHONY: format format-go format-sh -format: format-go format-sh - -format-go: ## format the repo - @gci write --skip-generated -s standard -s default -s "prefix(github.com/cycloidio)" . > /dev/null - @goimports -w -local github.com/cycloidio . - -format-sh: - @shfmt -w . - -.PHONY: ci-test -.ONEFILE: -ci-test: - $(MAKEFILE_DIR)scripts/ci-tests.sh - -.git/hooks/pre-commit: - pre-commit-install diff --git a/README.md b/README.md index 18d383ca2..7201d8a77 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,53 @@ # Cycloid CLI (cy) -This repository hosts the source code of Cycloid command line to use Cycloid APIs. +Command-line interface for the [Cycloid](https://cycloid.io) platform. ## Installation -Precompiled binaries for released versions are available in the [release](https://github.com/cycloidio/cycloid-cli/releases) page on Github. +### Go install (recommended for developers) -Using the latest production release binary is the recommended way of installing the Cycloid CLI. +```sh +go install github.com/cycloidio/cycloid-cli@latest +``` -### In pipeline +This installs a lightweight shim that automatically downloads the correct platform binary on first run. -In a pipeline, use the [`cycloid/cycloid-toolkit`](https://hub.docker.com/r/cycloid/cycloid-toolkit) image that contains a wrapper around `cy` that will automatically download and use the correct CLI version against the Cycloid API version. +### Pre-built binaries -## Getting started +Download pre-built binaries from the [releases page](https://github.com/cycloidio/cycloid-cli/releases). -Look up the official CLI documentation [here](https://docs.cycloid.io/reference/cli/). +### In pipelines +Use the [`cycloid/cycloid-toolkit`](https://hub.docker.com/r/cycloid/cycloid-toolkit) Docker image, which includes a wrapper that automatically downloads the correct CLI version matching your Cycloid API. + +## Usage + +```sh +# First run downloads the real binary (~12 MB), then executes it +cy organizations list + +# Pin a specific version +CY_VERSION=v6.10.24 cy --version + +# Check shim version +cy --shim-version +``` + +## How it works + +The `go install` binary is a thin installer shim (~3 MB). On first run it: + +1. Determines your platform (linux/darwin/windows, amd64/arm64) +2. Downloads the matching pre-built `cy` binary from GitHub Releases +3. Caches it at `~/.cycloid/bin/cy-` +4. Exec's the real binary with all your arguments + +Subsequent runs use the cached binary directly (no network call). + +## Documentation + +Full CLI documentation: [docs.cycloid.io/reference/cli](https://docs.cycloid.io/reference/cli/) + +## License + +[MIT](LICENSE) diff --git a/changelog/releases/.gitkeep b/changelog/releases/.gitkeep deleted file mode 100644 index e69de29bb..000000000 diff --git a/changelog/releases/0.md b/changelog/releases/0.md deleted file mode 100644 index d79c95e67..000000000 --- a/changelog/releases/0.md +++ /dev/null @@ -1,45 +0,0 @@ -## [0] _2025-07-18_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- Add support for components CRUD in the CLI ([CLI#339]) -*This allows you to manipulate components using the CLI* -- Add multi platform builds ([CLI#339]) - -- Add cy project list-env command. ([CLI#342]) -*This allow to list the envs linked to a project.* -**BREAKING** -- Remove old `cy project create-env` and `cy project update-env` commands ([CLI#339]) -*Use the `cy components create` and `cy components update` commands instead.* -**CHANGED** -- Update client to version v6.0.8 ([CLI#332]) - -- Update client to version v6.0.9 ([CLI#333]) - -- Update client to version v6.0.17 ([CLI#335]) - -- Update client to version v6.0.69 ([CLI#337]) - -- Update client to version v6.0.98 ([CLI#340]) - -- Updated project / env command to the new component layer ([CLI#339]) -*As with components, what used to be env creation become components.* -- Update client to version v6.1.25 ([CLI#]) - -- Update client to version v6.0.114 ([CLI#351]) - -**FIXED** -- Migrated all project commands to component layer ([CLI#342]) - - -[CLI#339]: https://github.com/cycloidio/cycloid-cli/pull/339 -[CLI#342]: https://github.com/cycloidio/cycloid-cli/pull/342 -[CLI#332]: https://github.com/cycloidio/cycloid-cli/pull/332 -[CLI#333]: https://github.com/cycloidio/cycloid-cli/pull/333 -[CLI#335]: https://github.com/cycloidio/cycloid-cli/pull/335 -[CLI#337]: https://github.com/cycloidio/cycloid-cli/pull/337 -[CLI#340]: https://github.com/cycloidio/cycloid-cli/pull/340 -[CLI#]: https://github.com/cycloidio/cycloid-cli/pull/ -[CLI#351]: https://github.com/cycloidio/cycloid-cli/pull/351 diff --git a/changelog/releases/v3.1.47.md b/changelog/releases/v3.1.47.md deleted file mode 100644 index d70066796..000000000 --- a/changelog/releases/v3.1.47.md +++ /dev/null @@ -1,14 +0,0 @@ -## [v3.1.47] _2022-07-14_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- Now using Changie for changelog file ([CLI#142]) - -**CHANGED** -- Update client to version v3.1.47 ([CLI#143]) - - -[CLI#142]: https://github.com/cycloidio/cycloid-cli/pull/142 -[CLI#143]: https://github.com/cycloidio/cycloid-cli/pull/143 diff --git a/changelog/releases/v3.2.44.md b/changelog/releases/v3.2.44.md deleted file mode 100644 index 8d3630e9f..000000000 --- a/changelog/releases/v3.2.44.md +++ /dev/null @@ -1,13 +0,0 @@ -## [v3.2.44] _2022-11-11_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v3.1.247 ([CLI#154]) - -- Update client to version v3.2.44 ([CLI#162]) - - -[CLI#154]: https://github.com/cycloidio/cycloid-cli/pull/154 -[CLI#162]: https://github.com/cycloidio/cycloid-cli/pull/162 diff --git a/changelog/releases/v3.3.26.md b/changelog/releases/v3.3.26.md deleted file mode 100644 index ffe52a608..000000000 --- a/changelog/releases/v3.3.26.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v3.3.26] _2023-01-12_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v3.3.26 ([CLI#171]) - - -[CLI#171]: https://github.com/cycloidio/cycloid-cli/pull/171 diff --git a/changelog/releases/v4.0.11.md b/changelog/releases/v4.0.11.md deleted file mode 100644 index 013484933..000000000 --- a/changelog/releases/v4.0.11.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v4.0.11] _2023-02-09_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v4.0.11 ([CLI#176]) - - -[CLI#176]: https://github.com/cycloidio/cycloid-cli/pull/176 diff --git a/changelog/releases/v4.0.133.md b/changelog/releases/v4.0.133.md deleted file mode 100644 index 263ed53d6..000000000 --- a/changelog/releases/v4.0.133.md +++ /dev/null @@ -1,13 +0,0 @@ -## [v4.0.133] _2023-05-23_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v4.0.57 ([CLI#182]) - -- Update client to version v4.0.133 ([CLI#189]) - - -[CLI#182]: https://github.com/cycloidio/cycloid-cli/pull/182 -[CLI#189]: https://github.com/cycloidio/cycloid-cli/pull/189 diff --git a/changelog/releases/v4.0.162.md b/changelog/releases/v4.0.162.md deleted file mode 100644 index 59eb0d27f..000000000 --- a/changelog/releases/v4.0.162.md +++ /dev/null @@ -1,13 +0,0 @@ -## [v4.0.162] _2023-06-22_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v4.0.140 ([CLI#192]) - -- Update client to version v4.0.162 ([CLI#196]) - - -[CLI#192]: https://github.com/cycloidio/cycloid-cli/pull/192 -[CLI#196]: https://github.com/cycloidio/cycloid-cli/pull/196 diff --git a/changelog/releases/v4.0.17.md b/changelog/releases/v4.0.17.md deleted file mode 100644 index 104dbcdf8..000000000 --- a/changelog/releases/v4.0.17.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v4.0.17] _2023-02-13_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v4.0.17 ([CLI#178]) - - -[CLI#178]: https://github.com/cycloidio/cycloid-cli/pull/178 diff --git a/changelog/releases/v4.0.178.md b/changelog/releases/v4.0.178.md deleted file mode 100644 index 3e6bb3c36..000000000 --- a/changelog/releases/v4.0.178.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v4.0.178] _2023-10-26_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v4.0.178 ([CLI#198]) - - -[CLI#198]: https://github.com/cycloidio/cycloid-cli/pull/198 diff --git a/changelog/releases/v4.0.20.md b/changelog/releases/v4.0.20.md deleted file mode 100644 index 89ce861fa..000000000 --- a/changelog/releases/v4.0.20.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v4.0.20] _2023-02-15_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v4.0.20 ([CLI#179]) - - -[CLI#179]: https://github.com/cycloidio/cycloid-cli/pull/179 diff --git a/changelog/releases/v4.0.290.md b/changelog/releases/v4.0.290.md deleted file mode 100644 index ffe7c3a3e..000000000 --- a/changelog/releases/v4.0.290.md +++ /dev/null @@ -1,13 +0,0 @@ -## [v4.0.290] _2024-01-25_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v4.0.220 ([CLI#206]) - -- Update client to version v4.0.290 ([CLI#228]) - - -[CLI#206]: https://github.com/cycloidio/cycloid-cli/pull/206 -[CLI#228]: https://github.com/cycloidio/cycloid-cli/pull/228 diff --git a/changelog/releases/v4.0.295.md b/changelog/releases/v4.0.295.md deleted file mode 100644 index 83b2e2f0d..000000000 --- a/changelog/releases/v4.0.295.md +++ /dev/null @@ -1,13 +0,0 @@ -## [v4.0.295] _2024-02-01_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v4.0.294 ([CLI#233]) - -- Update client to version v4.0.295 ([CLI#234]) - - -[CLI#233]: https://github.com/cycloidio/cycloid-cli/pull/233 -[CLI#234]: https://github.com/cycloidio/cycloid-cli/pull/234 diff --git a/changelog/releases/v4.0.340.md b/changelog/releases/v4.0.340.md deleted file mode 100644 index 332c4fc5d..000000000 --- a/changelog/releases/v4.0.340.md +++ /dev/null @@ -1,20 +0,0 @@ -## [v4.0.340] _2024-04-16_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v4.0.340 ([CLI#253]) - -### Credentials -**ADDED** -- Added the 'update' for Credentials ([CLI#236]) - -### Other -**ADDED** -- Added more middleware methods for external backends ([CLI#254]) - - -[CLI#253]: https://github.com/cycloidio/cycloid-cli/pull/253 -[CLI#236]: https://github.com/cycloidio/cycloid-cli/pull/236 -[CLI#254]: https://github.com/cycloidio/cycloid-cli/pull/254 diff --git a/changelog/releases/v5.0.20.md b/changelog/releases/v5.0.20.md deleted file mode 100644 index 9bff5ecff..000000000 --- a/changelog/releases/v5.0.20.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v5.0.20] _2024-05-16_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v5.0.20 ([CLI#265]) -*Fixed external backend and list project issues associated with the upgrade* - -[CLI#265]: https://github.com/cycloidio/cycloid-cli/pull/265 diff --git a/changelog/releases/v5.0.34.md b/changelog/releases/v5.0.34.md deleted file mode 100644 index 9cfc64f44..000000000 --- a/changelog/releases/v5.0.34.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v5.0.34] _2024-05-23_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v5.0.34 ([CLI#267]) - - -[CLI#267]: https://github.com/cycloidio/cycloid-cli/pull/267 diff --git a/changelog/releases/v5.0.49.md b/changelog/releases/v5.0.49.md deleted file mode 100644 index 48224ff29..000000000 --- a/changelog/releases/v5.0.49.md +++ /dev/null @@ -1,15 +0,0 @@ -## [v5.0.49] _2024-06-19_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- Add a `cy stacks get-config ` to retrieve a stack default config ([CLI#277]) - -- Make `cy project create-stackforms-env` fetch default by default` ([CLI#277]) -*This behavior can be disabled with the `--no-fetch-defaults` flag* -**FIXED** -- Fix forms config parsing for stackforms related commands not sending the correct vars keys. ([CLI#277]) - - -[CLI#277]: https://github.com/cycloidio/cycloid-cli/pull/277 diff --git a/changelog/releases/v5.0.66.md b/changelog/releases/v5.0.66.md deleted file mode 100644 index e45332f13..000000000 --- a/changelog/releases/v5.0.66.md +++ /dev/null @@ -1,33 +0,0 @@ -## [v5.0.66] _2024-07-04_ - -Cycloid CLI changelog: - -### CLI -**BREAKING** -- Env var TOKEN is replaced by CY_API_KEY for giving token via env var. ([CLI#274]) -*The old `TOKEN` env var still works but emits a warning. It will be removed in a futur release.* -**CHANGED** -- Allow to create a project without an environment. ([CLI#278]) -*The env creation with the old flags still exists, but is now deprecated and will be removed in a further release.* -- Allow to use CY_ORG env var to define the current org instead of --org flag ([CLI#274]) -*You can still use the --org flag, the CLI flag will have precedence over the env var.* -- Update client to version v5.0.66 ([CLI#279]) - -**FIXED** -- Fix version for release ([CLI#269]) - -- Remove API validation on bad playload from API for catalog repository refresh ([CLI#278]) - -- --org flag is now global ([CLI#274]) -*This fixes inconsistency between commands, you can also set the org via env vars now.* -**SECURITY** -- Make the configuration write as 0600 permissions in user home config ([CLI#274]) - -- Allow to login using CY_API_TOKEN instead of providing the token via --api-token flag ([CLI#274]) -*This will become the default way, using the flag will be deprecated in the future.* - -[CLI#274]: https://github.com/cycloidio/cycloid-cli/pull/274 -[CLI#278]: https://github.com/cycloidio/cycloid-cli/pull/278 -[CLI#279]: https://github.com/cycloidio/cycloid-cli/pull/279 -[CLI#269]: https://github.com/cycloidio/cycloid-cli/pull/269 - diff --git a/changelog/releases/v5.1.134.md b/changelog/releases/v5.1.134.md deleted file mode 100644 index a3a92ee36..000000000 --- a/changelog/releases/v5.1.134.md +++ /dev/null @@ -1,89 +0,0 @@ -## [v5.1.134] _2024-12-10_ - -Cycloid CLI changelog: - -### CLI -**BREAKING** -- create-env uses now stackforms by default ([CLI#313]) -*the old create-env logic will apply if you give the legacy flags, but they won't be advertised anymore on the CLI.* -**CHANGED** -- Update client to version v5.1.10 ([CLI#290]) - -- Update client to version v5.1.14 ([CLI#291]) - -- Update client to version v5.1.15 ([CLI#292]) - -- Update client to version v5.1.26 ([CLI#293]) - -- Update client to version v5.1.30 ([CLI#294]) - -- Update client to version v5.1.31 ([CLI#295]) - -- Update client to version v5.1.35 ([CLI#296]) - -- Update client to version v5.1.43 ([CLI#297]) - -- Update client to version v5.1.56 ([CLI#302]) - -- Update client to version v5.1.58 ([CLI#303]) - -- Update client to version v5.1.61 ([CLI#304]) - -- Update client to version v5.1.67 ([CLI#305]) - -- Update client to version v5.1.76 ([CLI#306]) - -- Update client to version v5.1.98 ([CLI#308]) - -- Update client to version v5.1.102 ([CLI#309]) - -- Update client to version v5.1.116 ([CLI#311]) - -- Update client to version v5.1.124 ([CLI#312]) - -- Update client to version v5.1.129 ([CLI#314]) - -- Update client to version v5.1.130 ([CLI#315]) - -- Update client to version v5.1.134 ([CLI#316]) - -**FIXED** -- Cycloid CLI now correctly uses CY_API_KEY env var instead of CY_API_TOKEN. ([CLI#299]) -*Old env vars still works, TOKEN and CY_API_TOKEN will be deprecated on the future.* -- Fixed bugs related to the API update ([CLI#313]) -*CLI should behave as expected now.* -- Fixed an issue where stackforms vars input precedence was not respected on certain types ([CLI#313]) - -- Fixed inconsistency on --org and CY_ORG parameter ([CLI#313]) - -### Other -**ADDED** -- Added linter for the CLI code ([CLI#285]) - -- Added go code formatter ([CLI#286]) - - -[CLI#313]: https://github.com/cycloidio/cycloid-cli/pull/313 -[CLI#290]: https://github.com/cycloidio/cycloid-cli/pull/290 -[CLI#291]: https://github.com/cycloidio/cycloid-cli/pull/291 -[CLI#292]: https://github.com/cycloidio/cycloid-cli/pull/292 -[CLI#293]: https://github.com/cycloidio/cycloid-cli/pull/293 -[CLI#294]: https://github.com/cycloidio/cycloid-cli/pull/294 -[CLI#295]: https://github.com/cycloidio/cycloid-cli/pull/295 -[CLI#296]: https://github.com/cycloidio/cycloid-cli/pull/296 -[CLI#297]: https://github.com/cycloidio/cycloid-cli/pull/297 -[CLI#302]: https://github.com/cycloidio/cycloid-cli/pull/302 -[CLI#303]: https://github.com/cycloidio/cycloid-cli/pull/303 -[CLI#304]: https://github.com/cycloidio/cycloid-cli/pull/304 -[CLI#305]: https://github.com/cycloidio/cycloid-cli/pull/305 -[CLI#306]: https://github.com/cycloidio/cycloid-cli/pull/306 -[CLI#308]: https://github.com/cycloidio/cycloid-cli/pull/308 -[CLI#309]: https://github.com/cycloidio/cycloid-cli/pull/309 -[CLI#311]: https://github.com/cycloidio/cycloid-cli/pull/311 -[CLI#312]: https://github.com/cycloidio/cycloid-cli/pull/312 -[CLI#314]: https://github.com/cycloidio/cycloid-cli/pull/314 -[CLI#315]: https://github.com/cycloidio/cycloid-cli/pull/315 -[CLI#316]: https://github.com/cycloidio/cycloid-cli/pull/316 -[CLI#299]: https://github.com/cycloidio/cycloid-cli/pull/299 -[CLI#285]: https://github.com/cycloidio/cycloid-cli/pull/285 -[CLI#286]: https://github.com/cycloidio/cycloid-cli/pull/286 diff --git a/changelog/releases/v5.1.144.md b/changelog/releases/v5.1.144.md deleted file mode 100644 index 14cf7dc1d..000000000 --- a/changelog/releases/v5.1.144.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v5.1.144] _2024-12-12_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- Add `cy event list` for listing events ([CLI#324]) -*This is a basic implementation of the getEvents API endpoint.* - -[CLI#324]: https://github.com/cycloidio/cycloid-cli/pull/324 diff --git a/changelog/releases/v5.1.151.md b/changelog/releases/v5.1.151.md deleted file mode 100644 index cf3b1022f..000000000 --- a/changelog/releases/v5.1.151.md +++ /dev/null @@ -1,18 +0,0 @@ -## [v5.1.151] _2025-03-03_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- cy project create-env / update-env --var (-V) flag now support explicit quoting of strings ([CLI#330]) -*Users can now use the -V `section.group.string="mystring"` to explicitely quote strings that could be misinterpreted as numbers or booleans.* -**FIXED** -- cy project create-env/update-env now correctly support all value update types with --var (-V) flag ([CLI#323]) -*Previously, all value would have been treated as string, we now support all native types (int, float, bool, string) and valid JSON (array and objects).* -- Fixed bugs in variable updates on environment update ([CLI#323]) - -- Fixed cy project get-env command returning null or invalid config. ([CLI#330]) - - -[CLI#330]: https://github.com/cycloidio/cycloid-cli/pull/330 -[CLI#323]: https://github.com/cycloidio/cycloid-cli/pull/323 diff --git a/changelog/releases/v5.1.153.md b/changelog/releases/v5.1.153.md deleted file mode 100644 index a1f43035a..000000000 --- a/changelog/releases/v5.1.153.md +++ /dev/null @@ -1,13 +0,0 @@ -## [v5.1.153] _2025-03-13_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- Add `cy pipeline last-used` command ([CLI#334]) -*This command allows you to list pipelines not triggered since x days.* -**CHANGED** -- `cy stack update` only manage visibility and team settings now. ([CLI#334]) -*This is on par with our stack visibility update. see changelog for Cycloid v5.1.153.* - -[CLI#334]: https://github.com/cycloidio/cycloid-cli/pull/334 diff --git a/changelog/releases/v5.1.9.md b/changelog/releases/v5.1.9.md deleted file mode 100644 index 8b9577601..000000000 --- a/changelog/releases/v5.1.9.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v5.1.9] _2024-07-15_ - -Cycloid CLI changelog: - -### Members -**CHANGED** -- Updated members commands to fit the recent endpoints changes. ([CLI#270]) - - -[CLI#270]: https://github.com/cycloidio/cycloid-cli/pull/270 diff --git a/changelog/releases/v6.10.24.md b/changelog/releases/v6.10.24.md deleted file mode 100644 index 440fa61a9..000000000 --- a/changelog/releases/v6.10.24.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v6.10.24] _2026-05-27_ - -Cycloid CLI changelog: - -### Environments -**ADDED** -- Org-scoped environment management commands: `cy environment`, `cy cloud-account`, and `cy environment-type` ([CLI#445]) -*New commands let you create, update, get, list, and delete org-level environments (decoupled from pipelines), attach cloud accounts, set environment types, and link/unlink environments to projects. Environment type on create is now optional — the API auto-detects it from canonical keywords.* - -[CLI#445]: https://github.com/cycloidio/cycloid-cli/pull/445 diff --git a/changelog/releases/v6.10.25.md b/changelog/releases/v6.10.25.md deleted file mode 100644 index 1f07e87bd..000000000 --- a/changelog/releases/v6.10.25.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v6.10.25] _2026-06-19_ - -Cycloid CLI changelog: - -### Authentication -**ADDED** -- OIDC group mapping commands: `cy oidc mappings`, `cy oidc settings`, and `cy oidc integration` ([CLI#452]) -*Manage OIDC-driven org access from the CLI: map IdP group claims to teams (`cy oidc mappings create|list|delete`), configure per-org reconciliation (`cy oidc settings set` — default role, oidc-managed mode, no-match policy), and set up the OIDC SSO integration including the groups claim name (`cy oidc integration set`).* - -[CLI#452]: https://github.com/cycloidio/cycloid-cli/pull/452 diff --git a/changelog/releases/v6.10.8.md b/changelog/releases/v6.10.8.md deleted file mode 100644 index fbf58f94a..000000000 --- a/changelog/releases/v6.10.8.md +++ /dev/null @@ -1,40 +0,0 @@ -## [v6.10.8] _2026-05-24_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- `cy plugin registry plugin version install --retry` to idempotently install a plugin version ([CLI#432]) -*Adds `--retry` flag to `cy plugin registry plugin version install`. When the install returns HTTP 409 (already installed), the command retries via the retry endpoint instead of failing. Safe for use in CI/CD pipelines.* -- `cy plugin registry plugin version publish --docker-image` to publish Docker image-based plugin versions ([CLI#426]) -*Adds `--docker-image` as a mutually exclusive alternative to `--url` in the version publish command. Accepts Docker image references (e.g. `registry:5000/org/plugin:tag`) that are not valid URIs, which the existing `--url` flag rejects.* -- `--stack-version` flag on `cy component create`, `cy component update`, `cy stacks get-config`, and `cy beta config interpolate` unifies stack version selection. Accepts a bare value (auto-detected as tag, branch, or commit hash) or an explicit type prefix: `tag:`, `branch:`, `sha:`. Shell completion is prefix-aware: `--stack-version=tag:` lists tags only. ([CLI#]) -*Bare values are resolved via ListStackVersions with precedence tag > branch > commit-hash-prefix (min 7 chars). Collisions between a tag and branch of the same name produce an actionable error with prefix-form hints. Prefixed values require no API call.* -- Added delete options (skip-hooks, ignore-config-files-err) to delete component/environment/project ([CLI#440]) - -- Added `cy organization licence activate` and `cy organization licence get` commands ([CLI#]) - -**CHANGED** -- `--output` now supports table column selection, jq expressions, and field extraction ([CLI#999]) -*Extended `--output` grammar: `table=col1,col2` selects specific columns; `table:noheader` suppresses the header row; `jq=` runs an arbitrary jq expression over the full JSON response; any other value (e.g. `canonical`, `owner.username`) extracts that field, one value per line. A `--jq ` flag was added as shorthand for `-o jq=`. Shell completion for `--output` is now model-aware: `cy project list -o ` suggests model fields alongside `json`, `yaml`, `table`, and `jq=`. Pipe pattern enabled: `cy project delete $(cy project list -o canonical)`. Default table columns are curated per resource (e.g. projects show Canonical, Name, Description, Owner).* -- Table output has been reworked: configurable borders, dynamic column expansion, and persistent default output format ([CLI#999]) -*The default table uses a kubectl-style separator (─) between header and rows. A new `table:border` option switches to nushell-style rounded-border grid (`╭─┬─╮`). On wide terminals, extra struct fields are shown beyond the curated defaults; as the terminal narrows, extra columns are dropped first while curated columns are preserved. Nested structs render as `{record N fields}` instead of the type name. A new `cy output set ` command persists the default output format to `~/.config/cycloid-cli/config.yaml`; `cy output get` shows the current effective value; `cy output reset` clears it. The `CY_OUTPUT` environment variable sets the default at runtime. Priority: `--jq` > `--output` > `CY_OUTPUT` > `cy output set` > `table`.* -- `cy beta plugin` commands promoted to top-level `cy plugin` ([CLI#426]) -*Plugin management commands are no longer experimental. `cy beta plugin` is removed; use `cy plugin` instead. This release also adds `cy plugin registry update`, `cy plugin registry plugin update`, `cy plugin component list/relation-set`, `cy plugin widget list/query`, and `cy plugin component widget list/query`.* -**DEPRECATED** -- `--stack-tag`, `--stack-branch`, and `--stack-commit-hash` flags are deprecated in favour of `--stack-version`. They remain functional and will be removed in the next major release. ([CLI#]) -*Migrate: --stack-tag=v1.0.0 → --stack-version=tag:v1.0.0 | --stack-branch=main → --stack-version=branch:main | --stack-commit-hash=abc123 → --stack-version=sha:abc123* -**FIXED** -- `cy plugin manager create` now fully registers the plugin manager instead of leaving an unresolvable pending invitation ([CLI#443]) -*Previously the create command sent the invitation-only request, producing an `invite_pending` row that the Plugin Manager never received and that could not be accepted or deleted. The command now sends `auto_register: true` so the Plugin Manager is contacted and activated in one step.* -### Pipelines Overview -**ADDED** -- `cy pipeline builds logs` and `cy pipeline job logs` to stream build event logs from past and in-progress builds ([CLI#426]) -*`builds logs --build-id ` dumps the event log for a specific build (or tails it with `--watch`). `job logs` fetches the latest build's logs for a job; with `--watch` it continuously tails future builds as they start, polling at a configurable `--poll-interval`.* - -[CLI#432]: https://github.com/cycloidio/cycloid-cli/pull/432 -[CLI#426]: https://github.com/cycloidio/cycloid-cli/pull/426 -[CLI#]: https://github.com/cycloidio/cycloid-cli/pull/ -[CLI#440]: https://github.com/cycloidio/cycloid-cli/pull/440 -[CLI#999]: https://github.com/cycloidio/cycloid-cli/pull/999 -[CLI#443]: https://github.com/cycloidio/cycloid-cli/pull/443 diff --git a/changelog/releases/v6.2.112.md b/changelog/releases/v6.2.112.md deleted file mode 100644 index b7a186cca..000000000 --- a/changelog/releases/v6.2.112.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v6.2.112] _2025-09-23_ - -Cycloid CLI changelog: - -### CLI -**INTERNAL** -- Add support for new component creation logic (creation + config split + PUT) ([CLI#385]) - - -[CLI#385]: https://github.com/cycloidio/cycloid-cli/pull/385 diff --git a/changelog/releases/v6.2.43.md b/changelog/releases/v6.2.43.md deleted file mode 100644 index ca66b759f..000000000 --- a/changelog/releases/v6.2.43.md +++ /dev/null @@ -1,43 +0,0 @@ -## [v6.2.43] _2025-07-23_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- Add completion for --color and --icon flags ([CLI#354]) - -- Added flag completion to the CLI ([CLI#356]) -*The CLI is now able to complete most arguments, fetching resources from the API still requires auth.* -- Add `cy api-key create` command ([CLI#360]) - -- Add `cy credential create --update` flag ([CLI#367]) - -**BREAKING** -- Pipeline subcommand are renamed to follow convention ([CLI#358]) -*build related command are now in the subcommand `cy pipeline build` and jobs are in `cy pipeline jobs` subcommand.* -**CHANGED** -- Make the CLI pick a random icon/color with sane defaults for envs if not set by the user. ([CLI#354]) - -- cy credential get|delete accept now cred canonicals as argument. ([CLI#367]) -*flags have the priority on precedence.* -- Update client to version v6.2.43 ([CLI#372]) - -**FIXED** -- Project and env updates will persist current icon / color instead of using the default one if not set by the user. ([CLI#354]) - -- Update pipelines commands to work with components layer ([CLI#358]) - -- Fixed CLI version ([CLI#369]) - -**REMOVED** -- Removed the version warning on each commands ([CLI#364]) - - -[CLI#354]: https://github.com/cycloidio/cycloid-cli/pull/354 -[CLI#356]: https://github.com/cycloidio/cycloid-cli/pull/356 -[CLI#360]: https://github.com/cycloidio/cycloid-cli/pull/360 -[CLI#367]: https://github.com/cycloidio/cycloid-cli/pull/367 -[CLI#358]: https://github.com/cycloidio/cycloid-cli/pull/358 -[CLI#372]: https://github.com/cycloidio/cycloid-cli/pull/372 -[CLI#369]: https://github.com/cycloidio/cycloid-cli/pull/369 -[CLI#364]: https://github.com/cycloidio/cycloid-cli/pull/364 diff --git a/changelog/releases/v6.2.62.md b/changelog/releases/v6.2.62.md deleted file mode 100644 index a1cea1d34..000000000 --- a/changelog/releases/v6.2.62.md +++ /dev/null @@ -1,34 +0,0 @@ -## [v6.2.62] _2025-08-21_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- Add `cy stack create` ([CLI#373]) -*This command allow you to create a stack with our Blueprint feature: https://docs.cycloid.io/reference/stack-blueprint/#using-a-blueprint* -**CHANGED** -- Move child org creation to the `cy org create --name --parent-canonical ` ([CLI#375]) -*This will give more clarity to the child org creation process. Deprecating the `cy org create-child` command.* -- `cy credential create` now requires the `--canonical` flag ([CLI#380]) - -- Update client to version v6.2.62 ([CLI#381]) - -**DEPRECATED** -- `cy org create-child` command is officially deprecated, replaced by `cy org create --name --parent-canonical ` ([CLI#375]) -*This command was confusing and non standard.* -**FIXED** -- `cy comp create --var`: Fixed trailling quote when forcing string type with single quotes `'` ([CLI#377]) - -- Fixed a bug where create commands with `--update` flag would misbehave on API error ([CLI#382]) -*In some cases, like a 5xx from the API, the CLI would try to update a non-existent resource and fail to report the correct error message.* -**INTERNAL** -- Removed payload validation ([CLI#378]) - - -[CLI#373]: https://github.com/cycloidio/cycloid-cli/pull/373 -[CLI#375]: https://github.com/cycloidio/cycloid-cli/pull/375 -[CLI#380]: https://github.com/cycloidio/cycloid-cli/pull/380 -[CLI#381]: https://github.com/cycloidio/cycloid-cli/pull/381 -[CLI#377]: https://github.com/cycloidio/cycloid-cli/pull/377 -[CLI#382]: https://github.com/cycloidio/cycloid-cli/pull/382 -[CLI#378]: https://github.com/cycloidio/cycloid-cli/pull/378 diff --git a/changelog/releases/v6.3.3.md b/changelog/releases/v6.3.3.md deleted file mode 100644 index 283279e62..000000000 --- a/changelog/releases/v6.3.3.md +++ /dev/null @@ -1,13 +0,0 @@ -## [v6.3.3] _2025-09-29_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v6.3.2 ([CLI#388]) - -- Update client to version v6.3.3 ([CLI#390]) - - -[CLI#388]: https://github.com/cycloidio/cycloid-cli/pull/388 -[CLI#390]: https://github.com/cycloidio/cycloid-cli/pull/390 diff --git a/changelog/releases/v6.4.1.md b/changelog/releases/v6.4.1.md deleted file mode 100644 index 4f571ac6a..000000000 --- a/changelog/releases/v6.4.1.md +++ /dev/null @@ -1,13 +0,0 @@ -## [v6.4.1] _2025-10-03_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v6.3.9 ([CLI#391]) - -- Update client to version v6.4.1 ([CLI#393]) - - -[CLI#391]: https://github.com/cycloidio/cycloid-cli/pull/391 -[CLI#393]: https://github.com/cycloidio/cycloid-cli/pull/393 diff --git a/changelog/releases/v6.7.16.md b/changelog/releases/v6.7.16.md deleted file mode 100644 index 940ca1276..000000000 --- a/changelog/releases/v6.7.16.md +++ /dev/null @@ -1,14 +0,0 @@ -## [v6.7.16] _2026-02-03_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- Add support for common proxy env vars (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`) ([CLI#405]) - -**CHANGED** -- Update client to version v6.7.16 ([CLI#403]) - - -[CLI#405]: https://github.com/cycloidio/cycloid-cli/pull/405 -[CLI#403]: https://github.com/cycloidio/cycloid-cli/pull/403 diff --git a/changelog/releases/v6.7.2.md b/changelog/releases/v6.7.2.md deleted file mode 100644 index 28fda0d6b..000000000 --- a/changelog/releases/v6.7.2.md +++ /dev/null @@ -1,24 +0,0 @@ -## [v6.7.2] _2026-01-14_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- Add cycloid uri schema commands `cy get` and `cy uri interpolate` ([CLI#383]) -*Those commands allows you to fetch and inject values from Cycloid in files.* -**CHANGED** -- Update user registration and login to support new API schema ([CLI#]) -*User registration now uses full_name instead of separate given_name/family_name fields. Username is now optional. Login now only accepts email (username parameter removed).* -- Update client to version v6.7.2 ([CLI#401]) - -**FIXED** -- Make interpolator output consistent regarding trailling newlines ([CLI#395]) -*All output will end with a newline.* -- Fixed cases where component update would error on non-configured components ([CLI#396]) - - -[CLI#383]: https://github.com/cycloidio/cycloid-cli/pull/383 -[CLI#]: https://github.com/cycloidio/cycloid-cli/pull/ -[CLI#401]: https://github.com/cycloidio/cycloid-cli/pull/401 -[CLI#395]: https://github.com/cycloidio/cycloid-cli/pull/395 -[CLI#396]: https://github.com/cycloidio/cycloid-cli/pull/396 diff --git a/changelog/releases/v6.7.3.md b/changelog/releases/v6.7.3.md deleted file mode 100644 index 32cd533c3..000000000 --- a/changelog/releases/v6.7.3.md +++ /dev/null @@ -1,14 +0,0 @@ -## [v6.7.3] _2026-01-15_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- Add support for stack versioning ([CLI#399]) - -**FIXED** -- Fixed component version inference ([CLI#402]) -*Version by default will fallback to branch unless specified.* - -[CLI#399]: https://github.com/cycloidio/cycloid-cli/pull/399 -[CLI#402]: https://github.com/cycloidio/cycloid-cli/pull/402 diff --git a/changelog/releases/v6.7.38.md b/changelog/releases/v6.7.38.md deleted file mode 100644 index b47a70f37..000000000 --- a/changelog/releases/v6.7.38.md +++ /dev/null @@ -1,10 +0,0 @@ -## [v6.7.38] _2026-02-05_ - -Cycloid CLI changelog: - -### CLI -**CHANGED** -- Update client to version v6.7.38 ([CLI#406]) - - -[CLI#406]: https://github.com/cycloidio/cycloid-cli/pull/406 diff --git a/changelog/releases/v6.7.48.md b/changelog/releases/v6.7.48.md deleted file mode 100644 index 10a110aa7..000000000 --- a/changelog/releases/v6.7.48.md +++ /dev/null @@ -1,14 +0,0 @@ -## [v6.7.48] _2026-02-19_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- Update teams commands and added member management commands ([CLI#411]) -*Lookup `cy team --help` and `cy team members --help` commands* -**CHANGED** -- Update client to version v6.7.48 ([CLI#407]) - - -[CLI#411]: https://github.com/cycloidio/cycloid-cli/pull/411 -[CLI#407]: https://github.com/cycloidio/cycloid-cli/pull/407 diff --git a/changelog/releases/v6.7.57.md b/changelog/releases/v6.7.57.md deleted file mode 100644 index 1bd43b9de..000000000 --- a/changelog/releases/v6.7.57.md +++ /dev/null @@ -1,13 +0,0 @@ -## [v6.7.57] _2026-02-27_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- Add `cy organization subscription update` command to register a subscription to an organization. ([CLI#410]) - -**CHANGED** -- Update client to version v6.7.57 ([CLI#410]) - - -[CLI#410]: https://github.com/cycloidio/cycloid-cli/pull/410 diff --git a/changelog/releases/v6.8.23.md b/changelog/releases/v6.8.23.md deleted file mode 100644 index 0461e46be..000000000 --- a/changelog/releases/v6.8.23.md +++ /dev/null @@ -1,40 +0,0 @@ -## [v6.8.23] _2026-04-01_ - -Cycloid CLI changelog: - -### CLI -**ADDED** -- `debug` verbosity level will now dump the content of the HTTP requests and response with the API ([CLI#418]) -*This is usefull to debug errors with the backend. Be warned that playload -may include sensitive values for e.g. credentials. Be careful in uses in CI/CD. -* -- `cy roles update` and `cy roles create --update` commands ([CLI#423]) -*Add also a `cy role` alias* -- **Beta:** `cy pipeline build trigger --watch` streams Concourse build events with human-readable output, optional raw JSON via `--output json`, and debug-verbosity event detail ([CLI#420]) -*Beta feature: watch polls until the build finishes while printing formatted SSE lines (or NDJSON when `--output json`). -Includes default console deep link (`https://console.cycloid.io`, overridable with `CY_CONSOLE_URL`), stderr hints for Ctrl+C (first aborts the build, second exits watch with code 130), `--watch-cancel-on-timeout`, and `--job` required on trigger. -Set `--verbosity debug` for verbose watch output. See `docs/pipeline-build-watch-output.md`. -* -- Add `--update` to `organization create`, `config-repo create`, `catalog-repo create`, and `stack create`; fix `team create --update` when only `--name` is set ([CLI#420]) -*Catalog-repo create accepts optional `--canonical` for identity. AGENTS.md and CLAUDE.md require shipping tests with each feature. E2E and docs/testing.md cover upsert flows.* -- Project and environment create can infer missing canonicals from `--name` when appropriate ([CLI#420]) - -**CHANGED** -- API errors may include the request path and a raw response body fallback when JSON error parsing fails ([CLI#420]) - -- Environment create picks a random theme color when `--color` is left at the default ([CLI#420]) - -- Regenerate API client models; `client/version` set to v6.8.22 ([CLI#420]) - -**FIXED** -- Improve help examples for pipeline job commands and `stack forms validate` ([CLI#420]) - -- `cy credentials create --update` resolves an existing credential by path/name instead of always attempting a create ([CLI#420]) - -**INTERNAL** -- Refactor middleware out of go-swagger client ([CLI#418]) - - -[CLI#418]: https://github.com/cycloidio/cycloid-cli/pull/418 -[CLI#423]: https://github.com/cycloidio/cycloid-cli/pull/423 -[CLI#420]: https://github.com/cycloidio/cycloid-cli/pull/420 diff --git a/changelog/releases/v6.9.9.md b/changelog/releases/v6.9.9.md deleted file mode 100644 index fb0b3d627..000000000 --- a/changelog/releases/v6.9.9.md +++ /dev/null @@ -1,34 +0,0 @@ -## [v6.9.9] _2026-05-01_ - -Cycloid CLI changelog: - -### API Keys -**ADDED** -- `api-key create --recreate` flag to delete-and-recreate an existing key in one step ([CLI#999]) -*Without `--recreate`, creating an API key that already exists now fails with an explicit error instead of silently succeeding or failing. With `--recreate`, the existing key is deleted and a new one is created with the provided settings. Useful for rotating keys in automation.* -### CLI -**CHANGED** -- get/delete commands now accept resource canonicals as positional arguments ([CLI#999]) -*Affected commands: `catalog-repo get/delete/refresh`, `config-repo get/delete`, `api-key get/delete`, `project get/delete`. The previous `--canonical` / `--project` flags are still accepted for backward compatibility. Example: `cy catalog-repo get my-repo` instead of `cy catalog-repo get --canonical my-repo`. Multiple args are supported: `cy catalog-repo delete repo-a repo-b`.* -- Shell completion improvements across all normalized commands ([CLI#999]) -*get/delete commands now complete resource canonicals from the API. `stack forms validate` completion is restricted to `.yml` / `.yaml` files only. `members` command gains `member` alias; `events` `e` alias removed (was conflicting with `environments`).* -**FIXED** -- `cy component update` without `--stack-branch`/`--stack-tag`/`--stack-commit-hash` no longer resets the stack version to the catalog default ([CLI#427]) - -**REMOVED** -- `infra-policy` commands removed (get, list, create, update, delete, validate) ([CLI#999]) -*The infra-policy feature has been dropped from the CLI. Remove any scripts using `cy infra-policy` commands.* -### Service Catalog -**ADDED** -- `catalog-repo refresh` now accepts multiple repository canonicals at once ([CLI#999]) -*Refresh several catalog repositories in a single command: `cy catalog-repo refresh repo-a repo-b repo-c`. Previously only one canonical was accepted.* -### StackForms -**CHANGED** -- `stack forms validate` accepts multiple files and defaults to `.forms.yml` / `.forms.yaml` in the current directory ([CLI#999]) -*Running `cy stack forms validate` with no arguments now auto-discovers `.forms.yml` or `.forms.yaml` in the current directory. Multiple files can be validated at once: `cy stack forms validate .forms.yml other/.forms.yaml`. The command now exits with a non-zero status code when validation errors are found, making it usable in CI pipelines.* -**FIXED** -- `stack get-config ` positional argument now works correctly ([CLI#999]) -*Passing the use-case as a positional argument (e.g. `cy stack get-config -p proj -e env -c comp my-usecase`) was silently ignored and produced a "missing use-case argument" error. The `--use-case` flag is still supported.* - -[CLI#999]: https://github.com/cycloidio/cycloid-cli/pull/999 -[CLI#427]: https://github.com/cycloidio/cycloid-cli/pull/427 diff --git a/changelog/unreleased/.gitkeep b/changelog/unreleased/.gitkeep deleted file mode 100644 index e69de29bb..000000000 diff --git a/client/models/a_w_s_cloud_watch_logs.go b/client/models/a_w_s_cloud_watch_logs.go deleted file mode 100644 index 66bc89c39..000000000 --- a/client/models/a_w_s_cloud_watch_logs.go +++ /dev/null @@ -1,160 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AWSCloudWatchLogs Representation of AWS cloud watch logs for external backend. -// Must be matched with a credential of the "aws" type. -// -// swagger:model AWSCloudWatchLogs -type AWSCloudWatchLogs struct { - - // The AWS region where the resource exists - // - // Required: true - Region *string `json:"region"` -} - -// Engine gets the engine of this subtype -func (m *AWSCloudWatchLogs) Engine() string { - return "AWSCloudWatchLogs" -} - -// SetEngine sets the engine of this subtype -func (m *AWSCloudWatchLogs) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *AWSCloudWatchLogs) UnmarshalJSON(raw []byte) error { - var data struct { - - // The AWS region where the resource exists - // - // Required: true - Region *string `json:"region"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result AWSCloudWatchLogs - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.Region = data.Region - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m AWSCloudWatchLogs) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The AWS region where the resource exists - // - // Required: true - Region *string `json:"region"` - }{ - - Region: m.Region, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this a w s cloud watch logs -func (m *AWSCloudWatchLogs) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateRegion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AWSCloudWatchLogs) validateRegion(formats strfmt.Registry) error { - - if err := validate.Required("region", "body", m.Region); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this a w s cloud watch logs based on the context it is used -func (m *AWSCloudWatchLogs) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *AWSCloudWatchLogs) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AWSCloudWatchLogs) UnmarshalBinary(b []byte) error { - var res AWSCloudWatchLogs - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/a_w_s_infrastructure_resource_bucket.go b/client/models/a_w_s_infrastructure_resource_bucket.go deleted file mode 100644 index 0620a4265..000000000 --- a/client/models/a_w_s_infrastructure_resource_bucket.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// AWSInfrastructureResourceBucket AWS Infrastructure S3 bucket Resource -// -// This object contains the items described in the S3 bucket data type described in but it also contains its associated tags which are documented in the properties of this object definition. This object will contain a property named 'Tags' which is of the type defined by the schema definition '#/definitions/AWSTags' -// -// swagger:model AWSInfrastructureResourceBucket -type AWSInfrastructureResourceBucket any diff --git a/client/models/a_w_s_infrastructure_resource_d_b_instance.go b/client/models/a_w_s_infrastructure_resource_d_b_instance.go deleted file mode 100644 index 0fb3f6d10..000000000 --- a/client/models/a_w_s_infrastructure_resource_d_b_instance.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// AWSInfrastructureResourceDBInstance AWS Infrastructure RDS DB instance Resource -// -// This object contains the items described in the RDS DB instance data type described in https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DBInstance.html but it also contains its associated tags which are documented in the properties of this object definition. This object will contain a property named 'Tags' which is of the type defined by the schema definition '#/definitions/AWSTags' -// -// swagger:model AWSInfrastructureResourceDBInstance -type AWSInfrastructureResourceDBInstance any diff --git a/client/models/a_w_s_infrastructure_resource_elasticache_cluster.go b/client/models/a_w_s_infrastructure_resource_elasticache_cluster.go deleted file mode 100644 index cbae1c23b..000000000 --- a/client/models/a_w_s_infrastructure_resource_elasticache_cluster.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// AWSInfrastructureResourceElasticacheCluster AWS Infrastructure Elasticache cluster Resource -// -// This object contains the items described in the ElastiCache cluster data type described in https://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_CacheCluster.html but it also contains its associated tags which are documented in the properties of this object definition. This object will contain a property named 'Tags' which is of the type defined by the schema definition '#/definitions/AWSTags' -// -// swagger:model AWSInfrastructureResourceElasticacheCluster -type AWSInfrastructureResourceElasticacheCluster any diff --git a/client/models/a_w_s_infrastructure_resource_image.go b/client/models/a_w_s_infrastructure_resource_image.go deleted file mode 100644 index fb5828a03..000000000 --- a/client/models/a_w_s_infrastructure_resource_image.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// AWSInfrastructureResourceImage AWS Infrastructure image Resource -// -// This object contains the items described in the image data type described in https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Image.html Tags property is set, for guaranteeing that the respond will always have the property of the type array, not allowing null in case that the resource doesn't have any, hence an empty array is used in such case. This object will contain a property named 'Tags' which is of the type defined by the schema definition '#/definitions/AWSTags' -// -// swagger:model AWSInfrastructureResourceImage -type AWSInfrastructureResourceImage any diff --git a/client/models/a_w_s_infrastructure_resource_instance.go b/client/models/a_w_s_infrastructure_resource_instance.go deleted file mode 100644 index fc37eada5..000000000 --- a/client/models/a_w_s_infrastructure_resource_instance.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// AWSInfrastructureResourceInstance AWS Infrastructure Instance Resource -// -// This object contains the items described in the instance data type described in https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Instance.html Tags property is set, for guaranteeing that the respond will always have the property of the type array, not allowing null in case that the resource doesn't have any, hence an empty array is used in such case. This object will contain a property named 'Tags' which is of the type defined by the schema definition '#/definitions/AWSTags' -// -// swagger:model AWSInfrastructureResourceInstance -type AWSInfrastructureResourceInstance any diff --git a/client/models/a_w_s_infrastructure_resource_load_balancer_v1.go b/client/models/a_w_s_infrastructure_resource_load_balancer_v1.go deleted file mode 100644 index c2f857088..000000000 --- a/client/models/a_w_s_infrastructure_resource_load_balancer_v1.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// AWSInfrastructureResourceLoadBalancerV1 AWS Infrastructure load balancer (ELB) Resource -// -// This object contains the items described in the load balancer (ELB) data type described in https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_LoadBalancerDescription.html but it also contains its associated tags which are documented in the properties of this object definition. This object will contain a property named 'Tags' which is of the type defined by the schema definition '#/definitions/AWSTags' -// -// swagger:model AWSInfrastructureResourceLoadBalancerV1 -type AWSInfrastructureResourceLoadBalancerV1 any diff --git a/client/models/a_w_s_infrastructure_resource_load_balancer_v2.go b/client/models/a_w_s_infrastructure_resource_load_balancer_v2.go deleted file mode 100644 index 13eba48ee..000000000 --- a/client/models/a_w_s_infrastructure_resource_load_balancer_v2.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// AWSInfrastructureResourceLoadBalancerV2 AWS Infrastructure load balancer (ELB v2 or a.k.a ALB) Resource -// -// This object contains the items described in the load balancer (ELB v2 or a.k.a ALB) data type described in https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_LoadBalancer.html but it also contains its associated tags which are documented in the properties of this object definition. This object will contain a property named 'Tags' which is of the type defined by the schema definition '#/definitions/AWSTags' -// -// swagger:model AWSInfrastructureResourceLoadBalancerV2 -type AWSInfrastructureResourceLoadBalancerV2 any diff --git a/client/models/a_w_s_infrastructure_resource_security_group.go b/client/models/a_w_s_infrastructure_resource_security_group.go deleted file mode 100644 index f188a7d0d..000000000 --- a/client/models/a_w_s_infrastructure_resource_security_group.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// AWSInfrastructureResourceSecurityGroup AWS Infrastructure security group Resource -// -// This object contains the items described in the security group data type described in https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SecurityGroup.html Tags property is set, for guaranteeing that the respond will always have the property of the type array, not allowing null in case that the resource doesn't have any, hence an empty array is used in such case. This object will contain a property named 'Tags' which is of the type defined by the schema definition '#/definitions/AWSTags' -// -// swagger:model AWSInfrastructureResourceSecurityGroup -type AWSInfrastructureResourceSecurityGroup any diff --git a/client/models/a_w_s_infrastructure_resource_snapshot.go b/client/models/a_w_s_infrastructure_resource_snapshot.go deleted file mode 100644 index ae3ac1698..000000000 --- a/client/models/a_w_s_infrastructure_resource_snapshot.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// AWSInfrastructureResourceSnapshot AWS Infrastructure snapshot Resource -// -// This object contains the items described in the snapshot data type described in https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Snapshot.html Tags property is set, for guaranteeing that the respond will always have the property of the type array, not allowing null in case that the resource doesn't have any, hence an empty array is used in such case. This object will contain a property named 'Tags' which is of the type defined by the schema definition '#/definitions/AWSTags' -// -// swagger:model AWSInfrastructureResourceSnapshot -type AWSInfrastructureResourceSnapshot any diff --git a/client/models/a_w_s_infrastructure_resource_subnet.go b/client/models/a_w_s_infrastructure_resource_subnet.go deleted file mode 100644 index 14d7b9d82..000000000 --- a/client/models/a_w_s_infrastructure_resource_subnet.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// AWSInfrastructureResourceSubnet AWS Infrastructure subnet Resource -// -// This object contains the items described in the subnet data type described in https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Subnet.html Tags property is set, for guaranteeing that the respond will always have the property of the type array, not allowing null in case that the resource doesn't have any, hence an empty array is used in such case. This object will contain a property named 'Tags' which is of the type defined by the schema definition '#/definitions/AWSTags' -// -// swagger:model AWSInfrastructureResourceSubnet -type AWSInfrastructureResourceSubnet any diff --git a/client/models/a_w_s_infrastructure_resource_v_p_c.go b/client/models/a_w_s_infrastructure_resource_v_p_c.go deleted file mode 100644 index b3229f479..000000000 --- a/client/models/a_w_s_infrastructure_resource_v_p_c.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// AWSInfrastructureResourceVPC AWS Infrastructure VPC Resource -// -// This object contains the items described in the VPC data type described in https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Vpc.html Tags property is set, for guaranteeing that the respond will always have the property of the type array, not allowing null in case that the resource doesn't have any, hence an empty array is used in such case. This object will contain a property named 'Tags' which is of the type defined by the schema definition '#/definitions/AWSTags' -// -// swagger:model AWSInfrastructureResourceVPC -type AWSInfrastructureResourceVPC any diff --git a/client/models/a_w_s_infrastructure_resource_volume.go b/client/models/a_w_s_infrastructure_resource_volume.go deleted file mode 100644 index 7d5f75e5f..000000000 --- a/client/models/a_w_s_infrastructure_resource_volume.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// AWSInfrastructureResourceVolume AWS Infrastructure volume Resource -// -// This object contains the items described in the volume data type described in https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Volume.html Tags property is set, for guaranteeing that the respond will always have the property of the type array, not allowing null in case that the resource doesn't have any, hence an empty array is used in such case. This object will contain a property named 'Tags' which is of the type defined by the schema definition '#/definitions/AWSTags' -// -// swagger:model AWSInfrastructureResourceVolume -type AWSInfrastructureResourceVolume any diff --git a/client/models/a_w_s_infrastructure_resources_aggregation.go b/client/models/a_w_s_infrastructure_resources_aggregation.go deleted file mode 100644 index c481b6288..000000000 --- a/client/models/a_w_s_infrastructure_resources_aggregation.go +++ /dev/null @@ -1,970 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// AWSInfrastructureResourcesAggregation AWS Infrastructure Resources Aggregation -// -// MinProperties: 1 -// MaxProperties: 12 -// -// swagger:model AWSInfrastructureResourcesAggregation -type AWSInfrastructureResourcesAggregation struct { - - // buckets - Buckets *InfrastructureResourcesAggregationItem `json:"buckets,omitempty"` - - // cache clusters - CacheClusters *InfrastructureResourcesAggregationItem `json:"cache_clusters,omitempty"` - - // db instances - DbInstances *InfrastructureResourcesAggregationItem `json:"db_instances,omitempty"` - - // images - Images *InfrastructureResourcesAggregationItem `json:"images,omitempty"` - - // instances - Instances *InfrastructureResourcesAggregationItem `json:"instances,omitempty"` - - // load balancers v1 - LoadBalancersV1 *InfrastructureResourcesAggregationItem `json:"load_balancers_v1,omitempty"` - - // load balancers v2 - LoadBalancersV2 *InfrastructureResourcesAggregationItem `json:"load_balancers_v2,omitempty"` - - // security groups - SecurityGroups *InfrastructureResourcesAggregationItem `json:"security_groups,omitempty"` - - // snapshots - Snapshots *InfrastructureResourcesAggregationItem `json:"snapshots,omitempty"` - - // subnets - Subnets *InfrastructureResourcesAggregationItem `json:"subnets,omitempty"` - - // volumes - Volumes *InfrastructureResourcesAggregationItem `json:"volumes,omitempty"` - - // vpcs - Vpcs *InfrastructureResourcesAggregationItem `json:"vpcs,omitempty"` - - // a w s infrastructure resources aggregation additional properties - AWSInfrastructureResourcesAggregationAdditionalProperties map[string]any `json:"-"` -} - -// UnmarshalJSON unmarshals this object with additional properties from JSON -func (m *AWSInfrastructureResourcesAggregation) UnmarshalJSON(data []byte) error { - // stage 1, bind the properties - var stage1 struct { - - // buckets - Buckets *InfrastructureResourcesAggregationItem `json:"buckets,omitempty"` - - // cache clusters - CacheClusters *InfrastructureResourcesAggregationItem `json:"cache_clusters,omitempty"` - - // db instances - DbInstances *InfrastructureResourcesAggregationItem `json:"db_instances,omitempty"` - - // images - Images *InfrastructureResourcesAggregationItem `json:"images,omitempty"` - - // instances - Instances *InfrastructureResourcesAggregationItem `json:"instances,omitempty"` - - // load balancers v1 - LoadBalancersV1 *InfrastructureResourcesAggregationItem `json:"load_balancers_v1,omitempty"` - - // load balancers v2 - LoadBalancersV2 *InfrastructureResourcesAggregationItem `json:"load_balancers_v2,omitempty"` - - // security groups - SecurityGroups *InfrastructureResourcesAggregationItem `json:"security_groups,omitempty"` - - // snapshots - Snapshots *InfrastructureResourcesAggregationItem `json:"snapshots,omitempty"` - - // subnets - Subnets *InfrastructureResourcesAggregationItem `json:"subnets,omitempty"` - - // volumes - Volumes *InfrastructureResourcesAggregationItem `json:"volumes,omitempty"` - - // vpcs - Vpcs *InfrastructureResourcesAggregationItem `json:"vpcs,omitempty"` - } - if err := json.Unmarshal(data, &stage1); err != nil { - return err - } - var rcv AWSInfrastructureResourcesAggregation - - rcv.Buckets = stage1.Buckets - rcv.CacheClusters = stage1.CacheClusters - rcv.DbInstances = stage1.DbInstances - rcv.Images = stage1.Images - rcv.Instances = stage1.Instances - rcv.LoadBalancersV1 = stage1.LoadBalancersV1 - rcv.LoadBalancersV2 = stage1.LoadBalancersV2 - rcv.SecurityGroups = stage1.SecurityGroups - rcv.Snapshots = stage1.Snapshots - rcv.Subnets = stage1.Subnets - rcv.Volumes = stage1.Volumes - rcv.Vpcs = stage1.Vpcs - *m = rcv - - // stage 2, remove properties and add to map - stage2 := make(map[string]json.RawMessage) - if err := json.Unmarshal(data, &stage2); err != nil { - return err - } - - delete(stage2, "buckets") - delete(stage2, "cache_clusters") - delete(stage2, "db_instances") - delete(stage2, "images") - delete(stage2, "instances") - delete(stage2, "load_balancers_v1") - delete(stage2, "load_balancers_v2") - delete(stage2, "security_groups") - delete(stage2, "snapshots") - delete(stage2, "subnets") - delete(stage2, "volumes") - delete(stage2, "vpcs") - // stage 3, add additional properties values - if len(stage2) > 0 { - result := make(map[string]any) - for k, v := range stage2 { - var toadd any - if err := json.Unmarshal(v, &toadd); err != nil { - return err - } - result[k] = toadd - } - m.AWSInfrastructureResourcesAggregationAdditionalProperties = result - } - - return nil -} - -// MarshalJSON marshals this object with additional properties into a JSON object -func (m AWSInfrastructureResourcesAggregation) MarshalJSON() ([]byte, error) { - var stage1 struct { - - // buckets - Buckets *InfrastructureResourcesAggregationItem `json:"buckets,omitempty"` - - // cache clusters - CacheClusters *InfrastructureResourcesAggregationItem `json:"cache_clusters,omitempty"` - - // db instances - DbInstances *InfrastructureResourcesAggregationItem `json:"db_instances,omitempty"` - - // images - Images *InfrastructureResourcesAggregationItem `json:"images,omitempty"` - - // instances - Instances *InfrastructureResourcesAggregationItem `json:"instances,omitempty"` - - // load balancers v1 - LoadBalancersV1 *InfrastructureResourcesAggregationItem `json:"load_balancers_v1,omitempty"` - - // load balancers v2 - LoadBalancersV2 *InfrastructureResourcesAggregationItem `json:"load_balancers_v2,omitempty"` - - // security groups - SecurityGroups *InfrastructureResourcesAggregationItem `json:"security_groups,omitempty"` - - // snapshots - Snapshots *InfrastructureResourcesAggregationItem `json:"snapshots,omitempty"` - - // subnets - Subnets *InfrastructureResourcesAggregationItem `json:"subnets,omitempty"` - - // volumes - Volumes *InfrastructureResourcesAggregationItem `json:"volumes,omitempty"` - - // vpcs - Vpcs *InfrastructureResourcesAggregationItem `json:"vpcs,omitempty"` - } - - stage1.Buckets = m.Buckets - stage1.CacheClusters = m.CacheClusters - stage1.DbInstances = m.DbInstances - stage1.Images = m.Images - stage1.Instances = m.Instances - stage1.LoadBalancersV1 = m.LoadBalancersV1 - stage1.LoadBalancersV2 = m.LoadBalancersV2 - stage1.SecurityGroups = m.SecurityGroups - stage1.Snapshots = m.Snapshots - stage1.Subnets = m.Subnets - stage1.Volumes = m.Volumes - stage1.Vpcs = m.Vpcs - - // make JSON object for known properties - props, err := json.Marshal(stage1) - if err != nil { - return nil, err - } - - if len(m.AWSInfrastructureResourcesAggregationAdditionalProperties) == 0 { // no additional properties - return props, nil - } - - // make JSON object for the additional properties - additional, err := json.Marshal(m.AWSInfrastructureResourcesAggregationAdditionalProperties) - if err != nil { - return nil, err - } - - if len(props) < 3 { // "{}": only additional properties - return additional, nil - } - - // concatenate the 2 objects - return swag.ConcatJSON(props, additional), nil -} - -// Validate validates this a w s infrastructure resources aggregation -func (m *AWSInfrastructureResourcesAggregation) Validate(formats strfmt.Registry) error { - var res []error - - // short circuits minProperties > 0 - if m == nil { - return errors.TooFewProperties("", "body", 1) - } - - props := make(map[string]json.RawMessage, 12+10) - j, err := swag.WriteJSON(m) - if err != nil { - return err - } - - if err = swag.ReadJSON(j, &props); err != nil { - return err - } - - nprops := len(props) - - // minProperties: 1 - if nprops < 1 { - return errors.TooFewProperties("", "body", 1) - } - - // maxProperties: 12 - if nprops > 12 { - return errors.TooManyProperties("", "body", 12) - } - - if err := m.validateBuckets(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCacheClusters(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDbInstances(formats); err != nil { - res = append(res, err) - } - - if err := m.validateImages(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInstances(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLoadBalancersV1(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLoadBalancersV2(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSecurityGroups(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSnapshots(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSubnets(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVolumes(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVpcs(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) validateBuckets(formats strfmt.Registry) error { - if swag.IsZero(m.Buckets) { // not required - return nil - } - - if m.Buckets != nil { - if err := m.Buckets.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("buckets") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("buckets") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) validateCacheClusters(formats strfmt.Registry) error { - if swag.IsZero(m.CacheClusters) { // not required - return nil - } - - if m.CacheClusters != nil { - if err := m.CacheClusters.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cache_clusters") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cache_clusters") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) validateDbInstances(formats strfmt.Registry) error { - if swag.IsZero(m.DbInstances) { // not required - return nil - } - - if m.DbInstances != nil { - if err := m.DbInstances.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("db_instances") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("db_instances") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) validateImages(formats strfmt.Registry) error { - if swag.IsZero(m.Images) { // not required - return nil - } - - if m.Images != nil { - if err := m.Images.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("images") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("images") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) validateInstances(formats strfmt.Registry) error { - if swag.IsZero(m.Instances) { // not required - return nil - } - - if m.Instances != nil { - if err := m.Instances.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("instances") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("instances") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) validateLoadBalancersV1(formats strfmt.Registry) error { - if swag.IsZero(m.LoadBalancersV1) { // not required - return nil - } - - if m.LoadBalancersV1 != nil { - if err := m.LoadBalancersV1.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("load_balancers_v1") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("load_balancers_v1") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) validateLoadBalancersV2(formats strfmt.Registry) error { - if swag.IsZero(m.LoadBalancersV2) { // not required - return nil - } - - if m.LoadBalancersV2 != nil { - if err := m.LoadBalancersV2.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("load_balancers_v2") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("load_balancers_v2") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) validateSecurityGroups(formats strfmt.Registry) error { - if swag.IsZero(m.SecurityGroups) { // not required - return nil - } - - if m.SecurityGroups != nil { - if err := m.SecurityGroups.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("security_groups") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("security_groups") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) validateSnapshots(formats strfmt.Registry) error { - if swag.IsZero(m.Snapshots) { // not required - return nil - } - - if m.Snapshots != nil { - if err := m.Snapshots.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("snapshots") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("snapshots") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) validateSubnets(formats strfmt.Registry) error { - if swag.IsZero(m.Subnets) { // not required - return nil - } - - if m.Subnets != nil { - if err := m.Subnets.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("subnets") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("subnets") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) validateVolumes(formats strfmt.Registry) error { - if swag.IsZero(m.Volumes) { // not required - return nil - } - - if m.Volumes != nil { - if err := m.Volumes.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("volumes") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("volumes") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) validateVpcs(formats strfmt.Registry) error { - if swag.IsZero(m.Vpcs) { // not required - return nil - } - - if m.Vpcs != nil { - if err := m.Vpcs.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("vpcs") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("vpcs") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this a w s infrastructure resources aggregation based on the context it is used -func (m *AWSInfrastructureResourcesAggregation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateBuckets(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateCacheClusters(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateDbInstances(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateImages(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateInstances(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateLoadBalancersV1(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateLoadBalancersV2(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateSecurityGroups(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateSnapshots(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateSubnets(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateVolumes(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateVpcs(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) contextValidateBuckets(ctx context.Context, formats strfmt.Registry) error { - - if m.Buckets != nil { - - if swag.IsZero(m.Buckets) { // not required - return nil - } - - if err := m.Buckets.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("buckets") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("buckets") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) contextValidateCacheClusters(ctx context.Context, formats strfmt.Registry) error { - - if m.CacheClusters != nil { - - if swag.IsZero(m.CacheClusters) { // not required - return nil - } - - if err := m.CacheClusters.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cache_clusters") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cache_clusters") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) contextValidateDbInstances(ctx context.Context, formats strfmt.Registry) error { - - if m.DbInstances != nil { - - if swag.IsZero(m.DbInstances) { // not required - return nil - } - - if err := m.DbInstances.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("db_instances") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("db_instances") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) contextValidateImages(ctx context.Context, formats strfmt.Registry) error { - - if m.Images != nil { - - if swag.IsZero(m.Images) { // not required - return nil - } - - if err := m.Images.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("images") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("images") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) contextValidateInstances(ctx context.Context, formats strfmt.Registry) error { - - if m.Instances != nil { - - if swag.IsZero(m.Instances) { // not required - return nil - } - - if err := m.Instances.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("instances") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("instances") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) contextValidateLoadBalancersV1(ctx context.Context, formats strfmt.Registry) error { - - if m.LoadBalancersV1 != nil { - - if swag.IsZero(m.LoadBalancersV1) { // not required - return nil - } - - if err := m.LoadBalancersV1.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("load_balancers_v1") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("load_balancers_v1") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) contextValidateLoadBalancersV2(ctx context.Context, formats strfmt.Registry) error { - - if m.LoadBalancersV2 != nil { - - if swag.IsZero(m.LoadBalancersV2) { // not required - return nil - } - - if err := m.LoadBalancersV2.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("load_balancers_v2") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("load_balancers_v2") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) contextValidateSecurityGroups(ctx context.Context, formats strfmt.Registry) error { - - if m.SecurityGroups != nil { - - if swag.IsZero(m.SecurityGroups) { // not required - return nil - } - - if err := m.SecurityGroups.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("security_groups") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("security_groups") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) contextValidateSnapshots(ctx context.Context, formats strfmt.Registry) error { - - if m.Snapshots != nil { - - if swag.IsZero(m.Snapshots) { // not required - return nil - } - - if err := m.Snapshots.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("snapshots") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("snapshots") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) contextValidateSubnets(ctx context.Context, formats strfmt.Registry) error { - - if m.Subnets != nil { - - if swag.IsZero(m.Subnets) { // not required - return nil - } - - if err := m.Subnets.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("subnets") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("subnets") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) contextValidateVolumes(ctx context.Context, formats strfmt.Registry) error { - - if m.Volumes != nil { - - if swag.IsZero(m.Volumes) { // not required - return nil - } - - if err := m.Volumes.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("volumes") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("volumes") - } - - return err - } - } - - return nil -} - -func (m *AWSInfrastructureResourcesAggregation) contextValidateVpcs(ctx context.Context, formats strfmt.Registry) error { - - if m.Vpcs != nil { - - if swag.IsZero(m.Vpcs) { // not required - return nil - } - - if err := m.Vpcs.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("vpcs") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("vpcs") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *AWSInfrastructureResourcesAggregation) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AWSInfrastructureResourcesAggregation) UnmarshalBinary(b []byte) error { - var res AWSInfrastructureResourcesAggregation - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/a_w_s_remote_t_f_state.go b/client/models/a_w_s_remote_t_f_state.go deleted file mode 100644 index 0ae920c24..000000000 --- a/client/models/a_w_s_remote_t_f_state.go +++ /dev/null @@ -1,255 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AWSRemoteTFState Deprecated. Please use AWSStorage. -// Representation of AWS remote tf state for external backend. -// Must be matched with a credential of the "aws" type. -// -// swagger:model AWSRemoteTFState -type AWSRemoteTFState struct { - - // The AWS bucket containing objects - // - // Required: true - Bucket *string `json:"bucket"` - - // A custom endpoint for the S3 API (default: s3.amazonaws.com) - // - Endpoint string `json:"endpoint,omitempty"` - - // The S3 Key uniquely identifies an object in a bucket, will - // be required if the EB is not the default one. - // - Key string `json:"key,omitempty"` - - // The AWS region where the resource exists - // - // Required: true - Region *string `json:"region"` - - // Always use path-style S3 URLs (https:/// instead of https://.) - // - S3ForcePathStyle bool `json:"s3_force_path_style,omitempty"` - - // Set this to `true` to not verify SSL certificates - // - SkipVerifySsl bool `json:"skip_verify_ssl,omitempty"` -} - -// Engine gets the engine of this subtype -func (m *AWSRemoteTFState) Engine() string { - return "AWSRemoteTFState" -} - -// SetEngine sets the engine of this subtype -func (m *AWSRemoteTFState) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *AWSRemoteTFState) UnmarshalJSON(raw []byte) error { - var data struct { - - // The AWS bucket containing objects - // - // Required: true - Bucket *string `json:"bucket"` - - // A custom endpoint for the S3 API (default: s3.amazonaws.com) - // - Endpoint string `json:"endpoint,omitempty"` - - // The S3 Key uniquely identifies an object in a bucket, will - // be required if the EB is not the default one. - // - Key string `json:"key,omitempty"` - - // The AWS region where the resource exists - // - // Required: true - Region *string `json:"region"` - - // Always use path-style S3 URLs (https:/// instead of https://.) - // - S3ForcePathStyle bool `json:"s3_force_path_style,omitempty"` - - // Set this to `true` to not verify SSL certificates - // - SkipVerifySsl bool `json:"skip_verify_ssl,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result AWSRemoteTFState - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.Bucket = data.Bucket - result.Endpoint = data.Endpoint - result.Key = data.Key - result.Region = data.Region - result.S3ForcePathStyle = data.S3ForcePathStyle - result.SkipVerifySsl = data.SkipVerifySsl - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m AWSRemoteTFState) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The AWS bucket containing objects - // - // Required: true - Bucket *string `json:"bucket"` - - // A custom endpoint for the S3 API (default: s3.amazonaws.com) - // - Endpoint string `json:"endpoint,omitempty"` - - // The S3 Key uniquely identifies an object in a bucket, will - // be required if the EB is not the default one. - // - Key string `json:"key,omitempty"` - - // The AWS region where the resource exists - // - // Required: true - Region *string `json:"region"` - - // Always use path-style S3 URLs (https:/// instead of https://.) - // - S3ForcePathStyle bool `json:"s3_force_path_style,omitempty"` - - // Set this to `true` to not verify SSL certificates - // - SkipVerifySsl bool `json:"skip_verify_ssl,omitempty"` - }{ - - Bucket: m.Bucket, - - Endpoint: m.Endpoint, - - Key: m.Key, - - Region: m.Region, - - S3ForcePathStyle: m.S3ForcePathStyle, - - SkipVerifySsl: m.SkipVerifySsl, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this a w s remote t f state -func (m *AWSRemoteTFState) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBucket(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRegion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AWSRemoteTFState) validateBucket(formats strfmt.Registry) error { - - if err := validate.Required("bucket", "body", m.Bucket); err != nil { - return err - } - - return nil -} - -func (m *AWSRemoteTFState) validateRegion(formats strfmt.Registry) error { - - if err := validate.Required("region", "body", m.Region); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this a w s remote t f state based on the context it is used -func (m *AWSRemoteTFState) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *AWSRemoteTFState) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AWSRemoteTFState) UnmarshalBinary(b []byte) error { - var res AWSRemoteTFState - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/a_w_s_storage.go b/client/models/a_w_s_storage.go deleted file mode 100644 index dfb979567..000000000 --- a/client/models/a_w_s_storage.go +++ /dev/null @@ -1,251 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AWSStorage Representation of AWS storage for external backend. -// Must be matched with a credential of the "aws" type. -// -// swagger:model AWSStorage -type AWSStorage struct { - - // The AWS bucket containing objects - // - // Required: true - Bucket *string `json:"bucket"` - - // A custom endpoint for the S3 API (default: s3.amazonaws.com) - // - Endpoint string `json:"endpoint,omitempty"` - - // The S3 Key uniquely identifies an object in a bucket - // - Key string `json:"key,omitempty"` - - // The AWS region where the resource exists - // - // Required: true - Region *string `json:"region"` - - // Always use path-style S3 URLs (https:/// instead of https://.) - // - S3ForcePathStyle bool `json:"s3_force_path_style,omitempty"` - - // Set this to `true` to not verify SSL certificates - // - SkipVerifySsl bool `json:"skip_verify_ssl,omitempty"` -} - -// Engine gets the engine of this subtype -func (m *AWSStorage) Engine() string { - return "AWSStorage" -} - -// SetEngine sets the engine of this subtype -func (m *AWSStorage) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *AWSStorage) UnmarshalJSON(raw []byte) error { - var data struct { - - // The AWS bucket containing objects - // - // Required: true - Bucket *string `json:"bucket"` - - // A custom endpoint for the S3 API (default: s3.amazonaws.com) - // - Endpoint string `json:"endpoint,omitempty"` - - // The S3 Key uniquely identifies an object in a bucket - // - Key string `json:"key,omitempty"` - - // The AWS region where the resource exists - // - // Required: true - Region *string `json:"region"` - - // Always use path-style S3 URLs (https:/// instead of https://.) - // - S3ForcePathStyle bool `json:"s3_force_path_style,omitempty"` - - // Set this to `true` to not verify SSL certificates - // - SkipVerifySsl bool `json:"skip_verify_ssl,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result AWSStorage - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.Bucket = data.Bucket - result.Endpoint = data.Endpoint - result.Key = data.Key - result.Region = data.Region - result.S3ForcePathStyle = data.S3ForcePathStyle - result.SkipVerifySsl = data.SkipVerifySsl - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m AWSStorage) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The AWS bucket containing objects - // - // Required: true - Bucket *string `json:"bucket"` - - // A custom endpoint for the S3 API (default: s3.amazonaws.com) - // - Endpoint string `json:"endpoint,omitempty"` - - // The S3 Key uniquely identifies an object in a bucket - // - Key string `json:"key,omitempty"` - - // The AWS region where the resource exists - // - // Required: true - Region *string `json:"region"` - - // Always use path-style S3 URLs (https:/// instead of https://.) - // - S3ForcePathStyle bool `json:"s3_force_path_style,omitempty"` - - // Set this to `true` to not verify SSL certificates - // - SkipVerifySsl bool `json:"skip_verify_ssl,omitempty"` - }{ - - Bucket: m.Bucket, - - Endpoint: m.Endpoint, - - Key: m.Key, - - Region: m.Region, - - S3ForcePathStyle: m.S3ForcePathStyle, - - SkipVerifySsl: m.SkipVerifySsl, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this a w s storage -func (m *AWSStorage) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBucket(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRegion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AWSStorage) validateBucket(formats strfmt.Registry) error { - - if err := validate.Required("bucket", "body", m.Bucket); err != nil { - return err - } - - return nil -} - -func (m *AWSStorage) validateRegion(formats strfmt.Registry) error { - - if err := validate.Required("region", "body", m.Region); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this a w s storage based on the context it is used -func (m *AWSStorage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *AWSStorage) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AWSStorage) UnmarshalBinary(b []byte) error { - var res AWSStorage - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/api_key.go b/client/models/api_key.go deleted file mode 100644 index cdfcca44a..000000000 --- a/client/models/api_key.go +++ /dev/null @@ -1,296 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// APIKey API key -// -// The entity which represents the information of an API key. The "token" field is only filled once, upon creation. It can only be used on an organization scope, for example user endpoints will not support it. -// -// swagger:model APIKey -type APIKey struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // description - Description string `json:"description,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // The last seven characters of API key. Allows user to differentiate between keys. - // Required: true - LastSeven *string `json:"last_seven"` - - // This field contains the date of the last usage of the API key - LastUsed uint64 `json:"last_used,omitempty"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // Organization member that owns this API key. When a user is the owner of an - // API key he has all the permissions on it. - // In the event where the user has been deleted that field might be empty. - // - Owner *User `json:"owner,omitempty"` - - // rules - // Required: true - Rules []*Rule `json:"rules"` - - // The actual API key in the format of JWT token, returned only upon creation. - Token string `json:"token,omitempty"` -} - -// Validate validates this API key -func (m *APIKey) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLastSeven(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRules(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *APIKey) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *APIKey) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *APIKey) validateLastSeven(formats strfmt.Registry) error { - - if err := validate.Required("last_seven", "body", m.LastSeven); err != nil { - return err - } - - return nil -} - -func (m *APIKey) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *APIKey) validateOwner(formats strfmt.Registry) error { - if swag.IsZero(m.Owner) { // not required - return nil - } - - if m.Owner != nil { - if err := m.Owner.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *APIKey) validateRules(formats strfmt.Registry) error { - - if err := validate.Required("rules", "body", m.Rules); err != nil { - return err - } - - for i := 0; i < len(m.Rules); i++ { - if swag.IsZero(m.Rules[i]) { // not required - continue - } - - if m.Rules[i] != nil { - if err := m.Rules[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("rules" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("rules" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this API key based on the context it is used -func (m *APIKey) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateOwner(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateRules(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *APIKey) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { - - if m.Owner != nil { - - if swag.IsZero(m.Owner) { // not required - return nil - } - - if err := m.Owner.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *APIKey) contextValidateRules(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Rules); i++ { - - if m.Rules[i] != nil { - - if swag.IsZero(m.Rules[i]) { // not required - return nil - } - - if err := m.Rules[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("rules" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("rules" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *APIKey) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *APIKey) UnmarshalBinary(b []byte) error { - var res APIKey - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/app_configuration.go b/client/models/app_configuration.go deleted file mode 100644 index 016ddfa8e..000000000 --- a/client/models/app_configuration.go +++ /dev/null @@ -1,79 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AppConfiguration AppConfiguration -// -// # Contains application-wide configuration -// -// swagger:model AppConfiguration -type AppConfiguration struct { - - // Base URL of the Cyclobot API the frontend should use. - CyclobotAPIURL string `json:"cyclobot_api_url,omitempty"` - - // Indicates if Cyclobot is enabled for the frontend. - CyclobotEnabled bool `json:"cyclobot_enabled,omitempty"` - - // Graph ID to use for the Cyclobot agent. - CyclobotGraphID string `json:"cyclobot_graph_id,omitempty"` - - // Indicates if Sentry is enabled. - // Required: true - SentryEnabled *bool `json:"sentry_enabled"` -} - -// Validate validates this app configuration -func (m *AppConfiguration) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateSentryEnabled(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AppConfiguration) validateSentryEnabled(formats strfmt.Registry) error { - - if err := validate.Required("sentry_enabled", "body", m.SentryEnabled); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this app configuration based on context it is used -func (m *AppConfiguration) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *AppConfiguration) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AppConfiguration) UnmarshalBinary(b []byte) error { - var res AppConfiguration - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/app_version.go b/client/models/app_version.go deleted file mode 100644 index 8e636c1f5..000000000 --- a/client/models/app_version.go +++ /dev/null @@ -1,122 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AppVersion AppVersion -// -// swagger:model AppVersion -type AppVersion struct { - - // The Git branch used to build the application. - // Required: true - // Min Length: 1 - Branch *string `json:"branch"` - - // The Git revision used to build the application. - // Required: true - // Max Length: 40 - // Min Length: 8 - Revision *string `json:"revision"` - - // The version of the application. - // Required: true - // Min Length: 5 - Version *string `json:"version"` -} - -// Validate validates this app version -func (m *AppVersion) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBranch(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRevision(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AppVersion) validateBranch(formats strfmt.Registry) error { - - if err := validate.Required("branch", "body", m.Branch); err != nil { - return err - } - - if err := validate.MinLength("branch", "body", *m.Branch, 1); err != nil { - return err - } - - return nil -} - -func (m *AppVersion) validateRevision(formats strfmt.Registry) error { - - if err := validate.Required("revision", "body", m.Revision); err != nil { - return err - } - - if err := validate.MinLength("revision", "body", *m.Revision, 8); err != nil { - return err - } - - if err := validate.MaxLength("revision", "body", *m.Revision, 40); err != nil { - return err - } - - return nil -} - -func (m *AppVersion) validateVersion(formats strfmt.Registry) error { - - if err := validate.Required("version", "body", m.Version); err != nil { - return err - } - - if err := validate.MinLength("version", "body", *m.Version, 5); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this app version based on context it is used -func (m *AppVersion) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *AppVersion) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AppVersion) UnmarshalBinary(b []byte) error { - var res AppVersion - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/appearance.go b/client/models/appearance.go deleted file mode 100644 index 5554b1645..000000000 --- a/client/models/appearance.go +++ /dev/null @@ -1,463 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Appearance Appearance -// -// # An Appearance holds the values of the branding configuration, which are rendered across an organization -// -// swagger:model Appearance -type Appearance struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // color - // Required: true - Color *AppearanceColor `json:"color"` - - // created at - // Minimum: 0 - CreatedAt *uint64 `json:"created_at,omitempty"` - - // display name - // Required: true - // Max Length: 50 - // Min Length: 1 - DisplayName *string `json:"display_name"` - - // favicon - // Required: true - // Format: uri - Favicon *strfmt.URI `json:"favicon"` - - // footer - // Required: true - // Max Length: 1000 - // Min Length: 0 - Footer *string `json:"footer"` - - // is active - IsActive bool `json:"is_active,omitempty"` - - // logo - // Required: true - // Format: uri - Logo *strfmt.URI `json:"logo"` - - // name - // Required: true - // Max Length: 50 - // Min Length: 1 - Name *string `json:"name"` - - // tab title - // Required: true - // Max Length: 50 - // Min Length: 1 - TabTitle *string `json:"tab_title"` - - // updated at - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` -} - -// Validate validates this appearance -func (m *Appearance) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateColor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDisplayName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFavicon(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFooter(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLogo(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTabTitle(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Appearance) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *Appearance) validateColor(formats strfmt.Registry) error { - - if err := validate.Required("color", "body", m.Color); err != nil { - return err - } - - if m.Color != nil { - if err := m.Color.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("color") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("color") - } - - return err - } - } - - return nil -} - -func (m *Appearance) validateCreatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Appearance) validateDisplayName(formats strfmt.Registry) error { - - if err := validate.Required("display_name", "body", m.DisplayName); err != nil { - return err - } - - if err := validate.MinLength("display_name", "body", *m.DisplayName, 1); err != nil { - return err - } - - if err := validate.MaxLength("display_name", "body", *m.DisplayName, 50); err != nil { - return err - } - - return nil -} - -func (m *Appearance) validateFavicon(formats strfmt.Registry) error { - - if err := validate.Required("favicon", "body", m.Favicon); err != nil { - return err - } - - if err := validate.FormatOf("favicon", "body", "uri", m.Favicon.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *Appearance) validateFooter(formats strfmt.Registry) error { - - if err := validate.Required("footer", "body", m.Footer); err != nil { - return err - } - - if err := validate.MinLength("footer", "body", *m.Footer, 0); err != nil { - return err - } - - if err := validate.MaxLength("footer", "body", *m.Footer, 1000); err != nil { - return err - } - - return nil -} - -func (m *Appearance) validateLogo(formats strfmt.Registry) error { - - if err := validate.Required("logo", "body", m.Logo); err != nil { - return err - } - - if err := validate.FormatOf("logo", "body", "uri", m.Logo.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *Appearance) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 50); err != nil { - return err - } - - return nil -} - -func (m *Appearance) validateTabTitle(formats strfmt.Registry) error { - - if err := validate.Required("tab_title", "body", m.TabTitle); err != nil { - return err - } - - if err := validate.MinLength("tab_title", "body", *m.TabTitle, 1); err != nil { - return err - } - - if err := validate.MaxLength("tab_title", "body", *m.TabTitle, 50); err != nil { - return err - } - - return nil -} - -func (m *Appearance) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this appearance based on the context it is used -func (m *Appearance) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateColor(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Appearance) contextValidateColor(ctx context.Context, formats strfmt.Registry) error { - - if m.Color != nil { - - if err := m.Color.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("color") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("color") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Appearance) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Appearance) UnmarshalBinary(b []byte) error { - var res Appearance - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} - -// AppearanceColor appearance color -// -// swagger:model AppearanceColor -type AppearanceColor struct { - - // Blue color value of the RGB color - // Required: true - // Maximum: 255 - // Minimum: 0 - B *uint32 `json:"b"` - - // Green color value of the RGB color - // Required: true - // Maximum: 255 - // Minimum: 0 - G *uint32 `json:"g"` - - // Red color value of the RGB color - // Required: true - // Maximum: 255 - // Minimum: 0 - R *uint32 `json:"r"` -} - -// Validate validates this appearance color -func (m *AppearanceColor) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateB(formats); err != nil { - res = append(res, err) - } - - if err := m.validateG(formats); err != nil { - res = append(res, err) - } - - if err := m.validateR(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AppearanceColor) validateB(formats strfmt.Registry) error { - - if err := validate.Required("color"+"."+"b", "body", m.B); err != nil { - return err - } - - if err := validate.MinimumUint("color"+"."+"b", "body", uint64(*m.B), 0, false); err != nil { - return err - } - - if err := validate.MaximumUint("color"+"."+"b", "body", uint64(*m.B), 255, false); err != nil { - return err - } - - return nil -} - -func (m *AppearanceColor) validateG(formats strfmt.Registry) error { - - if err := validate.Required("color"+"."+"g", "body", m.G); err != nil { - return err - } - - if err := validate.MinimumUint("color"+"."+"g", "body", uint64(*m.G), 0, false); err != nil { - return err - } - - if err := validate.MaximumUint("color"+"."+"g", "body", uint64(*m.G), 255, false); err != nil { - return err - } - - return nil -} - -func (m *AppearanceColor) validateR(formats strfmt.Registry) error { - - if err := validate.Required("color"+"."+"r", "body", m.R); err != nil { - return err - } - - if err := validate.MinimumUint("color"+"."+"r", "body", uint64(*m.R), 0, false); err != nil { - return err - } - - if err := validate.MaximumUint("color"+"."+"r", "body", uint64(*m.R), 255, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this appearance color based on context it is used -func (m *AppearanceColor) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *AppearanceColor) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AppearanceColor) UnmarshalBinary(b []byte) error { - var res AppearanceColor - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/authentication.go b/client/models/authentication.go deleted file mode 100644 index ca0fb5671..000000000 --- a/client/models/authentication.go +++ /dev/null @@ -1,176 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - stderrors "errors" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// Authentication AuthenticationWrapper -// -// swagger:model Authentication -type Authentication struct { - configField AuthenticationConfig -} - -// Config gets the config of this base type -func (m *Authentication) Config() AuthenticationConfig { - return m.configField -} - -// SetConfig sets the config of this base type -func (m *Authentication) SetConfig(val AuthenticationConfig) { - m.configField = val -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *Authentication) UnmarshalJSON(raw []byte) error { - var data struct { - Config json.RawMessage `json:"config,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var propConfig AuthenticationConfig - if string(data.Config) != "null" { - config, err := UnmarshalAuthenticationConfig(bytes.NewBuffer(data.Config), runtime.JSONConsumer()) - if err != nil && !stderrors.Is(err, io.EOF) { - return err - } - propConfig = config - } - - var result Authentication - - // config - result.configField = propConfig - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m Authentication) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - }{}) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Config AuthenticationConfig `json:"config,omitempty"` - }{ - - Config: m.configField, - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this authentication -func (m *Authentication) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfig(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Authentication) validateConfig(formats strfmt.Registry) error { - if swag.IsZero(m.Config()) { // not required - return nil - } - - if err := m.Config().Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("config") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("config") - } - - return err - } - - return nil -} - -// ContextValidate validate this authentication based on the context it is used -func (m *Authentication) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateConfig(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Authentication) contextValidateConfig(ctx context.Context, formats strfmt.Registry) error { - - if swag.IsZero(m.Config()) { // not required - return nil - } - - if err := m.Config().ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("config") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("config") - } - - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Authentication) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Authentication) UnmarshalBinary(b []byte) error { - var res Authentication - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/authentication_azure_a_d.go b/client/models/authentication_azure_a_d.go deleted file mode 100644 index f65385463..000000000 --- a/client/models/authentication_azure_a_d.go +++ /dev/null @@ -1,186 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AuthenticationAzureAD AuthenticationAzureAD -// -// # AzureAD Authentication configuration -// -// swagger:model AuthenticationAzureAD -type AuthenticationAzureAD struct { - enabledField *bool - - // ID of the OAuth client. - ClientID string `json:"client_id,omitempty"` - - // ID of the OAuth tenant. - TenantID string `json:"tenant_id,omitempty"` -} - -// Enabled gets the enabled of this subtype -func (m *AuthenticationAzureAD) Enabled() *bool { - return m.enabledField -} - -// SetEnabled sets the enabled of this subtype -func (m *AuthenticationAzureAD) SetEnabled(val *bool) { - m.enabledField = val -} - -// Type gets the type of this subtype -func (m *AuthenticationAzureAD) Type() string { - return "AuthenticationAzureAD" -} - -// SetType sets the type of this subtype -func (m *AuthenticationAzureAD) SetType(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *AuthenticationAzureAD) UnmarshalJSON(raw []byte) error { - var data struct { - - // ID of the OAuth client. - ClientID string `json:"client_id,omitempty"` - - // ID of the OAuth tenant. - TenantID string `json:"tenant_id,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Enabled *bool `json:"enabled"` - - Type string `json:"type"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result AuthenticationAzureAD - - result.enabledField = base.Enabled - - if base.Type != result.Type() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid type value: %q", base.Type) - } - - result.ClientID = data.ClientID - result.TenantID = data.TenantID - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m AuthenticationAzureAD) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // ID of the OAuth client. - ClientID string `json:"client_id,omitempty"` - - // ID of the OAuth tenant. - TenantID string `json:"tenant_id,omitempty"` - }{ - - ClientID: m.ClientID, - - TenantID: m.TenantID, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Enabled *bool `json:"enabled"` - - Type string `json:"type"` - }{ - - Enabled: m.Enabled(), - - Type: m.Type(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this authentication azure a d -func (m *AuthenticationAzureAD) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEnabled(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AuthenticationAzureAD) validateEnabled(formats strfmt.Registry) error { - - if err := validate.Required("enabled", "body", m.Enabled()); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this authentication azure a d based on the context it is used -func (m *AuthenticationAzureAD) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *AuthenticationAzureAD) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AuthenticationAzureAD) UnmarshalBinary(b []byte) error { - var res AuthenticationAzureAD - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/authentication_config.go b/client/models/authentication_config.go deleted file mode 100644 index 466da949d..000000000 --- a/client/models/authentication_config.go +++ /dev/null @@ -1,181 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" -) - -// AuthenticationConfig AuthenticationConfig -// -// swagger:discriminator AuthenticationConfig type -type AuthenticationConfig interface { - runtime.Validatable - runtime.ContextValidatable - - // Whether the authentication is enabled - // Required: true - Enabled() *bool - SetEnabled(*bool) - - // type - // Required: true - Type() string - SetType(string) - - // AdditionalProperties in base type shoud be handled just like regular properties - // At this moment, the base type property is pushed down to the subtype -} - -type authenticationConfig struct { - enabledField *bool - - typeField string -} - -// Enabled gets the enabled of this polymorphic type -func (m *authenticationConfig) Enabled() *bool { - return m.enabledField -} - -// SetEnabled sets the enabled of this polymorphic type -func (m *authenticationConfig) SetEnabled(val *bool) { - m.enabledField = val -} - -// Type gets the type of this polymorphic type -func (m *authenticationConfig) Type() string { - return "AuthenticationConfig" -} - -// SetType sets the type of this polymorphic type -func (m *authenticationConfig) SetType(val string) { -} - -// UnmarshalAuthenticationConfigSlice unmarshals polymorphic slices of AuthenticationConfig -func UnmarshalAuthenticationConfigSlice(reader io.Reader, consumer runtime.Consumer) ([]AuthenticationConfig, error) { - var elements []json.RawMessage - if err := consumer.Consume(reader, &elements); err != nil { - return nil, err - } - - var result []AuthenticationConfig - for _, element := range elements { - obj, err := unmarshalAuthenticationConfig(element, consumer) - if err != nil { - return nil, err - } - result = append(result, obj) - } - return result, nil -} - -// UnmarshalAuthenticationConfig unmarshals polymorphic AuthenticationConfig -func UnmarshalAuthenticationConfig(reader io.Reader, consumer runtime.Consumer) (AuthenticationConfig, error) { - // we need to read this twice, so first into a buffer - data, err := io.ReadAll(reader) - if err != nil { - return nil, err - } - return unmarshalAuthenticationConfig(data, consumer) -} - -func unmarshalAuthenticationConfig(data []byte, consumer runtime.Consumer) (AuthenticationConfig, error) { - buf := bytes.NewBuffer(data) - buf2 := bytes.NewBuffer(data) - - // the first time this is read is to fetch the value of the type property. - var getType struct { - Type string `json:"type"` - } - if err := consumer.Consume(buf, &getType); err != nil { - return nil, err - } - - if err := validate.RequiredString("type", "body", getType.Type); err != nil { - return nil, err - } - - // The value of type is used to determine which type to create and unmarshal the data into - switch getType.Type { - case "AuthenticationAzureAD": - var result AuthenticationAzureAD - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "AuthenticationConfig": - var result authenticationConfig - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "AuthenticationGitHub": - var result AuthenticationGitHub - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "AuthenticationGoogle": - var result AuthenticationGoogle - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "AuthenticationLocal": - var result AuthenticationLocal - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "AuthenticationOIDC": - var result AuthenticationOIDC - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "AuthenticationSAML": - var result AuthenticationSAML - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - } - return nil, errors.New(422, "invalid type value: %q", getType.Type) -} - -// Validate validates this authentication config -func (m *authenticationConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEnabled(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *authenticationConfig) validateEnabled(formats strfmt.Registry) error { - - if err := validate.Required("enabled", "body", m.Enabled()); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this authentication config based on context it is used -func (m *authenticationConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} diff --git a/client/models/authentication_git_hub.go b/client/models/authentication_git_hub.go deleted file mode 100644 index 805ceeb79..000000000 --- a/client/models/authentication_git_hub.go +++ /dev/null @@ -1,235 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AuthenticationGitHub AuthenticationGitHub -// -// # GitHub Authentication configuration -// -// swagger:model AuthenticationGitHub -type AuthenticationGitHub struct { - enabledField *bool - - // ID of the OAuth client. - ClientID string `json:"client_id,omitempty"` - - // The secret of the auth client, it'll not be returned on the public calls - ClientSecretID string `json:"client_secret_id,omitempty"` - - // Whether the client secret is set or not. - // Read Only: true - HasSecret *bool `json:"has_secret,omitempty"` - - // GitHub host address is used to determine where the request for the token should be sent. - // In most cases this address will be https://api.github.com`, but it could be different - // for onprem clients that use GitHub Enterprise. - // - HostAddress string `json:"host_address,omitempty"` -} - -// Enabled gets the enabled of this subtype -func (m *AuthenticationGitHub) Enabled() *bool { - return m.enabledField -} - -// SetEnabled sets the enabled of this subtype -func (m *AuthenticationGitHub) SetEnabled(val *bool) { - m.enabledField = val -} - -// Type gets the type of this subtype -func (m *AuthenticationGitHub) Type() string { - return "AuthenticationGitHub" -} - -// SetType sets the type of this subtype -func (m *AuthenticationGitHub) SetType(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *AuthenticationGitHub) UnmarshalJSON(raw []byte) error { - var data struct { - - // ID of the OAuth client. - ClientID string `json:"client_id,omitempty"` - - // The secret of the auth client, it'll not be returned on the public calls - ClientSecretID string `json:"client_secret_id,omitempty"` - - // Whether the client secret is set or not. - // Read Only: true - HasSecret *bool `json:"has_secret,omitempty"` - - // GitHub host address is used to determine where the request for the token should be sent. - // In most cases this address will be https://api.github.com`, but it could be different - // for onprem clients that use GitHub Enterprise. - // - HostAddress string `json:"host_address,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Enabled *bool `json:"enabled"` - - Type string `json:"type"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result AuthenticationGitHub - - result.enabledField = base.Enabled - - if base.Type != result.Type() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid type value: %q", base.Type) - } - - result.ClientID = data.ClientID - result.ClientSecretID = data.ClientSecretID - result.HasSecret = data.HasSecret - result.HostAddress = data.HostAddress - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m AuthenticationGitHub) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // ID of the OAuth client. - ClientID string `json:"client_id,omitempty"` - - // The secret of the auth client, it'll not be returned on the public calls - ClientSecretID string `json:"client_secret_id,omitempty"` - - // Whether the client secret is set or not. - // Read Only: true - HasSecret *bool `json:"has_secret,omitempty"` - - // GitHub host address is used to determine where the request for the token should be sent. - // In most cases this address will be https://api.github.com`, but it could be different - // for onprem clients that use GitHub Enterprise. - // - HostAddress string `json:"host_address,omitempty"` - }{ - - ClientID: m.ClientID, - - ClientSecretID: m.ClientSecretID, - - HasSecret: m.HasSecret, - - HostAddress: m.HostAddress, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Enabled *bool `json:"enabled"` - - Type string `json:"type"` - }{ - - Enabled: m.Enabled(), - - Type: m.Type(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this authentication git hub -func (m *AuthenticationGitHub) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEnabled(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AuthenticationGitHub) validateEnabled(formats strfmt.Registry) error { - - if err := validate.Required("enabled", "body", m.Enabled()); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this authentication git hub based on the context it is used -func (m *AuthenticationGitHub) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateHasSecret(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AuthenticationGitHub) contextValidateHasSecret(ctx context.Context, formats strfmt.Registry) error { - - if err := validate.ReadOnly(ctx, "has_secret", "body", m.HasSecret); err != nil { - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *AuthenticationGitHub) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AuthenticationGitHub) UnmarshalBinary(b []byte) error { - var res AuthenticationGitHub - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/authentication_google.go b/client/models/authentication_google.go deleted file mode 100644 index f34e8daef..000000000 --- a/client/models/authentication_google.go +++ /dev/null @@ -1,174 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AuthenticationGoogle AuthenticationGoogle -// -// # Google Authentication configuration -// -// swagger:model AuthenticationGoogle -type AuthenticationGoogle struct { - enabledField *bool - - // ID of the OAuth client. - ClientID string `json:"client_id,omitempty"` -} - -// Enabled gets the enabled of this subtype -func (m *AuthenticationGoogle) Enabled() *bool { - return m.enabledField -} - -// SetEnabled sets the enabled of this subtype -func (m *AuthenticationGoogle) SetEnabled(val *bool) { - m.enabledField = val -} - -// Type gets the type of this subtype -func (m *AuthenticationGoogle) Type() string { - return "AuthenticationGoogle" -} - -// SetType sets the type of this subtype -func (m *AuthenticationGoogle) SetType(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *AuthenticationGoogle) UnmarshalJSON(raw []byte) error { - var data struct { - - // ID of the OAuth client. - ClientID string `json:"client_id,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Enabled *bool `json:"enabled"` - - Type string `json:"type"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result AuthenticationGoogle - - result.enabledField = base.Enabled - - if base.Type != result.Type() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid type value: %q", base.Type) - } - - result.ClientID = data.ClientID - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m AuthenticationGoogle) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // ID of the OAuth client. - ClientID string `json:"client_id,omitempty"` - }{ - - ClientID: m.ClientID, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Enabled *bool `json:"enabled"` - - Type string `json:"type"` - }{ - - Enabled: m.Enabled(), - - Type: m.Type(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this authentication google -func (m *AuthenticationGoogle) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEnabled(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AuthenticationGoogle) validateEnabled(formats strfmt.Registry) error { - - if err := validate.Required("enabled", "body", m.Enabled()); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this authentication google based on the context it is used -func (m *AuthenticationGoogle) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *AuthenticationGoogle) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AuthenticationGoogle) UnmarshalBinary(b []byte) error { - var res AuthenticationGoogle - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/authentication_local.go b/client/models/authentication_local.go deleted file mode 100644 index 9b401bec3..000000000 --- a/client/models/authentication_local.go +++ /dev/null @@ -1,160 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AuthenticationLocal AuthenticationLocal -// -// # Local Authentication configuration -// -// swagger:model AuthenticationLocal -type AuthenticationLocal struct { - enabledField *bool -} - -// Enabled gets the enabled of this subtype -func (m *AuthenticationLocal) Enabled() *bool { - return m.enabledField -} - -// SetEnabled sets the enabled of this subtype -func (m *AuthenticationLocal) SetEnabled(val *bool) { - m.enabledField = val -} - -// Type gets the type of this subtype -func (m *AuthenticationLocal) Type() string { - return "AuthenticationLocal" -} - -// SetType sets the type of this subtype -func (m *AuthenticationLocal) SetType(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *AuthenticationLocal) UnmarshalJSON(raw []byte) error { - var data struct { - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Enabled *bool `json:"enabled"` - - Type string `json:"type"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result AuthenticationLocal - - result.enabledField = base.Enabled - - if base.Type != result.Type() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid type value: %q", base.Type) - } - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m AuthenticationLocal) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - }{}) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Enabled *bool `json:"enabled"` - - Type string `json:"type"` - }{ - - Enabled: m.Enabled(), - - Type: m.Type(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this authentication local -func (m *AuthenticationLocal) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEnabled(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AuthenticationLocal) validateEnabled(formats strfmt.Registry) error { - - if err := validate.Required("enabled", "body", m.Enabled()); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this authentication local based on the context it is used -func (m *AuthenticationLocal) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *AuthenticationLocal) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AuthenticationLocal) UnmarshalBinary(b []byte) error { - var res AuthenticationLocal - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/authentication_o_id_c.go b/client/models/authentication_o_id_c.go deleted file mode 100644 index 75f2d7be6..000000000 --- a/client/models/authentication_o_id_c.go +++ /dev/null @@ -1,326 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AuthenticationOIDC AuthenticationOIDC -// -// # OIDC Authentication configuration -// -// swagger:model AuthenticationOIDC -type AuthenticationOIDC struct { - enabledField *bool - - // Whether the CA certificate is set or not. - // Read Only: true - HasCaCertificate *bool `json:"has_ca_certificate,omitempty"` - - // Whether the client secret is set or not. - // Read Only: true - HasSecret *bool `json:"has_secret,omitempty"` - - // PEM-encoded CA certificate to verify the OIDC provider's TLS certificate. - OidcCaCert string `json:"oidc_ca_cert,omitempty"` - - // The public ID registered with the OIDC provider. Identifies your application. - OidcClientID string `json:"oidc_client_id,omitempty"` - - // The secret key used to securely exchange the authorization code for tokens. - OidcClientSecret string `json:"oidc_client_secret,omitempty"` - - // Enables client authentication via signed JWT (HS512) using the client secret, as per RFC 7523. - OidcClientSecretJwt bool `json:"oidc_client_secret_jwt,omitempty"` - - // The friendly name shown on the login button - OidcDisplayName string `json:"oidc_display_name,omitempty"` - - // URL of the icon to display on the OIDC authentication login screen. - OidcIcon string `json:"oidc_icon,omitempty"` - - // The base URL of the OIDC provider. Used for automatic endpoint discovery. - OidcIssuer string `json:"oidc_issuer,omitempty"` - - // Disables TLS certificate verification when connecting to the OIDC provider. Use only in development or with self-signed certificates. - OidcSkipTLSVerify bool `json:"oidc_skip_tls_verify,omitempty"` - - // Whether to use a custom CA certificate to verify the OIDC provider's TLS certificate. - OidcUseCaCert bool `json:"oidc_use_ca_cert,omitempty"` -} - -// Enabled gets the enabled of this subtype -func (m *AuthenticationOIDC) Enabled() *bool { - return m.enabledField -} - -// SetEnabled sets the enabled of this subtype -func (m *AuthenticationOIDC) SetEnabled(val *bool) { - m.enabledField = val -} - -// Type gets the type of this subtype -func (m *AuthenticationOIDC) Type() string { - return "AuthenticationOIDC" -} - -// SetType sets the type of this subtype -func (m *AuthenticationOIDC) SetType(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *AuthenticationOIDC) UnmarshalJSON(raw []byte) error { - var data struct { - - // Whether the CA certificate is set or not. - // Read Only: true - HasCaCertificate *bool `json:"has_ca_certificate,omitempty"` - - // Whether the client secret is set or not. - // Read Only: true - HasSecret *bool `json:"has_secret,omitempty"` - - // PEM-encoded CA certificate to verify the OIDC provider's TLS certificate. - OidcCaCert string `json:"oidc_ca_cert,omitempty"` - - // The public ID registered with the OIDC provider. Identifies your application. - OidcClientID string `json:"oidc_client_id,omitempty"` - - // The secret key used to securely exchange the authorization code for tokens. - OidcClientSecret string `json:"oidc_client_secret,omitempty"` - - // Enables client authentication via signed JWT (HS512) using the client secret, as per RFC 7523. - OidcClientSecretJwt bool `json:"oidc_client_secret_jwt,omitempty"` - - // The friendly name shown on the login button - OidcDisplayName string `json:"oidc_display_name,omitempty"` - - // URL of the icon to display on the OIDC authentication login screen. - OidcIcon string `json:"oidc_icon,omitempty"` - - // The base URL of the OIDC provider. Used for automatic endpoint discovery. - OidcIssuer string `json:"oidc_issuer,omitempty"` - - // Disables TLS certificate verification when connecting to the OIDC provider. Use only in development or with self-signed certificates. - OidcSkipTLSVerify bool `json:"oidc_skip_tls_verify,omitempty"` - - // Whether to use a custom CA certificate to verify the OIDC provider's TLS certificate. - OidcUseCaCert bool `json:"oidc_use_ca_cert,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Enabled *bool `json:"enabled"` - - Type string `json:"type"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result AuthenticationOIDC - - result.enabledField = base.Enabled - - if base.Type != result.Type() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid type value: %q", base.Type) - } - - result.HasCaCertificate = data.HasCaCertificate - result.HasSecret = data.HasSecret - result.OidcCaCert = data.OidcCaCert - result.OidcClientID = data.OidcClientID - result.OidcClientSecret = data.OidcClientSecret - result.OidcClientSecretJwt = data.OidcClientSecretJwt - result.OidcDisplayName = data.OidcDisplayName - result.OidcIcon = data.OidcIcon - result.OidcIssuer = data.OidcIssuer - result.OidcSkipTLSVerify = data.OidcSkipTLSVerify - result.OidcUseCaCert = data.OidcUseCaCert - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m AuthenticationOIDC) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // Whether the CA certificate is set or not. - // Read Only: true - HasCaCertificate *bool `json:"has_ca_certificate,omitempty"` - - // Whether the client secret is set or not. - // Read Only: true - HasSecret *bool `json:"has_secret,omitempty"` - - // PEM-encoded CA certificate to verify the OIDC provider's TLS certificate. - OidcCaCert string `json:"oidc_ca_cert,omitempty"` - - // The public ID registered with the OIDC provider. Identifies your application. - OidcClientID string `json:"oidc_client_id,omitempty"` - - // The secret key used to securely exchange the authorization code for tokens. - OidcClientSecret string `json:"oidc_client_secret,omitempty"` - - // Enables client authentication via signed JWT (HS512) using the client secret, as per RFC 7523. - OidcClientSecretJwt bool `json:"oidc_client_secret_jwt,omitempty"` - - // The friendly name shown on the login button - OidcDisplayName string `json:"oidc_display_name,omitempty"` - - // URL of the icon to display on the OIDC authentication login screen. - OidcIcon string `json:"oidc_icon,omitempty"` - - // The base URL of the OIDC provider. Used for automatic endpoint discovery. - OidcIssuer string `json:"oidc_issuer,omitempty"` - - // Disables TLS certificate verification when connecting to the OIDC provider. Use only in development or with self-signed certificates. - OidcSkipTLSVerify bool `json:"oidc_skip_tls_verify,omitempty"` - - // Whether to use a custom CA certificate to verify the OIDC provider's TLS certificate. - OidcUseCaCert bool `json:"oidc_use_ca_cert,omitempty"` - }{ - - HasCaCertificate: m.HasCaCertificate, - - HasSecret: m.HasSecret, - - OidcCaCert: m.OidcCaCert, - - OidcClientID: m.OidcClientID, - - OidcClientSecret: m.OidcClientSecret, - - OidcClientSecretJwt: m.OidcClientSecretJwt, - - OidcDisplayName: m.OidcDisplayName, - - OidcIcon: m.OidcIcon, - - OidcIssuer: m.OidcIssuer, - - OidcSkipTLSVerify: m.OidcSkipTLSVerify, - - OidcUseCaCert: m.OidcUseCaCert, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Enabled *bool `json:"enabled"` - - Type string `json:"type"` - }{ - - Enabled: m.Enabled(), - - Type: m.Type(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this authentication o ID c -func (m *AuthenticationOIDC) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEnabled(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AuthenticationOIDC) validateEnabled(formats strfmt.Registry) error { - - if err := validate.Required("enabled", "body", m.Enabled()); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this authentication o ID c based on the context it is used -func (m *AuthenticationOIDC) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateHasCaCertificate(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateHasSecret(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AuthenticationOIDC) contextValidateHasCaCertificate(ctx context.Context, formats strfmt.Registry) error { - - if err := validate.ReadOnly(ctx, "has_ca_certificate", "body", m.HasCaCertificate); err != nil { - return err - } - - return nil -} - -func (m *AuthenticationOIDC) contextValidateHasSecret(ctx context.Context, formats strfmt.Registry) error { - - if err := validate.ReadOnly(ctx, "has_secret", "body", m.HasSecret); err != nil { - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *AuthenticationOIDC) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AuthenticationOIDC) UnmarshalBinary(b []byte) error { - var res AuthenticationOIDC - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/authentication_s_a_m_l.go b/client/models/authentication_s_a_m_l.go deleted file mode 100644 index fe3e75636..000000000 --- a/client/models/authentication_s_a_m_l.go +++ /dev/null @@ -1,206 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AuthenticationSAML AuthenticationSAML -// -// # SAML Authentication configuration -// -// swagger:model AuthenticationSAML -type AuthenticationSAML struct { - enabledField *bool - - // Entity ID of the SAML2 identity provider. - Provider string `json:"provider,omitempty"` - - // SSO URL to which the user should be redirected in order to authenticate with the Identity Provider. - // Format: uri - SsoURL strfmt.URI `json:"sso_url,omitempty"` -} - -// Enabled gets the enabled of this subtype -func (m *AuthenticationSAML) Enabled() *bool { - return m.enabledField -} - -// SetEnabled sets the enabled of this subtype -func (m *AuthenticationSAML) SetEnabled(val *bool) { - m.enabledField = val -} - -// Type gets the type of this subtype -func (m *AuthenticationSAML) Type() string { - return "AuthenticationSAML" -} - -// SetType sets the type of this subtype -func (m *AuthenticationSAML) SetType(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *AuthenticationSAML) UnmarshalJSON(raw []byte) error { - var data struct { - - // Entity ID of the SAML2 identity provider. - Provider string `json:"provider,omitempty"` - - // SSO URL to which the user should be redirected in order to authenticate with the Identity Provider. - // Format: uri - SsoURL strfmt.URI `json:"sso_url,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Enabled *bool `json:"enabled"` - - Type string `json:"type"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result AuthenticationSAML - - result.enabledField = base.Enabled - - if base.Type != result.Type() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid type value: %q", base.Type) - } - - result.Provider = data.Provider - result.SsoURL = data.SsoURL - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m AuthenticationSAML) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // Entity ID of the SAML2 identity provider. - Provider string `json:"provider,omitempty"` - - // SSO URL to which the user should be redirected in order to authenticate with the Identity Provider. - // Format: uri - SsoURL strfmt.URI `json:"sso_url,omitempty"` - }{ - - Provider: m.Provider, - - SsoURL: m.SsoURL, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Enabled *bool `json:"enabled"` - - Type string `json:"type"` - }{ - - Enabled: m.Enabled(), - - Type: m.Type(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this authentication s a m l -func (m *AuthenticationSAML) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEnabled(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSsoURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AuthenticationSAML) validateEnabled(formats strfmt.Registry) error { - - if err := validate.Required("enabled", "body", m.Enabled()); err != nil { - return err - } - - return nil -} - -func (m *AuthenticationSAML) validateSsoURL(formats strfmt.Registry) error { - - if swag.IsZero(m.SsoURL) { // not required - return nil - } - - if err := validate.FormatOf("sso_url", "body", "uri", m.SsoURL.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this authentication s a m l based on the context it is used -func (m *AuthenticationSAML) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *AuthenticationSAML) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AuthenticationSAML) UnmarshalBinary(b []byte) error { - var res AuthenticationSAML - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/azure_cost_export.go b/client/models/azure_cost_export.go deleted file mode 100644 index d5246a743..000000000 --- a/client/models/azure_cost_export.go +++ /dev/null @@ -1,164 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// AzureCostExport Representation of AzureCostExport external backend. -// Must be matched with a credential of the "azure" type. -// -// swagger:model AzureCostExport -type AzureCostExport struct { - - // Endpoint of blob storage service containing the export files. - BlobServiceURL string `json:"blob_service_url,omitempty"` - - // Name of the export - Name string `json:"name,omitempty"` - - // Scope of the export - Scope string `json:"scope,omitempty"` -} - -// Engine gets the engine of this subtype -func (m *AzureCostExport) Engine() string { - return "AzureCostExport" -} - -// SetEngine sets the engine of this subtype -func (m *AzureCostExport) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *AzureCostExport) UnmarshalJSON(raw []byte) error { - var data struct { - - // Endpoint of blob storage service containing the export files. - BlobServiceURL string `json:"blob_service_url,omitempty"` - - // Name of the export - Name string `json:"name,omitempty"` - - // Scope of the export - Scope string `json:"scope,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result AzureCostExport - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.BlobServiceURL = data.BlobServiceURL - result.Name = data.Name - result.Scope = data.Scope - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m AzureCostExport) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // Endpoint of blob storage service containing the export files. - BlobServiceURL string `json:"blob_service_url,omitempty"` - - // Name of the export - Name string `json:"name,omitempty"` - - // Scope of the export - Scope string `json:"scope,omitempty"` - }{ - - BlobServiceURL: m.BlobServiceURL, - - Name: m.Name, - - Scope: m.Scope, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this azure cost export -func (m *AzureCostExport) Validate(formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// ContextValidate validate this azure cost export based on the context it is used -func (m *AzureCostExport) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *AzureCostExport) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AzureCostExport) UnmarshalBinary(b []byte) error { - var res AzureCostExport - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/azure_remote_t_f_state.go b/client/models/azure_remote_t_f_state.go deleted file mode 100644 index 6e68fbe5c..000000000 --- a/client/models/azure_remote_t_f_state.go +++ /dev/null @@ -1,200 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AzureRemoteTFState Deprecated. Please use AzureStorage. -// Representation of azure remote tf state for external backend. -// Must be matched with a credential of the "azure_storage" type. -// -// swagger:model AzureRemoteTFState -type AzureRemoteTFState struct { - - // The Azure blob contained in the container, will be - // required if the EB is not default - // - Blob string `json:"blob,omitempty"` - - // The Azure container where the resource exists - // - // Required: true - Container *string `json:"container"` - - // A custom endpoint for the Azure API - // (default: "https://{account_name}.blob.core.windows.net/", where - // the "account_name" is the one from the credential) - // - Endpoint string `json:"endpoint,omitempty"` -} - -// Engine gets the engine of this subtype -func (m *AzureRemoteTFState) Engine() string { - return "AzureRemoteTFState" -} - -// SetEngine sets the engine of this subtype -func (m *AzureRemoteTFState) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *AzureRemoteTFState) UnmarshalJSON(raw []byte) error { - var data struct { - - // The Azure blob contained in the container, will be - // required if the EB is not default - // - Blob string `json:"blob,omitempty"` - - // The Azure container where the resource exists - // - // Required: true - Container *string `json:"container"` - - // A custom endpoint for the Azure API - // (default: "https://{account_name}.blob.core.windows.net/", where - // the "account_name" is the one from the credential) - // - Endpoint string `json:"endpoint,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result AzureRemoteTFState - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.Blob = data.Blob - result.Container = data.Container - result.Endpoint = data.Endpoint - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m AzureRemoteTFState) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The Azure blob contained in the container, will be - // required if the EB is not default - // - Blob string `json:"blob,omitempty"` - - // The Azure container where the resource exists - // - // Required: true - Container *string `json:"container"` - - // A custom endpoint for the Azure API - // (default: "https://{account_name}.blob.core.windows.net/", where - // the "account_name" is the one from the credential) - // - Endpoint string `json:"endpoint,omitempty"` - }{ - - Blob: m.Blob, - - Container: m.Container, - - Endpoint: m.Endpoint, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this azure remote t f state -func (m *AzureRemoteTFState) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateContainer(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AzureRemoteTFState) validateContainer(formats strfmt.Registry) error { - - if err := validate.Required("container", "body", m.Container); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this azure remote t f state based on the context it is used -func (m *AzureRemoteTFState) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *AzureRemoteTFState) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AzureRemoteTFState) UnmarshalBinary(b []byte) error { - var res AzureRemoteTFState - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/azure_storage.go b/client/models/azure_storage.go deleted file mode 100644 index 17a68fd4e..000000000 --- a/client/models/azure_storage.go +++ /dev/null @@ -1,199 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AzureStorage Representation of azure remote tf state for external backend. -// Must be matched with a credential of the "azure_storage" type. -// -// swagger:model AzureStorage -type AzureStorage struct { - - // The Azure blob contained in the container, will be - // required if the EB is not default - // - Blob string `json:"blob,omitempty"` - - // The Azure container where the resource exists - // - // Required: true - Container *string `json:"container"` - - // A custom endpoint for the Azure API - // (default: "https://{account_name}.blob.core.windows.net/", where - // the "account_name" is the one from the credential) - // - Endpoint string `json:"endpoint,omitempty"` -} - -// Engine gets the engine of this subtype -func (m *AzureStorage) Engine() string { - return "AzureStorage" -} - -// SetEngine sets the engine of this subtype -func (m *AzureStorage) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *AzureStorage) UnmarshalJSON(raw []byte) error { - var data struct { - - // The Azure blob contained in the container, will be - // required if the EB is not default - // - Blob string `json:"blob,omitempty"` - - // The Azure container where the resource exists - // - // Required: true - Container *string `json:"container"` - - // A custom endpoint for the Azure API - // (default: "https://{account_name}.blob.core.windows.net/", where - // the "account_name" is the one from the credential) - // - Endpoint string `json:"endpoint,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result AzureStorage - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.Blob = data.Blob - result.Container = data.Container - result.Endpoint = data.Endpoint - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m AzureStorage) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The Azure blob contained in the container, will be - // required if the EB is not default - // - Blob string `json:"blob,omitempty"` - - // The Azure container where the resource exists - // - // Required: true - Container *string `json:"container"` - - // A custom endpoint for the Azure API - // (default: "https://{account_name}.blob.core.windows.net/", where - // the "account_name" is the one from the credential) - // - Endpoint string `json:"endpoint,omitempty"` - }{ - - Blob: m.Blob, - - Container: m.Container, - - Endpoint: m.Endpoint, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this azure storage -func (m *AzureStorage) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateContainer(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AzureStorage) validateContainer(formats strfmt.Registry) error { - - if err := validate.Required("container", "body", m.Container); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this azure storage based on the context it is used -func (m *AzureStorage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *AzureStorage) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AzureStorage) UnmarshalBinary(b []byte) error { - var res AzureStorage - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/bare_credential.go b/client/models/bare_credential.go deleted file mode 100644 index 6e7f77163..000000000 --- a/client/models/bare_credential.go +++ /dev/null @@ -1,249 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// BareCredential Bare Credential -// -// # Represents a minimal credential for options lookup without requiring all fields -// -// swagger:model BareCredential -type BareCredential struct { - - // Optional canonical identifier - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // Optional description of the credential - Description string `json:"description,omitempty"` - - // Optional credential name for context - Name string `json:"name,omitempty"` - - // Optional path for the credential - // Pattern: [a-zA-z0-9_\-./] - Path string `json:"path,omitempty"` - - // raw - // Required: true - Raw *CredentialRaw `json:"raw"` - - // type - // Required: true - // Enum: ["ssh","aws","custom","azure","azure_storage","gcp","basic_auth","elasticsearch","swift","vmware"] - Type *string `json:"type"` -} - -// Validate validates this bare credential -func (m *BareCredential) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePath(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRaw(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *BareCredential) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *BareCredential) validatePath(formats strfmt.Registry) error { - if swag.IsZero(m.Path) { // not required - return nil - } - - if err := validate.Pattern("path", "body", m.Path, `[a-zA-z0-9_\-./]`); err != nil { - return err - } - - return nil -} - -func (m *BareCredential) validateRaw(formats strfmt.Registry) error { - - if err := validate.Required("raw", "body", m.Raw); err != nil { - return err - } - - if m.Raw != nil { - if err := m.Raw.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("raw") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("raw") - } - - return err - } - } - - return nil -} - -var bareCredentialTypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["ssh","aws","custom","azure","azure_storage","gcp","basic_auth","elasticsearch","swift","vmware"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - bareCredentialTypeTypePropEnum = append(bareCredentialTypeTypePropEnum, v) - } -} - -const ( - - // BareCredentialTypeSSH captures enum value "ssh" - BareCredentialTypeSSH string = "ssh" - - // BareCredentialTypeAws captures enum value "aws" - BareCredentialTypeAws string = "aws" - - // BareCredentialTypeCustom captures enum value "custom" - BareCredentialTypeCustom string = "custom" - - // BareCredentialTypeAzure captures enum value "azure" - BareCredentialTypeAzure string = "azure" - - // BareCredentialTypeAzureStorage captures enum value "azure_storage" - BareCredentialTypeAzureStorage string = "azure_storage" - - // BareCredentialTypeGcp captures enum value "gcp" - BareCredentialTypeGcp string = "gcp" - - // BareCredentialTypeBasicAuth captures enum value "basic_auth" - BareCredentialTypeBasicAuth string = "basic_auth" - - // BareCredentialTypeElasticsearch captures enum value "elasticsearch" - BareCredentialTypeElasticsearch string = "elasticsearch" - - // BareCredentialTypeSwift captures enum value "swift" - BareCredentialTypeSwift string = "swift" - - // BareCredentialTypeVmware captures enum value "vmware" - BareCredentialTypeVmware string = "vmware" -) - -// prop value enum -func (m *BareCredential) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, bareCredentialTypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *BareCredential) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this bare credential based on the context it is used -func (m *BareCredential) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateRaw(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *BareCredential) contextValidateRaw(ctx context.Context, formats strfmt.Registry) error { - - if m.Raw != nil { - - if err := m.Raw.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("raw") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("raw") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *BareCredential) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *BareCredential) UnmarshalBinary(b []byte) error { - var res BareCredential - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/build.go b/client/models/build.go deleted file mode 100644 index adcdc1eba..000000000 --- a/client/models/build.go +++ /dev/null @@ -1,156 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Build Build -// -// The information relative to a build. -// -// swagger:model Build -type Build struct { - - // api url - // Required: true - APIURL *string `json:"api_url"` - - // end time - EndTime uint64 `json:"end_time,omitempty"` - - // id - // Required: true - ID *uint64 `json:"id"` - - // job name - JobName string `json:"job_name,omitempty"` - - // name - // Required: true - Name *string `json:"name"` - - // pipeline id - PipelineID uint64 `json:"pipeline_id,omitempty"` - - // pipeline name - PipelineName string `json:"pipeline_name,omitempty"` - - // reap time - ReapTime uint64 `json:"reap_time,omitempty"` - - // start time - StartTime uint64 `json:"start_time,omitempty"` - - // status - // Required: true - Status *string `json:"status"` - - // team name - // Required: true - TeamName *string `json:"team_name"` -} - -// Validate validates this build -func (m *Build) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAPIURL(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTeamName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Build) validateAPIURL(formats strfmt.Registry) error { - - if err := validate.Required("api_url", "body", m.APIURL); err != nil { - return err - } - - return nil -} - -func (m *Build) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - return nil -} - -func (m *Build) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *Build) validateStatus(formats strfmt.Registry) error { - - if err := validate.Required("status", "body", m.Status); err != nil { - return err - } - - return nil -} - -func (m *Build) validateTeamName(formats strfmt.Registry) error { - - if err := validate.Required("team_name", "body", m.TeamName); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this build based on context it is used -func (m *Build) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *Build) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Build) UnmarshalBinary(b []byte) error { - var res Build - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/build_inputs_outputs.go b/client/models/build_inputs_outputs.go deleted file mode 100644 index 9db475f16..000000000 --- a/client/models/build_inputs_outputs.go +++ /dev/null @@ -1,204 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// BuildInputsOutputs BuildInputsOutputs -// -// Represent the resources input/output related to a build -// -// swagger:model BuildInputsOutputs -type BuildInputsOutputs struct { - - // inputs - // Required: true - Inputs []*PublicBuildInput `json:"inputs"` - - // outputs - // Required: true - Outputs []*PublicBuildOutput `json:"outputs"` -} - -// Validate validates this build inputs outputs -func (m *BuildInputsOutputs) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateInputs(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOutputs(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *BuildInputsOutputs) validateInputs(formats strfmt.Registry) error { - - if err := validate.Required("inputs", "body", m.Inputs); err != nil { - return err - } - - for i := 0; i < len(m.Inputs); i++ { - if swag.IsZero(m.Inputs[i]) { // not required - continue - } - - if m.Inputs[i] != nil { - if err := m.Inputs[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("inputs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("inputs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *BuildInputsOutputs) validateOutputs(formats strfmt.Registry) error { - - if err := validate.Required("outputs", "body", m.Outputs); err != nil { - return err - } - - for i := 0; i < len(m.Outputs); i++ { - if swag.IsZero(m.Outputs[i]) { // not required - continue - } - - if m.Outputs[i] != nil { - if err := m.Outputs[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("outputs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("outputs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this build inputs outputs based on the context it is used -func (m *BuildInputsOutputs) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateInputs(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateOutputs(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *BuildInputsOutputs) contextValidateInputs(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Inputs); i++ { - - if m.Inputs[i] != nil { - - if swag.IsZero(m.Inputs[i]) { // not required - return nil - } - - if err := m.Inputs[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("inputs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("inputs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *BuildInputsOutputs) contextValidateOutputs(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Outputs); i++ { - - if m.Outputs[i] != nil { - - if swag.IsZero(m.Outputs[i]) { // not required - return nil - } - - if err := m.Outputs[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("outputs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("outputs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *BuildInputsOutputs) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *BuildInputsOutputs) UnmarshalBinary(b []byte) error { - var res BuildInputsOutputs - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/build_summary.go b/client/models/build_summary.go deleted file mode 100644 index 80afc36e2..000000000 --- a/client/models/build_summary.go +++ /dev/null @@ -1,139 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// BuildSummary BuildSummary -// -// The information relative to a build summary. -// -// swagger:model BuildSummary -type BuildSummary struct { - - // end time - EndTime uint64 `json:"end_time,omitempty"` - - // id - // Required: true - ID *uint64 `json:"id"` - - // job name - JobName string `json:"job_name,omitempty"` - - // name - // Required: true - Name *string `json:"name"` - - // pipeline id - PipelineID uint64 `json:"pipeline_id,omitempty"` - - // pipeline name - PipelineName string `json:"pipeline_name,omitempty"` - - // plan - Plan any `json:"plan,omitempty"` - - // start time - StartTime uint64 `json:"start_time,omitempty"` - - // status - // Required: true - Status *string `json:"status"` - - // team name - // Required: true - TeamName *string `json:"team_name"` -} - -// Validate validates this build summary -func (m *BuildSummary) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTeamName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *BuildSummary) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - return nil -} - -func (m *BuildSummary) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *BuildSummary) validateStatus(formats strfmt.Registry) error { - - if err := validate.Required("status", "body", m.Status); err != nil { - return err - } - - return nil -} - -func (m *BuildSummary) validateTeamName(formats strfmt.Registry) error { - - if err := validate.Required("team_name", "body", m.TeamName); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this build summary based on context it is used -func (m *BuildSummary) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *BuildSummary) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *BuildSummary) UnmarshalBinary(b []byte) error { - var res BuildSummary - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/c_i_version.go b/client/models/c_i_version.go deleted file mode 100644 index 3fe592194..000000000 --- a/client/models/c_i_version.go +++ /dev/null @@ -1,26 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" -) - -// CIVersion CIVersion -// -// # Represent a version of a resource -// -// swagger:model CIVersion -type CIVersion map[string]string - -// Validate validates this c i version -func (m CIVersion) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this c i version based on context it is used -func (m CIVersion) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} diff --git a/client/models/can_do_input.go b/client/models/can_do_input.go deleted file mode 100644 index 33542aa87..000000000 --- a/client/models/can_do_input.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CanDoInput CanDoInput -// -// The input of the 'can_do' endpoint -// -// swagger:model CanDoInput -type CanDoInput struct { - - // action - // Required: true - Action *string `json:"action"` - - // List of the canonicals to the Resource excluding the Organization - // Required: true - EntityCanonicals []string `json:"entity_canonicals"` -} - -// Validate validates this can do input -func (m *CanDoInput) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAction(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEntityCanonicals(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CanDoInput) validateAction(formats strfmt.Registry) error { - - if err := validate.Required("action", "body", m.Action); err != nil { - return err - } - - return nil -} - -func (m *CanDoInput) validateEntityCanonicals(formats strfmt.Registry) error { - - if err := validate.Required("entity_canonicals", "body", m.EntityCanonicals); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this can do input based on context it is used -func (m *CanDoInput) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *CanDoInput) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CanDoInput) UnmarshalBinary(b []byte) error { - var res CanDoInput - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/can_do_output.go b/client/models/can_do_output.go deleted file mode 100644 index 42ddfbda2..000000000 --- a/client/models/can_do_output.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CanDoOutput CanDoOutput -// -// The output of the 'can_do' endpoint -// -// swagger:model CanDoOutput -type CanDoOutput struct { - - // entity canonicals - EntityCanonicals []string `json:"entity_canonicals"` - - // ok - // Required: true - Ok *bool `json:"ok"` -} - -// Validate validates this can do output -func (m *CanDoOutput) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateOk(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CanDoOutput) validateOk(formats strfmt.Registry) error { - - if err := validate.Required("ok", "body", m.Ok); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this can do output based on context it is used -func (m *CanDoOutput) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *CanDoOutput) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CanDoOutput) UnmarshalBinary(b []byte) error { - var res CanDoOutput - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/check_report.go b/client/models/check_report.go deleted file mode 100644 index 310fa170c..000000000 --- a/client/models/check_report.go +++ /dev/null @@ -1,173 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CheckReport CheckReport -// -// swagger:model CheckReport -type CheckReport struct { - - // The name of the service checked. - // Required: true - // Min Length: 1 - Canonical *string `json:"canonical"` - - // The category of the service checked. - // Required: true - // Min Length: 1 - Category *string `json:"category"` - - // The message providing information regarding the state of the service. - // Required: true - // Min Length: 1 - Message *string `json:"message"` - - // The status of the service checked. - // Required: true - // Enum: ["Unknown","Success","Error"] - Status *string `json:"status"` -} - -// Validate validates this check report -func (m *CheckReport) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCategory(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CheckReport) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - return nil -} - -func (m *CheckReport) validateCategory(formats strfmt.Registry) error { - - if err := validate.Required("category", "body", m.Category); err != nil { - return err - } - - if err := validate.MinLength("category", "body", *m.Category, 1); err != nil { - return err - } - - return nil -} - -func (m *CheckReport) validateMessage(formats strfmt.Registry) error { - - if err := validate.Required("message", "body", m.Message); err != nil { - return err - } - - if err := validate.MinLength("message", "body", *m.Message, 1); err != nil { - return err - } - - return nil -} - -var checkReportTypeStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["Unknown","Success","Error"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - checkReportTypeStatusPropEnum = append(checkReportTypeStatusPropEnum, v) - } -} - -const ( - - // CheckReportStatusUnknown captures enum value "Unknown" - CheckReportStatusUnknown string = "Unknown" - - // CheckReportStatusSuccess captures enum value "Success" - CheckReportStatusSuccess string = "Success" - - // CheckReportStatusError captures enum value "Error" - CheckReportStatusError string = "Error" -) - -// prop value enum -func (m *CheckReport) validateStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, checkReportTypeStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *CheckReport) validateStatus(formats strfmt.Registry) error { - - if err := validate.Required("status", "body", m.Status); err != nil { - return err - } - - // value enum - if err := m.validateStatusEnum("status", "body", *m.Status); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this check report based on context it is used -func (m *CheckReport) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *CheckReport) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CheckReport) UnmarshalBinary(b []byte) error { - var res CheckReport - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/clear_task_cache.go b/client/models/clear_task_cache.go deleted file mode 100644 index 17f03e83e..000000000 --- a/client/models/clear_task_cache.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ClearTaskCache ClearTaskCache -// -// The entity which represents number of cache cleared for a task. -// -// swagger:model ClearTaskCache -type ClearTaskCache struct { - - // caches removed - // Required: true - CachesRemoved *int64 `json:"caches_removed"` -} - -// Validate validates this clear task cache -func (m *ClearTaskCache) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCachesRemoved(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ClearTaskCache) validateCachesRemoved(formats strfmt.Registry) error { - - if err := validate.Required("caches_removed", "body", m.CachesRemoved); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this clear task cache based on context it is used -func (m *ClearTaskCache) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *ClearTaskCache) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ClearTaskCache) UnmarshalBinary(b []byte) error { - var res ClearTaskCache - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_account.go b/client/models/cloud_account.go deleted file mode 100644 index 318366785..000000000 --- a/client/models/cloud_account.go +++ /dev/null @@ -1,322 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudAccount Cloud Account -// -// CloudAccount represents a cloud account entity that wraps cloud credentials and is organization-scoped. Supports built-in cloud providers (canonicals: aws, google, azurerm; aliases such as gcp/microsoft azure are accepted and normalized) and custom cloud providers. -// -// swagger:model CloudAccount -type CloudAccount struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // The canonical of the associated cloud provider. Can be a built-in provider canonical (aws, google, azurerm; aliases like gcp/microsoft azure are accepted and normalized) or an org-scoped custom cloud provider canonical. - // Required: true - CloudProvider *string `json:"cloud_provider"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // credential - // Required: true - Credential *CredentialSimple `json:"credential"` - - // An optional description for the cloud account - Description string `json:"description,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // A user-defined name for the cloud account - // Required: true - // Max Length: 255 - // Min Length: 1 - Name *string `json:"name"` - - // Organization member that owns this cloud account. - // In the event where the user has been deleted this field might be empty. - // - Owner *User `json:"owner,omitempty"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` -} - -// Validate validates this cloud account -func (m *CloudAccount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredential(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudAccount) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *CloudAccount) validateCloudProvider(formats strfmt.Registry) error { - - if err := validate.Required("cloud_provider", "body", m.CloudProvider); err != nil { - return err - } - - return nil -} - -func (m *CloudAccount) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *CloudAccount) validateCredential(formats strfmt.Registry) error { - - if err := validate.Required("credential", "body", m.Credential); err != nil { - return err - } - - if m.Credential != nil { - if err := m.Credential.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("credential") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("credential") - } - - return err - } - } - - return nil -} - -func (m *CloudAccount) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *CloudAccount) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 255); err != nil { - return err - } - - return nil -} - -func (m *CloudAccount) validateOwner(formats strfmt.Registry) error { - if swag.IsZero(m.Owner) { // not required - return nil - } - - if m.Owner != nil { - if err := m.Owner.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *CloudAccount) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this cloud account based on the context it is used -func (m *CloudAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateCredential(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateOwner(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudAccount) contextValidateCredential(ctx context.Context, formats strfmt.Registry) error { - - if m.Credential != nil { - - if err := m.Credential.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("credential") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("credential") - } - - return err - } - } - - return nil -} - -func (m *CloudAccount) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { - - if m.Owner != nil { - - if swag.IsZero(m.Owner) { // not required - return nil - } - - if err := m.Owner.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CloudAccount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudAccount) UnmarshalBinary(b []byte) error { - var res CloudAccount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_account_detail.go b/client/models/cloud_account_detail.go deleted file mode 100644 index b4710de8b..000000000 --- a/client/models/cloud_account_detail.go +++ /dev/null @@ -1,265 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// CloudAccountDetail Cloud Account Detail -// -// Full detail of a Cloud Account including its associated Cloud Cost Management account when finops is enabled, and the environments linked to this cloud account. -// -// swagger:model CloudAccountDetail -type CloudAccountDetail struct { - CloudAccount - - // The environments linked to this cloud account - Environments []*EnvironmentSimple `json:"environments"` - - // The associated Cloud Cost Management account, present when finops_enabled is true - FinopsAccount *CloudCostManagementAccount `json:"finops_account,omitempty"` - - // Whether a Cloud Cost Management account is associated with this cloud account - FinopsEnabled bool `json:"finops_enabled,omitempty"` -} - -// UnmarshalJSON unmarshals this object from a JSON structure -func (m *CloudAccountDetail) UnmarshalJSON(raw []byte) error { - // AO0 - var aO0 CloudAccount - if err := swag.ReadJSON(raw, &aO0); err != nil { - return err - } - m.CloudAccount = aO0 - - // AO1 - var dataAO1 struct { - Environments []*EnvironmentSimple `json:"environments"` - - FinopsAccount *CloudCostManagementAccount `json:"finops_account,omitempty"` - - FinopsEnabled bool `json:"finops_enabled,omitempty"` - } - if err := swag.ReadJSON(raw, &dataAO1); err != nil { - return err - } - - m.Environments = dataAO1.Environments - - m.FinopsAccount = dataAO1.FinopsAccount - - m.FinopsEnabled = dataAO1.FinopsEnabled - - return nil -} - -// MarshalJSON marshals this object to a JSON structure -func (m CloudAccountDetail) MarshalJSON() ([]byte, error) { - _parts := make([][]byte, 0, 2) - - aO0, err := swag.WriteJSON(m.CloudAccount) - if err != nil { - return nil, err - } - _parts = append(_parts, aO0) - var dataAO1 struct { - Environments []*EnvironmentSimple `json:"environments"` - - FinopsAccount *CloudCostManagementAccount `json:"finops_account,omitempty"` - - FinopsEnabled bool `json:"finops_enabled,omitempty"` - } - - dataAO1.Environments = m.Environments - - dataAO1.FinopsAccount = m.FinopsAccount - - dataAO1.FinopsEnabled = m.FinopsEnabled - - jsonDataAO1, errAO1 := swag.WriteJSON(dataAO1) - if errAO1 != nil { - return nil, errAO1 - } - _parts = append(_parts, jsonDataAO1) - return swag.ConcatJSON(_parts...), nil -} - -// Validate validates this cloud account detail -func (m *CloudAccountDetail) Validate(formats strfmt.Registry) error { - var res []error - - // validation for a type composition with CloudAccount - if err := m.CloudAccount.Validate(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironments(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFinopsAccount(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudAccountDetail) validateEnvironments(formats strfmt.Registry) error { - - if swag.IsZero(m.Environments) { // not required - return nil - } - - for i := 0; i < len(m.Environments); i++ { - if swag.IsZero(m.Environments[i]) { // not required - continue - } - - if m.Environments[i] != nil { - if err := m.Environments[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environments" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environments" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *CloudAccountDetail) validateFinopsAccount(formats strfmt.Registry) error { - - if swag.IsZero(m.FinopsAccount) { // not required - return nil - } - - if m.FinopsAccount != nil { - if err := m.FinopsAccount.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("finops_account") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("finops_account") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this cloud account detail based on the context it is used -func (m *CloudAccountDetail) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - // validation for a type composition with CloudAccount - if err := m.CloudAccount.ContextValidate(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateEnvironments(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateFinopsAccount(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudAccountDetail) contextValidateEnvironments(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Environments); i++ { - - if m.Environments[i] != nil { - - if swag.IsZero(m.Environments[i]) { // not required - return nil - } - - if err := m.Environments[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environments" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environments" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *CloudAccountDetail) contextValidateFinopsAccount(ctx context.Context, formats strfmt.Registry) error { - - if m.FinopsAccount != nil { - - if swag.IsZero(m.FinopsAccount) { // not required - return nil - } - - if err := m.FinopsAccount.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("finops_account") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("finops_account") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CloudAccountDetail) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudAccountDetail) UnmarshalBinary(b []byte) error { - var res CloudAccountDetail - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_account_simple.go b/client/models/cloud_account_simple.go deleted file mode 100644 index 067717534..000000000 --- a/client/models/cloud_account_simple.go +++ /dev/null @@ -1,151 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudAccountSimple Cloud Account Simple -// -// A simplified cloud account representation without credentials, used when embedding a cloud account in other entities. -// -// swagger:model CloudAccountSimple -type CloudAccountSimple struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // The canonical of the associated cloud provider. Can be a built-in provider canonical (aws, google, azurerm; aliases like gcp/microsoft azure are accepted and normalized) or an org-scoped custom cloud provider canonical. - // Required: true - CloudProvider *string `json:"cloud_provider"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // A user-defined name for the cloud account - // Required: true - // Max Length: 255 - // Min Length: 1 - Name *string `json:"name"` -} - -// Validate validates this cloud account simple -func (m *CloudAccountSimple) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudAccountSimple) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *CloudAccountSimple) validateCloudProvider(formats strfmt.Registry) error { - - if err := validate.Required("cloud_provider", "body", m.CloudProvider); err != nil { - return err - } - - return nil -} - -func (m *CloudAccountSimple) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *CloudAccountSimple) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 255); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this cloud account simple based on context it is used -func (m *CloudAccountSimple) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *CloudAccountSimple) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudAccountSimple) UnmarshalBinary(b []byte) error { - var res CloudAccountSimple - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_cost_management_account.go b/client/models/cloud_cost_management_account.go deleted file mode 100644 index 389ca3541..000000000 --- a/client/models/cloud_cost_management_account.go +++ /dev/null @@ -1,476 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudCostManagementAccount CloudCostManagementAccount -// -// # Object containing Cloud Cost Management account parameters -// -// swagger:model CloudCostManagementAccount -type CloudCostManagementAccount struct { - - // The ID of an account on the CP - // Required: true - AccountID *string `json:"account_id"` - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // cloud provider - // Required: true - CloudProvider *CloudProvider `json:"cloud_provider"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // enabled - // Required: true - Enabled *bool `json:"enabled"` - - // external backend - ExternalBackend *ExternalBackend `json:"external_backend,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // last ingestion ended at - // Minimum: 0 - LastIngestionEndedAt *uint64 `json:"last_ingestion_ended_at,omitempty"` - - // last ingestion started at - // Minimum: 0 - LastIngestionStartedAt *uint64 `json:"last_ingestion_started_at,omitempty"` - - // A user-defined name for the account - // Required: true - Name *string `json:"name"` - - // phase - // Enum: ["green","blue"] - Phase string `json:"phase,omitempty"` - - // status - // Required: true - // Enum: ["idle","error","import"] - Status *string `json:"status"` - - // status message - StatusMessage string `json:"status_message,omitempty"` - - // unfinalized period - UnfinalizedPeriod string `json:"unfinalized_period,omitempty"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` -} - -// Validate validates this cloud cost management account -func (m *CloudCostManagementAccount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAccountID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnabled(formats); err != nil { - res = append(res, err) - } - - if err := m.validateExternalBackend(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLastIngestionEndedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLastIngestionStartedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePhase(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementAccount) validateAccountID(formats strfmt.Registry) error { - - if err := validate.Required("account_id", "body", m.AccountID); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementAccount) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementAccount) validateCloudProvider(formats strfmt.Registry) error { - - if err := validate.Required("cloud_provider", "body", m.CloudProvider); err != nil { - return err - } - - if m.CloudProvider != nil { - if err := m.CloudProvider.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cloud_provider") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cloud_provider") - } - - return err - } - } - - return nil -} - -func (m *CloudCostManagementAccount) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementAccount) validateEnabled(formats strfmt.Registry) error { - - if err := validate.Required("enabled", "body", m.Enabled); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementAccount) validateExternalBackend(formats strfmt.Registry) error { - if swag.IsZero(m.ExternalBackend) { // not required - return nil - } - - if m.ExternalBackend != nil { - if err := m.ExternalBackend.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("external_backend") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("external_backend") - } - - return err - } - } - - return nil -} - -func (m *CloudCostManagementAccount) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementAccount) validateLastIngestionEndedAt(formats strfmt.Registry) error { - if swag.IsZero(m.LastIngestionEndedAt) { // not required - return nil - } - - if err := validate.MinimumUint("last_ingestion_ended_at", "body", *m.LastIngestionEndedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementAccount) validateLastIngestionStartedAt(formats strfmt.Registry) error { - if swag.IsZero(m.LastIngestionStartedAt) { // not required - return nil - } - - if err := validate.MinimumUint("last_ingestion_started_at", "body", *m.LastIngestionStartedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementAccount) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -var cloudCostManagementAccountTypePhasePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["green","blue"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - cloudCostManagementAccountTypePhasePropEnum = append(cloudCostManagementAccountTypePhasePropEnum, v) - } -} - -const ( - - // CloudCostManagementAccountPhaseGreen captures enum value "green" - CloudCostManagementAccountPhaseGreen string = "green" - - // CloudCostManagementAccountPhaseBlue captures enum value "blue" - CloudCostManagementAccountPhaseBlue string = "blue" -) - -// prop value enum -func (m *CloudCostManagementAccount) validatePhaseEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, cloudCostManagementAccountTypePhasePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *CloudCostManagementAccount) validatePhase(formats strfmt.Registry) error { - if swag.IsZero(m.Phase) { // not required - return nil - } - - // value enum - if err := m.validatePhaseEnum("phase", "body", m.Phase); err != nil { - return err - } - - return nil -} - -var cloudCostManagementAccountTypeStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["idle","error","import"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - cloudCostManagementAccountTypeStatusPropEnum = append(cloudCostManagementAccountTypeStatusPropEnum, v) - } -} - -const ( - - // CloudCostManagementAccountStatusIdle captures enum value "idle" - CloudCostManagementAccountStatusIdle string = "idle" - - // CloudCostManagementAccountStatusError captures enum value "error" - CloudCostManagementAccountStatusError string = "error" - - // CloudCostManagementAccountStatusImport captures enum value "import" - CloudCostManagementAccountStatusImport string = "import" -) - -// prop value enum -func (m *CloudCostManagementAccount) validateStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, cloudCostManagementAccountTypeStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *CloudCostManagementAccount) validateStatus(formats strfmt.Registry) error { - - if err := validate.Required("status", "body", m.Status); err != nil { - return err - } - - // value enum - if err := m.validateStatusEnum("status", "body", *m.Status); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementAccount) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this cloud cost management account based on the context it is used -func (m *CloudCostManagementAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateCloudProvider(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateExternalBackend(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementAccount) contextValidateCloudProvider(ctx context.Context, formats strfmt.Registry) error { - - if m.CloudProvider != nil { - - if err := m.CloudProvider.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cloud_provider") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cloud_provider") - } - - return err - } - } - - return nil -} - -func (m *CloudCostManagementAccount) contextValidateExternalBackend(ctx context.Context, formats strfmt.Registry) error { - - if m.ExternalBackend != nil { - - if swag.IsZero(m.ExternalBackend) { // not required - return nil - } - - if err := m.ExternalBackend.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("external_backend") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("external_backend") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CloudCostManagementAccount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudCostManagementAccount) UnmarshalBinary(b []byte) error { - var res CloudCostManagementAccount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_cost_management_bucket.go b/client/models/cloud_cost_management_bucket.go deleted file mode 100644 index 374f02015..000000000 --- a/client/models/cloud_cost_management_bucket.go +++ /dev/null @@ -1,206 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudCostManagementBucket CloudCostManagementBucket -// -// A sum of the cost generated in a period aggregated by one or more terms, -// for example if we aggregate costs by project here we have all the cost -// generated by a specific project in the period of time defined by the -// filters of the histogram. In case the filter specifies more than one -// aggregation term this type will recursively contain the other levels of -// aggregation. -// -// swagger:model CloudCostManagementBucket -type CloudCostManagementBucket struct { - - // buckets - Buckets []*CloudCostManagementBucket `json:"buckets"` - - // The total CO2e emissions for the aggregated usage, in metric tons. - // Required: true - Co2e *float64 `json:"co2e"` - - // cost - // Required: true - Cost *float64 `json:"cost"` - - // The total energy consumption for the aggregated usage, in kwh - // Required: true - Kwh *float64 `json:"kwh"` - - // The value of the aggregation term, for example if we aggregate cost - // by region aggregate_value can be us-east-2, if we aggregate by project - // this can be cool_project_number_42, by service can be S3 or EC2, etc.. - // - // Required: true - Value *string `json:"value"` -} - -// Validate validates this cloud cost management bucket -func (m *CloudCostManagementBucket) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBuckets(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCo2e(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCost(formats); err != nil { - res = append(res, err) - } - - if err := m.validateKwh(formats); err != nil { - res = append(res, err) - } - - if err := m.validateValue(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementBucket) validateBuckets(formats strfmt.Registry) error { - if swag.IsZero(m.Buckets) { // not required - return nil - } - - for i := 0; i < len(m.Buckets); i++ { - if swag.IsZero(m.Buckets[i]) { // not required - continue - } - - if m.Buckets[i] != nil { - if err := m.Buckets[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("buckets" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("buckets" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *CloudCostManagementBucket) validateCo2e(formats strfmt.Registry) error { - - if err := validate.Required("co2e", "body", m.Co2e); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementBucket) validateCost(formats strfmt.Registry) error { - - if err := validate.Required("cost", "body", m.Cost); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementBucket) validateKwh(formats strfmt.Registry) error { - - if err := validate.Required("kwh", "body", m.Kwh); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementBucket) validateValue(formats strfmt.Registry) error { - - if err := validate.Required("value", "body", m.Value); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this cloud cost management bucket based on the context it is used -func (m *CloudCostManagementBucket) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateBuckets(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementBucket) contextValidateBuckets(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Buckets); i++ { - - if m.Buckets[i] != nil { - - if swag.IsZero(m.Buckets[i]) { // not required - return nil - } - - if err := m.Buckets[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("buckets" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("buckets" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CloudCostManagementBucket) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudCostManagementBucket) UnmarshalBinary(b []byte) error { - var res CloudCostManagementBucket - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_cost_management_dashboard.go b/client/models/cloud_cost_management_dashboard.go deleted file mode 100644 index 6285e4132..000000000 --- a/client/models/cloud_cost_management_dashboard.go +++ /dev/null @@ -1,319 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudCostManagementDashboard CloudCostManagementDashboard -// -// The dashboard of the Cloud Cost Management, it contains -// - a histogram of the cost in the period aggregated by provider and -// by time granularity -// - a histogram of the cost aggregated by the top projects and providers -// and filtered by the top projects -// - a list of resources and relative cost for each top projects -// - a map containing properties that can be specified filtering the -// returned results, with a set of valid values for each. -// -// swagger:model CloudCostManagementDashboard -type CloudCostManagementDashboard struct { - - // filter values - // Required: true - FilterValues *CloudCostManagementFilterValues `json:"filter_values"` - - // project resources - // Required: true - ProjectResources []*CloudCostManagementProjectResources `json:"project_resources"` - - // projects - // Required: true - Projects *CloudCostManagementHistogram `json:"projects"` - - // providers - // Required: true - Providers *CloudCostManagementHistogram `json:"providers"` - - // total co2e - TotalCo2e float64 `json:"total_co2e,omitempty"` - - // total cost - TotalCost float64 `json:"total_cost,omitempty"` - - // total kwh - TotalKwh float64 `json:"total_kwh,omitempty"` -} - -// Validate validates this cloud cost management dashboard -func (m *CloudCostManagementDashboard) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateFilterValues(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjectResources(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjects(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProviders(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementDashboard) validateFilterValues(formats strfmt.Registry) error { - - if err := validate.Required("filter_values", "body", m.FilterValues); err != nil { - return err - } - - if m.FilterValues != nil { - if err := m.FilterValues.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("filter_values") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("filter_values") - } - - return err - } - } - - return nil -} - -func (m *CloudCostManagementDashboard) validateProjectResources(formats strfmt.Registry) error { - - if err := validate.Required("project_resources", "body", m.ProjectResources); err != nil { - return err - } - - for i := 0; i < len(m.ProjectResources); i++ { - if swag.IsZero(m.ProjectResources[i]) { // not required - continue - } - - if m.ProjectResources[i] != nil { - if err := m.ProjectResources[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project_resources" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project_resources" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *CloudCostManagementDashboard) validateProjects(formats strfmt.Registry) error { - - if err := validate.Required("projects", "body", m.Projects); err != nil { - return err - } - - if m.Projects != nil { - if err := m.Projects.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("projects") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("projects") - } - - return err - } - } - - return nil -} - -func (m *CloudCostManagementDashboard) validateProviders(formats strfmt.Registry) error { - - if err := validate.Required("providers", "body", m.Providers); err != nil { - return err - } - - if m.Providers != nil { - if err := m.Providers.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("providers") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("providers") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this cloud cost management dashboard based on the context it is used -func (m *CloudCostManagementDashboard) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateFilterValues(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateProjectResources(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateProjects(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateProviders(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementDashboard) contextValidateFilterValues(ctx context.Context, formats strfmt.Registry) error { - - if m.FilterValues != nil { - - if err := m.FilterValues.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("filter_values") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("filter_values") - } - - return err - } - } - - return nil -} - -func (m *CloudCostManagementDashboard) contextValidateProjectResources(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.ProjectResources); i++ { - - if m.ProjectResources[i] != nil { - - if swag.IsZero(m.ProjectResources[i]) { // not required - return nil - } - - if err := m.ProjectResources[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project_resources" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project_resources" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *CloudCostManagementDashboard) contextValidateProjects(ctx context.Context, formats strfmt.Registry) error { - - if m.Projects != nil { - - if err := m.Projects.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("projects") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("projects") - } - - return err - } - } - - return nil -} - -func (m *CloudCostManagementDashboard) contextValidateProviders(ctx context.Context, formats strfmt.Registry) error { - - if m.Providers != nil { - - if err := m.Providers.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("providers") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("providers") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CloudCostManagementDashboard) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudCostManagementDashboard) UnmarshalBinary(b []byte) error { - var res CloudCostManagementDashboard - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_cost_management_filter_values.go b/client/models/cloud_cost_management_filter_values.go deleted file mode 100644 index ed719b3cd..000000000 --- a/client/models/cloud_cost_management_filter_values.go +++ /dev/null @@ -1,92 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// CloudCostManagementFilterValues CloudCostManagementFilterValues -// -// A collection of the values for which the cost can be filtered, i.e. all -// the providers, services, regions, etc... for one org. -// -// swagger:model CloudCostManagementFilterValues -type CloudCostManagementFilterValues struct { - - // categories - Categories []string `json:"categories"` - - // components - Components []string `json:"components"` - - // currencies - Currencies []string `json:"currencies"` - - // environments - Environments []string `json:"environments"` - - // instance types - InstanceTypes []string `json:"instance_types"` - - // linked accounts - LinkedAccounts []string `json:"linked_accounts"` - - // linked accounts with cp - LinkedAccountsWithCp any `json:"linked_accounts_with_cp,omitempty"` - - // master accounts - MasterAccounts []string `json:"master_accounts"` - - // master accounts with cp - MasterAccountsWithCp any `json:"master_accounts_with_cp,omitempty"` - - // projects - Projects []string `json:"projects"` - - // providers - Providers []string `json:"providers"` - - // regions - Regions []string `json:"regions"` - - // resources - Resources []string `json:"resources"` - - // services - Services []string `json:"services"` - - // tags - Tags map[string][]string `json:"tags,omitempty"` -} - -// Validate validates this cloud cost management filter values -func (m *CloudCostManagementFilterValues) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this cloud cost management filter values based on context it is used -func (m *CloudCostManagementFilterValues) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *CloudCostManagementFilterValues) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudCostManagementFilterValues) UnmarshalBinary(b []byte) error { - var res CloudCostManagementFilterValues - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_cost_management_histogram.go b/client/models/cloud_cost_management_histogram.go deleted file mode 100644 index 1099cb106..000000000 --- a/client/models/cloud_cost_management_histogram.go +++ /dev/null @@ -1,183 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudCostManagementHistogram CloudCostManagementHistogram -// -// The histogram of the costs for a period composed of buckets that aggregate the costs. -// -// swagger:model CloudCostManagementHistogram -type CloudCostManagementHistogram struct { - - // buckets - // Required: true - Buckets []*CloudCostManagementBucket `json:"buckets"` - - // The total CO2e emissions for the period, in metric tons. - // Required: true - Co2e *float64 `json:"co2e"` - - // The total cost for the period. - // Required: true - Cost *float64 `json:"cost"` - - // The total energy consumption for the period, in kwh. - // Required: true - Kwh *float64 `json:"kwh"` -} - -// Validate validates this cloud cost management histogram -func (m *CloudCostManagementHistogram) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBuckets(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCo2e(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCost(formats); err != nil { - res = append(res, err) - } - - if err := m.validateKwh(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementHistogram) validateBuckets(formats strfmt.Registry) error { - - if err := validate.Required("buckets", "body", m.Buckets); err != nil { - return err - } - - for i := 0; i < len(m.Buckets); i++ { - if swag.IsZero(m.Buckets[i]) { // not required - continue - } - - if m.Buckets[i] != nil { - if err := m.Buckets[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("buckets" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("buckets" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *CloudCostManagementHistogram) validateCo2e(formats strfmt.Registry) error { - - if err := validate.Required("co2e", "body", m.Co2e); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementHistogram) validateCost(formats strfmt.Registry) error { - - if err := validate.Required("cost", "body", m.Cost); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementHistogram) validateKwh(formats strfmt.Registry) error { - - if err := validate.Required("kwh", "body", m.Kwh); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this cloud cost management histogram based on the context it is used -func (m *CloudCostManagementHistogram) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateBuckets(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementHistogram) contextValidateBuckets(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Buckets); i++ { - - if m.Buckets[i] != nil { - - if swag.IsZero(m.Buckets[i]) { // not required - return nil - } - - if err := m.Buckets[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("buckets" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("buckets" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CloudCostManagementHistogram) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudCostManagementHistogram) UnmarshalBinary(b []byte) error { - var res CloudCostManagementHistogram - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_cost_management_linked_account.go b/client/models/cloud_cost_management_linked_account.go deleted file mode 100644 index c17ab2c5a..000000000 --- a/client/models/cloud_cost_management_linked_account.go +++ /dev/null @@ -1,129 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudCostManagementLinkedAccount CloudCostManagementLinkedAccount -// -// An account that is linked to a Cloud Cost Management account in the cloud -// provider. It is not managed by Cloud Cost Management, but appears in the cost records. -// -// swagger:model CloudCostManagementLinkedAccount -type CloudCostManagementLinkedAccount struct { - - // ID of the account in the cloud provider - // Required: true - AccountID *string `json:"account_id"` - - // The cloud provider canonical that this project is using - between the - // supported ones. - // - // Required: true - CloudProvider *string `json:"cloud_provider"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // A user-defined name for the account - // Required: true - Name *string `json:"name"` -} - -// Validate validates this cloud cost management linked account -func (m *CloudCostManagementLinkedAccount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAccountID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementLinkedAccount) validateAccountID(formats strfmt.Registry) error { - - if err := validate.Required("account_id", "body", m.AccountID); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementLinkedAccount) validateCloudProvider(formats strfmt.Registry) error { - - if err := validate.Required("cloud_provider", "body", m.CloudProvider); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementLinkedAccount) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementLinkedAccount) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this cloud cost management linked account based on context it is used -func (m *CloudCostManagementLinkedAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *CloudCostManagementLinkedAccount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudCostManagementLinkedAccount) UnmarshalBinary(b []byte) error { - var res CloudCostManagementLinkedAccount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_cost_management_project_provider_resources.go b/client/models/cloud_cost_management_project_provider_resources.go deleted file mode 100644 index 7ad402518..000000000 --- a/client/models/cloud_cost_management_project_provider_resources.go +++ /dev/null @@ -1,155 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudCostManagementProjectProviderResources CloudCostManagementProjectProviderResources -// -// # Trend for a project -// -// swagger:model CloudCostManagementProjectProviderResources -type CloudCostManagementProjectProviderResources struct { - - // CO2e emissions for the project and provider, in metric tons - // Required: true - Co2e *float64 `json:"co2e"` - - // Cost of the project for the provider - // Required: true - Cost *float64 `json:"cost"` - - // Energy consumption for the project and provider, in kwh - // Required: true - Kwh *float64 `json:"kwh"` - - // new resources - // Required: true - NewResources *int64 `json:"new_resources"` - - // provider - // Required: true - Provider *string `json:"provider"` - - // resources - // Required: true - Resources *int64 `json:"resources"` -} - -// Validate validates this cloud cost management project provider resources -func (m *CloudCostManagementProjectProviderResources) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCo2e(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCost(formats); err != nil { - res = append(res, err) - } - - if err := m.validateKwh(formats); err != nil { - res = append(res, err) - } - - if err := m.validateNewResources(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateResources(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementProjectProviderResources) validateCo2e(formats strfmt.Registry) error { - - if err := validate.Required("co2e", "body", m.Co2e); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementProjectProviderResources) validateCost(formats strfmt.Registry) error { - - if err := validate.Required("cost", "body", m.Cost); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementProjectProviderResources) validateKwh(formats strfmt.Registry) error { - - if err := validate.Required("kwh", "body", m.Kwh); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementProjectProviderResources) validateNewResources(formats strfmt.Registry) error { - - if err := validate.Required("new_resources", "body", m.NewResources); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementProjectProviderResources) validateProvider(formats strfmt.Registry) error { - - if err := validate.Required("provider", "body", m.Provider); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementProjectProviderResources) validateResources(formats strfmt.Registry) error { - - if err := validate.Required("resources", "body", m.Resources); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this cloud cost management project provider resources based on context it is used -func (m *CloudCostManagementProjectProviderResources) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *CloudCostManagementProjectProviderResources) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudCostManagementProjectProviderResources) UnmarshalBinary(b []byte) error { - var res CloudCostManagementProjectProviderResources - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_cost_management_project_resources.go b/client/models/cloud_cost_management_project_resources.go deleted file mode 100644 index f902444b8..000000000 --- a/client/models/cloud_cost_management_project_resources.go +++ /dev/null @@ -1,166 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudCostManagementProjectResources CloudCostManagementProjectResources -// -// The new resources and associated cost for a project in a period of time. -// -// swagger:model CloudCostManagementProjectResources -type CloudCostManagementProjectResources struct { - - // Cost for the project in the period - // Required: true - Cost *float64 `json:"cost"` - - // project - // Required: true - Project *string `json:"project"` - - // providers - // Required: true - Providers []*CloudCostManagementProjectProviderResources `json:"providers"` -} - -// Validate validates this cloud cost management project resources -func (m *CloudCostManagementProjectResources) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCost(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProject(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProviders(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementProjectResources) validateCost(formats strfmt.Registry) error { - - if err := validate.Required("cost", "body", m.Cost); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementProjectResources) validateProject(formats strfmt.Registry) error { - - if err := validate.Required("project", "body", m.Project); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementProjectResources) validateProviders(formats strfmt.Registry) error { - - if err := validate.Required("providers", "body", m.Providers); err != nil { - return err - } - - for i := 0; i < len(m.Providers); i++ { - if swag.IsZero(m.Providers[i]) { // not required - continue - } - - if m.Providers[i] != nil { - if err := m.Providers[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("providers" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("providers" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this cloud cost management project resources based on the context it is used -func (m *CloudCostManagementProjectResources) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateProviders(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementProjectResources) contextValidateProviders(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Providers); i++ { - - if m.Providers[i] != nil { - - if swag.IsZero(m.Providers[i]) { // not required - return nil - } - - if err := m.Providers[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("providers" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("providers" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CloudCostManagementProjectResources) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudCostManagementProjectResources) UnmarshalBinary(b []byte) error { - var res CloudCostManagementProjectResources - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_cost_management_projects_dashboard.go b/client/models/cloud_cost_management_projects_dashboard.go deleted file mode 100644 index 32c56657b..000000000 --- a/client/models/cloud_cost_management_projects_dashboard.go +++ /dev/null @@ -1,175 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudCostManagementProjectsDashboard CloudCostManagementProjectsDashboard -// -// The projects dashboard of the Cloud Cost Management, it contains -// - a histogram of the cost aggregated by date and project -// - a histogram of cost aggregated by projects and providers -// -// swagger:model CloudCostManagementProjectsDashboard -type CloudCostManagementProjectsDashboard struct { - - // project providers - // Required: true - ProjectProviders *CloudCostManagementHistogram `json:"project_providers"` - - // projects - // Required: true - Projects *CloudCostManagementHistogram `json:"projects"` -} - -// Validate validates this cloud cost management projects dashboard -func (m *CloudCostManagementProjectsDashboard) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateProjectProviders(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjects(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementProjectsDashboard) validateProjectProviders(formats strfmt.Registry) error { - - if err := validate.Required("project_providers", "body", m.ProjectProviders); err != nil { - return err - } - - if m.ProjectProviders != nil { - if err := m.ProjectProviders.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project_providers") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project_providers") - } - - return err - } - } - - return nil -} - -func (m *CloudCostManagementProjectsDashboard) validateProjects(formats strfmt.Registry) error { - - if err := validate.Required("projects", "body", m.Projects); err != nil { - return err - } - - if m.Projects != nil { - if err := m.Projects.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("projects") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("projects") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this cloud cost management projects dashboard based on the context it is used -func (m *CloudCostManagementProjectsDashboard) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateProjectProviders(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateProjects(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementProjectsDashboard) contextValidateProjectProviders(ctx context.Context, formats strfmt.Registry) error { - - if m.ProjectProviders != nil { - - if err := m.ProjectProviders.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project_providers") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project_providers") - } - - return err - } - } - - return nil -} - -func (m *CloudCostManagementProjectsDashboard) contextValidateProjects(ctx context.Context, formats strfmt.Registry) error { - - if m.Projects != nil { - - if err := m.Projects.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("projects") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("projects") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CloudCostManagementProjectsDashboard) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudCostManagementProjectsDashboard) UnmarshalBinary(b []byte) error { - var res CloudCostManagementProjectsDashboard - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_cost_management_provider_details.go b/client/models/cloud_cost_management_provider_details.go deleted file mode 100644 index b41b788da..000000000 --- a/client/models/cloud_cost_management_provider_details.go +++ /dev/null @@ -1,175 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudCostManagementProviderDetails CloudCostManagementProviderDetails -// -// # Description of the costs of a specific provider -// -// swagger:model CloudCostManagementProviderDetails -type CloudCostManagementProviderDetails struct { - - // cost histogram - // Required: true - CostHistogram *CloudCostManagementHistogram `json:"cost_histogram"` - - // filter values - FilterValues *CloudCostManagementFilterValues `json:"filter_values,omitempty"` -} - -// Validate validates this cloud cost management provider details -func (m *CloudCostManagementProviderDetails) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCostHistogram(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFilterValues(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementProviderDetails) validateCostHistogram(formats strfmt.Registry) error { - - if err := validate.Required("cost_histogram", "body", m.CostHistogram); err != nil { - return err - } - - if m.CostHistogram != nil { - if err := m.CostHistogram.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cost_histogram") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cost_histogram") - } - - return err - } - } - - return nil -} - -func (m *CloudCostManagementProviderDetails) validateFilterValues(formats strfmt.Registry) error { - if swag.IsZero(m.FilterValues) { // not required - return nil - } - - if m.FilterValues != nil { - if err := m.FilterValues.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("filter_values") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("filter_values") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this cloud cost management provider details based on the context it is used -func (m *CloudCostManagementProviderDetails) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateCostHistogram(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateFilterValues(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementProviderDetails) contextValidateCostHistogram(ctx context.Context, formats strfmt.Registry) error { - - if m.CostHistogram != nil { - - if err := m.CostHistogram.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cost_histogram") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cost_histogram") - } - - return err - } - } - - return nil -} - -func (m *CloudCostManagementProviderDetails) contextValidateFilterValues(ctx context.Context, formats strfmt.Registry) error { - - if m.FilterValues != nil { - - if swag.IsZero(m.FilterValues) { // not required - return nil - } - - if err := m.FilterValues.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("filter_values") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("filter_values") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CloudCostManagementProviderDetails) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudCostManagementProviderDetails) UnmarshalBinary(b []byte) error { - var res CloudCostManagementProviderDetails - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_cost_management_providers.go b/client/models/cloud_cost_management_providers.go deleted file mode 100644 index 8d6345f2c..000000000 --- a/client/models/cloud_cost_management_providers.go +++ /dev/null @@ -1,116 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudCostManagementProviders CloudCostManagementProviders -// -// # Date histogram of the cost of all the providers -// -// swagger:model CloudCostManagementProviders -type CloudCostManagementProviders struct { - - // cost histogram - // Required: true - CostHistogram *CloudCostManagementHistogram `json:"cost_histogram"` -} - -// Validate validates this cloud cost management providers -func (m *CloudCostManagementProviders) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCostHistogram(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementProviders) validateCostHistogram(formats strfmt.Registry) error { - - if err := validate.Required("cost_histogram", "body", m.CostHistogram); err != nil { - return err - } - - if m.CostHistogram != nil { - if err := m.CostHistogram.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cost_histogram") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cost_histogram") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this cloud cost management providers based on the context it is used -func (m *CloudCostManagementProviders) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateCostHistogram(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementProviders) contextValidateCostHistogram(ctx context.Context, formats strfmt.Registry) error { - - if m.CostHistogram != nil { - - if err := m.CostHistogram.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cost_histogram") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cost_histogram") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CloudCostManagementProviders) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudCostManagementProviders) UnmarshalBinary(b []byte) error { - var res CloudCostManagementProviders - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_cost_management_tag_mapping.go b/client/models/cloud_cost_management_tag_mapping.go deleted file mode 100644 index e581021ce..000000000 --- a/client/models/cloud_cost_management_tag_mapping.go +++ /dev/null @@ -1,143 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudCostManagementTagMapping CloudCostManagementTagMapping -// -// Object containing Cloud Cost Management tag mapping. The mapping is used to -// identify resources belonging to projects and environments across cloud -// providers. The mapping can be a set of tag keys or a regexp to capture -// tag keys. -// -// swagger:model CloudCostManagementTagMapping -type CloudCostManagementTagMapping struct { - - // This is a list of all the tag keys in the DB for the Org - AllTags []string `json:"all_tags"` - - // component regex - ComponentRegex string `json:"component_regex,omitempty"` - - // component tags - ComponentTags []string `json:"component_tags"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // environment regex - EnvironmentRegex string `json:"environment_regex,omitempty"` - - // environment tags - EnvironmentTags []string `json:"environment_tags"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // project regex - ProjectRegex string `json:"project_regex,omitempty"` - - // project tags - ProjectTags []string `json:"project_tags"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` -} - -// Validate validates this cloud cost management tag mapping -func (m *CloudCostManagementTagMapping) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudCostManagementTagMapping) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementTagMapping) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *CloudCostManagementTagMapping) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this cloud cost management tag mapping based on context it is used -func (m *CloudCostManagementTagMapping) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *CloudCostManagementTagMapping) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudCostManagementTagMapping) UnmarshalBinary(b []byte) error { - var res CloudCostManagementTagMapping - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_provider.go b/client/models/cloud_provider.go deleted file mode 100644 index 983e811fa..000000000 --- a/client/models/cloud_provider.go +++ /dev/null @@ -1,266 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudProvider Cloud Provider -// -// CloudProvider represents a cloud provider. Those cloud providers are used to identify the scope of projects and/or stacks. -// -// swagger:model CloudProvider -type CloudProvider struct { - - // abbreviation - // Max Length: 60 - // Min Length: 2 - Abbreviation string `json:"abbreviation,omitempty"` - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - // Enum: ["aws","google","azurerm","flexibleengine","openstack","scaleway","vmware","ovh","alibaba","oracle","vsphere","kubernetes"] - Canonical *string `json:"canonical"` - - // created at - // Minimum: 0 - CreatedAt *uint64 `json:"created_at,omitempty"` - - // id - // Minimum: 1 - ID uint32 `json:"id,omitempty"` - - // name - // Required: true - // Max Length: 60 - // Min Length: 2 - Name *string `json:"name"` - - // regions - Regions []string `json:"regions"` - - // updated at - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` -} - -// Validate validates this cloud provider -func (m *CloudProvider) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAbbreviation(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudProvider) validateAbbreviation(formats strfmt.Registry) error { - if swag.IsZero(m.Abbreviation) { // not required - return nil - } - - if err := validate.MinLength("abbreviation", "body", m.Abbreviation, 2); err != nil { - return err - } - - if err := validate.MaxLength("abbreviation", "body", m.Abbreviation, 60); err != nil { - return err - } - - return nil -} - -var cloudProviderTypeCanonicalPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["aws","google","azurerm","flexibleengine","openstack","scaleway","vmware","ovh","alibaba","oracle","vsphere","kubernetes"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - cloudProviderTypeCanonicalPropEnum = append(cloudProviderTypeCanonicalPropEnum, v) - } -} - -const ( - - // CloudProviderCanonicalAws captures enum value "aws" - CloudProviderCanonicalAws string = "aws" - - // CloudProviderCanonicalGoogle captures enum value "google" - CloudProviderCanonicalGoogle string = "google" - - // CloudProviderCanonicalAzurerm captures enum value "azurerm" - CloudProviderCanonicalAzurerm string = "azurerm" - - // CloudProviderCanonicalFlexibleengine captures enum value "flexibleengine" - CloudProviderCanonicalFlexibleengine string = "flexibleengine" - - // CloudProviderCanonicalOpenstack captures enum value "openstack" - CloudProviderCanonicalOpenstack string = "openstack" - - // CloudProviderCanonicalScaleway captures enum value "scaleway" - CloudProviderCanonicalScaleway string = "scaleway" - - // CloudProviderCanonicalVmware captures enum value "vmware" - CloudProviderCanonicalVmware string = "vmware" - - // CloudProviderCanonicalOvh captures enum value "ovh" - CloudProviderCanonicalOvh string = "ovh" - - // CloudProviderCanonicalAlibaba captures enum value "alibaba" - CloudProviderCanonicalAlibaba string = "alibaba" - - // CloudProviderCanonicalOracle captures enum value "oracle" - CloudProviderCanonicalOracle string = "oracle" - - // CloudProviderCanonicalVsphere captures enum value "vsphere" - CloudProviderCanonicalVsphere string = "vsphere" - - // CloudProviderCanonicalKubernetes captures enum value "kubernetes" - CloudProviderCanonicalKubernetes string = "kubernetes" -) - -// prop value enum -func (m *CloudProvider) validateCanonicalEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, cloudProviderTypeCanonicalPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *CloudProvider) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - // value enum - if err := m.validateCanonicalEnum("canonical", "body", *m.Canonical); err != nil { - return err - } - - return nil -} - -func (m *CloudProvider) validateCreatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *CloudProvider) validateID(formats strfmt.Registry) error { - if swag.IsZero(m.ID) { // not required - return nil - } - - if err := validate.MinimumUint("id", "body", uint64(m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *CloudProvider) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 2); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 60); err != nil { - return err - } - - return nil -} - -func (m *CloudProvider) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this cloud provider based on context it is used -func (m *CloudProvider) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *CloudProvider) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudProvider) UnmarshalBinary(b []byte) error { - var res CloudProvider - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_provider_a_w_s_configuration.go b/client/models/cloud_provider_a_w_s_configuration.go deleted file mode 100644 index 9af0828f9..000000000 --- a/client/models/cloud_provider_a_w_s_configuration.go +++ /dev/null @@ -1,159 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudProviderAWSConfiguration Representation of AWS configuration -// -// swagger:model CloudProviderAWSConfiguration -type CloudProviderAWSConfiguration struct { - - // The AWS region where the resource exists - // - // Required: true - Region *string `json:"region"` -} - -// Type gets the type of this subtype -func (m *CloudProviderAWSConfiguration) Type() string { - return "CloudProviderAWSConfiguration" -} - -// SetType sets the type of this subtype -func (m *CloudProviderAWSConfiguration) SetType(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *CloudProviderAWSConfiguration) UnmarshalJSON(raw []byte) error { - var data struct { - - // The AWS region where the resource exists - // - // Required: true - Region *string `json:"region"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Type string `json:"type"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result CloudProviderAWSConfiguration - - if base.Type != result.Type() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid type value: %q", base.Type) - } - - result.Region = data.Region - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m CloudProviderAWSConfiguration) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The AWS region where the resource exists - // - // Required: true - Region *string `json:"region"` - }{ - - Region: m.Region, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Type string `json:"type"` - }{ - - Type: m.Type(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this cloud provider a w s configuration -func (m *CloudProviderAWSConfiguration) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateRegion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudProviderAWSConfiguration) validateRegion(formats strfmt.Registry) error { - - if err := validate.Required("region", "body", m.Region); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this cloud provider a w s configuration based on the context it is used -func (m *CloudProviderAWSConfiguration) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *CloudProviderAWSConfiguration) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudProviderAWSConfiguration) UnmarshalBinary(b []byte) error { - var res CloudProviderAWSConfiguration - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_provider_azure_configuration.go b/client/models/cloud_provider_azure_configuration.go deleted file mode 100644 index f6a6403a5..000000000 --- a/client/models/cloud_provider_azure_configuration.go +++ /dev/null @@ -1,199 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudProviderAzureConfiguration Representation of Azure configuration -// -// swagger:model CloudProviderAzureConfiguration -type CloudProviderAzureConfiguration struct { - - // The Azure environment of the configuration - // - // Required: true - Environment *string `json:"environment"` - - // The Azure resource group name of the configuration - // - // Required: true - // Min Items: 1 - ResourceGroupNames []string `json:"resource_group_names"` -} - -// Type gets the type of this subtype -func (m *CloudProviderAzureConfiguration) Type() string { - return "CloudProviderAzureConfiguration" -} - -// SetType sets the type of this subtype -func (m *CloudProviderAzureConfiguration) SetType(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *CloudProviderAzureConfiguration) UnmarshalJSON(raw []byte) error { - var data struct { - - // The Azure environment of the configuration - // - // Required: true - Environment *string `json:"environment"` - - // The Azure resource group name of the configuration - // - // Required: true - // Min Items: 1 - ResourceGroupNames []string `json:"resource_group_names"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Type string `json:"type"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result CloudProviderAzureConfiguration - - if base.Type != result.Type() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid type value: %q", base.Type) - } - - result.Environment = data.Environment - result.ResourceGroupNames = data.ResourceGroupNames - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m CloudProviderAzureConfiguration) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The Azure environment of the configuration - // - // Required: true - Environment *string `json:"environment"` - - // The Azure resource group name of the configuration - // - // Required: true - // Min Items: 1 - ResourceGroupNames []string `json:"resource_group_names"` - }{ - - Environment: m.Environment, - - ResourceGroupNames: m.ResourceGroupNames, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Type string `json:"type"` - }{ - - Type: m.Type(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this cloud provider azure configuration -func (m *CloudProviderAzureConfiguration) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEnvironment(formats); err != nil { - res = append(res, err) - } - - if err := m.validateResourceGroupNames(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudProviderAzureConfiguration) validateEnvironment(formats strfmt.Registry) error { - - if err := validate.Required("environment", "body", m.Environment); err != nil { - return err - } - - return nil -} - -func (m *CloudProviderAzureConfiguration) validateResourceGroupNames(formats strfmt.Registry) error { - - if err := validate.Required("resource_group_names", "body", m.ResourceGroupNames); err != nil { - return err - } - - iResourceGroupNamesSize := int64(len(m.ResourceGroupNames)) - - if err := validate.MinItems("resource_group_names", "body", iResourceGroupNamesSize, 1); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this cloud provider azure configuration based on the context it is used -func (m *CloudProviderAzureConfiguration) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *CloudProviderAzureConfiguration) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudProviderAzureConfiguration) UnmarshalBinary(b []byte) error { - var res CloudProviderAzureConfiguration - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_provider_configuration.go b/client/models/cloud_provider_configuration.go deleted file mode 100644 index 10d3a0181..000000000 --- a/client/models/cloud_provider_configuration.go +++ /dev/null @@ -1,134 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" -) - -// CloudProviderConfiguration cloud provider configuration -// -// swagger:discriminator CloudProviderConfiguration type -type CloudProviderConfiguration interface { - runtime.Validatable - runtime.ContextValidatable - - // type - // Required: true - Type() string - SetType(string) - - // AdditionalProperties in base type shoud be handled just like regular properties - // At this moment, the base type property is pushed down to the subtype -} - -type cloudProviderConfiguration struct { - typeField string -} - -// Type gets the type of this polymorphic type -func (m *cloudProviderConfiguration) Type() string { - return "CloudProviderConfiguration" -} - -// SetType sets the type of this polymorphic type -func (m *cloudProviderConfiguration) SetType(val string) { -} - -// UnmarshalCloudProviderConfigurationSlice unmarshals polymorphic slices of CloudProviderConfiguration -func UnmarshalCloudProviderConfigurationSlice(reader io.Reader, consumer runtime.Consumer) ([]CloudProviderConfiguration, error) { - var elements []json.RawMessage - if err := consumer.Consume(reader, &elements); err != nil { - return nil, err - } - - var result []CloudProviderConfiguration - for _, element := range elements { - obj, err := unmarshalCloudProviderConfiguration(element, consumer) - if err != nil { - return nil, err - } - result = append(result, obj) - } - return result, nil -} - -// UnmarshalCloudProviderConfiguration unmarshals polymorphic CloudProviderConfiguration -func UnmarshalCloudProviderConfiguration(reader io.Reader, consumer runtime.Consumer) (CloudProviderConfiguration, error) { - // we need to read this twice, so first into a buffer - data, err := io.ReadAll(reader) - if err != nil { - return nil, err - } - return unmarshalCloudProviderConfiguration(data, consumer) -} - -func unmarshalCloudProviderConfiguration(data []byte, consumer runtime.Consumer) (CloudProviderConfiguration, error) { - buf := bytes.NewBuffer(data) - buf2 := bytes.NewBuffer(data) - - // the first time this is read is to fetch the value of the type property. - var getType struct { - Type string `json:"type"` - } - if err := consumer.Consume(buf, &getType); err != nil { - return nil, err - } - - if err := validate.RequiredString("type", "body", getType.Type); err != nil { - return nil, err - } - - // The value of type is used to determine which type to create and unmarshal the data into - switch getType.Type { - case "CloudProviderAWSConfiguration": - var result CloudProviderAWSConfiguration - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "CloudProviderAzureConfiguration": - var result CloudProviderAzureConfiguration - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "CloudProviderConfiguration": - var result cloudProviderConfiguration - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "CloudProviderGCPConfiguration": - var result CloudProviderGCPConfiguration - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "CloudProviderVMWareVSphereConfiguration": - var result CloudProviderVMWareVSphereConfiguration - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - } - return nil, errors.New(422, "invalid type value: %q", getType.Type) -} - -// Validate validates this cloud provider configuration -func (m *cloudProviderConfiguration) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this cloud provider configuration based on context it is used -func (m *cloudProviderConfiguration) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} diff --git a/client/models/cloud_provider_g_c_p_configuration.go b/client/models/cloud_provider_g_c_p_configuration.go deleted file mode 100644 index 90c48f4d6..000000000 --- a/client/models/cloud_provider_g_c_p_configuration.go +++ /dev/null @@ -1,190 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudProviderGCPConfiguration Representation of Google configuration -// -// swagger:model CloudProviderGCPConfiguration -type CloudProviderGCPConfiguration struct { - - // The Google project where the resource exists - // - // Required: true - Project *string `json:"project"` - - // The Google region where the resource exists - // - // Required: true - Region *string `json:"region"` -} - -// Type gets the type of this subtype -func (m *CloudProviderGCPConfiguration) Type() string { - return "CloudProviderGCPConfiguration" -} - -// SetType sets the type of this subtype -func (m *CloudProviderGCPConfiguration) SetType(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *CloudProviderGCPConfiguration) UnmarshalJSON(raw []byte) error { - var data struct { - - // The Google project where the resource exists - // - // Required: true - Project *string `json:"project"` - - // The Google region where the resource exists - // - // Required: true - Region *string `json:"region"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Type string `json:"type"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result CloudProviderGCPConfiguration - - if base.Type != result.Type() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid type value: %q", base.Type) - } - - result.Project = data.Project - result.Region = data.Region - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m CloudProviderGCPConfiguration) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The Google project where the resource exists - // - // Required: true - Project *string `json:"project"` - - // The Google region where the resource exists - // - // Required: true - Region *string `json:"region"` - }{ - - Project: m.Project, - - Region: m.Region, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Type string `json:"type"` - }{ - - Type: m.Type(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this cloud provider g c p configuration -func (m *CloudProviderGCPConfiguration) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateProject(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRegion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudProviderGCPConfiguration) validateProject(formats strfmt.Registry) error { - - if err := validate.Required("project", "body", m.Project); err != nil { - return err - } - - return nil -} - -func (m *CloudProviderGCPConfiguration) validateRegion(formats strfmt.Registry) error { - - if err := validate.Required("region", "body", m.Region); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this cloud provider g c p configuration based on the context it is used -func (m *CloudProviderGCPConfiguration) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *CloudProviderGCPConfiguration) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudProviderGCPConfiguration) UnmarshalBinary(b []byte) error { - var res CloudProviderGCPConfiguration - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cloud_provider_vm_ware_v_sphere_configuration.go b/client/models/cloud_provider_vm_ware_v_sphere_configuration.go deleted file mode 100644 index 1300c8e8c..000000000 --- a/client/models/cloud_provider_vm_ware_v_sphere_configuration.go +++ /dev/null @@ -1,190 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CloudProviderVMWareVSphereConfiguration Representation of VMware vSphere configuration -// -// swagger:model CloudProviderVMWareVSphereConfiguration -type CloudProviderVMWareVSphereConfiguration struct { - - // Used to disable verification of server's SSL certificate. - // - // Required: true - AllowUnverifiedSsl *bool `json:"allow_unverified_ssl"` - - // This is the vCenter Server FQDN or IP Address for vSphere API operations - // - // Required: true - Server *string `json:"server"` -} - -// Type gets the type of this subtype -func (m *CloudProviderVMWareVSphereConfiguration) Type() string { - return "CloudProviderVMWareVSphereConfiguration" -} - -// SetType sets the type of this subtype -func (m *CloudProviderVMWareVSphereConfiguration) SetType(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *CloudProviderVMWareVSphereConfiguration) UnmarshalJSON(raw []byte) error { - var data struct { - - // Used to disable verification of server's SSL certificate. - // - // Required: true - AllowUnverifiedSsl *bool `json:"allow_unverified_ssl"` - - // This is the vCenter Server FQDN or IP Address for vSphere API operations - // - // Required: true - Server *string `json:"server"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Type string `json:"type"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result CloudProviderVMWareVSphereConfiguration - - if base.Type != result.Type() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid type value: %q", base.Type) - } - - result.AllowUnverifiedSsl = data.AllowUnverifiedSsl - result.Server = data.Server - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m CloudProviderVMWareVSphereConfiguration) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // Used to disable verification of server's SSL certificate. - // - // Required: true - AllowUnverifiedSsl *bool `json:"allow_unverified_ssl"` - - // This is the vCenter Server FQDN or IP Address for vSphere API operations - // - // Required: true - Server *string `json:"server"` - }{ - - AllowUnverifiedSsl: m.AllowUnverifiedSsl, - - Server: m.Server, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Type string `json:"type"` - }{ - - Type: m.Type(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this cloud provider VM ware v sphere configuration -func (m *CloudProviderVMWareVSphereConfiguration) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAllowUnverifiedSsl(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServer(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CloudProviderVMWareVSphereConfiguration) validateAllowUnverifiedSsl(formats strfmt.Registry) error { - - if err := validate.Required("allow_unverified_ssl", "body", m.AllowUnverifiedSsl); err != nil { - return err - } - - return nil -} - -func (m *CloudProviderVMWareVSphereConfiguration) validateServer(formats strfmt.Registry) error { - - if err := validate.Required("server", "body", m.Server); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this cloud provider VM ware v sphere configuration based on the context it is used -func (m *CloudProviderVMWareVSphereConfiguration) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *CloudProviderVMWareVSphereConfiguration) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CloudProviderVMWareVSphereConfiguration) UnmarshalBinary(b []byte) error { - var res CloudProviderVMWareVSphereConfiguration - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/component.go b/client/models/component.go deleted file mode 100644 index a327de4ce..000000000 --- a/client/models/component.go +++ /dev/null @@ -1,579 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Component Component -// -// The entity which represents the information of a component. -// -// swagger:model Component -type Component struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$ - Canonical *string `json:"canonical"` - - // The cloud provider object that this environment is using. - // In the event where the cloud provider is not yet defined/supported - // that field might be empty. - // - CloudProvider *CloudProvider `json:"cloud_provider,omitempty"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // description - Description string `json:"description,omitempty"` - - // The environment object that this component is using. - // Required: true - Environment *Environment `json:"environment"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // The import process status. - // Enum: ["succeeded","failed","importing"] - ImportStatus string `json:"import_status,omitempty"` - - // The status of the component. - IsConfigured bool `json:"is_configured,omitempty"` - - // name - // Required: true - // Min Length: 1 - Name *string `json:"name"` - - // The project object that this component is using. - // Required: true - Project *ProjectSimple `json:"project"` - - // The Service Catalog that was used to create project. - // Required: true - ServiceCatalog *ServiceCatalog `json:"service_catalog"` - - // Unix timestamp in milliseconds of when the component was last configured via StackForms. Absent if the component has never been configured or the information is unavailable. - // Minimum: 0 - StackformUpdatedAt *uint64 `json:"stackform_updated_at,omitempty"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` - - // use case - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - UseCase string `json:"use_case,omitempty"` - - // The version used by the Component - // Required: true - Version *ServiceCatalogSourceVersion `json:"version"` -} - -// Validate validates this component -func (m *Component) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironment(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateImportStatus(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProject(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalog(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStackformUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUseCase(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Component) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$`); err != nil { - return err - } - - return nil -} - -func (m *Component) validateCloudProvider(formats strfmt.Registry) error { - if swag.IsZero(m.CloudProvider) { // not required - return nil - } - - if m.CloudProvider != nil { - if err := m.CloudProvider.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cloud_provider") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cloud_provider") - } - - return err - } - } - - return nil -} - -func (m *Component) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Component) validateEnvironment(formats strfmt.Registry) error { - - if err := validate.Required("environment", "body", m.Environment); err != nil { - return err - } - - if m.Environment != nil { - if err := m.Environment.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment") - } - - return err - } - } - - return nil -} - -func (m *Component) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -var componentTypeImportStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["succeeded","failed","importing"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - componentTypeImportStatusPropEnum = append(componentTypeImportStatusPropEnum, v) - } -} - -const ( - - // ComponentImportStatusSucceeded captures enum value "succeeded" - ComponentImportStatusSucceeded string = "succeeded" - - // ComponentImportStatusFailed captures enum value "failed" - ComponentImportStatusFailed string = "failed" - - // ComponentImportStatusImporting captures enum value "importing" - ComponentImportStatusImporting string = "importing" -) - -// prop value enum -func (m *Component) validateImportStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, componentTypeImportStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *Component) validateImportStatus(formats strfmt.Registry) error { - if swag.IsZero(m.ImportStatus) { // not required - return nil - } - - // value enum - if err := m.validateImportStatusEnum("import_status", "body", m.ImportStatus); err != nil { - return err - } - - return nil -} - -func (m *Component) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - return nil -} - -func (m *Component) validateProject(formats strfmt.Registry) error { - - if err := validate.Required("project", "body", m.Project); err != nil { - return err - } - - if m.Project != nil { - if err := m.Project.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project") - } - - return err - } - } - - return nil -} - -func (m *Component) validateServiceCatalog(formats strfmt.Registry) error { - - if err := validate.Required("service_catalog", "body", m.ServiceCatalog); err != nil { - return err - } - - if m.ServiceCatalog != nil { - if err := m.ServiceCatalog.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("service_catalog") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("service_catalog") - } - - return err - } - } - - return nil -} - -func (m *Component) validateStackformUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.StackformUpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("stackform_updated_at", "body", *m.StackformUpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Component) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Component) validateUseCase(formats strfmt.Registry) error { - if swag.IsZero(m.UseCase) { // not required - return nil - } - - if err := validate.MinLength("use_case", "body", m.UseCase, 1); err != nil { - return err - } - - if err := validate.MaxLength("use_case", "body", m.UseCase, 100); err != nil { - return err - } - - if err := validate.Pattern("use_case", "body", m.UseCase, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -func (m *Component) validateVersion(formats strfmt.Registry) error { - - if err := validate.Required("version", "body", m.Version); err != nil { - return err - } - - if m.Version != nil { - if err := m.Version.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("version") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("version") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this component based on the context it is used -func (m *Component) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateCloudProvider(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateEnvironment(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateProject(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateServiceCatalog(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateVersion(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Component) contextValidateCloudProvider(ctx context.Context, formats strfmt.Registry) error { - - if m.CloudProvider != nil { - - if swag.IsZero(m.CloudProvider) { // not required - return nil - } - - if err := m.CloudProvider.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cloud_provider") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cloud_provider") - } - - return err - } - } - - return nil -} - -func (m *Component) contextValidateEnvironment(ctx context.Context, formats strfmt.Registry) error { - - if m.Environment != nil { - - if err := m.Environment.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment") - } - - return err - } - } - - return nil -} - -func (m *Component) contextValidateProject(ctx context.Context, formats strfmt.Registry) error { - - if m.Project != nil { - - if err := m.Project.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project") - } - - return err - } - } - - return nil -} - -func (m *Component) contextValidateServiceCatalog(ctx context.Context, formats strfmt.Registry) error { - - if m.ServiceCatalog != nil { - - if err := m.ServiceCatalog.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("service_catalog") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("service_catalog") - } - - return err - } - } - - return nil -} - -func (m *Component) contextValidateVersion(ctx context.Context, formats strfmt.Registry) error { - - if m.Version != nil { - - if err := m.Version.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("version") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("version") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Component) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Component) UnmarshalBinary(b []byte) error { - var res Component - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/component_simple.go b/client/models/component_simple.go deleted file mode 100644 index 7c6f0ff37..000000000 --- a/client/models/component_simple.go +++ /dev/null @@ -1,388 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ComponentSimple ComponentSimple -// -// The entity which represents minimal information of a component. -// -// swagger:model ComponentSimple -type ComponentSimple struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$ - Canonical *string `json:"canonical"` - - // The cloud provider object that this environment is using. - // In the event where the cloud provider is not yet defined/supported - // that field might be empty. - // - CloudProvider *CloudProvider `json:"cloud_provider,omitempty"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // description - Description string `json:"description,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // name - // Required: true - // Min Length: 1 - Name *string `json:"name"` - - // The Service Catalog that was used to create project. - // Required: true - ServiceCatalog *ServiceCatalog `json:"service_catalog"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` - - // use case - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - UseCase string `json:"use_case,omitempty"` - - // The version used by the Component - // Required: true - Version *ServiceCatalogSourceVersion `json:"version"` -} - -// Validate validates this component simple -func (m *ComponentSimple) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalog(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUseCase(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ComponentSimple) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$`); err != nil { - return err - } - - return nil -} - -func (m *ComponentSimple) validateCloudProvider(formats strfmt.Registry) error { - if swag.IsZero(m.CloudProvider) { // not required - return nil - } - - if m.CloudProvider != nil { - if err := m.CloudProvider.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cloud_provider") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cloud_provider") - } - - return err - } - } - - return nil -} - -func (m *ComponentSimple) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *ComponentSimple) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *ComponentSimple) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - return nil -} - -func (m *ComponentSimple) validateServiceCatalog(formats strfmt.Registry) error { - - if err := validate.Required("service_catalog", "body", m.ServiceCatalog); err != nil { - return err - } - - if m.ServiceCatalog != nil { - if err := m.ServiceCatalog.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("service_catalog") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("service_catalog") - } - - return err - } - } - - return nil -} - -func (m *ComponentSimple) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *ComponentSimple) validateUseCase(formats strfmt.Registry) error { - if swag.IsZero(m.UseCase) { // not required - return nil - } - - if err := validate.MinLength("use_case", "body", m.UseCase, 1); err != nil { - return err - } - - if err := validate.MaxLength("use_case", "body", m.UseCase, 100); err != nil { - return err - } - - if err := validate.Pattern("use_case", "body", m.UseCase, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -func (m *ComponentSimple) validateVersion(formats strfmt.Registry) error { - - if err := validate.Required("version", "body", m.Version); err != nil { - return err - } - - if m.Version != nil { - if err := m.Version.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("version") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("version") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this component simple based on the context it is used -func (m *ComponentSimple) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateCloudProvider(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateServiceCatalog(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateVersion(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ComponentSimple) contextValidateCloudProvider(ctx context.Context, formats strfmt.Registry) error { - - if m.CloudProvider != nil { - - if swag.IsZero(m.CloudProvider) { // not required - return nil - } - - if err := m.CloudProvider.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cloud_provider") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cloud_provider") - } - - return err - } - } - - return nil -} - -func (m *ComponentSimple) contextValidateServiceCatalog(ctx context.Context, formats strfmt.Registry) error { - - if m.ServiceCatalog != nil { - - if err := m.ServiceCatalog.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("service_catalog") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("service_catalog") - } - - return err - } - } - - return nil -} - -func (m *ComponentSimple) contextValidateVersion(ctx context.Context, formats strfmt.Registry) error { - - if m.Version != nil { - - if err := m.Version.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("version") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("version") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ComponentSimple) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ComponentSimple) UnmarshalBinary(b []byte) error { - var res ComponentSimple - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/config_file.go b/client/models/config_file.go deleted file mode 100644 index 80af2fdde..000000000 --- a/client/models/config_file.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ConfigFile SC config file -// -// # This object contains SC config file name and its content -// -// swagger:model ConfigFile -type ConfigFile struct { - - // content - // Required: true - // Format: byte - Content *strfmt.Base64 `json:"content"` - - // path - // Required: true - Path *string `json:"path"` -} - -// Validate validates this config file -func (m *ConfigFile) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateContent(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePath(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ConfigFile) validateContent(formats strfmt.Registry) error { - - if err := validate.Required("content", "body", m.Content); err != nil { - return err - } - - return nil -} - -func (m *ConfigFile) validatePath(formats strfmt.Registry) error { - - if err := validate.Required("path", "body", m.Path); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this config file based on context it is used -func (m *ConfigFile) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *ConfigFile) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ConfigFile) UnmarshalBinary(b []byte) error { - var res ConfigFile - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/config_repository.go b/client/models/config_repository.go deleted file mode 100644 index feb76ea81..000000000 --- a/client/models/config_repository.go +++ /dev/null @@ -1,234 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ConfigRepository ConfigRepository -// -// swagger:model ConfigRepository -type ConfigRepository struct { - - // branch - Branch string `json:"branch,omitempty"` - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // created at - // Minimum: 0 - CreatedAt *uint64 `json:"created_at,omitempty"` - - // credential canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical string `json:"credential_canonical,omitempty"` - - // default - // Required: true - Default *bool `json:"default"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // name - // Required: true - Name *string `json:"name"` - - // updated at - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` - - // url - // Required: true - // Pattern: ^((/|~)[^/]*)+.(\.git)|(([\w\]+@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(/)? - URL *string `json:"url"` -} - -// Validate validates this config repository -func (m *ConfigRepository) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDefault(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ConfigRepository) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *ConfigRepository) validateCreatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *ConfigRepository) validateCredentialCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.CredentialCanonical) { // not required - return nil - } - - if err := validate.MinLength("credential_canonical", "body", m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *ConfigRepository) validateDefault(formats strfmt.Registry) error { - - if err := validate.Required("default", "body", m.Default); err != nil { - return err - } - - return nil -} - -func (m *ConfigRepository) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *ConfigRepository) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *ConfigRepository) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *ConfigRepository) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - if err := validate.Pattern("url", "body", *m.URL, `^((/|~)[^/]*)+.(\.git)|(([\w\]+@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(/)?`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this config repository based on context it is used -func (m *ConfigRepository) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *ConfigRepository) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ConfigRepository) UnmarshalBinary(b []byte) error { - var res ConfigRepository - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/configure_component.go b/client/models/configure_component.go deleted file mode 100644 index 06a830084..000000000 --- a/client/models/configure_component.go +++ /dev/null @@ -1,167 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ConfigureComponent Configure Component -// -// The entity which represents the information of a component to configure. -// -// swagger:model ConfigureComponent -type ConfigureComponent struct { - - // Is the ID of the new SCS Version used - // Minimum: 1 - ServiceCatalogSourceVersionID uint32 `json:"service_catalog_source_version_id,omitempty"` - - // use case - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - UseCase *string `json:"use_case"` - - // vars - Vars FormVariables `json:"vars,omitempty"` -} - -// Validate validates this configure component -func (m *ConfigureComponent) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateServiceCatalogSourceVersionID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUseCase(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVars(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ConfigureComponent) validateServiceCatalogSourceVersionID(formats strfmt.Registry) error { - if swag.IsZero(m.ServiceCatalogSourceVersionID) { // not required - return nil - } - - if err := validate.MinimumUint("service_catalog_source_version_id", "body", uint64(m.ServiceCatalogSourceVersionID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *ConfigureComponent) validateUseCase(formats strfmt.Registry) error { - - if err := validate.Required("use_case", "body", m.UseCase); err != nil { - return err - } - - if err := validate.MinLength("use_case", "body", *m.UseCase, 1); err != nil { - return err - } - - if err := validate.MaxLength("use_case", "body", *m.UseCase, 100); err != nil { - return err - } - - if err := validate.Pattern("use_case", "body", *m.UseCase, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -func (m *ConfigureComponent) validateVars(formats strfmt.Registry) error { - if swag.IsZero(m.Vars) { // not required - return nil - } - - if m.Vars != nil { - if err := m.Vars.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("vars") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("vars") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this configure component based on the context it is used -func (m *ConfigureComponent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateVars(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ConfigureComponent) contextValidateVars(ctx context.Context, formats strfmt.Registry) error { - - if swag.IsZero(m.Vars) { // not required - return nil - } - - if err := m.Vars.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("vars") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("vars") - } - - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ConfigureComponent) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ConfigureComponent) UnmarshalBinary(b []byte) error { - var res ConfigureComponent - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cost_estimation_component.go b/client/models/cost_estimation_component.go deleted file mode 100644 index 300aea1ba..000000000 --- a/client/models/cost_estimation_component.go +++ /dev/null @@ -1,217 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CostEstimationComponent CostEstimationComponent -// -// Cost component of a cloud resource estimate. -// -// swagger:model CostEstimationComponent -type CostEstimationComponent struct { - - // Human-readable label of the component. - // Required: true - Label *string `json:"label"` - - // planned - Planned *CostEstimationComponentState `json:"planned,omitempty"` - - // prior - Prior *CostEstimationComponentState `json:"prior,omitempty"` - - // Monthly rate per unit. - // Required: true - Rate *string `json:"rate"` - - // Unit of estimation. - Unit string `json:"unit,omitempty"` - - // If the price is from usage or configuration - Usage bool `json:"usage,omitempty"` -} - -// Validate validates this cost estimation component -func (m *CostEstimationComponent) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateLabel(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePlanned(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePrior(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRate(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CostEstimationComponent) validateLabel(formats strfmt.Registry) error { - - if err := validate.Required("label", "body", m.Label); err != nil { - return err - } - - return nil -} - -func (m *CostEstimationComponent) validatePlanned(formats strfmt.Registry) error { - if swag.IsZero(m.Planned) { // not required - return nil - } - - if m.Planned != nil { - if err := m.Planned.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("planned") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("planned") - } - - return err - } - } - - return nil -} - -func (m *CostEstimationComponent) validatePrior(formats strfmt.Registry) error { - if swag.IsZero(m.Prior) { // not required - return nil - } - - if m.Prior != nil { - if err := m.Prior.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("prior") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("prior") - } - - return err - } - } - - return nil -} - -func (m *CostEstimationComponent) validateRate(formats strfmt.Registry) error { - - if err := validate.Required("rate", "body", m.Rate); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this cost estimation component based on the context it is used -func (m *CostEstimationComponent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidatePlanned(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidatePrior(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CostEstimationComponent) contextValidatePlanned(ctx context.Context, formats strfmt.Registry) error { - - if m.Planned != nil { - - if swag.IsZero(m.Planned) { // not required - return nil - } - - if err := m.Planned.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("planned") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("planned") - } - - return err - } - } - - return nil -} - -func (m *CostEstimationComponent) contextValidatePrior(ctx context.Context, formats strfmt.Registry) error { - - if m.Prior != nil { - - if swag.IsZero(m.Prior) { // not required - return nil - } - - if err := m.Prior.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("prior") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("prior") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CostEstimationComponent) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CostEstimationComponent) UnmarshalBinary(b []byte) error { - var res CostEstimationComponent - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cost_estimation_component_state.go b/client/models/cost_estimation_component_state.go deleted file mode 100644 index 482b56e0d..000000000 --- a/client/models/cost_estimation_component_state.go +++ /dev/null @@ -1,121 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CostEstimationComponentState CostEstimationComponentState -// -// Either a Prior or Planned cost component state. -// -// swagger:model CostEstimationComponentState -type CostEstimationComponentState struct { - - // Monthly cost of the component state in decimal form. - // Required: true - Cost *string `json:"cost"` - - // List of items on which the cost is dependent. - // Required: true - Details []string `json:"details"` - - // Hourly cost of the component state in decimal form. - // Required: true - HourlyCost *string `json:"hourly_cost"` - - // Quantity of units. - // Required: true - Quantity *uint32 `json:"quantity"` -} - -// Validate validates this cost estimation component state -func (m *CostEstimationComponentState) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCost(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDetails(formats); err != nil { - res = append(res, err) - } - - if err := m.validateHourlyCost(formats); err != nil { - res = append(res, err) - } - - if err := m.validateQuantity(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CostEstimationComponentState) validateCost(formats strfmt.Registry) error { - - if err := validate.Required("cost", "body", m.Cost); err != nil { - return err - } - - return nil -} - -func (m *CostEstimationComponentState) validateDetails(formats strfmt.Registry) error { - - if err := validate.Required("details", "body", m.Details); err != nil { - return err - } - - return nil -} - -func (m *CostEstimationComponentState) validateHourlyCost(formats strfmt.Registry) error { - - if err := validate.Required("hourly_cost", "body", m.HourlyCost); err != nil { - return err - } - - return nil -} - -func (m *CostEstimationComponentState) validateQuantity(formats strfmt.Registry) error { - - if err := validate.Required("quantity", "body", m.Quantity); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this cost estimation component state based on context it is used -func (m *CostEstimationComponentState) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *CostEstimationComponentState) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CostEstimationComponentState) UnmarshalBinary(b []byte) error { - var res CostEstimationComponentState - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cost_estimation_resource_estimate.go b/client/models/cost_estimation_resource_estimate.go deleted file mode 100644 index 9b9efc0a7..000000000 --- a/client/models/cost_estimation_resource_estimate.go +++ /dev/null @@ -1,215 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CostEstimationResourceEstimate CostEstimationResourceEstimate -// -// Estimate for a single cloud resource. -// -// swagger:model CostEstimationResourceEstimate -type CostEstimationResourceEstimate struct { - - // Unique identifier of the resource. - // Required: true - Address *string `json:"address"` - - // List of resource cost components. - // Required: true - Components []*CostEstimationComponent `json:"components"` - - // Path to the image of the resource - // Format: uri - Image strfmt.URI `json:"image,omitempty"` - - // Planned monthly cost of the resource estimate in decimal form. - PlannedCost string `json:"planned_cost,omitempty"` - - // Planned hourly cost of the resource estimate in decimal form. - PlannedHourlyCost string `json:"planned_hourly_cost,omitempty"` - - // Prior monthly cost of the resource estimate in decimal form. - PriorCost string `json:"prior_cost,omitempty"` - - // Prior hourly cost of the resource estimate in decimal form. - PriorHourlyCost string `json:"prior_hourly_cost,omitempty"` - - // The resource's cloud provider. - // Required: true - Provider *string `json:"provider"` - - // Type of the resource. - // Required: true - Type *string `json:"type"` -} - -// Validate validates this cost estimation resource estimate -func (m *CostEstimationResourceEstimate) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAddress(formats); err != nil { - res = append(res, err) - } - - if err := m.validateComponents(formats); err != nil { - res = append(res, err) - } - - if err := m.validateImage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CostEstimationResourceEstimate) validateAddress(formats strfmt.Registry) error { - - if err := validate.Required("address", "body", m.Address); err != nil { - return err - } - - return nil -} - -func (m *CostEstimationResourceEstimate) validateComponents(formats strfmt.Registry) error { - - if err := validate.Required("components", "body", m.Components); err != nil { - return err - } - - for i := 0; i < len(m.Components); i++ { - if swag.IsZero(m.Components[i]) { // not required - continue - } - - if m.Components[i] != nil { - if err := m.Components[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("components" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("components" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *CostEstimationResourceEstimate) validateImage(formats strfmt.Registry) error { - if swag.IsZero(m.Image) { // not required - return nil - } - - if err := validate.FormatOf("image", "body", "uri", m.Image.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *CostEstimationResourceEstimate) validateProvider(formats strfmt.Registry) error { - - if err := validate.Required("provider", "body", m.Provider); err != nil { - return err - } - - return nil -} - -func (m *CostEstimationResourceEstimate) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this cost estimation resource estimate based on the context it is used -func (m *CostEstimationResourceEstimate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateComponents(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CostEstimationResourceEstimate) contextValidateComponents(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Components); i++ { - - if m.Components[i] != nil { - - if swag.IsZero(m.Components[i]) { // not required - return nil - } - - if err := m.Components[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("components" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("components" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CostEstimationResourceEstimate) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CostEstimationResourceEstimate) UnmarshalBinary(b []byte) error { - var res CostEstimationResourceEstimate - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/cost_estimation_result.go b/client/models/cost_estimation_result.go deleted file mode 100644 index 93336fa35..000000000 --- a/client/models/cost_estimation_result.go +++ /dev/null @@ -1,155 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CostEstimationResult CostEstimationResult -// -// The result of cost estimation. -// -// swagger:model CostEstimationResult -type CostEstimationResult struct { - - // Extra details regarding estimation - usually related to no known resources, unknown providers, etc. - Info string `json:"info,omitempty"` - - // Name of the current estimation - Name string `json:"name,omitempty"` - - // Planned monthly cost of the plan in decimal form. - PlannedCost string `json:"planned_cost,omitempty"` - - // Planned hourly cost of the plan in decimal form. - PlannedHourlyCost string `json:"planned_hourly_cost,omitempty"` - - // Prior monthly cost of the plan in decimal form. - PriorCost string `json:"prior_cost,omitempty"` - - // Prior hourly cost of the plan in decimal form. - PriorHourlyCost string `json:"prior_hourly_cost,omitempty"` - - // resource estimates - // Required: true - ResourceEstimates []*CostEstimationResourceEstimate `json:"resource_estimates"` - - // A list of addresses of resources that were skipped from the estimation process. A resource might be skipped - // due to being invalid or unsupported by Terracost. - // - SkippedResourceAddresses []string `json:"skipped_resource_addresses"` -} - -// Validate validates this cost estimation result -func (m *CostEstimationResult) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateResourceEstimates(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CostEstimationResult) validateResourceEstimates(formats strfmt.Registry) error { - - if err := validate.Required("resource_estimates", "body", m.ResourceEstimates); err != nil { - return err - } - - for i := 0; i < len(m.ResourceEstimates); i++ { - if swag.IsZero(m.ResourceEstimates[i]) { // not required - continue - } - - if m.ResourceEstimates[i] != nil { - if err := m.ResourceEstimates[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("resource_estimates" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("resource_estimates" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this cost estimation result based on the context it is used -func (m *CostEstimationResult) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateResourceEstimates(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CostEstimationResult) contextValidateResourceEstimates(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.ResourceEstimates); i++ { - - if m.ResourceEstimates[i] != nil { - - if swag.IsZero(m.ResourceEstimates[i]) { // not required - return nil - } - - if err := m.ResourceEstimates[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("resource_estimates" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("resource_estimates" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CostEstimationResult) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CostEstimationResult) UnmarshalBinary(b []byte) error { - var res CostEstimationResult - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/country.go b/client/models/country.go deleted file mode 100644 index 2615f2ee8..000000000 --- a/client/models/country.go +++ /dev/null @@ -1,92 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Country Country -// -// # Single country Representation -// -// swagger:model Country -type Country struct { - - // code - // Required: true - // Pattern: ^[A-Z]{2}$ - Code *string `json:"code"` - - // name - // Required: true - Name *string `json:"name"` -} - -// Validate validates this country -func (m *Country) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCode(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Country) validateCode(formats strfmt.Registry) error { - - if err := validate.Required("code", "body", m.Code); err != nil { - return err - } - - if err := validate.Pattern("code", "body", *m.Code, `^[A-Z]{2}$`); err != nil { - return err - } - - return nil -} - -func (m *Country) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this country based on context it is used -func (m *Country) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *Country) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Country) UnmarshalBinary(b []byte) error { - var res Country - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/create_or_update_subscription.go b/client/models/create_or_update_subscription.go deleted file mode 100644 index 6b0fc2552..000000000 --- a/client/models/create_or_update_subscription.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CreateOrUpdateSubscription Create or Update Subscription -// -// # Idempotent create or update of a Subscription -// -// swagger:model CreateOrUpdateSubscription -type CreateOrUpdateSubscription struct { - - // The expiration date of the subscription in RFC3339 format - // Format: date-time - ExpiresAt strfmt.DateTime `json:"expires_at,omitempty"` - - // The maximum number of members allowed by the subscription - // Minimum: 1 - MembersCount uint64 `json:"members_count,omitempty"` - - // When true, allows overwriting an existing subscription. Required to update an existing subscription - Overwrite bool `json:"overwrite,omitempty"` - - // The canonical of the plan. If not provided, defaults to platform_teams which requires root organization privileges - // Enum: ["free_trial","platform_teams"] - PlanCanonical string `json:"plan_canonical,omitempty"` -} - -// Validate validates this create or update subscription -func (m *CreateOrUpdateSubscription) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateExpiresAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMembersCount(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePlanCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CreateOrUpdateSubscription) validateExpiresAt(formats strfmt.Registry) error { - if swag.IsZero(m.ExpiresAt) { // not required - return nil - } - - if err := validate.FormatOf("expires_at", "body", "date-time", m.ExpiresAt.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *CreateOrUpdateSubscription) validateMembersCount(formats strfmt.Registry) error { - if swag.IsZero(m.MembersCount) { // not required - return nil - } - - if err := validate.MinimumUint("members_count", "body", m.MembersCount, 1, false); err != nil { - return err - } - - return nil -} - -var createOrUpdateSubscriptionTypePlanCanonicalPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["free_trial","platform_teams"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - createOrUpdateSubscriptionTypePlanCanonicalPropEnum = append(createOrUpdateSubscriptionTypePlanCanonicalPropEnum, v) - } -} - -const ( - - // CreateOrUpdateSubscriptionPlanCanonicalFreeTrial captures enum value "free_trial" - CreateOrUpdateSubscriptionPlanCanonicalFreeTrial string = "free_trial" - - // CreateOrUpdateSubscriptionPlanCanonicalPlatformTeams captures enum value "platform_teams" - CreateOrUpdateSubscriptionPlanCanonicalPlatformTeams string = "platform_teams" -) - -// prop value enum -func (m *CreateOrUpdateSubscription) validatePlanCanonicalEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, createOrUpdateSubscriptionTypePlanCanonicalPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *CreateOrUpdateSubscription) validatePlanCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.PlanCanonical) { // not required - return nil - } - - // value enum - if err := m.validatePlanCanonicalEnum("plan_canonical", "body", m.PlanCanonical); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this create or update subscription based on context it is used -func (m *CreateOrUpdateSubscription) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *CreateOrUpdateSubscription) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CreateOrUpdateSubscription) UnmarshalBinary(b []byte) error { - var res CreateOrUpdateSubscription - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/credential.go b/client/models/credential.go deleted file mode 100644 index 21183507a..000000000 --- a/client/models/credential.go +++ /dev/null @@ -1,462 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Credential Credential -// -// # Represents the Credential -// -// swagger:model Credential -type Credential struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // created at - // Minimum: 0 - CreatedAt *uint64 `json:"created_at,omitempty"` - - // description - Description string `json:"description,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // in use - InUse *CredentialInUse `json:"in_use,omitempty"` - - // List of all the keys available for the Credential - // Required: true - Keys []string `json:"keys"` - - // name - // Required: true - Name *string `json:"name"` - - // Organization member that owns this credential. When a user is the owner of a - // credential he has all the permissions on it. - // In the event where the user has been deleted that field might be empty. - // - Owner *User `json:"owner,omitempty"` - - // path - // Required: true - Path *string `json:"path"` - - // raw - // Required: true - Raw *CredentialRaw `json:"raw"` - - // type - // Required: true - // Enum: ["ssh","aws","custom","azure","azure_storage","gcp","basic_auth","elasticsearch","swift","vmware"] - Type *string `json:"type"` - - // updated at - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` -} - -// Validate validates this credential -func (m *Credential) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInUse(formats); err != nil { - res = append(res, err) - } - - if err := m.validateKeys(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePath(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRaw(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Credential) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *Credential) validateCreatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Credential) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *Credential) validateInUse(formats strfmt.Registry) error { - if swag.IsZero(m.InUse) { // not required - return nil - } - - if m.InUse != nil { - if err := m.InUse.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("in_use") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("in_use") - } - - return err - } - } - - return nil -} - -func (m *Credential) validateKeys(formats strfmt.Registry) error { - - if err := validate.Required("keys", "body", m.Keys); err != nil { - return err - } - - return nil -} - -func (m *Credential) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *Credential) validateOwner(formats strfmt.Registry) error { - if swag.IsZero(m.Owner) { // not required - return nil - } - - if m.Owner != nil { - if err := m.Owner.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *Credential) validatePath(formats strfmt.Registry) error { - - if err := validate.Required("path", "body", m.Path); err != nil { - return err - } - - return nil -} - -func (m *Credential) validateRaw(formats strfmt.Registry) error { - - if err := validate.Required("raw", "body", m.Raw); err != nil { - return err - } - - if m.Raw != nil { - if err := m.Raw.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("raw") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("raw") - } - - return err - } - } - - return nil -} - -var credentialTypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["ssh","aws","custom","azure","azure_storage","gcp","basic_auth","elasticsearch","swift","vmware"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - credentialTypeTypePropEnum = append(credentialTypeTypePropEnum, v) - } -} - -const ( - - // CredentialTypeSSH captures enum value "ssh" - CredentialTypeSSH string = "ssh" - - // CredentialTypeAws captures enum value "aws" - CredentialTypeAws string = "aws" - - // CredentialTypeCustom captures enum value "custom" - CredentialTypeCustom string = "custom" - - // CredentialTypeAzure captures enum value "azure" - CredentialTypeAzure string = "azure" - - // CredentialTypeAzureStorage captures enum value "azure_storage" - CredentialTypeAzureStorage string = "azure_storage" - - // CredentialTypeGcp captures enum value "gcp" - CredentialTypeGcp string = "gcp" - - // CredentialTypeBasicAuth captures enum value "basic_auth" - CredentialTypeBasicAuth string = "basic_auth" - - // CredentialTypeElasticsearch captures enum value "elasticsearch" - CredentialTypeElasticsearch string = "elasticsearch" - - // CredentialTypeSwift captures enum value "swift" - CredentialTypeSwift string = "swift" - - // CredentialTypeVmware captures enum value "vmware" - CredentialTypeVmware string = "vmware" -) - -// prop value enum -func (m *Credential) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, credentialTypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *Credential) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -func (m *Credential) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this credential based on the context it is used -func (m *Credential) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateInUse(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateOwner(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateRaw(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Credential) contextValidateInUse(ctx context.Context, formats strfmt.Registry) error { - - if m.InUse != nil { - - if swag.IsZero(m.InUse) { // not required - return nil - } - - if err := m.InUse.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("in_use") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("in_use") - } - - return err - } - } - - return nil -} - -func (m *Credential) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { - - if m.Owner != nil { - - if swag.IsZero(m.Owner) { // not required - return nil - } - - if err := m.Owner.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *Credential) contextValidateRaw(ctx context.Context, formats strfmt.Registry) error { - - if m.Raw != nil { - - if err := m.Raw.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("raw") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("raw") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Credential) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Credential) UnmarshalBinary(b []byte) error { - var res Credential - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/credential_in_use.go b/client/models/credential_in_use.go deleted file mode 100644 index 77e21e305..000000000 --- a/client/models/credential_in_use.go +++ /dev/null @@ -1,269 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// CredentialInUse Credential in use -// -// InUse represents the resources that are using provided credential. -// -// swagger:model CredentialInUse -type CredentialInUse struct { - - // config repositories - ConfigRepositories []*InUseConfigRepository `json:"config_repositories"` - - // external backends - ExternalBackends []*InUseExternalBackend `json:"external_backends"` - - // service catalog sources - ServiceCatalogSources []*InUseServiceCatalogSource `json:"service_catalog_sources"` -} - -// Validate validates this credential in use -func (m *CredentialInUse) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfigRepositories(formats); err != nil { - res = append(res, err) - } - - if err := m.validateExternalBackends(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalogSources(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CredentialInUse) validateConfigRepositories(formats strfmt.Registry) error { - if swag.IsZero(m.ConfigRepositories) { // not required - return nil - } - - for i := 0; i < len(m.ConfigRepositories); i++ { - if swag.IsZero(m.ConfigRepositories[i]) { // not required - continue - } - - if m.ConfigRepositories[i] != nil { - if err := m.ConfigRepositories[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("config_repositories" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("config_repositories" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *CredentialInUse) validateExternalBackends(formats strfmt.Registry) error { - if swag.IsZero(m.ExternalBackends) { // not required - return nil - } - - for i := 0; i < len(m.ExternalBackends); i++ { - if swag.IsZero(m.ExternalBackends[i]) { // not required - continue - } - - if m.ExternalBackends[i] != nil { - if err := m.ExternalBackends[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("external_backends" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("external_backends" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *CredentialInUse) validateServiceCatalogSources(formats strfmt.Registry) error { - if swag.IsZero(m.ServiceCatalogSources) { // not required - return nil - } - - for i := 0; i < len(m.ServiceCatalogSources); i++ { - if swag.IsZero(m.ServiceCatalogSources[i]) { // not required - continue - } - - if m.ServiceCatalogSources[i] != nil { - if err := m.ServiceCatalogSources[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("service_catalog_sources" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("service_catalog_sources" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this credential in use based on the context it is used -func (m *CredentialInUse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateConfigRepositories(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateExternalBackends(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateServiceCatalogSources(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CredentialInUse) contextValidateConfigRepositories(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.ConfigRepositories); i++ { - - if m.ConfigRepositories[i] != nil { - - if swag.IsZero(m.ConfigRepositories[i]) { // not required - return nil - } - - if err := m.ConfigRepositories[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("config_repositories" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("config_repositories" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *CredentialInUse) contextValidateExternalBackends(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.ExternalBackends); i++ { - - if m.ExternalBackends[i] != nil { - - if swag.IsZero(m.ExternalBackends[i]) { // not required - return nil - } - - if err := m.ExternalBackends[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("external_backends" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("external_backends" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *CredentialInUse) contextValidateServiceCatalogSources(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.ServiceCatalogSources); i++ { - - if m.ServiceCatalogSources[i] != nil { - - if swag.IsZero(m.ServiceCatalogSources[i]) { // not required - return nil - } - - if err := m.ServiceCatalogSources[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("service_catalog_sources" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("service_catalog_sources" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CredentialInUse) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CredentialInUse) UnmarshalBinary(b []byte) error { - var res CredentialInUse - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/credential_raw.go b/client/models/credential_raw.go deleted file mode 100644 index d9c954e8c..000000000 --- a/client/models/credential_raw.go +++ /dev/null @@ -1,155 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CredentialRaw Credential Raw -// -// # All the possible fields inside it -// -// swagger:model CredentialRaw -type CredentialRaw struct { - - // access key - AccessKey string `json:"access_key,omitempty"` - - // account name - AccountName string `json:"account_name,omitempty"` - - // auth url - AuthURL string `json:"auth_url,omitempty"` - - // ca cert - CaCert string `json:"ca_cert,omitempty"` - - // client id - ClientID string `json:"client_id,omitempty"` - - // client secret - ClientSecret string `json:"client_secret,omitempty"` - - // domain id - DomainID string `json:"domain_id,omitempty"` - - // environment - // Enum: ["public","usgovernment","china","german"] - Environment string `json:"environment,omitempty"` - - // json key - JSONKey string `json:"json_key,omitempty"` - - // password - Password string `json:"password,omitempty"` - - // raw - Raw any `json:"raw,omitempty"` - - // secret key - SecretKey string `json:"secret_key,omitempty"` - - // ssh key - SSHKey string `json:"ssh_key,omitempty"` - - // subscription id - SubscriptionID string `json:"subscription_id,omitempty"` - - // tenant id - TenantID string `json:"tenant_id,omitempty"` - - // username - Username string `json:"username,omitempty"` -} - -// Validate validates this credential raw -func (m *CredentialRaw) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEnvironment(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -var credentialRawTypeEnvironmentPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["public","usgovernment","china","german"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - credentialRawTypeEnvironmentPropEnum = append(credentialRawTypeEnvironmentPropEnum, v) - } -} - -const ( - - // CredentialRawEnvironmentPublic captures enum value "public" - CredentialRawEnvironmentPublic string = "public" - - // CredentialRawEnvironmentUsgovernment captures enum value "usgovernment" - CredentialRawEnvironmentUsgovernment string = "usgovernment" - - // CredentialRawEnvironmentChina captures enum value "china" - CredentialRawEnvironmentChina string = "china" - - // CredentialRawEnvironmentGerman captures enum value "german" - CredentialRawEnvironmentGerman string = "german" -) - -// prop value enum -func (m *CredentialRaw) validateEnvironmentEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, credentialRawTypeEnvironmentPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *CredentialRaw) validateEnvironment(formats strfmt.Registry) error { - if swag.IsZero(m.Environment) { // not required - return nil - } - - // value enum - if err := m.validateEnvironmentEnum("environment", "body", m.Environment); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this credential raw based on context it is used -func (m *CredentialRaw) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *CredentialRaw) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CredentialRaw) UnmarshalBinary(b []byte) error { - var res CredentialRaw - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/credential_simple.go b/client/models/credential_simple.go deleted file mode 100644 index efb9d6839..000000000 --- a/client/models/credential_simple.go +++ /dev/null @@ -1,405 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CredentialSimple Credential Simple -// -// # Represents the Credential without the raw and owner -// -// swagger:model CredentialSimple -type CredentialSimple struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // created at - // Minimum: 0 - CreatedAt *uint64 `json:"created_at,omitempty"` - - // description - Description string `json:"description,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // in use - InUse *CredentialInUse `json:"in_use,omitempty"` - - // List of all the keys available for the Credential - // Required: true - Keys []string `json:"keys"` - - // name - // Required: true - Name *string `json:"name"` - - // Organization member that owns this credential. When a user is the owner of a - // credential he has all the permissions on it. - // In the event where the user has been deleted that field might be empty. - // - Owner *User `json:"owner,omitempty"` - - // path - // Required: true - Path *string `json:"path"` - - // type - // Required: true - // Enum: ["ssh","aws","custom","azure","azure_storage","gcp","basic_auth","elasticsearch","swift","vmware"] - Type *string `json:"type"` - - // updated at - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` -} - -// Validate validates this credential simple -func (m *CredentialSimple) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInUse(formats); err != nil { - res = append(res, err) - } - - if err := m.validateKeys(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePath(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CredentialSimple) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *CredentialSimple) validateCreatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *CredentialSimple) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *CredentialSimple) validateInUse(formats strfmt.Registry) error { - if swag.IsZero(m.InUse) { // not required - return nil - } - - if m.InUse != nil { - if err := m.InUse.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("in_use") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("in_use") - } - - return err - } - } - - return nil -} - -func (m *CredentialSimple) validateKeys(formats strfmt.Registry) error { - - if err := validate.Required("keys", "body", m.Keys); err != nil { - return err - } - - return nil -} - -func (m *CredentialSimple) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *CredentialSimple) validateOwner(formats strfmt.Registry) error { - if swag.IsZero(m.Owner) { // not required - return nil - } - - if m.Owner != nil { - if err := m.Owner.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *CredentialSimple) validatePath(formats strfmt.Registry) error { - - if err := validate.Required("path", "body", m.Path); err != nil { - return err - } - - return nil -} - -var credentialSimpleTypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["ssh","aws","custom","azure","azure_storage","gcp","basic_auth","elasticsearch","swift","vmware"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - credentialSimpleTypeTypePropEnum = append(credentialSimpleTypeTypePropEnum, v) - } -} - -const ( - - // CredentialSimpleTypeSSH captures enum value "ssh" - CredentialSimpleTypeSSH string = "ssh" - - // CredentialSimpleTypeAws captures enum value "aws" - CredentialSimpleTypeAws string = "aws" - - // CredentialSimpleTypeCustom captures enum value "custom" - CredentialSimpleTypeCustom string = "custom" - - // CredentialSimpleTypeAzure captures enum value "azure" - CredentialSimpleTypeAzure string = "azure" - - // CredentialSimpleTypeAzureStorage captures enum value "azure_storage" - CredentialSimpleTypeAzureStorage string = "azure_storage" - - // CredentialSimpleTypeGcp captures enum value "gcp" - CredentialSimpleTypeGcp string = "gcp" - - // CredentialSimpleTypeBasicAuth captures enum value "basic_auth" - CredentialSimpleTypeBasicAuth string = "basic_auth" - - // CredentialSimpleTypeElasticsearch captures enum value "elasticsearch" - CredentialSimpleTypeElasticsearch string = "elasticsearch" - - // CredentialSimpleTypeSwift captures enum value "swift" - CredentialSimpleTypeSwift string = "swift" - - // CredentialSimpleTypeVmware captures enum value "vmware" - CredentialSimpleTypeVmware string = "vmware" -) - -// prop value enum -func (m *CredentialSimple) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, credentialSimpleTypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *CredentialSimple) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -func (m *CredentialSimple) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this credential simple based on the context it is used -func (m *CredentialSimple) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateInUse(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateOwner(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CredentialSimple) contextValidateInUse(ctx context.Context, formats strfmt.Registry) error { - - if m.InUse != nil { - - if swag.IsZero(m.InUse) { // not required - return nil - } - - if err := m.InUse.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("in_use") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("in_use") - } - - return err - } - } - - return nil -} - -func (m *CredentialSimple) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { - - if m.Owner != nil { - - if swag.IsZero(m.Owner) { // not required - return nil - } - - if err := m.Owner.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CredentialSimple) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CredentialSimple) UnmarshalBinary(b []byte) error { - var res CredentialSimple - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/elasticsearch_logs.go b/client/models/elasticsearch_logs.go deleted file mode 100644 index 4699bbdcb..000000000 --- a/client/models/elasticsearch_logs.go +++ /dev/null @@ -1,501 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ElasticsearchLogs Representation of Elasticsearch logs for external backend. -// Must be matched with a credential of the "elasticsearch" type. -// -// swagger:model ElasticsearchLogs -type ElasticsearchLogs struct { - - // It's an object where the key is the 'environment' and the value - // another object where the key is the 'source-name' and value a Source. - // - // Required: true - Sources map[string]map[string]ElasticsearchLogsSourcesAnon `json:"sources"` - - // List of the URLs - // - // Required: true - Urls []string `json:"urls"` - - // Only 7 is supported - // - // Required: true - Version *string `json:"version"` -} - -// Engine gets the engine of this subtype -func (m *ElasticsearchLogs) Engine() string { - return "ElasticsearchLogs" -} - -// SetEngine sets the engine of this subtype -func (m *ElasticsearchLogs) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *ElasticsearchLogs) UnmarshalJSON(raw []byte) error { - var data struct { - - // It's an object where the key is the 'environment' and the value - // another object where the key is the 'source-name' and value a Source. - // - // Required: true - Sources map[string]map[string]ElasticsearchLogsSourcesAnon `json:"sources"` - - // List of the URLs - // - // Required: true - Urls []string `json:"urls"` - - // Only 7 is supported - // - // Required: true - Version *string `json:"version"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result ElasticsearchLogs - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.Sources = data.Sources - result.Urls = data.Urls - result.Version = data.Version - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m ElasticsearchLogs) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // It's an object where the key is the 'environment' and the value - // another object where the key is the 'source-name' and value a Source. - // - // Required: true - Sources map[string]map[string]ElasticsearchLogsSourcesAnon `json:"sources"` - - // List of the URLs - // - // Required: true - Urls []string `json:"urls"` - - // Only 7 is supported - // - // Required: true - Version *string `json:"version"` - }{ - - Sources: m.Sources, - - Urls: m.Urls, - - Version: m.Version, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this elasticsearch logs -func (m *ElasticsearchLogs) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateSources(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUrls(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ElasticsearchLogs) validateSources(formats strfmt.Registry) error { - - if err := validate.Required("sources", "body", m.Sources); err != nil { - return err - } - - for k := range m.Sources { - - if err := validate.Required("sources"+"."+k, "body", m.Sources[k]); err != nil { - return err - } - - if err := validate.Required("sources"+"."+k, "body", m.Sources[k]); err != nil { - return err - } - - for kk := range m.Sources[k] { - - if err := validate.Required("sources"+"."+k+"."+kk, "body", m.Sources[k][kk]); err != nil { - return err - } - if val, ok := m.Sources[k][kk]; ok { - if err := val.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("sources" + "." + k + "." + kk) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("sources" + "." + k + "." + kk) - } - - return err - } - } - - } - - } - - return nil -} - -func (m *ElasticsearchLogs) validateUrls(formats strfmt.Registry) error { - - if err := validate.Required("urls", "body", m.Urls); err != nil { - return err - } - - return nil -} - -func (m *ElasticsearchLogs) validateVersion(formats strfmt.Registry) error { - - if err := validate.Required("version", "body", m.Version); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this elasticsearch logs based on the context it is used -func (m *ElasticsearchLogs) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateSources(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ElasticsearchLogs) contextValidateSources(ctx context.Context, formats strfmt.Registry) error { - - if err := validate.Required("sources", "body", m.Sources); err != nil { - return err - } - - for k := range m.Sources { - - if err := validate.Required("sources"+"."+k, "body", m.Sources[k]); err != nil { - return err - } - - for kk := range m.Sources[k] { - - if val, ok := m.Sources[k][kk]; ok { - if err := val.ContextValidate(ctx, formats); err != nil { - return err - } - } - - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ElasticsearchLogs) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ElasticsearchLogs) UnmarshalBinary(b []byte) error { - var res ElasticsearchLogs - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} - -// ElasticsearchLogsSourcesAnon elasticsearch logs sources anon -// -// swagger:model ElasticsearchLogsSourcesAnon -type ElasticsearchLogsSourcesAnon struct { - - // Index to use - // - Index string `json:"index,omitempty"` - - // mapping - Mapping *ElasticsearchLogsSourcesAnonMapping `json:"mapping,omitempty"` - - // JSON representing the prefilters to apply to the index to get - // the specific values. - // - Prefilters any `json:"prefilters,omitempty"` - - // List of URLs to override the main URL defined - // - Urls []string `json:"urls"` -} - -// Validate validates this elasticsearch logs sources anon -func (m *ElasticsearchLogsSourcesAnon) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateMapping(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ElasticsearchLogsSourcesAnon) validateMapping(formats strfmt.Registry) error { - if swag.IsZero(m.Mapping) { // not required - return nil - } - - if m.Mapping != nil { - if err := m.Mapping.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("mapping") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("mapping") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this elasticsearch logs sources anon based on the context it is used -func (m *ElasticsearchLogsSourcesAnon) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateMapping(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ElasticsearchLogsSourcesAnon) contextValidateMapping(ctx context.Context, formats strfmt.Registry) error { - - if m.Mapping != nil { - - if swag.IsZero(m.Mapping) { // not required - return nil - } - - if err := m.Mapping.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("mapping") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("mapping") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ElasticsearchLogsSourcesAnon) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ElasticsearchLogsSourcesAnon) UnmarshalBinary(b []byte) error { - var res ElasticsearchLogsSourcesAnon - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} - -// ElasticsearchLogsSourcesAnonMapping Object with the mapping to know which attributes are the ones -// we have to map to the ones we want -// -// swagger:model ElasticsearchLogsSourcesAnonMapping -type ElasticsearchLogsSourcesAnonMapping struct { - - // The Host of the log - // - // Required: true - Host *string `json:"host"` - - // The Message the user wants to show - // - // Required: true - Message *string `json:"message"` - - // The Timestamp of the log - // - // Required: true - Timestamp *string `json:"timestamp"` -} - -// Validate validates this elasticsearch logs sources anon mapping -func (m *ElasticsearchLogsSourcesAnonMapping) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateHost(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTimestamp(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ElasticsearchLogsSourcesAnonMapping) validateHost(formats strfmt.Registry) error { - - if err := validate.Required("mapping"+"."+"host", "body", m.Host); err != nil { - return err - } - - return nil -} - -func (m *ElasticsearchLogsSourcesAnonMapping) validateMessage(formats strfmt.Registry) error { - - if err := validate.Required("mapping"+"."+"message", "body", m.Message); err != nil { - return err - } - - return nil -} - -func (m *ElasticsearchLogsSourcesAnonMapping) validateTimestamp(formats strfmt.Registry) error { - - if err := validate.Required("mapping"+"."+"timestamp", "body", m.Timestamp); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this elasticsearch logs sources anon mapping based on context it is used -func (m *ElasticsearchLogsSourcesAnonMapping) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *ElasticsearchLogsSourcesAnonMapping) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ElasticsearchLogsSourcesAnonMapping) UnmarshalBinary(b []byte) error { - var res ElasticsearchLogsSourcesAnonMapping - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/ensure_plan.go b/client/models/ensure_plan.go deleted file mode 100644 index 1274e5454..000000000 --- a/client/models/ensure_plan.go +++ /dev/null @@ -1,173 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// EnsurePlan EnsurePlan -// -// The plan to ensure to be run. -// -// swagger:model EnsurePlan -type EnsurePlan struct { - - // next - // Required: true - Next *Plan `json:"next"` - - // step - // Required: true - Step *Plan `json:"step"` -} - -// Validate validates this ensure plan -func (m *EnsurePlan) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateNext(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStep(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *EnsurePlan) validateNext(formats strfmt.Registry) error { - - if err := validate.Required("next", "body", m.Next); err != nil { - return err - } - - if m.Next != nil { - if err := m.Next.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next") - } - - return err - } - } - - return nil -} - -func (m *EnsurePlan) validateStep(formats strfmt.Registry) error { - - if err := validate.Required("step", "body", m.Step); err != nil { - return err - } - - if m.Step != nil { - if err := m.Step.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("step") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("step") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this ensure plan based on the context it is used -func (m *EnsurePlan) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateNext(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateStep(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *EnsurePlan) contextValidateNext(ctx context.Context, formats strfmt.Registry) error { - - if m.Next != nil { - - if err := m.Next.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next") - } - - return err - } - } - - return nil -} - -func (m *EnsurePlan) contextValidateStep(ctx context.Context, formats strfmt.Registry) error { - - if m.Step != nil { - - if err := m.Step.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("step") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("step") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *EnsurePlan) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *EnsurePlan) UnmarshalBinary(b []byte) error { - var res EnsurePlan - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/environment.go b/client/models/environment.go deleted file mode 100644 index 3bb54c1e5..000000000 --- a/client/models/environment.go +++ /dev/null @@ -1,600 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Environment Environment -// -// Represent an environment that belongs to an organization. This is the base environment entity without project-specific relations. -// -// swagger:model Environment -type Environment struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$ - Canonical *string `json:"canonical"` - - // cloud accounts - CloudAccounts []*CloudAccountSimple `json:"cloud_accounts"` - - // components - Components []*Component `json:"components"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // Optional description of the environment - // Max Length: 1000 - Description string `json:"description,omitempty"` - - // environment type - EnvironmentType *EnvironmentType `json:"environment_type,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // The display name of the environment - // Max Length: 100 - // Min Length: 1 - Name string `json:"name,omitempty"` - - // Organization member that owns this environment. When a user is the owner of an - // environment it has all the permissions on it. - // In the event where the user has been deleted this field might be empty. - // - Owner *User `json:"owner,omitempty"` - - // The total count of resources attributed to this environment - // Required: true - // Minimum: 0 - ResourcesCount *uint32 `json:"resources_count"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` - - // Full set of environment variables attached to this environment, available under the `.environment.variables` template path during interpolation. - Variables []*EnvironmentVariableItem `json:"variables"` - - // Aggregated value of the Components Version.Status in this environment. Only populated when the environment is returned alongside a Project. - VersionStatus []string `json:"version_status"` -} - -// Validate validates this environment -func (m *Environment) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudAccounts(formats); err != nil { - res = append(res, err) - } - - if err := m.validateComponents(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironmentType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validateResourcesCount(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVariables(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersionStatus(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Environment) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$`); err != nil { - return err - } - - return nil -} - -func (m *Environment) validateCloudAccounts(formats strfmt.Registry) error { - if swag.IsZero(m.CloudAccounts) { // not required - return nil - } - - for i := 0; i < len(m.CloudAccounts); i++ { - if swag.IsZero(m.CloudAccounts[i]) { // not required - continue - } - - if m.CloudAccounts[i] != nil { - if err := m.CloudAccounts[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cloud_accounts" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cloud_accounts" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Environment) validateComponents(formats strfmt.Registry) error { - if swag.IsZero(m.Components) { // not required - return nil - } - - for i := 0; i < len(m.Components); i++ { - if swag.IsZero(m.Components[i]) { // not required - continue - } - - if m.Components[i] != nil { - if err := m.Components[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("components" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("components" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Environment) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Environment) validateDescription(formats strfmt.Registry) error { - if swag.IsZero(m.Description) { // not required - return nil - } - - if err := validate.MaxLength("description", "body", m.Description, 1000); err != nil { - return err - } - - return nil -} - -func (m *Environment) validateEnvironmentType(formats strfmt.Registry) error { - if swag.IsZero(m.EnvironmentType) { // not required - return nil - } - - if m.EnvironmentType != nil { - if err := m.EnvironmentType.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment_type") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment_type") - } - - return err - } - } - - return nil -} - -func (m *Environment) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *Environment) validateName(formats strfmt.Registry) error { - if swag.IsZero(m.Name) { // not required - return nil - } - - if err := validate.MinLength("name", "body", m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", m.Name, 100); err != nil { - return err - } - - return nil -} - -func (m *Environment) validateOwner(formats strfmt.Registry) error { - if swag.IsZero(m.Owner) { // not required - return nil - } - - if m.Owner != nil { - if err := m.Owner.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *Environment) validateResourcesCount(formats strfmt.Registry) error { - - if err := validate.Required("resources_count", "body", m.ResourcesCount); err != nil { - return err - } - - if err := validate.MinimumUint("resources_count", "body", uint64(*m.ResourcesCount), 0, false); err != nil { - return err - } - - return nil -} - -func (m *Environment) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Environment) validateVariables(formats strfmt.Registry) error { - if swag.IsZero(m.Variables) { // not required - return nil - } - - for i := 0; i < len(m.Variables); i++ { - if swag.IsZero(m.Variables[i]) { // not required - continue - } - - if m.Variables[i] != nil { - if err := m.Variables[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("variables" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("variables" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -var environmentVersionStatusItemsEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["no_status","latest","active","deleted","outdated"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - environmentVersionStatusItemsEnum = append(environmentVersionStatusItemsEnum, v) - } -} - -func (m *Environment) validateVersionStatusItemsEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, environmentVersionStatusItemsEnum, true); err != nil { - return err - } - return nil -} - -func (m *Environment) validateVersionStatus(formats strfmt.Registry) error { - if swag.IsZero(m.VersionStatus) { // not required - return nil - } - - for i := 0; i < len(m.VersionStatus); i++ { - - // value enum - if err := m.validateVersionStatusItemsEnum("version_status"+"."+strconv.Itoa(i), "body", m.VersionStatus[i]); err != nil { - return err - } - - } - - return nil -} - -// ContextValidate validate this environment based on the context it is used -func (m *Environment) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateCloudAccounts(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateComponents(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateEnvironmentType(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateOwner(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateVariables(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Environment) contextValidateCloudAccounts(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.CloudAccounts); i++ { - - if m.CloudAccounts[i] != nil { - - if swag.IsZero(m.CloudAccounts[i]) { // not required - return nil - } - - if err := m.CloudAccounts[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cloud_accounts" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cloud_accounts" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Environment) contextValidateComponents(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Components); i++ { - - if m.Components[i] != nil { - - if swag.IsZero(m.Components[i]) { // not required - return nil - } - - if err := m.Components[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("components" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("components" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Environment) contextValidateEnvironmentType(ctx context.Context, formats strfmt.Registry) error { - - if m.EnvironmentType != nil { - - if swag.IsZero(m.EnvironmentType) { // not required - return nil - } - - if err := m.EnvironmentType.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment_type") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment_type") - } - - return err - } - } - - return nil -} - -func (m *Environment) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { - - if m.Owner != nil { - - if swag.IsZero(m.Owner) { // not required - return nil - } - - if err := m.Owner.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *Environment) contextValidateVariables(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Variables); i++ { - - if m.Variables[i] != nil { - - if swag.IsZero(m.Variables[i]) { // not required - return nil - } - - if err := m.Variables[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("variables" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("variables" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Environment) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Environment) UnmarshalBinary(b []byte) error { - var res Environment - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/environment_simple.go b/client/models/environment_simple.go deleted file mode 100644 index 1b7eea17f..000000000 --- a/client/models/environment_simple.go +++ /dev/null @@ -1,134 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// EnvironmentSimple Environment Simple -// -// A simplified environment representation used when embedding environments in other entities. -// -// swagger:model EnvironmentSimple -type EnvironmentSimple struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$ - Canonical *string `json:"canonical"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // The display name of the environment - // Required: true - // Max Length: 100 - // Min Length: 1 - Name *string `json:"name"` -} - -// Validate validates this environment simple -func (m *EnvironmentSimple) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *EnvironmentSimple) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$`); err != nil { - return err - } - - return nil -} - -func (m *EnvironmentSimple) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *EnvironmentSimple) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 100); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this environment simple based on context it is used -func (m *EnvironmentSimple) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *EnvironmentSimple) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *EnvironmentSimple) UnmarshalBinary(b []byte) error { - var res EnvironmentSimple - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/environment_type.go b/client/models/environment_type.go deleted file mode 100644 index 18b77bf88..000000000 --- a/client/models/environment_type.go +++ /dev/null @@ -1,234 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// EnvironmentType Environment Type -// -// Represent an environment type that belongs to an organization. Environment types are used to categorize environments (e.g., production, staging, development). -// -// swagger:model EnvironmentType -type EnvironmentType struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-z]+(?:[\da-z\-._]+[\da-z]|[\da-z])$ - Canonical *string `json:"canonical"` - - // Color associated with this environment type - // Required: true - // Max Length: 64 - Color *string `json:"color"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // The total count of environments using this environment type - // Required: true - EnvironmentsCount *uint32 `json:"environments_count"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // Indicates if this is a system-provided default environment type that cannot be deleted or renamed - // Required: true - IsDefault *bool `json:"is_default"` - - // name - // Required: true - // Max Length: 255 - // Min Length: 1 - Name *string `json:"name"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` -} - -// Validate validates this environment type -func (m *EnvironmentType) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateColor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironmentsCount(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIsDefault(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *EnvironmentType) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[\da-z]+(?:[\da-z\-._]+[\da-z]|[\da-z])$`); err != nil { - return err - } - - return nil -} - -func (m *EnvironmentType) validateColor(formats strfmt.Registry) error { - - if err := validate.Required("color", "body", m.Color); err != nil { - return err - } - - if err := validate.MaxLength("color", "body", *m.Color, 64); err != nil { - return err - } - - return nil -} - -func (m *EnvironmentType) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *EnvironmentType) validateEnvironmentsCount(formats strfmt.Registry) error { - - if err := validate.Required("environments_count", "body", m.EnvironmentsCount); err != nil { - return err - } - - return nil -} - -func (m *EnvironmentType) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *EnvironmentType) validateIsDefault(formats strfmt.Registry) error { - - if err := validate.Required("is_default", "body", m.IsDefault); err != nil { - return err - } - - return nil -} - -func (m *EnvironmentType) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 255); err != nil { - return err - } - - return nil -} - -func (m *EnvironmentType) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this environment type based on context it is used -func (m *EnvironmentType) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *EnvironmentType) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *EnvironmentType) UnmarshalBinary(b []byte) error { - var res EnvironmentType - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/environment_variable_item.go b/client/models/environment_variable_item.go deleted file mode 100644 index d2309ef15..000000000 --- a/client/models/environment_variable_item.go +++ /dev/null @@ -1,229 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// EnvironmentVariableItem Environment Variable Item -// -// A single key/value pair attached to an Environment. The value is surfaced to interpolation contexts (StackForms, value_ref, pipelines, Terraform templates) under the `.environment.variables` template path. -// -// swagger:model EnvironmentVariableItem -type EnvironmentVariableItem struct { - - // The date and time (unix timestamp) the variable was created. - // Read Only: true - CreatedAt uint64 `json:"created_at,omitempty"` - - // Optional free-form description of the variable. - // Max Length: 1000 - Description string `json:"description,omitempty"` - - // Identifier used to reference the variable in templates (e.g. `($ .environment.variables.my_key $)`). Must not contain dots and must include at least one alphanumeric character. - // Required: true - // Max Length: 255 - // Min Length: 1 - // Pattern: ^[^.]*[A-Za-z0-9][^.]*$ - Key *string `json:"key"` - - // Display hint for the UI to mask this value. The API returns the value in plaintext regardless. - Sensitive *bool `json:"sensitive,omitempty"` - - // Declared shape of the value. Names mirror stackforms widget types so the two APIs stay consistent. - // Required: true - // Enum: ["string","boolean","integer","float","array","map"] - Type *string `json:"type"` - - // The date and time (unix timestamp) the variable was last updated. - // Read Only: true - UpdatedAt uint64 `json:"updated_at,omitempty"` - - // The variable value. Its shape must match the `type` field: a JSON string, boolean, integer, float, array or object respectively. - // Required: true - Value any `json:"value"` -} - -// Validate validates this environment variable item -func (m *EnvironmentVariableItem) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateKey(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateValue(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *EnvironmentVariableItem) validateDescription(formats strfmt.Registry) error { - if swag.IsZero(m.Description) { // not required - return nil - } - - if err := validate.MaxLength("description", "body", m.Description, 1000); err != nil { - return err - } - - return nil -} - -func (m *EnvironmentVariableItem) validateKey(formats strfmt.Registry) error { - - if err := validate.Required("key", "body", m.Key); err != nil { - return err - } - - if err := validate.MinLength("key", "body", *m.Key, 1); err != nil { - return err - } - - if err := validate.MaxLength("key", "body", *m.Key, 255); err != nil { - return err - } - - if err := validate.Pattern("key", "body", *m.Key, `^[^.]*[A-Za-z0-9][^.]*$`); err != nil { - return err - } - - return nil -} - -var environmentVariableItemTypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["string","boolean","integer","float","array","map"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - environmentVariableItemTypeTypePropEnum = append(environmentVariableItemTypeTypePropEnum, v) - } -} - -const ( - - // EnvironmentVariableItemTypeString captures enum value "string" - EnvironmentVariableItemTypeString string = "string" - - // EnvironmentVariableItemTypeBoolean captures enum value "boolean" - EnvironmentVariableItemTypeBoolean string = "boolean" - - // EnvironmentVariableItemTypeInteger captures enum value "integer" - EnvironmentVariableItemTypeInteger string = "integer" - - // EnvironmentVariableItemTypeFloat captures enum value "float" - EnvironmentVariableItemTypeFloat string = "float" - - // EnvironmentVariableItemTypeArray captures enum value "array" - EnvironmentVariableItemTypeArray string = "array" - - // EnvironmentVariableItemTypeMap captures enum value "map" - EnvironmentVariableItemTypeMap string = "map" -) - -// prop value enum -func (m *EnvironmentVariableItem) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, environmentVariableItemTypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *EnvironmentVariableItem) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -func (m *EnvironmentVariableItem) validateValue(formats strfmt.Registry) error { - - if m.Value == nil { - return errors.Required("value", "body", nil) - } - - return nil -} - -// ContextValidate validate this environment variable item based on the context it is used -func (m *EnvironmentVariableItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateCreatedAt(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateUpdatedAt(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *EnvironmentVariableItem) contextValidateCreatedAt(ctx context.Context, formats strfmt.Registry) error { - - if err := validate.ReadOnly(ctx, "created_at", "body", m.CreatedAt); err != nil { - return err - } - - return nil -} - -func (m *EnvironmentVariableItem) contextValidateUpdatedAt(ctx context.Context, formats strfmt.Registry) error { - - if err := validate.ReadOnly(ctx, "updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *EnvironmentVariableItem) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *EnvironmentVariableItem) UnmarshalBinary(b []byte) error { - var res EnvironmentVariableItem - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/error_details_item.go b/client/models/error_details_item.go deleted file mode 100644 index 982d3629d..000000000 --- a/client/models/error_details_item.go +++ /dev/null @@ -1,90 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ErrorDetailsItem Error details item -// -// Represents an item of the list of details of an error. -// -// swagger:model ErrorDetailsItem -type ErrorDetailsItem struct { - - // code - // Required: true - Code *string `json:"code"` - - // details - Details []string `json:"details"` - - // message - // Required: true - Message *string `json:"message"` -} - -// Validate validates this error details item -func (m *ErrorDetailsItem) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCode(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMessage(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ErrorDetailsItem) validateCode(formats strfmt.Registry) error { - - if err := validate.Required("code", "body", m.Code); err != nil { - return err - } - - return nil -} - -func (m *ErrorDetailsItem) validateMessage(formats strfmt.Registry) error { - - if err := validate.Required("message", "body", m.Message); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this error details item based on context it is used -func (m *ErrorDetailsItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *ErrorDetailsItem) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ErrorDetailsItem) UnmarshalBinary(b []byte) error { - var res ErrorDetailsItem - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/error_payload.go b/client/models/error_payload.go deleted file mode 100644 index 6413e6dfd..000000000 --- a/client/models/error_payload.go +++ /dev/null @@ -1,135 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ErrorPayload Error Payload -// -// The payload used by the server to response to the client with an Error, those errors could be any of the ones listed [here](https://github.com/cycloidio/youdeploy-http-api/blob/develop/errors/code.go#L10), only the CODE of the error is the one that is guaranteed to not change between the same major version, the MESSAGE could change. -// -// swagger:model ErrorPayload -type ErrorPayload struct { - - // errors - // Required: true - Errors []*ErrorDetailsItem `json:"errors"` - - // request id - RequestID string `json:"request_id,omitempty"` -} - -// Validate validates this error payload -func (m *ErrorPayload) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateErrors(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ErrorPayload) validateErrors(formats strfmt.Registry) error { - - if err := validate.Required("errors", "body", m.Errors); err != nil { - return err - } - - for i := 0; i < len(m.Errors); i++ { - if swag.IsZero(m.Errors[i]) { // not required - continue - } - - if m.Errors[i] != nil { - if err := m.Errors[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("errors" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("errors" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this error payload based on the context it is used -func (m *ErrorPayload) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateErrors(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ErrorPayload) contextValidateErrors(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Errors); i++ { - - if m.Errors[i] != nil { - - if swag.IsZero(m.Errors[i]) { // not required - return nil - } - - if err := m.Errors[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("errors" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("errors" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ErrorPayload) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ErrorPayload) UnmarshalBinary(b []byte) error { - var res ErrorPayload - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/event.go b/client/models/event.go deleted file mode 100644 index 45724b045..000000000 --- a/client/models/event.go +++ /dev/null @@ -1,377 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Event An event -// -// A event which has registered an activity in the Cycloid platform. -// -// swagger:model Event -type Event struct { - - // The HTML color associated to the event. The valid colors are the ones listed in the CSS 2 specification: https://www.w3.org/TR/CSS2/syndata.html#value-def-color. Only the keyword are accepted, the hexadecimal values are not valid. - // Max Length: 20 - // Min Length: 3 - // Pattern: [a-z]+ - Color string `json:"color,omitempty"` - - // [A Font Awesome class name](https://fontawesome.com/icons) - // Min Length: 3 - Icon string `json:"icon,omitempty"` - - // The unique ID of the event from the database. - // Required: true - ID *uint32 `json:"id"` - - // The message associated to the event. - // Required: true - // Min Length: 1 - Message *string `json:"message"` - - // The severity associated to the event. - // Required: true - // Enum: ["info","warn","err","crit"] - Severity *string `json:"severity"` - - // The list of tags associated to the event. - // Required: true - Tags []*Tag `json:"tags"` - - // The timestamp when the event was created in milliseconds. - // Required: true - Timestamp *uint64 `json:"timestamp"` - - // The title of the event. - // Required: true - // Min Length: 1 - Title *string `json:"title"` - - // The type of the event - // Required: true - // Enum: ["Cycloid","AWS","Monitoring","Custom"] - Type *string `json:"type"` -} - -// Validate validates this event -func (m *Event) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateColor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIcon(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSeverity(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTags(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTimestamp(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTitle(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Event) validateColor(formats strfmt.Registry) error { - if swag.IsZero(m.Color) { // not required - return nil - } - - if err := validate.MinLength("color", "body", m.Color, 3); err != nil { - return err - } - - if err := validate.MaxLength("color", "body", m.Color, 20); err != nil { - return err - } - - if err := validate.Pattern("color", "body", m.Color, `[a-z]+`); err != nil { - return err - } - - return nil -} - -func (m *Event) validateIcon(formats strfmt.Registry) error { - if swag.IsZero(m.Icon) { // not required - return nil - } - - if err := validate.MinLength("icon", "body", m.Icon, 3); err != nil { - return err - } - - return nil -} - -func (m *Event) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - return nil -} - -func (m *Event) validateMessage(formats strfmt.Registry) error { - - if err := validate.Required("message", "body", m.Message); err != nil { - return err - } - - if err := validate.MinLength("message", "body", *m.Message, 1); err != nil { - return err - } - - return nil -} - -var eventTypeSeverityPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["info","warn","err","crit"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - eventTypeSeverityPropEnum = append(eventTypeSeverityPropEnum, v) - } -} - -const ( - - // EventSeverityInfo captures enum value "info" - EventSeverityInfo string = "info" - - // EventSeverityWarn captures enum value "warn" - EventSeverityWarn string = "warn" - - // EventSeverityErr captures enum value "err" - EventSeverityErr string = "err" - - // EventSeverityCrit captures enum value "crit" - EventSeverityCrit string = "crit" -) - -// prop value enum -func (m *Event) validateSeverityEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, eventTypeSeverityPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *Event) validateSeverity(formats strfmt.Registry) error { - - if err := validate.Required("severity", "body", m.Severity); err != nil { - return err - } - - // value enum - if err := m.validateSeverityEnum("severity", "body", *m.Severity); err != nil { - return err - } - - return nil -} - -func (m *Event) validateTags(formats strfmt.Registry) error { - - if err := validate.Required("tags", "body", m.Tags); err != nil { - return err - } - - for i := 0; i < len(m.Tags); i++ { - if swag.IsZero(m.Tags[i]) { // not required - continue - } - - if m.Tags[i] != nil { - if err := m.Tags[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("tags" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("tags" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Event) validateTimestamp(formats strfmt.Registry) error { - - if err := validate.Required("timestamp", "body", m.Timestamp); err != nil { - return err - } - - return nil -} - -func (m *Event) validateTitle(formats strfmt.Registry) error { - - if err := validate.Required("title", "body", m.Title); err != nil { - return err - } - - if err := validate.MinLength("title", "body", *m.Title, 1); err != nil { - return err - } - - return nil -} - -var eventTypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["Cycloid","AWS","Monitoring","Custom"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - eventTypeTypePropEnum = append(eventTypeTypePropEnum, v) - } -} - -const ( - - // EventTypeCycloid captures enum value "Cycloid" - EventTypeCycloid string = "Cycloid" - - // EventTypeAWS captures enum value "AWS" - EventTypeAWS string = "AWS" - - // EventTypeMonitoring captures enum value "Monitoring" - EventTypeMonitoring string = "Monitoring" - - // EventTypeCustom captures enum value "Custom" - EventTypeCustom string = "Custom" -) - -// prop value enum -func (m *Event) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, eventTypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *Event) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this event based on the context it is used -func (m *Event) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateTags(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Event) contextValidateTags(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Tags); i++ { - - if m.Tags[i] != nil { - - if swag.IsZero(m.Tags[i]) { // not required - return nil - } - - if err := m.Tags[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("tags" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("tags" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Event) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Event) UnmarshalBinary(b []byte) error { - var res Event - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/events_actions_and_entities.go b/client/models/events_actions_and_entities.go deleted file mode 100644 index 5eb3796eb..000000000 --- a/client/models/events_actions_and_entities.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// EventsActionsAndEntities Events Actions and Entities -// -// # The entity which represents the information of the actions and entities of an event -// -// swagger:model EventsActionsAndEntities -type EventsActionsAndEntities struct { - - // actions - // Required: true - Actions []string `json:"actions"` - - // entities - // Required: true - Entities []string `json:"entities"` -} - -// Validate validates this events actions and entities -func (m *EventsActionsAndEntities) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateActions(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEntities(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *EventsActionsAndEntities) validateActions(formats strfmt.Registry) error { - - if err := validate.Required("actions", "body", m.Actions); err != nil { - return err - } - - return nil -} - -func (m *EventsActionsAndEntities) validateEntities(formats strfmt.Registry) error { - - if err := validate.Required("entities", "body", m.Entities); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this events actions and entities based on context it is used -func (m *EventsActionsAndEntities) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *EventsActionsAndEntities) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *EventsActionsAndEntities) UnmarshalBinary(b []byte) error { - var res EventsActionsAndEntities - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/events_count.go b/client/models/events_count.go deleted file mode 100644 index 3f47e528b..000000000 --- a/client/models/events_count.go +++ /dev/null @@ -1,109 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// EventsCount Events Count -// -// # The entity which represents the information of the count of events -// -// swagger:model EventsCount -type EventsCount struct { - - // count - // Required: true - // Minimum: 0 - Count *uint64 `json:"count"` - - // end - // Required: true - End *uint64 `json:"end"` - - // start - // Required: true - Start *uint64 `json:"start"` -} - -// Validate validates this events count -func (m *EventsCount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCount(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnd(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStart(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *EventsCount) validateCount(formats strfmt.Registry) error { - - if err := validate.Required("count", "body", m.Count); err != nil { - return err - } - - if err := validate.MinimumUint("count", "body", *m.Count, 0, false); err != nil { - return err - } - - return nil -} - -func (m *EventsCount) validateEnd(formats strfmt.Registry) error { - - if err := validate.Required("end", "body", m.End); err != nil { - return err - } - - return nil -} - -func (m *EventsCount) validateStart(formats strfmt.Registry) error { - - if err := validate.Required("start", "body", m.Start); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this events count based on context it is used -func (m *EventsCount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *EventsCount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *EventsCount) UnmarshalBinary(b []byte) error { - var res EventsCount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/external_backend.go b/client/models/external_backend.go deleted file mode 100644 index 87dc40b20..000000000 --- a/client/models/external_backend.go +++ /dev/null @@ -1,480 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - stderrors "errors" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ExternalBackend External backend -// -// An external backend contains the configuration needed in order to be plugged into the Cycloid system. A backend is a general purpose concept, but Cycloid specifies which ones are supported and the list of those which are supported for every concrete feature. -// -// swagger:model ExternalBackend -type ExternalBackend struct { - - // component canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$ - ComponentCanonical string `json:"component_canonical,omitempty"` - - configurationField ExternalBackendConfiguration - - // created at - // Minimum: 0 - CreatedAt *uint64 `json:"created_at,omitempty"` - - // credential canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical string `json:"credential_canonical,omitempty"` - - // Will mark this EB as default for the specific purpose - // Required: true - Default *bool `json:"default"` - - // environment canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$ - EnvironmentCanonical string `json:"environment_canonical,omitempty"` - - // id - // Minimum: 1 - ID uint32 `json:"id,omitempty"` - - // JWT is a credential identifying this EB for a public interaction right now it's only filled when the Purpose == RemoteTFState as we'll use it for the Inventory. - Jwt string `json:"jwt,omitempty"` - - // project canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - ProjectCanonical string `json:"project_canonical,omitempty"` - - // purpose - // Required: true - Purpose *string `json:"purpose"` - - // updated at - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` -} - -// Configuration gets the configuration of this base type -func (m *ExternalBackend) Configuration() ExternalBackendConfiguration { - return m.configurationField -} - -// SetConfiguration sets the configuration of this base type -func (m *ExternalBackend) SetConfiguration(val ExternalBackendConfiguration) { - m.configurationField = val -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *ExternalBackend) UnmarshalJSON(raw []byte) error { - var data struct { - ComponentCanonical string `json:"component_canonical,omitempty"` - - Configuration json.RawMessage `json:"configuration"` - - CreatedAt *uint64 `json:"created_at,omitempty"` - - CredentialCanonical string `json:"credential_canonical,omitempty"` - - Default *bool `json:"default"` - - EnvironmentCanonical string `json:"environment_canonical,omitempty"` - - ID uint32 `json:"id,omitempty"` - - Jwt string `json:"jwt,omitempty"` - - ProjectCanonical string `json:"project_canonical,omitempty"` - - Purpose *string `json:"purpose"` - - UpdatedAt *uint64 `json:"updated_at,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - propConfiguration, err := UnmarshalExternalBackendConfiguration(bytes.NewBuffer(data.Configuration), runtime.JSONConsumer()) - if err != nil && !stderrors.Is(err, io.EOF) { - return err - } - - var result ExternalBackend - - // component_canonical - result.ComponentCanonical = data.ComponentCanonical - - // configuration - result.configurationField = propConfiguration - - // created_at - result.CreatedAt = data.CreatedAt - - // credential_canonical - result.CredentialCanonical = data.CredentialCanonical - - // default - result.Default = data.Default - - // environment_canonical - result.EnvironmentCanonical = data.EnvironmentCanonical - - // id - result.ID = data.ID - - // jwt - result.Jwt = data.Jwt - - // project_canonical - result.ProjectCanonical = data.ProjectCanonical - - // purpose - result.Purpose = data.Purpose - - // updated_at - result.UpdatedAt = data.UpdatedAt - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m ExternalBackend) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - ComponentCanonical string `json:"component_canonical,omitempty"` - - CreatedAt *uint64 `json:"created_at,omitempty"` - - CredentialCanonical string `json:"credential_canonical,omitempty"` - - Default *bool `json:"default"` - - EnvironmentCanonical string `json:"environment_canonical,omitempty"` - - ID uint32 `json:"id,omitempty"` - - Jwt string `json:"jwt,omitempty"` - - ProjectCanonical string `json:"project_canonical,omitempty"` - - Purpose *string `json:"purpose"` - - UpdatedAt *uint64 `json:"updated_at,omitempty"` - }{ - - ComponentCanonical: m.ComponentCanonical, - - CreatedAt: m.CreatedAt, - - CredentialCanonical: m.CredentialCanonical, - - Default: m.Default, - - EnvironmentCanonical: m.EnvironmentCanonical, - - ID: m.ID, - - Jwt: m.Jwt, - - ProjectCanonical: m.ProjectCanonical, - - Purpose: m.Purpose, - - UpdatedAt: m.UpdatedAt, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Configuration ExternalBackendConfiguration `json:"configuration"` - }{ - - Configuration: m.configurationField, - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this external backend -func (m *ExternalBackend) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateComponentCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateConfiguration(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDefault(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironmentCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjectCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePurpose(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ExternalBackend) validateComponentCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ComponentCanonical) { // not required - return nil - } - - if err := validate.MinLength("component_canonical", "body", m.ComponentCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("component_canonical", "body", m.ComponentCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("component_canonical", "body", m.ComponentCanonical, `^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$`); err != nil { - return err - } - - return nil -} - -func (m *ExternalBackend) validateConfiguration(formats strfmt.Registry) error { - - if err := validate.Required("configuration", "body", m.Configuration()); err != nil { - return err - } - - if err := m.Configuration().Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -func (m *ExternalBackend) validateCreatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *ExternalBackend) validateCredentialCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.CredentialCanonical) { // not required - return nil - } - - if err := validate.MinLength("credential_canonical", "body", m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *ExternalBackend) validateDefault(formats strfmt.Registry) error { - - if err := validate.Required("default", "body", m.Default); err != nil { - return err - } - - return nil -} - -func (m *ExternalBackend) validateEnvironmentCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.EnvironmentCanonical) { // not required - return nil - } - - if err := validate.MinLength("environment_canonical", "body", m.EnvironmentCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("environment_canonical", "body", m.EnvironmentCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("environment_canonical", "body", m.EnvironmentCanonical, `^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$`); err != nil { - return err - } - - return nil -} - -func (m *ExternalBackend) validateID(formats strfmt.Registry) error { - if swag.IsZero(m.ID) { // not required - return nil - } - - if err := validate.MinimumUint("id", "body", uint64(m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *ExternalBackend) validateProjectCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ProjectCanonical) { // not required - return nil - } - - if err := validate.MinLength("project_canonical", "body", m.ProjectCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("project_canonical", "body", m.ProjectCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("project_canonical", "body", m.ProjectCanonical, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -func (m *ExternalBackend) validatePurpose(formats strfmt.Registry) error { - - if err := validate.Required("purpose", "body", m.Purpose); err != nil { - return err - } - - return nil -} - -func (m *ExternalBackend) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this external backend based on the context it is used -func (m *ExternalBackend) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateConfiguration(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ExternalBackend) contextValidateConfiguration(ctx context.Context, formats strfmt.Registry) error { - - if err := m.Configuration().ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ExternalBackend) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ExternalBackend) UnmarshalBinary(b []byte) error { - var res ExternalBackend - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/external_backend_configuration.go b/client/models/external_backend_configuration.go deleted file mode 100644 index 8163c1473..000000000 --- a/client/models/external_backend_configuration.go +++ /dev/null @@ -1,200 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" -) - -// ExternalBackendConfiguration external backend configuration -// -// swagger:discriminator ExternalBackendConfiguration engine -type ExternalBackendConfiguration interface { - runtime.Validatable - runtime.ContextValidatable - - // engine - // Required: true - Engine() string - SetEngine(string) - - // AdditionalProperties in base type shoud be handled just like regular properties - // At this moment, the base type property is pushed down to the subtype -} - -type externalBackendConfiguration struct { - engineField string -} - -// Engine gets the engine of this polymorphic type -func (m *externalBackendConfiguration) Engine() string { - return "ExternalBackendConfiguration" -} - -// SetEngine sets the engine of this polymorphic type -func (m *externalBackendConfiguration) SetEngine(val string) { -} - -// UnmarshalExternalBackendConfigurationSlice unmarshals polymorphic slices of ExternalBackendConfiguration -func UnmarshalExternalBackendConfigurationSlice(reader io.Reader, consumer runtime.Consumer) ([]ExternalBackendConfiguration, error) { - var elements []json.RawMessage - if err := consumer.Consume(reader, &elements); err != nil { - return nil, err - } - - var result []ExternalBackendConfiguration - for _, element := range elements { - obj, err := unmarshalExternalBackendConfiguration(element, consumer) - if err != nil { - return nil, err - } - result = append(result, obj) - } - return result, nil -} - -// UnmarshalExternalBackendConfiguration unmarshals polymorphic ExternalBackendConfiguration -func UnmarshalExternalBackendConfiguration(reader io.Reader, consumer runtime.Consumer) (ExternalBackendConfiguration, error) { - // we need to read this twice, so first into a buffer - data, err := io.ReadAll(reader) - if err != nil { - return nil, err - } - return unmarshalExternalBackendConfiguration(data, consumer) -} - -func unmarshalExternalBackendConfiguration(data []byte, consumer runtime.Consumer) (ExternalBackendConfiguration, error) { - buf := bytes.NewBuffer(data) - buf2 := bytes.NewBuffer(data) - - // the first time this is read is to fetch the value of the engine property. - var getType struct { - Engine string `json:"engine"` - } - if err := consumer.Consume(buf, &getType); err != nil { - return nil, err - } - - if err := validate.RequiredString("engine", "body", getType.Engine); err != nil { - return nil, err - } - - // The value of engine is used to determine which type to create and unmarshal the data into - switch getType.Engine { - case "AWSCloudWatchLogs": - var result AWSCloudWatchLogs - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "AWSRemoteTFState": - var result AWSRemoteTFState - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "AWSStorage": - var result AWSStorage - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "AzureCostExport": - var result AzureCostExport - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "AzureRemoteTFState": - var result AzureRemoteTFState - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "AzureStorage": - var result AzureStorage - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "ElasticsearchLogs": - var result ElasticsearchLogs - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "ExternalBackendConfiguration": - var result externalBackendConfiguration - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "GCPCostStorage": - var result GCPCostStorage - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "GCPRemoteTFState": - var result GCPRemoteTFState - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "GCPStorage": - var result GCPStorage - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "GitLabHTTPStorage": - var result GitLabHTTPStorage - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "HTTPStorage": - var result HTTPStorage - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "SwiftRemoteTFState": - var result SwiftRemoteTFState - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "SwiftStorage": - var result SwiftStorage - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - case "VMwareVsphere": - var result VMwareVsphere - if err := consumer.Consume(buf2, &result); err != nil { - return nil, err - } - return &result, nil - } - return nil, errors.New(422, "invalid engine value: %q", getType.Engine) -} - -// Validate validates this external backend configuration -func (m *externalBackendConfiguration) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this external backend configuration based on context it is used -func (m *externalBackendConfiguration) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} diff --git a/client/models/filters.go b/client/models/filters.go deleted file mode 100644 index 570aaf1ae..000000000 --- a/client/models/filters.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// Filters Filters -// -// # Filters is the possible values the filters can have on list requests -// -// swagger:model Filters -type Filters any diff --git a/client/models/form_entity.go b/client/models/form_entity.go deleted file mode 100644 index 040012e20..000000000 --- a/client/models/form_entity.go +++ /dev/null @@ -1,346 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// FormEntity Forms file's Entity -// -// # This describes all the attributes possible to configure a form's variable -// -// swagger:model FormEntity -type FormEntity struct { - - // The current value that was previously configured for this variable upon creation or update. In case of shared variables having different values, it will be empty, and 'mismatch_values' will be filled instead. - Current any `json:"current,omitempty"` - - // Default can take 2 kinds of definition. - // The first one is simply the variable to assign if nothing is given by the user and that the variable is required. - // The second one is dynamic default, meaning default that can vary based on conditions. The format is as follows: - // options: - // - name: "Name of set (can be omitted)" - // condition: "$env == 'dev'" - // default: t2.micro - // - condition: "$env == 'prod'" - // default: t2.large - Default any `json:"default,omitempty"` - - // List of keys that are required to use this entity - DependsOn []string `json:"depends_on"` - - // The description helping users understand the interest/impact of such variable/change - Description string `json:"description,omitempty"` - - // Whether or not the entity should be displayed to the user. This entity must be usable as such (not required, or with a default if required) - Folded bool `json:"folded,omitempty"` - - // The key is the name of variables for the ansible/pipeline/terraform technologies. If this is a first level variable then: keyX. If you have multiple terraform modules then use: module.Y.keyX to help identify the unique variable. - // Required: true - Key *string `json:"key"` - - // This is filled only when a shared variable does not have the same values anymore. e.g. a variable 'foo' was shared between 'ansible' and 'pipeline', was set to 'bar', but now the value found for 'ansible' is 'bus', while it's still 'bar' for the pipeline. In such situation, the Forms don't know anymore which is the correct data and will return both, while unsetting the 'Current' field. - MismatchValues []any `json:"mismatch_values"` - - // The name of the variable displayed to the user - // Required: true - Name *string `json:"name"` - - // Whether or not the entity is displayed to the user but cannot be modified. Useful for showing computed or immutable values. - ReadOnly bool `json:"read_only,omitempty"` - - // Whether or not the field is required - that helps distinguish "optional" variables and allows to set default if necessary and present - Required bool `json:"required,omitempty"` - - // The source is only used for the branch widget to reference the key of the SCS or CR that the branches have to be read from. Because a branch in itself cannot exist, the user has to indicate from which SCS or CR he wants to retrieve branches. The source has to reference the key of an entity of a widget: 'CyCRS' or 'CySCS' - Source string `json:"source,omitempty"` - - // The type of data handled - used to manipulate/validate the input, and also validate default/values - // Required: true - // Enum: ["integer","float","string","array","boolean","map"] - Type *string `json:"type"` - - // The unit to be displayed for the variable, helping to know what's being manipulated: amount of servers, Go, users, etc. - Unit string `json:"unit,omitempty"` - - // An array of validations and relative errors for this entitiy. For example: - // validations: - // - regexp: "^proj_.*$" - // error_message: "the value must have 'proj_' as prefix" - // - regexp: "^.*_awesome$" - // error_message: "the value must have '_awesome' as suffix" - // At the moment only regexp validations are implemented but we can expect objects with a 'type', and 'error_message' field. The type field can hold the constraint, as in the case of regexp or hipotetically a moe complex object. - Validations []any `json:"validations"` - - // Values can take 2 kinds of definition. - // First one is a list of object, such as list of integer, maps, etc. Values allowed, e.g. [1, 10, 20, 50]. Note: In case of SliderRange only 2 values should be provided: [min, max], in case of providing them the other way around some validation test will fail. - // Second one is dynamic values, meaning values that can vary based on conditions. The format is as follows: - // options: - // - name: "Name of set (can be omitted)" - // condition: "$env == 'dev'" - // values: [dev-ami1, dev-ami2, dev-ami3] - // - condition: "$env == 'prod'" - // values: [prod-ami1, prod-ami2, prod-ami3] - Values any `json:"values,omitempty"` - - // It's a URL in which the values have to be fetched from - ValuesRef string `json:"values_ref,omitempty"` - - // The widget used to display the data in the most suitable way - // Required: true - // Enum: ["auto_complete","dropdown","radios","slider_list","slider_range","number","simple_text","switch","text_area","cy_cred","cy_scs","cy_crs","cy_branch","cy_inventory_resource","cy_inventory_output","date_time","hidden"] - Widget *string `json:"widget"` - - // Some specific configuration that could be applied to that widget. Currently only a few widgets can be configured: - // * cy_cred - // * 'cred_types' (list): reduce the types of credentials retrieved to that list. See supported types of credentials - // * 'display_keys' (bool): to specify if the path + key have to be written or only the path - // * 'format' (enum): credential format, one of: 'path' | 'uri'. Defaults to path. Only credentials in URI format can be shared between technologies. - // * 'uri_parameters' (map): optional query parameters that should be encoded and added to the resulting credential URI by the client. For example, they may be used to specify the output format (e.g., JSON). Applies only if format='uri'. - // * radio - // * 'orientation' (string): whether you want to display it in an 'horizontal' or 'vertical' way - // * cy_inventory_resource - // * 'attribute' (string): REQUIRED The path to the attribute to actually use as value - // * 'filters': (object): The filters to apply, selected from the list below: - // * 'provider' (string): The provider like '"provider[\"registry.terraform.io/hashicorp/aws\"]"' - // * 'type' (string): The type of the resource like 'aws_vpc' - // * 'name' (string): The name of the resource like 'front' - // * 'module' (string): The module name like 'module.lemp' - // * 'label' (string): The label of the resource, this only applies for resources created directly from the API/FE - // * 'attributes' (string): The query string to filter the attributes like 'ingress[0].protocol[eq]=tcp' - // * 'custom_attributes' (string): The query string to filter the custom_attributes like 'ingress[0].protocol[eq]=tcp' - // * 'project' (string): Linked project canonical - // * 'environment' (string): Linked environment canonical - // * 'component' (string): Linked component canonical - // * date_time - // * 'format' (string): the date/time format string for display and storage (e.g. 'YYYY-MM-DD', 'YYYY-MM-DD HH:mm', 'YYYY-MM-DDTHH:mm:ssZ'). Defaults to 'YYYY-MM-DDTHH:mm:ssZ' if not specified. - // * 'block_weekends' (bool): prevents selection of Saturday and Sunday dates. Defaults to false. - // * 'date_only' (bool): restricts picker to date selection only (no time inputs). When true, format defaults to 'YYYY-MM-DD'. Defaults to false. - // * cy_inventory_output - // * 'attribute' (string): Path to the output's attribute, which value will be used - // * 'filters': (object): The filters to apply, selected from the list below: - // * 'attributes' (string): The query string to filter the attributes like 'ingress[0].protocol[eq]=tcp' - // * 'keys' (list(string)): List of output keys to select from - // * 'project' (string): Linked project canonical - // * 'environment' (string): Linked environment canonical - // * 'component' (string): Linked component canonical - // * 'service_catalogs' (list(string)): Linked service catalog (stack) canonicals - WidgetConfig any `json:"widget_config,omitempty"` -} - -// Validate validates this form entity -func (m *FormEntity) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateKey(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateWidget(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormEntity) validateKey(formats strfmt.Registry) error { - - if err := validate.Required("key", "body", m.Key); err != nil { - return err - } - - return nil -} - -func (m *FormEntity) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -var formEntityTypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["integer","float","string","array","boolean","map"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - formEntityTypeTypePropEnum = append(formEntityTypeTypePropEnum, v) - } -} - -const ( - - // FormEntityTypeInteger captures enum value "integer" - FormEntityTypeInteger string = "integer" - - // FormEntityTypeFloat captures enum value "float" - FormEntityTypeFloat string = "float" - - // FormEntityTypeString captures enum value "string" - FormEntityTypeString string = "string" - - // FormEntityTypeArray captures enum value "array" - FormEntityTypeArray string = "array" - - // FormEntityTypeBoolean captures enum value "boolean" - FormEntityTypeBoolean string = "boolean" - - // FormEntityTypeMap captures enum value "map" - FormEntityTypeMap string = "map" -) - -// prop value enum -func (m *FormEntity) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, formEntityTypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *FormEntity) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -var formEntityTypeWidgetPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["auto_complete","dropdown","radios","slider_list","slider_range","number","simple_text","switch","text_area","cy_cred","cy_scs","cy_crs","cy_branch","cy_inventory_resource","cy_inventory_output","date_time","hidden"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - formEntityTypeWidgetPropEnum = append(formEntityTypeWidgetPropEnum, v) - } -} - -const ( - - // FormEntityWidgetAutoComplete captures enum value "auto_complete" - FormEntityWidgetAutoComplete string = "auto_complete" - - // FormEntityWidgetDropdown captures enum value "dropdown" - FormEntityWidgetDropdown string = "dropdown" - - // FormEntityWidgetRadios captures enum value "radios" - FormEntityWidgetRadios string = "radios" - - // FormEntityWidgetSliderList captures enum value "slider_list" - FormEntityWidgetSliderList string = "slider_list" - - // FormEntityWidgetSliderRange captures enum value "slider_range" - FormEntityWidgetSliderRange string = "slider_range" - - // FormEntityWidgetNumber captures enum value "number" - FormEntityWidgetNumber string = "number" - - // FormEntityWidgetSimpleText captures enum value "simple_text" - FormEntityWidgetSimpleText string = "simple_text" - - // FormEntityWidgetSwitch captures enum value "switch" - FormEntityWidgetSwitch string = "switch" - - // FormEntityWidgetTextArea captures enum value "text_area" - FormEntityWidgetTextArea string = "text_area" - - // FormEntityWidgetCyCred captures enum value "cy_cred" - FormEntityWidgetCyCred string = "cy_cred" - - // FormEntityWidgetCyScs captures enum value "cy_scs" - FormEntityWidgetCyScs string = "cy_scs" - - // FormEntityWidgetCyCrs captures enum value "cy_crs" - FormEntityWidgetCyCrs string = "cy_crs" - - // FormEntityWidgetCyBranch captures enum value "cy_branch" - FormEntityWidgetCyBranch string = "cy_branch" - - // FormEntityWidgetCyInventoryResource captures enum value "cy_inventory_resource" - FormEntityWidgetCyInventoryResource string = "cy_inventory_resource" - - // FormEntityWidgetCyInventoryOutput captures enum value "cy_inventory_output" - FormEntityWidgetCyInventoryOutput string = "cy_inventory_output" - - // FormEntityWidgetDateTime captures enum value "date_time" - FormEntityWidgetDateTime string = "date_time" - - // FormEntityWidgetHidden captures enum value "hidden" - FormEntityWidgetHidden string = "hidden" -) - -// prop value enum -func (m *FormEntity) validateWidgetEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, formEntityTypeWidgetPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *FormEntity) validateWidget(formats strfmt.Registry) error { - - if err := validate.Required("widget", "body", m.Widget); err != nil { - return err - } - - // value enum - if err := m.validateWidgetEnum("widget", "body", *m.Widget); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this form entity based on context it is used -func (m *FormEntity) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *FormEntity) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *FormEntity) UnmarshalBinary(b []byte) error { - var res FormEntity - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/form_group.go b/client/models/form_group.go deleted file mode 100644 index cc19980af..000000000 --- a/client/models/form_group.go +++ /dev/null @@ -1,176 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// FormGroup Forms File Group -// -// swagger:model FormGroup -type FormGroup struct { - - // Condition required to be respected to be able to configure that group. - Condition string `json:"condition,omitempty"` - - // An optional description to display for this group - Description string `json:"description,omitempty"` - - // Whether or not the group should be displayed to the user. Variables within this group must be usable as such (not required, or with a default if required) - Folded bool `json:"folded,omitempty"` - - // name - // Required: true - Name *string `json:"name"` - - // Whether or not the variables of the group are displayed to the user but cannot be modified. Useful for showing computed or immutable values. - ReadOnly bool `json:"read_only,omitempty"` - - // technologies - // Required: true - Technologies []string `json:"technologies"` - - // vars - // Required: true - Vars []*FormEntity `json:"vars"` -} - -// Validate validates this form group -func (m *FormGroup) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTechnologies(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVars(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormGroup) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *FormGroup) validateTechnologies(formats strfmt.Registry) error { - - if err := validate.Required("technologies", "body", m.Technologies); err != nil { - return err - } - - return nil -} - -func (m *FormGroup) validateVars(formats strfmt.Registry) error { - - if err := validate.Required("vars", "body", m.Vars); err != nil { - return err - } - - for i := 0; i < len(m.Vars); i++ { - if swag.IsZero(m.Vars[i]) { // not required - continue - } - - if m.Vars[i] != nil { - if err := m.Vars[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("vars" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("vars" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this form group based on the context it is used -func (m *FormGroup) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateVars(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormGroup) contextValidateVars(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Vars); i++ { - - if m.Vars[i] != nil { - - if swag.IsZero(m.Vars[i]) { // not required - return nil - } - - if err := m.Vars[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("vars" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("vars" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *FormGroup) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *FormGroup) UnmarshalBinary(b []byte) error { - var res FormGroup - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/form_section.go b/client/models/form_section.go deleted file mode 100644 index c1f9ba96d..000000000 --- a/client/models/form_section.go +++ /dev/null @@ -1,150 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// FormSection Forms File Section -// -// swagger:model FormSection -type FormSection struct { - - // An optional description to display for this section - Description string `json:"description,omitempty"` - - // groups - // Required: true - Groups []*FormGroup `json:"groups"` - - // name - // Required: true - Name *string `json:"name"` -} - -// Validate validates this form section -func (m *FormSection) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateGroups(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormSection) validateGroups(formats strfmt.Registry) error { - - if err := validate.Required("groups", "body", m.Groups); err != nil { - return err - } - - for i := 0; i < len(m.Groups); i++ { - if swag.IsZero(m.Groups[i]) { // not required - continue - } - - if m.Groups[i] != nil { - if err := m.Groups[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("groups" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("groups" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *FormSection) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this form section based on the context it is used -func (m *FormSection) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateGroups(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormSection) contextValidateGroups(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Groups); i++ { - - if m.Groups[i] != nil { - - if swag.IsZero(m.Groups[i]) { // not required - return nil - } - - if err := m.Groups[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("groups" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("groups" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *FormSection) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *FormSection) UnmarshalBinary(b []byte) error { - var res FormSection - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/form_use_case.go b/client/models/form_use_case.go deleted file mode 100644 index 0143a3383..000000000 --- a/client/models/form_use_case.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// FormUseCase Forms File Use case -// -// swagger:model FormUseCase -type FormUseCase struct { - - // name - // Required: true - Name *string `json:"name"` - - // sections - // Required: true - Sections []*FormSection `json:"sections"` -} - -// Validate validates this form use case -func (m *FormUseCase) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSections(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormUseCase) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *FormUseCase) validateSections(formats strfmt.Registry) error { - - if err := validate.Required("sections", "body", m.Sections); err != nil { - return err - } - - for i := 0; i < len(m.Sections); i++ { - if swag.IsZero(m.Sections[i]) { // not required - continue - } - - if m.Sections[i] != nil { - if err := m.Sections[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("sections" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("sections" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this form use case based on the context it is used -func (m *FormUseCase) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateSections(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormUseCase) contextValidateSections(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Sections); i++ { - - if m.Sections[i] != nil { - - if swag.IsZero(m.Sections[i]) { // not required - return nil - } - - if err := m.Sections[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("sections" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("sections" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *FormUseCase) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *FormUseCase) UnmarshalBinary(b []byte) error { - var res FormUseCase - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/form_variables.go b/client/models/form_variables.go deleted file mode 100644 index 0d1e549c9..000000000 --- a/client/models/form_variables.go +++ /dev/null @@ -1,49 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" -) - -// FormVariables Forms variables filled, the format to respect is as follows -// -// { -// "sectionX": { -// "group1": { -// "key1": "value1", -// "key2": "value2", -// "key3": "value3" -// }, -// }, -// "sectionY": { -// "group2": { -// "key1": "value1", -// "key2": "value2", -// "key3": "value3" -// }, -// }, -// "sectionZ": { -// "group3": { -// "key1": "value2" -// }, -// } -// } -// -// Keys being the variable name that you want to see substituted/defined, -// while the section and group are the one from the form's file. -// -// swagger:model FormVariables -type FormVariables map[string]map[string]map[string]any - -// Validate validates this form variables -func (m FormVariables) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this form variables based on context it is used -func (m FormVariables) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} diff --git a/client/models/forms_file_v3.go b/client/models/forms_file_v3.go deleted file mode 100644 index 18dc9b54a..000000000 --- a/client/models/forms_file_v3.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// FormsFileV3 Forms File V3 -// -// swagger:model FormsFileV3 -type FormsFileV3 struct { - - // use cases - // Required: true - UseCases []*FormUseCase `json:"use_cases"` - - // version - // Required: true - Version *string `json:"version"` -} - -// Validate validates this forms file v3 -func (m *FormsFileV3) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateUseCases(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormsFileV3) validateUseCases(formats strfmt.Registry) error { - - if err := validate.Required("use_cases", "body", m.UseCases); err != nil { - return err - } - - for i := 0; i < len(m.UseCases); i++ { - if swag.IsZero(m.UseCases[i]) { // not required - continue - } - - if m.UseCases[i] != nil { - if err := m.UseCases[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("use_cases" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("use_cases" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *FormsFileV3) validateVersion(formats strfmt.Registry) error { - - if err := validate.Required("version", "body", m.Version); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this forms file v3 based on the context it is used -func (m *FormsFileV3) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateUseCases(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormsFileV3) contextValidateUseCases(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.UseCases); i++ { - - if m.UseCases[i] != nil { - - if swag.IsZero(m.UseCases[i]) { // not required - return nil - } - - if err := m.UseCases[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("use_cases" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("use_cases" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *FormsFileV3) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *FormsFileV3) UnmarshalBinary(b []byte) error { - var res FormsFileV3 - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/forms_validation.go b/client/models/forms_validation.go deleted file mode 100644 index 08da53764..000000000 --- a/client/models/forms_validation.go +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// FormsValidation Forms validation -// -// # Validates a given Form's file -// -// swagger:model FormsValidation -type FormsValidation struct { - - // A form's file to any given version - // Required: true - FormFile any `json:"form_file"` -} - -// Validate validates this forms validation -func (m *FormsValidation) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateFormFile(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormsValidation) validateFormFile(formats strfmt.Registry) error { - - if m.FormFile == nil { - return errors.Required("form_file", "body", nil) - } - - return nil -} - -// ContextValidate validates this forms validation based on context it is used -func (m *FormsValidation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *FormsValidation) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *FormsValidation) UnmarshalBinary(b []byte) error { - var res FormsValidation - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/forms_validation_result.go b/client/models/forms_validation_result.go deleted file mode 100644 index 904a5d3f1..000000000 --- a/client/models/forms_validation_result.go +++ /dev/null @@ -1,133 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// FormsValidationResult FormsValidationResult -// -// # The result of the validation, if errors is empty means that is correct -// -// swagger:model FormsValidationResult -type FormsValidationResult struct { - - // errors - // Required: true - Errors []string `json:"errors"` - - // forms - // Required: true - Forms *FormsFileV3 `json:"forms"` -} - -// Validate validates this forms validation result -func (m *FormsValidationResult) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateErrors(formats); err != nil { - res = append(res, err) - } - - if err := m.validateForms(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormsValidationResult) validateErrors(formats strfmt.Registry) error { - - if err := validate.Required("errors", "body", m.Errors); err != nil { - return err - } - - return nil -} - -func (m *FormsValidationResult) validateForms(formats strfmt.Registry) error { - - if err := validate.Required("forms", "body", m.Forms); err != nil { - return err - } - - if m.Forms != nil { - if err := m.Forms.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("forms") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("forms") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this forms validation result based on the context it is used -func (m *FormsValidationResult) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateForms(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormsValidationResult) contextValidateForms(ctx context.Context, formats strfmt.Registry) error { - - if m.Forms != nil { - - if err := m.Forms.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("forms") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("forms") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *FormsValidationResult) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *FormsValidationResult) UnmarshalBinary(b []byte) error { - var res FormsValidationResult - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/forms_values_ref.go b/client/models/forms_values_ref.go deleted file mode 100644 index d44563817..000000000 --- a/client/models/forms_values_ref.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// FormsValuesRef Forms values ref -// -// # It has the information to get the values of an entity of the Form -// -// swagger:model FormsValuesRef -type FormsValuesRef struct { - - // The url to which fetch the results - // Required: true - URL *string `json:"url"` -} - -// Validate validates this forms values ref -func (m *FormsValuesRef) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *FormsValuesRef) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this forms values ref based on context it is used -func (m *FormsValuesRef) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *FormsValuesRef) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *FormsValuesRef) UnmarshalBinary(b []byte) error { - var res FormsValuesRef - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/g_c_p_cost_storage.go b/client/models/g_c_p_cost_storage.go deleted file mode 100644 index b35e06028..000000000 --- a/client/models/g_c_p_cost_storage.go +++ /dev/null @@ -1,173 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// GCPCostStorage Representation of BigQuery external backend. -// Must be matched with a credential of the "gcp" type. -// -// swagger:model GCPCostStorage -type GCPCostStorage struct { - - // The GCP BigQuery dataset containing tables - // - Dataset string `json:"dataset,omitempty"` - - // The project that contains the BigQuery dataset. - // - ProjectID string `json:"project_id,omitempty"` - - // The GCP BigQuery table containing data - // - Table string `json:"table,omitempty"` -} - -// Engine gets the engine of this subtype -func (m *GCPCostStorage) Engine() string { - return "GCPCostStorage" -} - -// SetEngine sets the engine of this subtype -func (m *GCPCostStorage) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *GCPCostStorage) UnmarshalJSON(raw []byte) error { - var data struct { - - // The GCP BigQuery dataset containing tables - // - Dataset string `json:"dataset,omitempty"` - - // The project that contains the BigQuery dataset. - // - ProjectID string `json:"project_id,omitempty"` - - // The GCP BigQuery table containing data - // - Table string `json:"table,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result GCPCostStorage - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.Dataset = data.Dataset - result.ProjectID = data.ProjectID - result.Table = data.Table - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m GCPCostStorage) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The GCP BigQuery dataset containing tables - // - Dataset string `json:"dataset,omitempty"` - - // The project that contains the BigQuery dataset. - // - ProjectID string `json:"project_id,omitempty"` - - // The GCP BigQuery table containing data - // - Table string `json:"table,omitempty"` - }{ - - Dataset: m.Dataset, - - ProjectID: m.ProjectID, - - Table: m.Table, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this g c p cost storage -func (m *GCPCostStorage) Validate(formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// ContextValidate validate this g c p cost storage based on the context it is used -func (m *GCPCostStorage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *GCPCostStorage) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *GCPCostStorage) UnmarshalBinary(b []byte) error { - var res GCPCostStorage - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/g_c_p_remote_t_f_state.go b/client/models/g_c_p_remote_t_f_state.go deleted file mode 100644 index c52e4f9ac..000000000 --- a/client/models/g_c_p_remote_t_f_state.go +++ /dev/null @@ -1,176 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// GCPRemoteTFState Deprecated. Please use GCPStorage. -// Representation of GCP remote tf state for external backend. -// Must be matched with a credential of the "gcp" type. -// -// swagger:model GCPRemoteTFState -type GCPRemoteTFState struct { - - // The GCP bucket containing objects - // - // Required: true - Bucket *string `json:"bucket"` - - // The GCP object uniquely identifying an object in a bucket - // - Object string `json:"object,omitempty"` -} - -// Engine gets the engine of this subtype -func (m *GCPRemoteTFState) Engine() string { - return "GCPRemoteTFState" -} - -// SetEngine sets the engine of this subtype -func (m *GCPRemoteTFState) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *GCPRemoteTFState) UnmarshalJSON(raw []byte) error { - var data struct { - - // The GCP bucket containing objects - // - // Required: true - Bucket *string `json:"bucket"` - - // The GCP object uniquely identifying an object in a bucket - // - Object string `json:"object,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result GCPRemoteTFState - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.Bucket = data.Bucket - result.Object = data.Object - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m GCPRemoteTFState) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The GCP bucket containing objects - // - // Required: true - Bucket *string `json:"bucket"` - - // The GCP object uniquely identifying an object in a bucket - // - Object string `json:"object,omitempty"` - }{ - - Bucket: m.Bucket, - - Object: m.Object, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this g c p remote t f state -func (m *GCPRemoteTFState) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBucket(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *GCPRemoteTFState) validateBucket(formats strfmt.Registry) error { - - if err := validate.Required("bucket", "body", m.Bucket); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this g c p remote t f state based on the context it is used -func (m *GCPRemoteTFState) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *GCPRemoteTFState) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *GCPRemoteTFState) UnmarshalBinary(b []byte) error { - var res GCPRemoteTFState - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/g_c_p_storage.go b/client/models/g_c_p_storage.go deleted file mode 100644 index 6668238a9..000000000 --- a/client/models/g_c_p_storage.go +++ /dev/null @@ -1,178 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// GCPStorage Representation of GCP remote tf state for external backend. -// Must be matched with a credential of the "gcp" type. -// -// swagger:model GCPStorage -type GCPStorage struct { - - // The GCP bucket containing objects - // - // Required: true - Bucket *string `json:"bucket"` - - // The GCP object uniquely identifying an object in a bucket, - // will be required if the EB is not default - // - Object string `json:"object,omitempty"` -} - -// Engine gets the engine of this subtype -func (m *GCPStorage) Engine() string { - return "GCPStorage" -} - -// SetEngine sets the engine of this subtype -func (m *GCPStorage) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *GCPStorage) UnmarshalJSON(raw []byte) error { - var data struct { - - // The GCP bucket containing objects - // - // Required: true - Bucket *string `json:"bucket"` - - // The GCP object uniquely identifying an object in a bucket, - // will be required if the EB is not default - // - Object string `json:"object,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result GCPStorage - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.Bucket = data.Bucket - result.Object = data.Object - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m GCPStorage) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The GCP bucket containing objects - // - // Required: true - Bucket *string `json:"bucket"` - - // The GCP object uniquely identifying an object in a bucket, - // will be required if the EB is not default - // - Object string `json:"object,omitempty"` - }{ - - Bucket: m.Bucket, - - Object: m.Object, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this g c p storage -func (m *GCPStorage) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBucket(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *GCPStorage) validateBucket(formats strfmt.Registry) error { - - if err := validate.Required("bucket", "body", m.Bucket); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this g c p storage based on the context it is used -func (m *GCPStorage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *GCPStorage) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *GCPStorage) UnmarshalBinary(b []byte) error { - var res GCPStorage - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/general_status.go b/client/models/general_status.go deleted file mode 100644 index 68d2f0679..000000000 --- a/client/models/general_status.go +++ /dev/null @@ -1,208 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// GeneralStatus GeneralStatus -// -// swagger:model GeneralStatus -type GeneralStatus struct { - - // List of all checks report type/name/status. - // Required: true - Checks []*CheckReport `json:"checks"` - - // Message providing information regarding the status. - // Required: true - // Min Length: 1 - Message *string `json:"message"` - - // The overall status for the application. - // Required: true - // Enum: ["Unknown","Success","Error"] - Status *string `json:"status"` -} - -// Validate validates this general status -func (m *GeneralStatus) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateChecks(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *GeneralStatus) validateChecks(formats strfmt.Registry) error { - - if err := validate.Required("checks", "body", m.Checks); err != nil { - return err - } - - for i := 0; i < len(m.Checks); i++ { - if swag.IsZero(m.Checks[i]) { // not required - continue - } - - if m.Checks[i] != nil { - if err := m.Checks[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("checks" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("checks" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *GeneralStatus) validateMessage(formats strfmt.Registry) error { - - if err := validate.Required("message", "body", m.Message); err != nil { - return err - } - - if err := validate.MinLength("message", "body", *m.Message, 1); err != nil { - return err - } - - return nil -} - -var generalStatusTypeStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["Unknown","Success","Error"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - generalStatusTypeStatusPropEnum = append(generalStatusTypeStatusPropEnum, v) - } -} - -const ( - - // GeneralStatusStatusUnknown captures enum value "Unknown" - GeneralStatusStatusUnknown string = "Unknown" - - // GeneralStatusStatusSuccess captures enum value "Success" - GeneralStatusStatusSuccess string = "Success" - - // GeneralStatusStatusError captures enum value "Error" - GeneralStatusStatusError string = "Error" -) - -// prop value enum -func (m *GeneralStatus) validateStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, generalStatusTypeStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *GeneralStatus) validateStatus(formats strfmt.Registry) error { - - if err := validate.Required("status", "body", m.Status); err != nil { - return err - } - - // value enum - if err := m.validateStatusEnum("status", "body", *m.Status); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this general status based on the context it is used -func (m *GeneralStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateChecks(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *GeneralStatus) contextValidateChecks(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Checks); i++ { - - if m.Checks[i] != nil { - - if swag.IsZero(m.Checks[i]) { // not required - return nil - } - - if err := m.Checks[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("checks" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("checks" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *GeneralStatus) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *GeneralStatus) UnmarshalBinary(b []byte) error { - var res GeneralStatus - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/get_plan.go b/client/models/get_plan.go deleted file mode 100644 index 407c823aa..000000000 --- a/client/models/get_plan.go +++ /dev/null @@ -1,204 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// GetPlan GetPlan -// -// The plan to get before running another one. -// -// swagger:model GetPlan -type GetPlan struct { - - // name - Name string `json:"name,omitempty"` - - // params - Params map[string]any `json:"params,omitempty"` - - // resource - // Required: true - Resource *string `json:"resource"` - - // source - // Required: true - Source map[string]any `json:"source"` - - // tags - Tags []string `json:"tags"` - - // type - // Required: true - Type *string `json:"type"` - - // version - Version map[string]string `json:"version,omitempty"` - - // version from - VersionFrom string `json:"version_from,omitempty"` - - // versioned resource types - VersionedResourceTypes []*VersionedResourceType `json:"versioned_resource_types"` -} - -// Validate validates this get plan -func (m *GetPlan) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateResource(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSource(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersionedResourceTypes(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *GetPlan) validateResource(formats strfmt.Registry) error { - - if err := validate.Required("resource", "body", m.Resource); err != nil { - return err - } - - return nil -} - -func (m *GetPlan) validateSource(formats strfmt.Registry) error { - - if err := validate.Required("source", "body", m.Source); err != nil { - return err - } - - for k := range m.Source { - - if err := validate.Required("source"+"."+k, "body", m.Source[k]); err != nil { - return err - } - - } - - return nil -} - -func (m *GetPlan) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - return nil -} - -func (m *GetPlan) validateVersionedResourceTypes(formats strfmt.Registry) error { - if swag.IsZero(m.VersionedResourceTypes) { // not required - return nil - } - - for i := 0; i < len(m.VersionedResourceTypes); i++ { - if swag.IsZero(m.VersionedResourceTypes[i]) { // not required - continue - } - - if m.VersionedResourceTypes[i] != nil { - if err := m.VersionedResourceTypes[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("versioned_resource_types" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("versioned_resource_types" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this get plan based on the context it is used -func (m *GetPlan) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateVersionedResourceTypes(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *GetPlan) contextValidateVersionedResourceTypes(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.VersionedResourceTypes); i++ { - - if m.VersionedResourceTypes[i] != nil { - - if swag.IsZero(m.VersionedResourceTypes[i]) { // not required - return nil - } - - if err := m.VersionedResourceTypes[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("versioned_resource_types" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("versioned_resource_types" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *GetPlan) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *GetPlan) UnmarshalBinary(b []byte) error { - var res GetPlan - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/git_lab_http_storage.go b/client/models/git_lab_http_storage.go deleted file mode 100644 index dae8a6942..000000000 --- a/client/models/git_lab_http_storage.go +++ /dev/null @@ -1,160 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// GitLabHTTPStorage Representation of GitLab HTTP storage for external backend. -// Must be matched with a credential of the "basic_auth" type. -// -// swagger:model GitLabHTTPStorage -type GitLabHTTPStorage struct { - - // The URL endpoint to use - // - // Required: true - URL *string `json:"url"` -} - -// Engine gets the engine of this subtype -func (m *GitLabHTTPStorage) Engine() string { - return "GitLabHTTPStorage" -} - -// SetEngine sets the engine of this subtype -func (m *GitLabHTTPStorage) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *GitLabHTTPStorage) UnmarshalJSON(raw []byte) error { - var data struct { - - // The URL endpoint to use - // - // Required: true - URL *string `json:"url"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result GitLabHTTPStorage - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.URL = data.URL - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m GitLabHTTPStorage) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The URL endpoint to use - // - // Required: true - URL *string `json:"url"` - }{ - - URL: m.URL, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this git lab HTTP storage -func (m *GitLabHTTPStorage) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *GitLabHTTPStorage) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this git lab HTTP storage based on the context it is used -func (m *GitLabHTTPStorage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *GitLabHTTPStorage) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *GitLabHTTPStorage) UnmarshalBinary(b []byte) error { - var res GitLabHTTPStorage - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/group_config.go b/client/models/group_config.go deleted file mode 100644 index 938d08c41..000000000 --- a/client/models/group_config.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// GroupConfig GroupConfig -// -// # The entity which represents pipeline group config -// -// swagger:model GroupConfig -type GroupConfig struct { - - // jobs - Jobs []string `json:"jobs"` - - // name - // Required: true - Name *string `json:"name"` - - // resources - Resources []string `json:"resources"` -} - -// Validate validates this group config -func (m *GroupConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *GroupConfig) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this group config based on context it is used -func (m *GroupConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *GroupConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *GroupConfig) UnmarshalBinary(b []byte) error { - var res GroupConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/http_storage.go b/client/models/http_storage.go deleted file mode 100644 index 8ce09f902..000000000 --- a/client/models/http_storage.go +++ /dev/null @@ -1,160 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// HTTPStorage Representation of HTTP storage for external backend. -// Must be matched with a credential of the "basic_auth" type. -// -// swagger:model HTTPStorage -type HTTPStorage struct { - - // The URL endpoint to use - // - // Required: true - URL *string `json:"url"` -} - -// Engine gets the engine of this subtype -func (m *HTTPStorage) Engine() string { - return "HTTPStorage" -} - -// SetEngine sets the engine of this subtype -func (m *HTTPStorage) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *HTTPStorage) UnmarshalJSON(raw []byte) error { - var data struct { - - // The URL endpoint to use - // - // Required: true - URL *string `json:"url"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result HTTPStorage - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.URL = data.URL - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m HTTPStorage) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The URL endpoint to use - // - // Required: true - URL *string `json:"url"` - }{ - - URL: m.URL, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this HTTP storage -func (m *HTTPStorage) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *HTTPStorage) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this HTTP storage based on the context it is used -func (m *HTTPStorage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *HTTPStorage) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *HTTPStorage) UnmarshalBinary(b []byte) error { - var res HTTPStorage - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/in_use_component.go b/client/models/in_use_component.go deleted file mode 100644 index a11f9bc2c..000000000 --- a/client/models/in_use_component.go +++ /dev/null @@ -1,85 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InUseComponent InUseComponent -// -// # Represents a component that's using credential -// -// swagger:model InUseComponent -type InUseComponent struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - Canonical *string `json:"canonical"` -} - -// Validate validates this in use component -func (m *InUseComponent) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InUseComponent) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this in use component based on context it is used -func (m *InUseComponent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *InUseComponent) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InUseComponent) UnmarshalBinary(b []byte) error { - var res InUseComponent - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/in_use_config_repository.go b/client/models/in_use_config_repository.go deleted file mode 100644 index 5dbef6e7f..000000000 --- a/client/models/in_use_config_repository.go +++ /dev/null @@ -1,102 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InUseConfigRepository InUseConfigRepository -// -// # Represents a Config repository that's using credential -// -// swagger:model InUseConfigRepository -type InUseConfigRepository struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // name - // Required: true - Name *string `json:"name"` -} - -// Validate validates this in use config repository -func (m *InUseConfigRepository) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InUseConfigRepository) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *InUseConfigRepository) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this in use config repository based on context it is used -func (m *InUseConfigRepository) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *InUseConfigRepository) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InUseConfigRepository) UnmarshalBinary(b []byte) error { - var res InUseConfigRepository - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/in_use_environment.go b/client/models/in_use_environment.go deleted file mode 100644 index e34972f52..000000000 --- a/client/models/in_use_environment.go +++ /dev/null @@ -1,85 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InUseEnvironment InUseEnvironment -// -// # Represents an environment that's using credential -// -// swagger:model InUseEnvironment -type InUseEnvironment struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - Canonical *string `json:"canonical"` -} - -// Validate validates this in use environment -func (m *InUseEnvironment) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InUseEnvironment) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this in use environment based on context it is used -func (m *InUseEnvironment) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *InUseEnvironment) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InUseEnvironment) UnmarshalBinary(b []byte) error { - var res InUseEnvironment - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/in_use_external_backend.go b/client/models/in_use_external_backend.go deleted file mode 100644 index b764b1b39..000000000 --- a/client/models/in_use_external_backend.go +++ /dev/null @@ -1,270 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InUseExternalBackend InUseExternalBackend -// -// # Represents a external backend that's using credential -// -// swagger:model InUseExternalBackend -type InUseExternalBackend struct { - - // component - Component *InUseComponent `json:"component,omitempty"` - - // engine - // Required: true - Engine *string `json:"engine"` - - // environment - Environment *InUseEnvironment `json:"environment,omitempty"` - - // project - Project *InUseProject `json:"project,omitempty"` - - // purpose - // Required: true - Purpose *string `json:"purpose"` -} - -// Validate validates this in use external backend -func (m *InUseExternalBackend) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateComponent(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEngine(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironment(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProject(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePurpose(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InUseExternalBackend) validateComponent(formats strfmt.Registry) error { - if swag.IsZero(m.Component) { // not required - return nil - } - - if m.Component != nil { - if err := m.Component.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("component") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("component") - } - - return err - } - } - - return nil -} - -func (m *InUseExternalBackend) validateEngine(formats strfmt.Registry) error { - - if err := validate.Required("engine", "body", m.Engine); err != nil { - return err - } - - return nil -} - -func (m *InUseExternalBackend) validateEnvironment(formats strfmt.Registry) error { - if swag.IsZero(m.Environment) { // not required - return nil - } - - if m.Environment != nil { - if err := m.Environment.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment") - } - - return err - } - } - - return nil -} - -func (m *InUseExternalBackend) validateProject(formats strfmt.Registry) error { - if swag.IsZero(m.Project) { // not required - return nil - } - - if m.Project != nil { - if err := m.Project.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project") - } - - return err - } - } - - return nil -} - -func (m *InUseExternalBackend) validatePurpose(formats strfmt.Registry) error { - - if err := validate.Required("purpose", "body", m.Purpose); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this in use external backend based on the context it is used -func (m *InUseExternalBackend) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateComponent(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateEnvironment(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateProject(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InUseExternalBackend) contextValidateComponent(ctx context.Context, formats strfmt.Registry) error { - - if m.Component != nil { - - if swag.IsZero(m.Component) { // not required - return nil - } - - if err := m.Component.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("component") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("component") - } - - return err - } - } - - return nil -} - -func (m *InUseExternalBackend) contextValidateEnvironment(ctx context.Context, formats strfmt.Registry) error { - - if m.Environment != nil { - - if swag.IsZero(m.Environment) { // not required - return nil - } - - if err := m.Environment.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment") - } - - return err - } - } - - return nil -} - -func (m *InUseExternalBackend) contextValidateProject(ctx context.Context, formats strfmt.Registry) error { - - if m.Project != nil { - - if swag.IsZero(m.Project) { // not required - return nil - } - - if err := m.Project.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *InUseExternalBackend) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InUseExternalBackend) UnmarshalBinary(b []byte) error { - var res InUseExternalBackend - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/in_use_project.go b/client/models/in_use_project.go deleted file mode 100644 index 12f42348d..000000000 --- a/client/models/in_use_project.go +++ /dev/null @@ -1,102 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InUseProject InUseProject -// -// # Represents a project that's using credential -// -// swagger:model InUseProject -type InUseProject struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - Canonical *string `json:"canonical"` - - // name - // Required: true - Name *string `json:"name"` -} - -// Validate validates this in use project -func (m *InUseProject) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InUseProject) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -func (m *InUseProject) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this in use project based on context it is used -func (m *InUseProject) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *InUseProject) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InUseProject) UnmarshalBinary(b []byte) error { - var res InUseProject - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/in_use_service_catalog_source.go b/client/models/in_use_service_catalog_source.go deleted file mode 100644 index 9da231aae..000000000 --- a/client/models/in_use_service_catalog_source.go +++ /dev/null @@ -1,102 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InUseServiceCatalogSource InUseServiceCatalogSource -// -// # Represents a Service catalog source that's using credential -// -// swagger:model InUseServiceCatalogSource -type InUseServiceCatalogSource struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // name - // Required: true - Name *string `json:"name"` -} - -// Validate validates this in use service catalog source -func (m *InUseServiceCatalogSource) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InUseServiceCatalogSource) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *InUseServiceCatalogSource) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this in use service catalog source based on context it is used -func (m *InUseServiceCatalogSource) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *InUseServiceCatalogSource) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InUseServiceCatalogSource) UnmarshalBinary(b []byte) error { - var res InUseServiceCatalogSource - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infra_import.go b/client/models/infra_import.go deleted file mode 100644 index 9e16d521d..000000000 --- a/client/models/infra_import.go +++ /dev/null @@ -1,250 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InfraImport Infra Import -// -// The entity which represents the information of for the import of a new Stack or Project. -// -// swagger:model InfraImport -type InfraImport struct { - - // component canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$ - ComponentCanonical string `json:"component_canonical,omitempty"` - - // environment canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$ - EnvironmentCanonical string `json:"environment_canonical,omitempty"` - - // error - // Required: true - Error *string `json:"error"` - - // logs - // Required: true - Logs *string `json:"logs"` - - // project canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - ProjectCanonical string `json:"project_canonical,omitempty"` - - // It's the ref of the Service Catalog, like 'cycloidio:stack-magento' - // Required: true - ServiceCatalogRef *string `json:"service_catalog_ref"` - - // The import process status. - // Required: true - // Enum: ["succeeded","failed","importing"] - Status *string `json:"status"` -} - -// Validate validates this infra import -func (m *InfraImport) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateComponentCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironmentCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateError(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLogs(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjectCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalogRef(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraImport) validateComponentCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ComponentCanonical) { // not required - return nil - } - - if err := validate.MinLength("component_canonical", "body", m.ComponentCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("component_canonical", "body", m.ComponentCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("component_canonical", "body", m.ComponentCanonical, `^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$`); err != nil { - return err - } - - return nil -} - -func (m *InfraImport) validateEnvironmentCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.EnvironmentCanonical) { // not required - return nil - } - - if err := validate.MinLength("environment_canonical", "body", m.EnvironmentCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("environment_canonical", "body", m.EnvironmentCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("environment_canonical", "body", m.EnvironmentCanonical, `^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$`); err != nil { - return err - } - - return nil -} - -func (m *InfraImport) validateError(formats strfmt.Registry) error { - - if err := validate.Required("error", "body", m.Error); err != nil { - return err - } - - return nil -} - -func (m *InfraImport) validateLogs(formats strfmt.Registry) error { - - if err := validate.Required("logs", "body", m.Logs); err != nil { - return err - } - - return nil -} - -func (m *InfraImport) validateProjectCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ProjectCanonical) { // not required - return nil - } - - if err := validate.MinLength("project_canonical", "body", m.ProjectCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("project_canonical", "body", m.ProjectCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("project_canonical", "body", m.ProjectCanonical, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -func (m *InfraImport) validateServiceCatalogRef(formats strfmt.Registry) error { - - if err := validate.Required("service_catalog_ref", "body", m.ServiceCatalogRef); err != nil { - return err - } - - return nil -} - -var infraImportTypeStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["succeeded","failed","importing"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - infraImportTypeStatusPropEnum = append(infraImportTypeStatusPropEnum, v) - } -} - -const ( - - // InfraImportStatusSucceeded captures enum value "succeeded" - InfraImportStatusSucceeded string = "succeeded" - - // InfraImportStatusFailed captures enum value "failed" - InfraImportStatusFailed string = "failed" - - // InfraImportStatusImporting captures enum value "importing" - InfraImportStatusImporting string = "importing" -) - -// prop value enum -func (m *InfraImport) validateStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, infraImportTypeStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *InfraImport) validateStatus(formats strfmt.Registry) error { - - if err := validate.Required("status", "body", m.Status); err != nil { - return err - } - - // value enum - if err := m.validateStatusEnum("status", "body", *m.Status); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this infra import based on context it is used -func (m *InfraImport) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *InfraImport) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InfraImport) UnmarshalBinary(b []byte) error { - var res InfraImport - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infra_import_preset.go b/client/models/infra_import_preset.go deleted file mode 100644 index 552e53e7f..000000000 --- a/client/models/infra_import_preset.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InfraImportPreset InfraImportPreset -// -// Infra Import's pre-configured group with Resources commonly used together in a specific context. -// -// swagger:model InfraImportPreset -type InfraImportPreset struct { - - // name - // Required: true - Name *string `json:"name"` - - // resources - // Required: true - Resources []string `json:"resources"` -} - -// Validate validates this infra import preset -func (m *InfraImportPreset) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateResources(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraImportPreset) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *InfraImportPreset) validateResources(formats strfmt.Registry) error { - - if err := validate.Required("resources", "body", m.Resources); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this infra import preset based on context it is used -func (m *InfraImportPreset) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *InfraImportPreset) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InfraImportPreset) UnmarshalBinary(b []byte) error { - var res InfraImportPreset - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infra_import_resource.go b/client/models/infra_import_resource.go deleted file mode 100644 index 8a13a9fe5..000000000 --- a/client/models/infra_import_resource.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InfraImportResource Infra Import Resource -// -// The representation of the Infra Import's Resource of a Cloud Provider. -// -// swagger:model InfraImportResource -type InfraImportResource struct { - - // id - // Required: true - ID *string `json:"id"` -} - -// Validate validates this infra import resource -func (m *InfraImportResource) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraImportResource) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this infra import resource based on context it is used -func (m *InfraImportResource) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *InfraImportResource) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InfraImportResource) UnmarshalBinary(b []byte) error { - var res InfraImportResource - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infra_import_resource_body.go b/client/models/infra_import_resource_body.go deleted file mode 100644 index 27ae47fe4..000000000 --- a/client/models/infra_import_resource_body.go +++ /dev/null @@ -1,225 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - stderrors "errors" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InfraImportResourceBody Provider Resources body -// -// # Entry that represents all the data needed for fetching resource -// -// swagger:model InfraImportResourceBody -type InfraImportResourceBody struct { - configurationField CloudProviderConfiguration - - // Credential that will be used to import from the provider - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical *string `json:"credential_canonical"` - - // tags - Tags []string `json:"tags"` -} - -// Configuration gets the configuration of this base type -func (m *InfraImportResourceBody) Configuration() CloudProviderConfiguration { - return m.configurationField -} - -// SetConfiguration sets the configuration of this base type -func (m *InfraImportResourceBody) SetConfiguration(val CloudProviderConfiguration) { - m.configurationField = val -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *InfraImportResourceBody) UnmarshalJSON(raw []byte) error { - var data struct { - Configuration json.RawMessage `json:"configuration"` - - CredentialCanonical *string `json:"credential_canonical"` - - Tags []string `json:"tags"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - propConfiguration, err := UnmarshalCloudProviderConfiguration(bytes.NewBuffer(data.Configuration), runtime.JSONConsumer()) - if err != nil && !stderrors.Is(err, io.EOF) { - return err - } - - var result InfraImportResourceBody - - // configuration - result.configurationField = propConfiguration - - // credential_canonical - result.CredentialCanonical = data.CredentialCanonical - - // tags - result.Tags = data.Tags - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m InfraImportResourceBody) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - CredentialCanonical *string `json:"credential_canonical"` - - Tags []string `json:"tags"` - }{ - - CredentialCanonical: m.CredentialCanonical, - - Tags: m.Tags, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Configuration CloudProviderConfiguration `json:"configuration"` - }{ - - Configuration: m.configurationField, - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this infra import resource body -func (m *InfraImportResourceBody) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfiguration(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraImportResourceBody) validateConfiguration(formats strfmt.Registry) error { - - if err := validate.Required("configuration", "body", m.Configuration()); err != nil { - return err - } - - if err := m.Configuration().Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -func (m *InfraImportResourceBody) validateCredentialCanonical(formats strfmt.Registry) error { - - if err := validate.Required("credential_canonical", "body", m.CredentialCanonical); err != nil { - return err - } - - if err := validate.MinLength("credential_canonical", "body", *m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", *m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", *m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this infra import resource body based on the context it is used -func (m *InfraImportResourceBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateConfiguration(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraImportResourceBody) contextValidateConfiguration(ctx context.Context, formats strfmt.Registry) error { - - if err := m.Configuration().ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *InfraImportResourceBody) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InfraImportResourceBody) UnmarshalBinary(b []byte) error { - var res InfraImportResourceBody - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infra_import_resources_body.go b/client/models/infra_import_resources_body.go deleted file mode 100644 index 77b73aa64..000000000 --- a/client/models/infra_import_resources_body.go +++ /dev/null @@ -1,213 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - stderrors "errors" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InfraImportResourcesBody Provider's Resources body -// -// # Entry that represents all the data needed for fetching resources -// -// swagger:model InfraImportResourcesBody -type InfraImportResourcesBody struct { - configurationField CloudProviderConfiguration - - // Credential that will be used to import from the provider - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical *string `json:"credential_canonical"` -} - -// Configuration gets the configuration of this base type -func (m *InfraImportResourcesBody) Configuration() CloudProviderConfiguration { - return m.configurationField -} - -// SetConfiguration sets the configuration of this base type -func (m *InfraImportResourcesBody) SetConfiguration(val CloudProviderConfiguration) { - m.configurationField = val -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *InfraImportResourcesBody) UnmarshalJSON(raw []byte) error { - var data struct { - Configuration json.RawMessage `json:"configuration"` - - CredentialCanonical *string `json:"credential_canonical"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - propConfiguration, err := UnmarshalCloudProviderConfiguration(bytes.NewBuffer(data.Configuration), runtime.JSONConsumer()) - if err != nil && !stderrors.Is(err, io.EOF) { - return err - } - - var result InfraImportResourcesBody - - // configuration - result.configurationField = propConfiguration - - // credential_canonical - result.CredentialCanonical = data.CredentialCanonical - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m InfraImportResourcesBody) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - CredentialCanonical *string `json:"credential_canonical"` - }{ - - CredentialCanonical: m.CredentialCanonical, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Configuration CloudProviderConfiguration `json:"configuration"` - }{ - - Configuration: m.configurationField, - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this infra import resources body -func (m *InfraImportResourcesBody) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfiguration(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraImportResourcesBody) validateConfiguration(formats strfmt.Registry) error { - - if err := validate.Required("configuration", "body", m.Configuration()); err != nil { - return err - } - - if err := m.Configuration().Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -func (m *InfraImportResourcesBody) validateCredentialCanonical(formats strfmt.Registry) error { - - if err := validate.Required("credential_canonical", "body", m.CredentialCanonical); err != nil { - return err - } - - if err := validate.MinLength("credential_canonical", "body", *m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", *m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", *m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this infra import resources body based on the context it is used -func (m *InfraImportResourcesBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateConfiguration(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraImportResourcesBody) contextValidateConfiguration(ctx context.Context, formats strfmt.Registry) error { - - if err := m.Configuration().ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *InfraImportResourcesBody) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InfraImportResourcesBody) UnmarshalBinary(b []byte) error { - var res InfraImportResourcesBody - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infra_policies_validation_result.go b/client/models/infra_policies_validation_result.go deleted file mode 100644 index 810671038..000000000 --- a/client/models/infra_policies_validation_result.go +++ /dev/null @@ -1,269 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// InfraPoliciesValidationResult Infra policies validation results. -// -// The set of not respected rules for the checked policies. -// -// swagger:model InfraPoliciesValidationResult -type InfraPoliciesValidationResult struct { - - // advisories - Advisories []*InfraPoliciesValidationResultItem `json:"advisories"` - - // criticals - Criticals []*InfraPoliciesValidationResultItem `json:"criticals"` - - // warnings - Warnings []*InfraPoliciesValidationResultItem `json:"warnings"` -} - -// Validate validates this infra policies validation result -func (m *InfraPoliciesValidationResult) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAdvisories(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCriticals(formats); err != nil { - res = append(res, err) - } - - if err := m.validateWarnings(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraPoliciesValidationResult) validateAdvisories(formats strfmt.Registry) error { - if swag.IsZero(m.Advisories) { // not required - return nil - } - - for i := 0; i < len(m.Advisories); i++ { - if swag.IsZero(m.Advisories[i]) { // not required - continue - } - - if m.Advisories[i] != nil { - if err := m.Advisories[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("advisories" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("advisories" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *InfraPoliciesValidationResult) validateCriticals(formats strfmt.Registry) error { - if swag.IsZero(m.Criticals) { // not required - return nil - } - - for i := 0; i < len(m.Criticals); i++ { - if swag.IsZero(m.Criticals[i]) { // not required - continue - } - - if m.Criticals[i] != nil { - if err := m.Criticals[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("criticals" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("criticals" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *InfraPoliciesValidationResult) validateWarnings(formats strfmt.Registry) error { - if swag.IsZero(m.Warnings) { // not required - return nil - } - - for i := 0; i < len(m.Warnings); i++ { - if swag.IsZero(m.Warnings[i]) { // not required - continue - } - - if m.Warnings[i] != nil { - if err := m.Warnings[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("warnings" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("warnings" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this infra policies validation result based on the context it is used -func (m *InfraPoliciesValidationResult) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateAdvisories(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateCriticals(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateWarnings(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraPoliciesValidationResult) contextValidateAdvisories(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Advisories); i++ { - - if m.Advisories[i] != nil { - - if swag.IsZero(m.Advisories[i]) { // not required - return nil - } - - if err := m.Advisories[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("advisories" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("advisories" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *InfraPoliciesValidationResult) contextValidateCriticals(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Criticals); i++ { - - if m.Criticals[i] != nil { - - if swag.IsZero(m.Criticals[i]) { // not required - return nil - } - - if err := m.Criticals[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("criticals" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("criticals" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *InfraPoliciesValidationResult) contextValidateWarnings(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Warnings); i++ { - - if m.Warnings[i] != nil { - - if swag.IsZero(m.Warnings[i]) { // not required - return nil - } - - if err := m.Warnings[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("warnings" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("warnings" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *InfraPoliciesValidationResult) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InfraPoliciesValidationResult) UnmarshalBinary(b []byte) error { - var res InfraPoliciesValidationResult - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infra_policies_validation_result_item.go b/client/models/infra_policies_validation_result_item.go deleted file mode 100644 index 6d131203f..000000000 --- a/client/models/infra_policies_validation_result_item.go +++ /dev/null @@ -1,120 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InfraPoliciesValidationResultItem InfraPoliciesValidationResultItem represents a checked rule -// with a failed result generated from the validation process. -// -// swagger:model InfraPoliciesValidationResultItem -type InfraPoliciesValidationResultItem struct { - - // infra policy - // Required: true - InfraPolicy *InfraPolicy `json:"infra_policy"` - - // The messages about the reason of the validation failure - // that's written in the InfraPolicy's Body of the failed rule. - // - Reasons []string `json:"reasons"` -} - -// Validate validates this infra policies validation result item -func (m *InfraPoliciesValidationResultItem) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateInfraPolicy(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraPoliciesValidationResultItem) validateInfraPolicy(formats strfmt.Registry) error { - - if err := validate.Required("infra_policy", "body", m.InfraPolicy); err != nil { - return err - } - - if m.InfraPolicy != nil { - if err := m.InfraPolicy.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("infra_policy") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("infra_policy") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this infra policies validation result item based on the context it is used -func (m *InfraPoliciesValidationResultItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateInfraPolicy(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraPoliciesValidationResultItem) contextValidateInfraPolicy(ctx context.Context, formats strfmt.Registry) error { - - if m.InfraPolicy != nil { - - if err := m.InfraPolicy.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("infra_policy") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("infra_policy") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *InfraPoliciesValidationResultItem) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InfraPoliciesValidationResultItem) UnmarshalBinary(b []byte) error { - var res InfraPoliciesValidationResultItem - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infra_policy.go b/client/models/infra_policy.go deleted file mode 100644 index 31c70ad23..000000000 --- a/client/models/infra_policy.go +++ /dev/null @@ -1,343 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InfraPolicy InfraPolicy -// -// The policy to control operations across infrastructure. -// -// swagger:model InfraPolicy -type InfraPolicy struct { - - // The body field is the code in plain text that defines the rules for the policy. - // Required: true - Body *string `json:"body"` - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // created at - // Required: true - CreatedAt *uint64 `json:"created_at"` - - // description - // Required: true - Description *string `json:"description"` - - // enabled - // Required: true - Enabled *bool `json:"enabled"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // Organization member that owns this InfraPolicy. When a user is the owner of an - // InfraPolicy it has all the permissions on it. - // In the event where the user has been deleted then it will be null. - // - Owner *User `json:"owner,omitempty"` - - // It defines the enforcement level. It must be used from the caller of the InfraPolicy - // validation endpoint to apply the specific logic in case of not respected InfraPolicies. - // Uses critical to block the changes. - // Uses warning to block the changes but allow to override manually. - // Uses advisory to allow them but a notification must be send. - // - // Required: true - // Enum: ["critical","warning","advisory"] - Severity *string `json:"severity"` - - // updated at - // Required: true - UpdatedAt *uint64 `json:"updated_at"` -} - -// Validate validates this infra policy -func (m *InfraPolicy) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBody(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnabled(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSeverity(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraPolicy) validateBody(formats strfmt.Registry) error { - - if err := validate.Required("body", "body", m.Body); err != nil { - return err - } - - return nil -} - -func (m *InfraPolicy) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *InfraPolicy) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - return nil -} - -func (m *InfraPolicy) validateDescription(formats strfmt.Registry) error { - - if err := validate.Required("description", "body", m.Description); err != nil { - return err - } - - return nil -} - -func (m *InfraPolicy) validateEnabled(formats strfmt.Registry) error { - - if err := validate.Required("enabled", "body", m.Enabled); err != nil { - return err - } - - return nil -} - -func (m *InfraPolicy) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *InfraPolicy) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *InfraPolicy) validateOwner(formats strfmt.Registry) error { - if swag.IsZero(m.Owner) { // not required - return nil - } - - if m.Owner != nil { - if err := m.Owner.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -var infraPolicyTypeSeverityPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["critical","warning","advisory"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - infraPolicyTypeSeverityPropEnum = append(infraPolicyTypeSeverityPropEnum, v) - } -} - -const ( - - // InfraPolicySeverityCritical captures enum value "critical" - InfraPolicySeverityCritical string = "critical" - - // InfraPolicySeverityWarning captures enum value "warning" - InfraPolicySeverityWarning string = "warning" - - // InfraPolicySeverityAdvisory captures enum value "advisory" - InfraPolicySeverityAdvisory string = "advisory" -) - -// prop value enum -func (m *InfraPolicy) validateSeverityEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, infraPolicyTypeSeverityPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *InfraPolicy) validateSeverity(formats strfmt.Registry) error { - - if err := validate.Required("severity", "body", m.Severity); err != nil { - return err - } - - // value enum - if err := m.validateSeverityEnum("severity", "body", *m.Severity); err != nil { - return err - } - - return nil -} - -func (m *InfraPolicy) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this infra policy based on the context it is used -func (m *InfraPolicy) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateOwner(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfraPolicy) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { - - if m.Owner != nil { - - if swag.IsZero(m.Owner) { // not required - return nil - } - - if err := m.Owner.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *InfraPolicy) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InfraPolicy) UnmarshalBinary(b []byte) error { - var res InfraPolicy - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infrastructure.go b/client/models/infrastructure.go deleted file mode 100644 index cfb3ec995..000000000 --- a/client/models/infrastructure.go +++ /dev/null @@ -1,133 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Infrastructure Infrastructure -// -// # Holds all the Infrastructure of the component -// -// swagger:model Infrastructure -type Infrastructure struct { - - // config - // Required: true - Config InfrastructureConfig `json:"config"` - - // graph - // Required: true - Graph *InfrastructureGraph `json:"graph"` -} - -// Validate validates this infrastructure -func (m *Infrastructure) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfig(formats); err != nil { - res = append(res, err) - } - - if err := m.validateGraph(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Infrastructure) validateConfig(formats strfmt.Registry) error { - - if m.Config == nil { - return errors.Required("config", "body", nil) - } - - return nil -} - -func (m *Infrastructure) validateGraph(formats strfmt.Registry) error { - - if err := validate.Required("graph", "body", m.Graph); err != nil { - return err - } - - if m.Graph != nil { - if err := m.Graph.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("graph") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("graph") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this infrastructure based on the context it is used -func (m *Infrastructure) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateGraph(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Infrastructure) contextValidateGraph(ctx context.Context, formats strfmt.Registry) error { - - if m.Graph != nil { - - if err := m.Graph.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("graph") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("graph") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Infrastructure) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Infrastructure) UnmarshalBinary(b []byte) error { - var res Infrastructure - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infrastructure_config.go b/client/models/infrastructure_config.go deleted file mode 100644 index 056c3b2ed..000000000 --- a/client/models/infrastructure_config.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// InfrastructureConfig InfrastructureConfig -// -// # Holds all the Infrastructure config of the TFState -// -// swagger:model InfrastructureConfig -type InfrastructureConfig any diff --git a/client/models/infrastructure_graph.go b/client/models/infrastructure_graph.go deleted file mode 100644 index 64f99578d..000000000 --- a/client/models/infrastructure_graph.go +++ /dev/null @@ -1,204 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InfrastructureGraph InfrastructureGraph -// -// # Holds all the Infrastructure of the component -// -// swagger:model InfrastructureGraph -type InfrastructureGraph struct { - - // edges - // Required: true - Edges []*InfrastructureGraphEdge `json:"edges"` - - // nodes - // Required: true - Nodes []*InfrastructureGraphNode `json:"nodes"` -} - -// Validate validates this infrastructure graph -func (m *InfrastructureGraph) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEdges(formats); err != nil { - res = append(res, err) - } - - if err := m.validateNodes(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfrastructureGraph) validateEdges(formats strfmt.Registry) error { - - if err := validate.Required("edges", "body", m.Edges); err != nil { - return err - } - - for i := 0; i < len(m.Edges); i++ { - if swag.IsZero(m.Edges[i]) { // not required - continue - } - - if m.Edges[i] != nil { - if err := m.Edges[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("edges" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("edges" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *InfrastructureGraph) validateNodes(formats strfmt.Registry) error { - - if err := validate.Required("nodes", "body", m.Nodes); err != nil { - return err - } - - for i := 0; i < len(m.Nodes); i++ { - if swag.IsZero(m.Nodes[i]) { // not required - continue - } - - if m.Nodes[i] != nil { - if err := m.Nodes[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("nodes" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("nodes" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this infrastructure graph based on the context it is used -func (m *InfrastructureGraph) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateEdges(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateNodes(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfrastructureGraph) contextValidateEdges(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Edges); i++ { - - if m.Edges[i] != nil { - - if swag.IsZero(m.Edges[i]) { // not required - return nil - } - - if err := m.Edges[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("edges" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("edges" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *InfrastructureGraph) contextValidateNodes(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Nodes); i++ { - - if m.Nodes[i] != nil { - - if swag.IsZero(m.Nodes[i]) { // not required - return nil - } - - if err := m.Nodes[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("nodes" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("nodes" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *InfrastructureGraph) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InfrastructureGraph) UnmarshalBinary(b []byte) error { - var res InfrastructureGraph - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infrastructure_graph_edge.go b/client/models/infrastructure_graph_edge.go deleted file mode 100644 index 0d2685ef3..000000000 --- a/client/models/infrastructure_graph_edge.go +++ /dev/null @@ -1,121 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InfrastructureGraphEdge Infrastructure -// -// # Holds the information of an Edge of the Graph -// -// swagger:model InfrastructureGraphEdge -type InfrastructureGraphEdge struct { - - // canonicals - // Required: true - Canonicals []string `json:"canonicals"` - - // id - // Required: true - ID *string `json:"id"` - - // source - // Required: true - Source *string `json:"source"` - - // target - // Required: true - Target *string `json:"target"` -} - -// Validate validates this infrastructure graph edge -func (m *InfrastructureGraphEdge) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonicals(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSource(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTarget(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfrastructureGraphEdge) validateCanonicals(formats strfmt.Registry) error { - - if err := validate.Required("canonicals", "body", m.Canonicals); err != nil { - return err - } - - return nil -} - -func (m *InfrastructureGraphEdge) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - return nil -} - -func (m *InfrastructureGraphEdge) validateSource(formats strfmt.Registry) error { - - if err := validate.Required("source", "body", m.Source); err != nil { - return err - } - - return nil -} - -func (m *InfrastructureGraphEdge) validateTarget(formats strfmt.Registry) error { - - if err := validate.Required("target", "body", m.Target); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this infrastructure graph edge based on context it is used -func (m *InfrastructureGraphEdge) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *InfrastructureGraphEdge) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InfrastructureGraphEdge) UnmarshalBinary(b []byte) error { - var res InfrastructureGraphEdge - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infrastructure_graph_node.go b/client/models/infrastructure_graph_node.go deleted file mode 100644 index 9752a03f4..000000000 --- a/client/models/infrastructure_graph_node.go +++ /dev/null @@ -1,170 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InfrastructureGraphNode Infrastructure -// -// # Holds the information of a Node of the Graph -// -// swagger:model InfrastructureGraphNode -type InfrastructureGraphNode struct { - - // canonical - // Required: true - Canonical *string `json:"canonical"` - - // id - // Required: true - ID *string `json:"id"` - - // name - Name string `json:"name,omitempty"` - - // It holds [x,y] - // Required: true - Position []uint64 `json:"position"` - - // resource - // Required: true - Resource *TerraformProviderResourceSimple `json:"resource"` -} - -// Validate validates this infrastructure graph node -func (m *InfrastructureGraphNode) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePosition(formats); err != nil { - res = append(res, err) - } - - if err := m.validateResource(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfrastructureGraphNode) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - return nil -} - -func (m *InfrastructureGraphNode) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - return nil -} - -func (m *InfrastructureGraphNode) validatePosition(formats strfmt.Registry) error { - - if err := validate.Required("position", "body", m.Position); err != nil { - return err - } - - return nil -} - -func (m *InfrastructureGraphNode) validateResource(formats strfmt.Registry) error { - - if err := validate.Required("resource", "body", m.Resource); err != nil { - return err - } - - if m.Resource != nil { - if err := m.Resource.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("resource") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("resource") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this infrastructure graph node based on the context it is used -func (m *InfrastructureGraphNode) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateResource(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfrastructureGraphNode) contextValidateResource(ctx context.Context, formats strfmt.Registry) error { - - if m.Resource != nil { - - if err := m.Resource.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("resource") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("resource") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *InfrastructureGraphNode) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InfrastructureGraphNode) UnmarshalBinary(b []byte) error { - var res InfrastructureGraphNode - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/infrastructure_resources_aggregation_item.go b/client/models/infrastructure_resources_aggregation_item.go deleted file mode 100644 index c12610272..000000000 --- a/client/models/infrastructure_resources_aggregation_item.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InfrastructureResourcesAggregationItem Infrastructure Resource Aggregation Item -// -// Contains aggregated data of a single type of an infrastructure resource. -// -// swagger:model InfrastructureResourcesAggregationItem -type InfrastructureResourcesAggregationItem struct { - - // The number of items of the specific type of resource. - // Required: true - TotalAmount *uint32 `json:"total_amount"` -} - -// Validate validates this infrastructure resources aggregation item -func (m *InfrastructureResourcesAggregationItem) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateTotalAmount(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InfrastructureResourcesAggregationItem) validateTotalAmount(formats strfmt.Registry) error { - - if err := validate.Required("total_amount", "body", m.TotalAmount); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this infrastructure resources aggregation item based on context it is used -func (m *InfrastructureResourcesAggregationItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *InfrastructureResourcesAggregationItem) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InfrastructureResourcesAggregationItem) UnmarshalBinary(b []byte) error { - var res InfrastructureResourcesAggregationItem - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/inventory_output.go b/client/models/inventory_output.go deleted file mode 100644 index f67311f27..000000000 --- a/client/models/inventory_output.go +++ /dev/null @@ -1,107 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InventoryOutput Output of inventory terraform states -// -// # Output of inventory terraform states -// -// swagger:model InventoryOutput -type InventoryOutput struct { - - // Description - Description string `json:"description,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // Output key used to identify the output - // Required: true - Key *string `json:"key"` - - // Defines whether this output is pinned. Pinned outputs are highlighted on the frontend. - Pinned bool `json:"pinned,omitempty"` - - // Whether this output is a sensitive field - Sensitive bool `json:"sensitive,omitempty"` - - // Output type - Type any `json:"type,omitempty"` - - // Output value - Value any `json:"value,omitempty"` -} - -// Validate validates this inventory output -func (m *InventoryOutput) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateKey(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InventoryOutput) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *InventoryOutput) validateKey(formats strfmt.Registry) error { - - if err := validate.Required("key", "body", m.Key); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this inventory output based on context it is used -func (m *InventoryOutput) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *InventoryOutput) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InventoryOutput) UnmarshalBinary(b []byte) error { - var res InventoryOutput - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/inventory_resource.go b/client/models/inventory_resource.go deleted file mode 100644 index 919b94d84..000000000 --- a/client/models/inventory_resource.go +++ /dev/null @@ -1,414 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InventoryResource Inventory Resource -// -// # The Resource of the Inventory representing an element of your infrastructure -// -// swagger:model InventoryResource -type InventoryResource struct { - - // attributes - Attributes any `json:"attributes,omitempty"` - - // Category of the resource type - Category string `json:"category,omitempty"` - - // Component in which this resource is used - Component *ComponentSimple `json:"component,omitempty"` - - // The amount of cpu that it has in units - // Minimum: 0 - CPU *uint64 `json:"cpu,omitempty"` - - // List of attributes of the Resource, can be anything - CustomAttributes any `json:"custom_attributes,omitempty"` - - // Full description of the resource type documentation - Description string `json:"description,omitempty"` - - // Environment in which this resource is used - Environment *Environment `json:"environment,omitempty"` - - // id - // Minimum: 1 - ID uint32 `json:"id,omitempty"` - - // Image of the resource type - // Format: uri - Image strfmt.URI `json:"image,omitempty"` - - // Set of keywords to categorize the resource type - Keywords []string `json:"keywords"` - - // A way to distinguish and categorize resources - Label string `json:"label,omitempty"` - - // The amount of memory that it has in MB - // Minimum: 0 - Memory *uint64 `json:"memory,omitempty"` - - // The way this resource is handled - Mode string `json:"mode,omitempty"` - - // The module it belongs to - Module string `json:"module,omitempty"` - - // The name of the resource - // Required: true - Name *string `json:"name"` - - // Project in which this resource is used - Project *ProjectSimple `json:"project,omitempty"` - - // The provider of the created Resource - // Required: true - Provider *string `json:"provider"` - - // Short description of the resource type documentation - ShortDescription string `json:"short_description,omitempty"` - - // The amount of storage that it has in MB - // Minimum: 0 - Storage *uint64 `json:"storage,omitempty"` - - // The type of the resource - // Required: true - Type *string `json:"type"` -} - -// Validate validates this inventory resource -func (m *InventoryResource) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateComponent(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCPU(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironment(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateImage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMemory(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProject(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStorage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InventoryResource) validateComponent(formats strfmt.Registry) error { - if swag.IsZero(m.Component) { // not required - return nil - } - - if m.Component != nil { - if err := m.Component.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("component") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("component") - } - - return err - } - } - - return nil -} - -func (m *InventoryResource) validateCPU(formats strfmt.Registry) error { - if swag.IsZero(m.CPU) { // not required - return nil - } - - if err := validate.MinimumUint("cpu", "body", *m.CPU, 0, false); err != nil { - return err - } - - return nil -} - -func (m *InventoryResource) validateEnvironment(formats strfmt.Registry) error { - if swag.IsZero(m.Environment) { // not required - return nil - } - - if m.Environment != nil { - if err := m.Environment.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment") - } - - return err - } - } - - return nil -} - -func (m *InventoryResource) validateID(formats strfmt.Registry) error { - if swag.IsZero(m.ID) { // not required - return nil - } - - if err := validate.MinimumUint("id", "body", uint64(m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *InventoryResource) validateImage(formats strfmt.Registry) error { - if swag.IsZero(m.Image) { // not required - return nil - } - - if err := validate.FormatOf("image", "body", "uri", m.Image.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *InventoryResource) validateMemory(formats strfmt.Registry) error { - if swag.IsZero(m.Memory) { // not required - return nil - } - - if err := validate.MinimumUint("memory", "body", *m.Memory, 0, false); err != nil { - return err - } - - return nil -} - -func (m *InventoryResource) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *InventoryResource) validateProject(formats strfmt.Registry) error { - if swag.IsZero(m.Project) { // not required - return nil - } - - if m.Project != nil { - if err := m.Project.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project") - } - - return err - } - } - - return nil -} - -func (m *InventoryResource) validateProvider(formats strfmt.Registry) error { - - if err := validate.Required("provider", "body", m.Provider); err != nil { - return err - } - - return nil -} - -func (m *InventoryResource) validateStorage(formats strfmt.Registry) error { - if swag.IsZero(m.Storage) { // not required - return nil - } - - if err := validate.MinimumUint("storage", "body", *m.Storage, 0, false); err != nil { - return err - } - - return nil -} - -func (m *InventoryResource) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this inventory resource based on the context it is used -func (m *InventoryResource) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateComponent(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateEnvironment(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateProject(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InventoryResource) contextValidateComponent(ctx context.Context, formats strfmt.Registry) error { - - if m.Component != nil { - - if swag.IsZero(m.Component) { // not required - return nil - } - - if err := m.Component.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("component") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("component") - } - - return err - } - } - - return nil -} - -func (m *InventoryResource) contextValidateEnvironment(ctx context.Context, formats strfmt.Registry) error { - - if m.Environment != nil { - - if swag.IsZero(m.Environment) { // not required - return nil - } - - if err := m.Environment.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment") - } - - return err - } - } - - return nil -} - -func (m *InventoryResource) contextValidateProject(ctx context.Context, formats strfmt.Registry) error { - - if m.Project != nil { - - if swag.IsZero(m.Project) { // not required - return nil - } - - if err := m.Project.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *InventoryResource) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InventoryResource) UnmarshalBinary(b []byte) error { - var res InventoryResource - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/inventory_resource_label.go b/client/models/inventory_resource_label.go deleted file mode 100644 index dc14b6407..000000000 --- a/client/models/inventory_resource_label.go +++ /dev/null @@ -1,136 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// InventoryResourceLabel Inventory Resource Label -// -// # Aggregated information of resources having a label -// -// swagger:model InventoryResourceLabel -type InventoryResourceLabel struct { - - // The aggregated amount of cpu of resources having the label - // Required: true - // Minimum: 0 - CPU *uint64 `json:"cpu"` - - // The aggregated amount of memory of resources having the label in MB - // Required: true - // Minimum: 0 - Memory *uint64 `json:"memory"` - - // Value of the resources' label - // Required: true - Name *string `json:"name"` - - // The aggregated amount of storage of resources having the label in MB - // Required: true - // Minimum: 0 - Storage *uint64 `json:"storage"` -} - -// Validate validates this inventory resource label -func (m *InventoryResourceLabel) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCPU(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMemory(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStorage(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *InventoryResourceLabel) validateCPU(formats strfmt.Registry) error { - - if err := validate.Required("cpu", "body", m.CPU); err != nil { - return err - } - - if err := validate.MinimumUint("cpu", "body", *m.CPU, 0, false); err != nil { - return err - } - - return nil -} - -func (m *InventoryResourceLabel) validateMemory(formats strfmt.Registry) error { - - if err := validate.Required("memory", "body", m.Memory); err != nil { - return err - } - - if err := validate.MinimumUint("memory", "body", *m.Memory, 0, false); err != nil { - return err - } - - return nil -} - -func (m *InventoryResourceLabel) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *InventoryResourceLabel) validateStorage(formats strfmt.Registry) error { - - if err := validate.Required("storage", "body", m.Storage); err != nil { - return err - } - - if err := validate.MinimumUint("storage", "body", *m.Storage, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this inventory resource label based on context it is used -func (m *InventoryResourceLabel) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *InventoryResourceLabel) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *InventoryResourceLabel) UnmarshalBinary(b []byte) error { - var res InventoryResourceLabel - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/job.go b/client/models/job.go deleted file mode 100644 index 75af63d33..000000000 --- a/client/models/job.go +++ /dev/null @@ -1,435 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Job Job -// -// The entity which represents a job output in the application. -// -// swagger:model Job -type Job struct { - - // disable manual trigger - DisableManualTrigger bool `json:"disable_manual_trigger,omitempty"` - - // finished build - FinishedBuild *Build `json:"finished_build,omitempty"` - - // first logged build id - FirstLoggedBuildID uint64 `json:"first_logged_build_id,omitempty"` - - // groups - Groups []string `json:"groups"` - - // has new inputs - HasNewInputs bool `json:"has_new_inputs,omitempty"` - - // id - // Required: true - ID *uint64 `json:"id"` - - // inputs - Inputs []*JobInput `json:"inputs"` - - // name - // Required: true - Name *string `json:"name"` - - // next build - NextBuild *Build `json:"next_build,omitempty"` - - // outputs - Outputs []*JobOutput `json:"outputs"` - - // paused - Paused bool `json:"paused,omitempty"` - - // pipeline id - PipelineID uint64 `json:"pipeline_id,omitempty"` - - // pipeline name - PipelineName string `json:"pipeline_name,omitempty"` - - // team name - TeamName string `json:"team_name,omitempty"` - - // transition build - TransitionBuild *Build `json:"transition_build,omitempty"` -} - -// Validate validates this job -func (m *Job) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateFinishedBuild(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInputs(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateNextBuild(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOutputs(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTransitionBuild(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Job) validateFinishedBuild(formats strfmt.Registry) error { - if swag.IsZero(m.FinishedBuild) { // not required - return nil - } - - if m.FinishedBuild != nil { - if err := m.FinishedBuild.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("finished_build") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("finished_build") - } - - return err - } - } - - return nil -} - -func (m *Job) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - return nil -} - -func (m *Job) validateInputs(formats strfmt.Registry) error { - if swag.IsZero(m.Inputs) { // not required - return nil - } - - for i := 0; i < len(m.Inputs); i++ { - if swag.IsZero(m.Inputs[i]) { // not required - continue - } - - if m.Inputs[i] != nil { - if err := m.Inputs[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("inputs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("inputs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Job) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *Job) validateNextBuild(formats strfmt.Registry) error { - if swag.IsZero(m.NextBuild) { // not required - return nil - } - - if m.NextBuild != nil { - if err := m.NextBuild.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next_build") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next_build") - } - - return err - } - } - - return nil -} - -func (m *Job) validateOutputs(formats strfmt.Registry) error { - if swag.IsZero(m.Outputs) { // not required - return nil - } - - for i := 0; i < len(m.Outputs); i++ { - if swag.IsZero(m.Outputs[i]) { // not required - continue - } - - if m.Outputs[i] != nil { - if err := m.Outputs[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("outputs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("outputs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Job) validateTransitionBuild(formats strfmt.Registry) error { - if swag.IsZero(m.TransitionBuild) { // not required - return nil - } - - if m.TransitionBuild != nil { - if err := m.TransitionBuild.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("transition_build") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("transition_build") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this job based on the context it is used -func (m *Job) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateFinishedBuild(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateInputs(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateNextBuild(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateOutputs(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateTransitionBuild(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Job) contextValidateFinishedBuild(ctx context.Context, formats strfmt.Registry) error { - - if m.FinishedBuild != nil { - - if swag.IsZero(m.FinishedBuild) { // not required - return nil - } - - if err := m.FinishedBuild.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("finished_build") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("finished_build") - } - - return err - } - } - - return nil -} - -func (m *Job) contextValidateInputs(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Inputs); i++ { - - if m.Inputs[i] != nil { - - if swag.IsZero(m.Inputs[i]) { // not required - return nil - } - - if err := m.Inputs[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("inputs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("inputs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Job) contextValidateNextBuild(ctx context.Context, formats strfmt.Registry) error { - - if m.NextBuild != nil { - - if swag.IsZero(m.NextBuild) { // not required - return nil - } - - if err := m.NextBuild.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next_build") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next_build") - } - - return err - } - } - - return nil -} - -func (m *Job) contextValidateOutputs(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Outputs); i++ { - - if m.Outputs[i] != nil { - - if swag.IsZero(m.Outputs[i]) { // not required - return nil - } - - if err := m.Outputs[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("outputs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("outputs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Job) contextValidateTransitionBuild(ctx context.Context, formats strfmt.Registry) error { - - if m.TransitionBuild != nil { - - if swag.IsZero(m.TransitionBuild) { // not required - return nil - } - - if err := m.TransitionBuild.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("transition_build") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("transition_build") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Job) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Job) UnmarshalBinary(b []byte) error { - var res Job - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/job_input.go b/client/models/job_input.go deleted file mode 100644 index 110503b90..000000000 --- a/client/models/job_input.go +++ /dev/null @@ -1,172 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// JobInput JobInput -// -// The entity which represents a job input in the application. -// -// swagger:model JobInput -type JobInput struct { - - // name - // Required: true - Name *string `json:"name"` - - // passed - Passed []string `json:"passed"` - - // resource - // Required: true - Resource *string `json:"resource"` - - // trigger - // Required: true - Trigger *bool `json:"trigger"` - - // version - Version *VersionConfig `json:"version,omitempty"` -} - -// Validate validates this job input -func (m *JobInput) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateResource(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTrigger(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *JobInput) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *JobInput) validateResource(formats strfmt.Registry) error { - - if err := validate.Required("resource", "body", m.Resource); err != nil { - return err - } - - return nil -} - -func (m *JobInput) validateTrigger(formats strfmt.Registry) error { - - if err := validate.Required("trigger", "body", m.Trigger); err != nil { - return err - } - - return nil -} - -func (m *JobInput) validateVersion(formats strfmt.Registry) error { - if swag.IsZero(m.Version) { // not required - return nil - } - - if m.Version != nil { - if err := m.Version.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("version") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("version") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this job input based on the context it is used -func (m *JobInput) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateVersion(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *JobInput) contextValidateVersion(ctx context.Context, formats strfmt.Registry) error { - - if m.Version != nil { - - if swag.IsZero(m.Version) { // not required - return nil - } - - if err := m.Version.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("version") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("version") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *JobInput) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *JobInput) UnmarshalBinary(b []byte) error { - var res JobInput - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/job_output.go b/client/models/job_output.go deleted file mode 100644 index ed9254f67..000000000 --- a/client/models/job_output.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// JobOutput JobOutput -// -// The entity which represents a job output in the application. -// -// swagger:model JobOutput -type JobOutput struct { - - // name - // Required: true - Name *string `json:"name"` - - // resource - // Required: true - Resource *string `json:"resource"` -} - -// Validate validates this job output -func (m *JobOutput) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateResource(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *JobOutput) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *JobOutput) validateResource(formats strfmt.Registry) error { - - if err := validate.Required("resource", "body", m.Resource); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this job output based on context it is used -func (m *JobOutput) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *JobOutput) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *JobOutput) UnmarshalBinary(b []byte) error { - var res JobOutput - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/k_p_i.go b/client/models/k_p_i.go deleted file mode 100644 index 0a13ddf39..000000000 --- a/client/models/k_p_i.go +++ /dev/null @@ -1,435 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// KPI KPI -// -// # A KPI -// -// swagger:model KPI -type KPI struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // component canonical - ComponentCanonical string `json:"component_canonical,omitempty"` - - // The config represent some extra parameters which are required for the configuration of certain KPIs. Please refer to the documentation for more details. - // - // Required: true - Config any `json:"config"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // The data is represented in CSV format. Depending on the widget configured for the KPI, the format may vary. For more information please refer to our product documentation. - DataSet []any `json:"data_set"` - - // description - // Required: true - Description *string `json:"description"` - - // environment canonical - EnvironmentCanonical string `json:"environment_canonical,omitempty"` - - // If an error occurred in the last import, that field will be filled with the message of the error - // Required: true - Error *string `json:"error"` - - // favorite - Favorite bool `json:"favorite,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // job name - JobName string `json:"job_name,omitempty"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // pipeline name - PipelineName string `json:"pipeline_name,omitempty"` - - // project - // Required: true - Project *Project `json:"project"` - - // type - // Required: true - // Enum: ["build_avg_time","build_frequency","build_history","code_coverage","time_to_release"] - Type *string `json:"type"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` - - // widget - // Required: true - // Enum: ["bars","stackbars","doughnut","history","line","pie","summary"] - Widget *string `json:"widget"` -} - -// Validate validates this k p i -func (m *KPI) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateConfig(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateError(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProject(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateWidget(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *KPI) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *KPI) validateConfig(formats strfmt.Registry) error { - - if m.Config == nil { - return errors.Required("config", "body", nil) - } - - return nil -} - -func (m *KPI) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *KPI) validateDescription(formats strfmt.Registry) error { - - if err := validate.Required("description", "body", m.Description); err != nil { - return err - } - - return nil -} - -func (m *KPI) validateError(formats strfmt.Registry) error { - - if err := validate.Required("error", "body", m.Error); err != nil { - return err - } - - return nil -} - -func (m *KPI) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *KPI) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *KPI) validateProject(formats strfmt.Registry) error { - - if err := validate.Required("project", "body", m.Project); err != nil { - return err - } - - if m.Project != nil { - if err := m.Project.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project") - } - - return err - } - } - - return nil -} - -var kPITypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["build_avg_time","build_frequency","build_history","code_coverage","time_to_release"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - kPITypeTypePropEnum = append(kPITypeTypePropEnum, v) - } -} - -const ( - - // KPITypeBuildAvgTime captures enum value "build_avg_time" - KPITypeBuildAvgTime string = "build_avg_time" - - // KPITypeBuildFrequency captures enum value "build_frequency" - KPITypeBuildFrequency string = "build_frequency" - - // KPITypeBuildHistory captures enum value "build_history" - KPITypeBuildHistory string = "build_history" - - // KPITypeCodeCoverage captures enum value "code_coverage" - KPITypeCodeCoverage string = "code_coverage" - - // KPITypeTimeToRelease captures enum value "time_to_release" - KPITypeTimeToRelease string = "time_to_release" -) - -// prop value enum -func (m *KPI) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, kPITypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *KPI) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -func (m *KPI) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -var kPITypeWidgetPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["bars","stackbars","doughnut","history","line","pie","summary"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - kPITypeWidgetPropEnum = append(kPITypeWidgetPropEnum, v) - } -} - -const ( - - // KPIWidgetBars captures enum value "bars" - KPIWidgetBars string = "bars" - - // KPIWidgetStackbars captures enum value "stackbars" - KPIWidgetStackbars string = "stackbars" - - // KPIWidgetDoughnut captures enum value "doughnut" - KPIWidgetDoughnut string = "doughnut" - - // KPIWidgetHistory captures enum value "history" - KPIWidgetHistory string = "history" - - // KPIWidgetLine captures enum value "line" - KPIWidgetLine string = "line" - - // KPIWidgetPie captures enum value "pie" - KPIWidgetPie string = "pie" - - // KPIWidgetSummary captures enum value "summary" - KPIWidgetSummary string = "summary" -) - -// prop value enum -func (m *KPI) validateWidgetEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, kPITypeWidgetPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *KPI) validateWidget(formats strfmt.Registry) error { - - if err := validate.Required("widget", "body", m.Widget); err != nil { - return err - } - - // value enum - if err := m.validateWidgetEnum("widget", "body", *m.Widget); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this k p i based on the context it is used -func (m *KPI) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateProject(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *KPI) contextValidateProject(ctx context.Context, formats strfmt.Registry) error { - - if m.Project != nil { - - if err := m.Project.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *KPI) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *KPI) UnmarshalBinary(b []byte) error { - var res KPI - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/licence.go b/client/models/licence.go deleted file mode 100644 index 3491e2138..000000000 --- a/client/models/licence.go +++ /dev/null @@ -1,248 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Licence Licence -// -// # Object containing licence parameters -// -// swagger:model Licence -type Licence struct { - - // company name - // Required: true - CompanyName *string `json:"company_name"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // current members - // Required: true - // Minimum: 0 - CurrentMembers *uint64 `json:"current_members"` - - // email address - // Required: true - EmailAddress *string `json:"email_address"` - - // expires at - // Required: true - // Minimum: 0 - ExpiresAt *uint64 `json:"expires_at"` - - // Licence's key in the JWT format - // Required: true - Key *string `json:"key"` - - // members count - // Required: true - // Minimum: 0 - MembersCount *uint64 `json:"members_count"` - - // on prem - // Required: true - OnPrem *bool `json:"on_prem"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` - - // version - // Required: true - Version *string `json:"version"` -} - -// Validate validates this licence -func (m *Licence) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCompanyName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCurrentMembers(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEmailAddress(formats); err != nil { - res = append(res, err) - } - - if err := m.validateExpiresAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateKey(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMembersCount(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOnPrem(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Licence) validateCompanyName(formats strfmt.Registry) error { - - if err := validate.Required("company_name", "body", m.CompanyName); err != nil { - return err - } - - return nil -} - -func (m *Licence) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Licence) validateCurrentMembers(formats strfmt.Registry) error { - - if err := validate.Required("current_members", "body", m.CurrentMembers); err != nil { - return err - } - - if err := validate.MinimumUint("current_members", "body", *m.CurrentMembers, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Licence) validateEmailAddress(formats strfmt.Registry) error { - - if err := validate.Required("email_address", "body", m.EmailAddress); err != nil { - return err - } - - return nil -} - -func (m *Licence) validateExpiresAt(formats strfmt.Registry) error { - - if err := validate.Required("expires_at", "body", m.ExpiresAt); err != nil { - return err - } - - if err := validate.MinimumUint("expires_at", "body", *m.ExpiresAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Licence) validateKey(formats strfmt.Registry) error { - - if err := validate.Required("key", "body", m.Key); err != nil { - return err - } - - return nil -} - -func (m *Licence) validateMembersCount(formats strfmt.Registry) error { - - if err := validate.Required("members_count", "body", m.MembersCount); err != nil { - return err - } - - if err := validate.MinimumUint("members_count", "body", *m.MembersCount, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Licence) validateOnPrem(formats strfmt.Registry) error { - - if err := validate.Required("on_prem", "body", m.OnPrem); err != nil { - return err - } - - return nil -} - -func (m *Licence) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Licence) validateVersion(formats strfmt.Registry) error { - - if err := validate.Required("version", "body", m.Version); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this licence based on context it is used -func (m *Licence) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *Licence) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Licence) UnmarshalBinary(b []byte) error { - var res Licence - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/log_source.go b/client/models/log_source.go deleted file mode 100644 index 38d86be17..000000000 --- a/client/models/log_source.go +++ /dev/null @@ -1,75 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// LogSource A log source -// -// The data associated to a log's source. Each log source is the context of a list of entries which are registered through the time. -// -// swagger:model LogSource -type LogSource struct { - - // id - // Required: true - // Min Length: 1 - ID *string `json:"id"` -} - -// Validate validates this log source -func (m *LogSource) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *LogSource) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinLength("id", "body", *m.ID, 1); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this log source based on context it is used -func (m *LogSource) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *LogSource) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *LogSource) UnmarshalBinary(b []byte) error { - var res LogSource - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/log_source_entry.go b/client/models/log_source_entry.go deleted file mode 100644 index daae9c64b..000000000 --- a/client/models/log_source_entry.go +++ /dev/null @@ -1,114 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// LogSourceEntry Log entry -// -// A log's entry which pertains to a specific log's source. -// -// swagger:model LogSourceEntry -type LogSourceEntry struct { - - // The host registered with the log's entry. - // Required: true - // Min Length: 1 - Host *string `json:"host"` - - // The original (i.e. raw) log's entry. - // Required: true - // Min Length: 1 - Message *string `json:"message"` - - // The timestamp extracted from the original log entry in order to be homogeneous to all the different supported underlying log systems. - // Required: true - Timestamp *string `json:"timestamp"` -} - -// Validate validates this log source entry -func (m *LogSourceEntry) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateHost(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTimestamp(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *LogSourceEntry) validateHost(formats strfmt.Registry) error { - - if err := validate.Required("host", "body", m.Host); err != nil { - return err - } - - if err := validate.MinLength("host", "body", *m.Host, 1); err != nil { - return err - } - - return nil -} - -func (m *LogSourceEntry) validateMessage(formats strfmt.Registry) error { - - if err := validate.Required("message", "body", m.Message); err != nil { - return err - } - - if err := validate.MinLength("message", "body", *m.Message, 1); err != nil { - return err - } - - return nil -} - -func (m *LogSourceEntry) validateTimestamp(formats strfmt.Registry) error { - - if err := validate.Required("timestamp", "body", m.Timestamp); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this log source entry based on context it is used -func (m *LogSourceEntry) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *LogSourceEntry) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *LogSourceEntry) UnmarshalBinary(b []byte) error { - var res LogSourceEntry - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/member_assignation.go b/client/models/member_assignation.go deleted file mode 100644 index 9761cbee7..000000000 --- a/client/models/member_assignation.go +++ /dev/null @@ -1,85 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// MemberAssignation Member assignation -// -// Member is a user who is associated to an entity of the system. The user is newly assigned or reassigned for updating is data. -// -// swagger:model MemberAssignation -type MemberAssignation struct { - - // The role of the member. - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - RoleCanonical *string `json:"role_canonical"` -} - -// Validate validates this member assignation -func (m *MemberAssignation) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateRoleCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *MemberAssignation) validateRoleCanonical(formats strfmt.Registry) error { - - if err := validate.Required("role_canonical", "body", m.RoleCanonical); err != nil { - return err - } - - if err := validate.MinLength("role_canonical", "body", *m.RoleCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("role_canonical", "body", *m.RoleCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("role_canonical", "body", *m.RoleCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this member assignation based on context it is used -func (m *MemberAssignation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *MemberAssignation) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *MemberAssignation) UnmarshalBinary(b []byte) error { - var res MemberAssignation - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/member_org.go b/client/models/member_org.go deleted file mode 100644 index b3e7f4126..000000000 --- a/client/models/member_org.go +++ /dev/null @@ -1,573 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// MemberOrg Member of an organization -// -// Member is a user who is associated to an organization. -// -// swagger:model MemberOrg -type MemberOrg struct { - - // When the user became a member. - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // user email - // Format: email - Email strfmt.Email `json:"email,omitempty"` - - // full name - FullName string `json:"full_name,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // The email address to which the invitation was sent. It's used to resend the invitation. - // Format: email - InvitationEmail strfmt.Email `json:"invitation_email,omitempty"` - - // invitation resent at - // Minimum: 0 - InvitationResentAt *uint64 `json:"invitation_resent_at,omitempty"` - - // invitation state - // Enum: ["pending","accepted","declined"] - InvitationState string `json:"invitation_state,omitempty"` - - // When the user had been invited to join as a member. When not present, the user is already a member, so she/he has verified her/his invitation. - // Minimum: 0 - InvitedAt *uint64 `json:"invited_at,omitempty"` - - // Organization member who invited the current user. - InvitedBy *SimpleMemberOrg `json:"invited_by,omitempty"` - - // When the user logged in last time. - // Minimum: 0 - LastLoginAt *uint64 `json:"last_login_at,omitempty"` - - // User's preferred language - // Enum: ["en","fr","es"] - Locale string `json:"locale,omitempty"` - - // mfa enabled - MfaEnabled bool `json:"mfa_enabled,omitempty"` - - // picture url - // Format: uri - PictureURL strfmt.URI `json:"picture_url,omitempty"` - - // role - // Required: true - Role *Role `json:"role"` - - // teams - Teams []*SimpleTeam `json:"teams"` - - // When the user had the role modified. - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` - - // username - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Username string `json:"username,omitempty"` -} - -// Validate validates this member org -func (m *MemberOrg) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInvitationEmail(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInvitationResentAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInvitationState(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInvitedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInvitedBy(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLastLoginAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLocale(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePictureURL(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRole(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTeams(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUsername(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *MemberOrg) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *MemberOrg) validateEmail(formats strfmt.Registry) error { - if swag.IsZero(m.Email) { // not required - return nil - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *MemberOrg) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *MemberOrg) validateInvitationEmail(formats strfmt.Registry) error { - if swag.IsZero(m.InvitationEmail) { // not required - return nil - } - - if err := validate.FormatOf("invitation_email", "body", "email", m.InvitationEmail.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *MemberOrg) validateInvitationResentAt(formats strfmt.Registry) error { - if swag.IsZero(m.InvitationResentAt) { // not required - return nil - } - - if err := validate.MinimumUint("invitation_resent_at", "body", *m.InvitationResentAt, 0, false); err != nil { - return err - } - - return nil -} - -var memberOrgTypeInvitationStatePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["pending","accepted","declined"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - memberOrgTypeInvitationStatePropEnum = append(memberOrgTypeInvitationStatePropEnum, v) - } -} - -const ( - - // MemberOrgInvitationStatePending captures enum value "pending" - MemberOrgInvitationStatePending string = "pending" - - // MemberOrgInvitationStateAccepted captures enum value "accepted" - MemberOrgInvitationStateAccepted string = "accepted" - - // MemberOrgInvitationStateDeclined captures enum value "declined" - MemberOrgInvitationStateDeclined string = "declined" -) - -// prop value enum -func (m *MemberOrg) validateInvitationStateEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, memberOrgTypeInvitationStatePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *MemberOrg) validateInvitationState(formats strfmt.Registry) error { - if swag.IsZero(m.InvitationState) { // not required - return nil - } - - // value enum - if err := m.validateInvitationStateEnum("invitation_state", "body", m.InvitationState); err != nil { - return err - } - - return nil -} - -func (m *MemberOrg) validateInvitedAt(formats strfmt.Registry) error { - if swag.IsZero(m.InvitedAt) { // not required - return nil - } - - if err := validate.MinimumUint("invited_at", "body", *m.InvitedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *MemberOrg) validateInvitedBy(formats strfmt.Registry) error { - if swag.IsZero(m.InvitedBy) { // not required - return nil - } - - if m.InvitedBy != nil { - if err := m.InvitedBy.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("invited_by") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("invited_by") - } - - return err - } - } - - return nil -} - -func (m *MemberOrg) validateLastLoginAt(formats strfmt.Registry) error { - if swag.IsZero(m.LastLoginAt) { // not required - return nil - } - - if err := validate.MinimumUint("last_login_at", "body", *m.LastLoginAt, 0, false); err != nil { - return err - } - - return nil -} - -var memberOrgTypeLocalePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["en","fr","es"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - memberOrgTypeLocalePropEnum = append(memberOrgTypeLocalePropEnum, v) - } -} - -const ( - - // MemberOrgLocaleEn captures enum value "en" - MemberOrgLocaleEn string = "en" - - // MemberOrgLocaleFr captures enum value "fr" - MemberOrgLocaleFr string = "fr" - - // MemberOrgLocaleEs captures enum value "es" - MemberOrgLocaleEs string = "es" -) - -// prop value enum -func (m *MemberOrg) validateLocaleEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, memberOrgTypeLocalePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *MemberOrg) validateLocale(formats strfmt.Registry) error { - if swag.IsZero(m.Locale) { // not required - return nil - } - - // value enum - if err := m.validateLocaleEnum("locale", "body", m.Locale); err != nil { - return err - } - - return nil -} - -func (m *MemberOrg) validatePictureURL(formats strfmt.Registry) error { - if swag.IsZero(m.PictureURL) { // not required - return nil - } - - if err := validate.FormatOf("picture_url", "body", "uri", m.PictureURL.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *MemberOrg) validateRole(formats strfmt.Registry) error { - - if err := validate.Required("role", "body", m.Role); err != nil { - return err - } - - if m.Role != nil { - if err := m.Role.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("role") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("role") - } - - return err - } - } - - return nil -} - -func (m *MemberOrg) validateTeams(formats strfmt.Registry) error { - if swag.IsZero(m.Teams) { // not required - return nil - } - - for i := 0; i < len(m.Teams); i++ { - if swag.IsZero(m.Teams[i]) { // not required - continue - } - - if m.Teams[i] != nil { - if err := m.Teams[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("teams" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("teams" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *MemberOrg) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *MemberOrg) validateUsername(formats strfmt.Registry) error { - if swag.IsZero(m.Username) { // not required - return nil - } - - if err := validate.MinLength("username", "body", m.Username, 3); err != nil { - return err - } - - if err := validate.MaxLength("username", "body", m.Username, 100); err != nil { - return err - } - - if err := validate.Pattern("username", "body", m.Username, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this member org based on the context it is used -func (m *MemberOrg) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateInvitedBy(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateRole(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateTeams(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *MemberOrg) contextValidateInvitedBy(ctx context.Context, formats strfmt.Registry) error { - - if m.InvitedBy != nil { - - if swag.IsZero(m.InvitedBy) { // not required - return nil - } - - if err := m.InvitedBy.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("invited_by") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("invited_by") - } - - return err - } - } - - return nil -} - -func (m *MemberOrg) contextValidateRole(ctx context.Context, formats strfmt.Registry) error { - - if m.Role != nil { - - if err := m.Role.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("role") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("role") - } - - return err - } - } - - return nil -} - -func (m *MemberOrg) contextValidateTeams(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Teams); i++ { - - if m.Teams[i] != nil { - - if swag.IsZero(m.Teams[i]) { // not required - return nil - } - - if err := m.Teams[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("teams" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("teams" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *MemberOrg) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *MemberOrg) UnmarshalBinary(b []byte) error { - var res MemberOrg - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/member_team.go b/client/models/member_team.go deleted file mode 100644 index 9c9936aae..000000000 --- a/client/models/member_team.go +++ /dev/null @@ -1,316 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// MemberTeam Member of a team -// -// Member is a user who is associated to a team. -// -// swagger:model MemberTeam -type MemberTeam struct { - - // When the user became a member. - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // user email - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` - - // Full name, can be empty in case if the user hasn't accepted the invitation yet. - // Max Length: 255 - // Min Length: 2 - FullName string `json:"full_name,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // Team member who invited the current user to the team. - InvitedBy *SimpleMemberOrg `json:"invited_by,omitempty"` - - // When the user logged in last time. - // Minimum: 0 - LastLoginAt *uint64 `json:"last_login_at,omitempty"` - - // mfa enabled - // Required: true - MfaEnabled *bool `json:"mfa_enabled"` - - // picture url - // Format: uri - PictureURL strfmt.URI `json:"picture_url,omitempty"` - - // When the user had the role modified. - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` - - // User canonical, can be empty in case if the user hasn't accepted the invitation yet. - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Username string `json:"username,omitempty"` -} - -// Validate validates this member team -func (m *MemberTeam) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFullName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInvitedBy(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLastLoginAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMfaEnabled(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePictureURL(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUsername(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *MemberTeam) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *MemberTeam) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *MemberTeam) validateFullName(formats strfmt.Registry) error { - if swag.IsZero(m.FullName) { // not required - return nil - } - - if err := validate.MinLength("full_name", "body", m.FullName, 2); err != nil { - return err - } - - if err := validate.MaxLength("full_name", "body", m.FullName, 255); err != nil { - return err - } - - return nil -} - -func (m *MemberTeam) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *MemberTeam) validateInvitedBy(formats strfmt.Registry) error { - if swag.IsZero(m.InvitedBy) { // not required - return nil - } - - if m.InvitedBy != nil { - if err := m.InvitedBy.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("invited_by") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("invited_by") - } - - return err - } - } - - return nil -} - -func (m *MemberTeam) validateLastLoginAt(formats strfmt.Registry) error { - if swag.IsZero(m.LastLoginAt) { // not required - return nil - } - - if err := validate.MinimumUint("last_login_at", "body", *m.LastLoginAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *MemberTeam) validateMfaEnabled(formats strfmt.Registry) error { - - if err := validate.Required("mfa_enabled", "body", m.MfaEnabled); err != nil { - return err - } - - return nil -} - -func (m *MemberTeam) validatePictureURL(formats strfmt.Registry) error { - if swag.IsZero(m.PictureURL) { // not required - return nil - } - - if err := validate.FormatOf("picture_url", "body", "uri", m.PictureURL.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *MemberTeam) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *MemberTeam) validateUsername(formats strfmt.Registry) error { - if swag.IsZero(m.Username) { // not required - return nil - } - - if err := validate.MinLength("username", "body", m.Username, 3); err != nil { - return err - } - - if err := validate.MaxLength("username", "body", m.Username, 100); err != nil { - return err - } - - if err := validate.Pattern("username", "body", m.Username, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this member team based on the context it is used -func (m *MemberTeam) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateInvitedBy(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *MemberTeam) contextValidateInvitedBy(ctx context.Context, formats strfmt.Registry) error { - - if m.InvitedBy != nil { - - if swag.IsZero(m.InvitedBy) { // not required - return nil - } - - if err := m.InvitedBy.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("invited_by") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("invited_by") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *MemberTeam) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *MemberTeam) UnmarshalBinary(b []byte) error { - var res MemberTeam - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/metadata_field.go b/client/models/metadata_field.go deleted file mode 100644 index 2997dab68..000000000 --- a/client/models/metadata_field.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// MetadataField MetadataField -// -// # Represent the metadata of a build input -// -// swagger:model MetadataField -type MetadataField struct { - - // name - // Required: true - Name *string `json:"name"` - - // value - // Required: true - Value *string `json:"value"` -} - -// Validate validates this metadata field -func (m *MetadataField) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateValue(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *MetadataField) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *MetadataField) validateValue(formats strfmt.Registry) error { - - if err := validate.Required("value", "body", m.Value); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this metadata field based on context it is used -func (m *MetadataField) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *MetadataField) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *MetadataField) UnmarshalBinary(b []byte) error { - var res MetadataField - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/migrate_component.go b/client/models/migrate_component.go deleted file mode 100644 index a033e6ed9..000000000 --- a/client/models/migrate_component.go +++ /dev/null @@ -1,146 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// MigrateComponent Migrate Component -// -// The entity which represents the information of a component to migrate. -// -// swagger:model MigrateComponent -type MigrateComponent struct { - - // destination component canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$ - DestinationComponentCanonical string `json:"destination_component_canonical,omitempty"` - - // destination component name - DestinationComponentName string `json:"destination_component_name,omitempty"` - - // destination environment canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$ - DestinationEnvironmentCanonical string `json:"destination_environment_canonical,omitempty"` - - // destination project canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - DestinationProjectCanonical string `json:"destination_project_canonical,omitempty"` -} - -// Validate validates this migrate component -func (m *MigrateComponent) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateDestinationComponentCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDestinationEnvironmentCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDestinationProjectCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *MigrateComponent) validateDestinationComponentCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.DestinationComponentCanonical) { // not required - return nil - } - - if err := validate.MinLength("destination_component_canonical", "body", m.DestinationComponentCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("destination_component_canonical", "body", m.DestinationComponentCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("destination_component_canonical", "body", m.DestinationComponentCanonical, `^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$`); err != nil { - return err - } - - return nil -} - -func (m *MigrateComponent) validateDestinationEnvironmentCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.DestinationEnvironmentCanonical) { // not required - return nil - } - - if err := validate.MinLength("destination_environment_canonical", "body", m.DestinationEnvironmentCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("destination_environment_canonical", "body", m.DestinationEnvironmentCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("destination_environment_canonical", "body", m.DestinationEnvironmentCanonical, `^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$`); err != nil { - return err - } - - return nil -} - -func (m *MigrateComponent) validateDestinationProjectCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.DestinationProjectCanonical) { // not required - return nil - } - - if err := validate.MinLength("destination_project_canonical", "body", m.DestinationProjectCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("destination_project_canonical", "body", m.DestinationProjectCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("destination_project_canonical", "body", m.DestinationProjectCanonical, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this migrate component based on context it is used -func (m *MigrateComponent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *MigrateComponent) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *MigrateComponent) UnmarshalBinary(b []byte) error { - var res MigrateComponent - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_a_w_s_marketplace_user_account.go b/client/models/new_a_w_s_marketplace_user_account.go deleted file mode 100644 index d5d688f60..000000000 --- a/client/models/new_a_w_s_marketplace_user_account.go +++ /dev/null @@ -1,255 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewAWSMarketplaceUserAccount Sign up from AWS Marketplace -// -// Create a new AWS Marketplace user account. -// -// swagger:model NewAWSMarketplaceUserAccount -type NewAWSMarketplaceUserAccount struct { - - // The AWS marketplace token - // Required: true - // Min Length: 1 - AwsMarketplaceToken *string `json:"aws_marketplace_token"` - - // Code of a country the user is from in alpha-2 format - // Pattern: ^[A-Z]{2}$ - CountryCode string `json:"country_code,omitempty"` - - // email - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` - - // full name - // Required: true - // Max Length: 255 - // Min Length: 2 - FullName *string `json:"full_name"` - - // User's preferred language - // Enum: ["en","fr","es"] - Locale string `json:"locale,omitempty"` - - // password - // Required: true - // Min Length: 12 - // Format: password - Password *strfmt.Password `json:"password"` - - // username - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Username string `json:"username,omitempty"` -} - -// Validate validates this new a w s marketplace user account -func (m *NewAWSMarketplaceUserAccount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAwsMarketplaceToken(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCountryCode(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFullName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLocale(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePassword(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUsername(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewAWSMarketplaceUserAccount) validateAwsMarketplaceToken(formats strfmt.Registry) error { - - if err := validate.Required("aws_marketplace_token", "body", m.AwsMarketplaceToken); err != nil { - return err - } - - if err := validate.MinLength("aws_marketplace_token", "body", *m.AwsMarketplaceToken, 1); err != nil { - return err - } - - return nil -} - -func (m *NewAWSMarketplaceUserAccount) validateCountryCode(formats strfmt.Registry) error { - if swag.IsZero(m.CountryCode) { // not required - return nil - } - - if err := validate.Pattern("country_code", "body", m.CountryCode, `^[A-Z]{2}$`); err != nil { - return err - } - - return nil -} - -func (m *NewAWSMarketplaceUserAccount) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *NewAWSMarketplaceUserAccount) validateFullName(formats strfmt.Registry) error { - - if err := validate.Required("full_name", "body", m.FullName); err != nil { - return err - } - - if err := validate.MinLength("full_name", "body", *m.FullName, 2); err != nil { - return err - } - - if err := validate.MaxLength("full_name", "body", *m.FullName, 255); err != nil { - return err - } - - return nil -} - -var newAWSMarketplaceUserAccountTypeLocalePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["en","fr","es"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - newAWSMarketplaceUserAccountTypeLocalePropEnum = append(newAWSMarketplaceUserAccountTypeLocalePropEnum, v) - } -} - -const ( - - // NewAWSMarketplaceUserAccountLocaleEn captures enum value "en" - NewAWSMarketplaceUserAccountLocaleEn string = "en" - - // NewAWSMarketplaceUserAccountLocaleFr captures enum value "fr" - NewAWSMarketplaceUserAccountLocaleFr string = "fr" - - // NewAWSMarketplaceUserAccountLocaleEs captures enum value "es" - NewAWSMarketplaceUserAccountLocaleEs string = "es" -) - -// prop value enum -func (m *NewAWSMarketplaceUserAccount) validateLocaleEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, newAWSMarketplaceUserAccountTypeLocalePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NewAWSMarketplaceUserAccount) validateLocale(formats strfmt.Registry) error { - if swag.IsZero(m.Locale) { // not required - return nil - } - - // value enum - if err := m.validateLocaleEnum("locale", "body", m.Locale); err != nil { - return err - } - - return nil -} - -func (m *NewAWSMarketplaceUserAccount) validatePassword(formats strfmt.Registry) error { - - if err := validate.Required("password", "body", m.Password); err != nil { - return err - } - - if err := validate.MinLength("password", "body", m.Password.String(), 12); err != nil { - return err - } - - if err := validate.FormatOf("password", "body", "password", m.Password.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *NewAWSMarketplaceUserAccount) validateUsername(formats strfmt.Registry) error { - if swag.IsZero(m.Username) { // not required - return nil - } - - if err := validate.MinLength("username", "body", m.Username, 3); err != nil { - return err - } - - if err := validate.MaxLength("username", "body", m.Username, 100); err != nil { - return err - } - - if err := validate.Pattern("username", "body", m.Username, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new a w s marketplace user account based on context it is used -func (m *NewAWSMarketplaceUserAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewAWSMarketplaceUserAccount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewAWSMarketplaceUserAccount) UnmarshalBinary(b []byte) error { - var res NewAWSMarketplaceUserAccount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_and_configured_component.go b/client/models/new_and_configured_component.go deleted file mode 100644 index f4501844f..000000000 --- a/client/models/new_and_configured_component.go +++ /dev/null @@ -1,253 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewAndConfiguredComponent New And Configured Component -// -// The entity which is used to create and configure a new component in one step. -// -// swagger:model NewAndConfiguredComponent -type NewAndConfiguredComponent struct { - - // canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$ - Canonical string `json:"canonical,omitempty"` - - // cloud provider canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CloudProviderCanonical string `json:"cloud_provider_canonical,omitempty"` - - // description - Description string `json:"description,omitempty"` - - // name - // Required: true - // Min Length: 1 - Name *string `json:"name"` - - // It's the ref of the Stack, like 'cycloidio:stack-magento' - ServiceCatalogRef string `json:"service_catalog_ref,omitempty"` - - // Is the ID of the new SCS Version used - // Minimum: 1 - ServiceCatalogSourceVersionID uint32 `json:"service_catalog_source_version_id,omitempty"` - - // use case - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - UseCase string `json:"use_case,omitempty"` - - // vars - Vars FormVariables `json:"vars,omitempty"` -} - -// Validate validates this new and configured component -func (m *NewAndConfiguredComponent) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProviderCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalogSourceVersionID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUseCase(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVars(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewAndConfiguredComponent) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$`); err != nil { - return err - } - - return nil -} - -func (m *NewAndConfiguredComponent) validateCloudProviderCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.CloudProviderCanonical) { // not required - return nil - } - - if err := validate.MinLength("cloud_provider_canonical", "body", m.CloudProviderCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("cloud_provider_canonical", "body", m.CloudProviderCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("cloud_provider_canonical", "body", m.CloudProviderCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewAndConfiguredComponent) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - return nil -} - -func (m *NewAndConfiguredComponent) validateServiceCatalogSourceVersionID(formats strfmt.Registry) error { - if swag.IsZero(m.ServiceCatalogSourceVersionID) { // not required - return nil - } - - if err := validate.MinimumUint("service_catalog_source_version_id", "body", uint64(m.ServiceCatalogSourceVersionID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *NewAndConfiguredComponent) validateUseCase(formats strfmt.Registry) error { - if swag.IsZero(m.UseCase) { // not required - return nil - } - - if err := validate.MinLength("use_case", "body", m.UseCase, 1); err != nil { - return err - } - - if err := validate.MaxLength("use_case", "body", m.UseCase, 100); err != nil { - return err - } - - if err := validate.Pattern("use_case", "body", m.UseCase, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -func (m *NewAndConfiguredComponent) validateVars(formats strfmt.Registry) error { - if swag.IsZero(m.Vars) { // not required - return nil - } - - if m.Vars != nil { - if err := m.Vars.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("vars") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("vars") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this new and configured component based on the context it is used -func (m *NewAndConfiguredComponent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateVars(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewAndConfiguredComponent) contextValidateVars(ctx context.Context, formats strfmt.Registry) error { - - if swag.IsZero(m.Vars) { // not required - return nil - } - - if err := m.Vars.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("vars") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("vars") - } - - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewAndConfiguredComponent) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewAndConfiguredComponent) UnmarshalBinary(b []byte) error { - var res NewAndConfiguredComponent - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_api_key.go b/client/models/new_api_key.go deleted file mode 100644 index 88eb2d6d6..000000000 --- a/client/models/new_api_key.go +++ /dev/null @@ -1,193 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewAPIKey Create API key -// -// The entity which represents the information of a new API key. -// -// swagger:model NewAPIKey -type NewAPIKey struct { - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // description - Description string `json:"description,omitempty"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // User canonical that owns this API key. If omitted then the person creating this - // credential will be assigned as owner. When a user is the owner of an API key he has - // all the permissions on it. - // - Owner string `json:"owner,omitempty"` - - // rules - // Required: true - Rules []*NewRule `json:"rules"` -} - -// Validate validates this new API key -func (m *NewAPIKey) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRules(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewAPIKey) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewAPIKey) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *NewAPIKey) validateRules(formats strfmt.Registry) error { - - if err := validate.Required("rules", "body", m.Rules); err != nil { - return err - } - - for i := 0; i < len(m.Rules); i++ { - if swag.IsZero(m.Rules[i]) { // not required - continue - } - - if m.Rules[i] != nil { - if err := m.Rules[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("rules" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("rules" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this new API key based on the context it is used -func (m *NewAPIKey) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateRules(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewAPIKey) contextValidateRules(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Rules); i++ { - - if m.Rules[i] != nil { - - if swag.IsZero(m.Rules[i]) { // not required - return nil - } - - if err := m.Rules[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("rules" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("rules" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewAPIKey) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewAPIKey) UnmarshalBinary(b []byte) error { - var res NewAPIKey - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_appearance.go b/client/models/new_appearance.go deleted file mode 100644 index f1da8bece..000000000 --- a/client/models/new_appearance.go +++ /dev/null @@ -1,388 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewAppearance Appearance -// -// # An Appearance holds the values of the branding configuration, which are rendered across an organization -// -// swagger:model NewAppearance -type NewAppearance struct { - - // color - // Required: true - Color *NewAppearanceColor `json:"color"` - - // display name - // Required: true - // Max Length: 50 - // Min Length: 1 - DisplayName *string `json:"display_name"` - - // favicon - // Required: true - // Format: uri - Favicon *strfmt.URI `json:"favicon"` - - // footer - // Required: true - // Max Length: 1000 - // Min Length: 0 - Footer *string `json:"footer"` - - // logo - // Required: true - // Format: uri - Logo *strfmt.URI `json:"logo"` - - // name - // Required: true - // Max Length: 50 - // Min Length: 1 - Name *string `json:"name"` - - // tab title - // Required: true - // Max Length: 50 - // Min Length: 1 - TabTitle *string `json:"tab_title"` -} - -// Validate validates this new appearance -func (m *NewAppearance) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateColor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDisplayName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFavicon(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFooter(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLogo(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTabTitle(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewAppearance) validateColor(formats strfmt.Registry) error { - - if err := validate.Required("color", "body", m.Color); err != nil { - return err - } - - if m.Color != nil { - if err := m.Color.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("color") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("color") - } - - return err - } - } - - return nil -} - -func (m *NewAppearance) validateDisplayName(formats strfmt.Registry) error { - - if err := validate.Required("display_name", "body", m.DisplayName); err != nil { - return err - } - - if err := validate.MinLength("display_name", "body", *m.DisplayName, 1); err != nil { - return err - } - - if err := validate.MaxLength("display_name", "body", *m.DisplayName, 50); err != nil { - return err - } - - return nil -} - -func (m *NewAppearance) validateFavicon(formats strfmt.Registry) error { - - if err := validate.Required("favicon", "body", m.Favicon); err != nil { - return err - } - - if err := validate.FormatOf("favicon", "body", "uri", m.Favicon.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *NewAppearance) validateFooter(formats strfmt.Registry) error { - - if err := validate.Required("footer", "body", m.Footer); err != nil { - return err - } - - if err := validate.MinLength("footer", "body", *m.Footer, 0); err != nil { - return err - } - - if err := validate.MaxLength("footer", "body", *m.Footer, 1000); err != nil { - return err - } - - return nil -} - -func (m *NewAppearance) validateLogo(formats strfmt.Registry) error { - - if err := validate.Required("logo", "body", m.Logo); err != nil { - return err - } - - if err := validate.FormatOf("logo", "body", "uri", m.Logo.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *NewAppearance) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 50); err != nil { - return err - } - - return nil -} - -func (m *NewAppearance) validateTabTitle(formats strfmt.Registry) error { - - if err := validate.Required("tab_title", "body", m.TabTitle); err != nil { - return err - } - - if err := validate.MinLength("tab_title", "body", *m.TabTitle, 1); err != nil { - return err - } - - if err := validate.MaxLength("tab_title", "body", *m.TabTitle, 50); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this new appearance based on the context it is used -func (m *NewAppearance) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateColor(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewAppearance) contextValidateColor(ctx context.Context, formats strfmt.Registry) error { - - if m.Color != nil { - - if err := m.Color.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("color") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("color") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewAppearance) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewAppearance) UnmarshalBinary(b []byte) error { - var res NewAppearance - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} - -// NewAppearanceColor new appearance color -// -// swagger:model NewAppearanceColor -type NewAppearanceColor struct { - - // Blue color value of the RGB color - // Required: true - // Maximum: 255 - // Minimum: 0 - B *uint32 `json:"b"` - - // Green color value of the RGB color - // Required: true - // Maximum: 255 - // Minimum: 0 - G *uint32 `json:"g"` - - // Red color value of the RGB color - // Required: true - // Maximum: 255 - // Minimum: 0 - R *uint32 `json:"r"` -} - -// Validate validates this new appearance color -func (m *NewAppearanceColor) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateB(formats); err != nil { - res = append(res, err) - } - - if err := m.validateG(formats); err != nil { - res = append(res, err) - } - - if err := m.validateR(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewAppearanceColor) validateB(formats strfmt.Registry) error { - - if err := validate.Required("color"+"."+"b", "body", m.B); err != nil { - return err - } - - if err := validate.MinimumUint("color"+"."+"b", "body", uint64(*m.B), 0, false); err != nil { - return err - } - - if err := validate.MaximumUint("color"+"."+"b", "body", uint64(*m.B), 255, false); err != nil { - return err - } - - return nil -} - -func (m *NewAppearanceColor) validateG(formats strfmt.Registry) error { - - if err := validate.Required("color"+"."+"g", "body", m.G); err != nil { - return err - } - - if err := validate.MinimumUint("color"+"."+"g", "body", uint64(*m.G), 0, false); err != nil { - return err - } - - if err := validate.MaximumUint("color"+"."+"g", "body", uint64(*m.G), 255, false); err != nil { - return err - } - - return nil -} - -func (m *NewAppearanceColor) validateR(formats strfmt.Registry) error { - - if err := validate.Required("color"+"."+"r", "body", m.R); err != nil { - return err - } - - if err := validate.MinimumUint("color"+"."+"r", "body", uint64(*m.R), 0, false); err != nil { - return err - } - - if err := validate.MaximumUint("color"+"."+"r", "body", uint64(*m.R), 255, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new appearance color based on context it is used -func (m *NewAppearanceColor) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewAppearanceColor) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewAppearanceColor) UnmarshalBinary(b []byte) error { - var res NewAppearanceColor - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_cloud_account.go b/client/models/new_cloud_account.go deleted file mode 100644 index 496079525..000000000 --- a/client/models/new_cloud_account.go +++ /dev/null @@ -1,177 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewCloudAccount Create Cloud Account -// -// Create a new Cloud Account to wrap cloud credentials. For built-in providers (canonicals aws, google, azurerm; aliases like gcp/microsoft azure are accepted and normalized) the credential type must match. For custom cloud providers, a 'custom' credential is required. -// -// swagger:model NewCloudAccount -type NewCloudAccount struct { - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // The canonical of the associated cloud provider. Can be a built-in provider canonical (aws, google, azurerm) or any free-form canonical representing a custom cloud provider for the organization. - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CloudProvider *string `json:"cloud_provider"` - - // Canonical of the credential to use - // Required: true - // Max Length: 100 - // Min Length: 3 - CredentialCanonical *string `json:"credential_canonical"` - - // An optional description for the cloud account - Description string `json:"description,omitempty"` - - // A user-defined name for the cloud account - // Required: true - // Max Length: 255 - // Min Length: 1 - Name *string `json:"name"` - - // User canonical that owns this cloud account. If omitted, the - // person creating this cloud account will be assigned as owner. - // - Owner string `json:"owner,omitempty"` -} - -// Validate validates this new cloud account -func (m *NewCloudAccount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewCloudAccount) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewCloudAccount) validateCloudProvider(formats strfmt.Registry) error { - - if err := validate.Required("cloud_provider", "body", m.CloudProvider); err != nil { - return err - } - - if err := validate.MinLength("cloud_provider", "body", *m.CloudProvider, 3); err != nil { - return err - } - - if err := validate.MaxLength("cloud_provider", "body", *m.CloudProvider, 100); err != nil { - return err - } - - if err := validate.Pattern("cloud_provider", "body", *m.CloudProvider, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewCloudAccount) validateCredentialCanonical(formats strfmt.Registry) error { - - if err := validate.Required("credential_canonical", "body", m.CredentialCanonical); err != nil { - return err - } - - if err := validate.MinLength("credential_canonical", "body", *m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", *m.CredentialCanonical, 100); err != nil { - return err - } - - return nil -} - -func (m *NewCloudAccount) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 255); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new cloud account based on context it is used -func (m *NewCloudAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewCloudAccount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewCloudAccount) UnmarshalBinary(b []byte) error { - var res NewCloudAccount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_cloud_account_credential.go b/client/models/new_cloud_account_credential.go deleted file mode 100644 index 262b57e70..000000000 --- a/client/models/new_cloud_account_credential.go +++ /dev/null @@ -1,263 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewCloudAccountCredential Cloud Account Credential -// -// Credential to create and associate with a cloud account. Unlike NewCredential, path is optional and defaults to a value derived from the cloud account canonical. -// -// swagger:model NewCloudAccountCredential -type NewCloudAccountCredential struct { - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // description - Description string `json:"description,omitempty"` - - // name - // Required: true - Name *string `json:"name"` - - // path - // Pattern: [a-zA-z0-9_\-./] - Path string `json:"path,omitempty"` - - // raw - // Required: true - Raw *CredentialRaw `json:"raw"` - - // type - // Required: true - // Enum: ["ssh","aws","custom","azure","azure_storage","gcp","basic_auth","elasticsearch","swift","vmware"] - Type *string `json:"type"` -} - -// Validate validates this new cloud account credential -func (m *NewCloudAccountCredential) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePath(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRaw(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewCloudAccountCredential) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewCloudAccountCredential) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *NewCloudAccountCredential) validatePath(formats strfmt.Registry) error { - if swag.IsZero(m.Path) { // not required - return nil - } - - if err := validate.Pattern("path", "body", m.Path, `[a-zA-z0-9_\-./]`); err != nil { - return err - } - - return nil -} - -func (m *NewCloudAccountCredential) validateRaw(formats strfmt.Registry) error { - - if err := validate.Required("raw", "body", m.Raw); err != nil { - return err - } - - if m.Raw != nil { - if err := m.Raw.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("raw") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("raw") - } - - return err - } - } - - return nil -} - -var newCloudAccountCredentialTypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["ssh","aws","custom","azure","azure_storage","gcp","basic_auth","elasticsearch","swift","vmware"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - newCloudAccountCredentialTypeTypePropEnum = append(newCloudAccountCredentialTypeTypePropEnum, v) - } -} - -const ( - - // NewCloudAccountCredentialTypeSSH captures enum value "ssh" - NewCloudAccountCredentialTypeSSH string = "ssh" - - // NewCloudAccountCredentialTypeAws captures enum value "aws" - NewCloudAccountCredentialTypeAws string = "aws" - - // NewCloudAccountCredentialTypeCustom captures enum value "custom" - NewCloudAccountCredentialTypeCustom string = "custom" - - // NewCloudAccountCredentialTypeAzure captures enum value "azure" - NewCloudAccountCredentialTypeAzure string = "azure" - - // NewCloudAccountCredentialTypeAzureStorage captures enum value "azure_storage" - NewCloudAccountCredentialTypeAzureStorage string = "azure_storage" - - // NewCloudAccountCredentialTypeGcp captures enum value "gcp" - NewCloudAccountCredentialTypeGcp string = "gcp" - - // NewCloudAccountCredentialTypeBasicAuth captures enum value "basic_auth" - NewCloudAccountCredentialTypeBasicAuth string = "basic_auth" - - // NewCloudAccountCredentialTypeElasticsearch captures enum value "elasticsearch" - NewCloudAccountCredentialTypeElasticsearch string = "elasticsearch" - - // NewCloudAccountCredentialTypeSwift captures enum value "swift" - NewCloudAccountCredentialTypeSwift string = "swift" - - // NewCloudAccountCredentialTypeVmware captures enum value "vmware" - NewCloudAccountCredentialTypeVmware string = "vmware" -) - -// prop value enum -func (m *NewCloudAccountCredential) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, newCloudAccountCredentialTypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NewCloudAccountCredential) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this new cloud account credential based on the context it is used -func (m *NewCloudAccountCredential) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateRaw(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewCloudAccountCredential) contextValidateRaw(ctx context.Context, formats strfmt.Registry) error { - - if m.Raw != nil { - - if err := m.Raw.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("raw") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("raw") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewCloudAccountCredential) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewCloudAccountCredential) UnmarshalBinary(b []byte) error { - var res NewCloudAccountCredential - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_cloud_account_with_credentials.go b/client/models/new_cloud_account_with_credentials.go deleted file mode 100644 index fb89a0013..000000000 --- a/client/models/new_cloud_account_with_credentials.go +++ /dev/null @@ -1,334 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewCloudAccountWithCredentials Create Cloud Account With Credentials -// -// Create a new Cloud Account along with its access credential. Optionally creates a Cloud Cost Management account (not available for custom cloud providers). The credential path defaults to cloud-accounts/{canonical}-access if omitted. -// -// swagger:model NewCloudAccountWithCredentials -type NewCloudAccountWithCredentials struct { - - // Credential to create and associate with this cloud account. If path is omitted, defaults to cloud-accounts/{ca-canonical}-access. - // Required: true - AccessCredential *NewCloudAccountCredential `json:"access_credential"` - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // The canonical of the associated cloud provider. Can be a built-in provider canonical (aws, google, azurerm) or any free-form canonical representing a custom cloud provider for the organization. - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CloudProvider *string `json:"cloud_provider"` - - // An optional description for the cloud account - Description string `json:"description,omitempty"` - - // Configuration for the Cloud Cost Management account, required when finops_enabled is true - FinopsConfig *NewCloudCostManagementAccount `json:"finops_config,omitempty"` - - // Dedicated credential for the CCM account. If omitted, the access_credential is reused. If path is omitted, defaults to cloud-accounts/{ca-canonical}-finops. - FinopsCredential *NewCloudAccountCredential `json:"finops_credential,omitempty"` - - // When true, a Cloud Cost Management account is also created using finops_config - FinopsEnabled bool `json:"finops_enabled,omitempty"` - - // A user-defined name for the cloud account - // Required: true - // Max Length: 255 - // Min Length: 1 - Name *string `json:"name"` - - // User canonical that owns this cloud account. If omitted, the - // person creating this cloud account will be assigned as owner. - // - Owner string `json:"owner,omitempty"` -} - -// Validate validates this new cloud account with credentials -func (m *NewCloudAccountWithCredentials) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAccessCredential(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFinopsConfig(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFinopsCredential(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewCloudAccountWithCredentials) validateAccessCredential(formats strfmt.Registry) error { - - if err := validate.Required("access_credential", "body", m.AccessCredential); err != nil { - return err - } - - if m.AccessCredential != nil { - if err := m.AccessCredential.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("access_credential") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("access_credential") - } - - return err - } - } - - return nil -} - -func (m *NewCloudAccountWithCredentials) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewCloudAccountWithCredentials) validateCloudProvider(formats strfmt.Registry) error { - - if err := validate.Required("cloud_provider", "body", m.CloudProvider); err != nil { - return err - } - - if err := validate.MinLength("cloud_provider", "body", *m.CloudProvider, 3); err != nil { - return err - } - - if err := validate.MaxLength("cloud_provider", "body", *m.CloudProvider, 100); err != nil { - return err - } - - if err := validate.Pattern("cloud_provider", "body", *m.CloudProvider, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewCloudAccountWithCredentials) validateFinopsConfig(formats strfmt.Registry) error { - if swag.IsZero(m.FinopsConfig) { // not required - return nil - } - - if m.FinopsConfig != nil { - if err := m.FinopsConfig.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("finops_config") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("finops_config") - } - - return err - } - } - - return nil -} - -func (m *NewCloudAccountWithCredentials) validateFinopsCredential(formats strfmt.Registry) error { - if swag.IsZero(m.FinopsCredential) { // not required - return nil - } - - if m.FinopsCredential != nil { - if err := m.FinopsCredential.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("finops_credential") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("finops_credential") - } - - return err - } - } - - return nil -} - -func (m *NewCloudAccountWithCredentials) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 255); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this new cloud account with credentials based on the context it is used -func (m *NewCloudAccountWithCredentials) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateAccessCredential(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateFinopsConfig(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateFinopsCredential(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewCloudAccountWithCredentials) contextValidateAccessCredential(ctx context.Context, formats strfmt.Registry) error { - - if m.AccessCredential != nil { - - if err := m.AccessCredential.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("access_credential") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("access_credential") - } - - return err - } - } - - return nil -} - -func (m *NewCloudAccountWithCredentials) contextValidateFinopsConfig(ctx context.Context, formats strfmt.Registry) error { - - if m.FinopsConfig != nil { - - if swag.IsZero(m.FinopsConfig) { // not required - return nil - } - - if err := m.FinopsConfig.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("finops_config") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("finops_config") - } - - return err - } - } - - return nil -} - -func (m *NewCloudAccountWithCredentials) contextValidateFinopsCredential(ctx context.Context, formats strfmt.Registry) error { - - if m.FinopsCredential != nil { - - if swag.IsZero(m.FinopsCredential) { // not required - return nil - } - - if err := m.FinopsCredential.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("finops_credential") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("finops_credential") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewCloudAccountWithCredentials) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewCloudAccountWithCredentials) UnmarshalBinary(b []byte) error { - var res NewCloudAccountWithCredentials - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_cloud_cost_management_account.go b/client/models/new_cloud_cost_management_account.go deleted file mode 100644 index 51c48b9cd..000000000 --- a/client/models/new_cloud_cost_management_account.go +++ /dev/null @@ -1,150 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewCloudCostManagementAccount Create CloudCostManagementAccount -// -// Create a new Cloud Cost Management account to connect CP. -// If a canonical is missing, the one from credential will be applied -// -// swagger:model NewCloudCostManagementAccount -type NewCloudCostManagementAccount struct { - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // external backend - // Required: true - ExternalBackend *NewExternalBackend `json:"external_backend"` - - // A user-defined name for the account - Name string `json:"name,omitempty"` -} - -// Validate validates this new cloud cost management account -func (m *NewCloudCostManagementAccount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateExternalBackend(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewCloudCostManagementAccount) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewCloudCostManagementAccount) validateExternalBackend(formats strfmt.Registry) error { - - if err := validate.Required("external_backend", "body", m.ExternalBackend); err != nil { - return err - } - - if m.ExternalBackend != nil { - if err := m.ExternalBackend.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("external_backend") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("external_backend") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this new cloud cost management account based on the context it is used -func (m *NewCloudCostManagementAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateExternalBackend(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewCloudCostManagementAccount) contextValidateExternalBackend(ctx context.Context, formats strfmt.Registry) error { - - if m.ExternalBackend != nil { - - if err := m.ExternalBackend.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("external_backend") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("external_backend") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewCloudCostManagementAccount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewCloudCostManagementAccount) UnmarshalBinary(b []byte) error { - var res NewCloudCostManagementAccount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_component.go b/client/models/new_component.go deleted file mode 100644 index dbc8bbde0..000000000 --- a/client/models/new_component.go +++ /dev/null @@ -1,175 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewComponent New Component -// -// The entity which represents the information of a new component. -// -// swagger:model NewComponent -type NewComponent struct { - - // canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$ - Canonical string `json:"canonical,omitempty"` - - // cloud provider canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CloudProviderCanonical string `json:"cloud_provider_canonical,omitempty"` - - // description - Description string `json:"description,omitempty"` - - // name - // Required: true - // Min Length: 1 - Name *string `json:"name"` - - // It's the ref of the Stack, like 'cycloidio:stack-magento' - // Required: true - ServiceCatalogRef *string `json:"service_catalog_ref"` - - // service catalog source version id - // Minimum: 1 - ServiceCatalogSourceVersionID uint32 `json:"service_catalog_source_version_id,omitempty"` -} - -// Validate validates this new component -func (m *NewComponent) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProviderCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalogRef(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalogSourceVersionID(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewComponent) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$`); err != nil { - return err - } - - return nil -} - -func (m *NewComponent) validateCloudProviderCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.CloudProviderCanonical) { // not required - return nil - } - - if err := validate.MinLength("cloud_provider_canonical", "body", m.CloudProviderCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("cloud_provider_canonical", "body", m.CloudProviderCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("cloud_provider_canonical", "body", m.CloudProviderCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewComponent) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - return nil -} - -func (m *NewComponent) validateServiceCatalogRef(formats strfmt.Registry) error { - - if err := validate.Required("service_catalog_ref", "body", m.ServiceCatalogRef); err != nil { - return err - } - - return nil -} - -func (m *NewComponent) validateServiceCatalogSourceVersionID(formats strfmt.Registry) error { - if swag.IsZero(m.ServiceCatalogSourceVersionID) { // not required - return nil - } - - if err := validate.MinimumUint("service_catalog_source_version_id", "body", uint64(m.ServiceCatalogSourceVersionID), 1, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new component based on context it is used -func (m *NewComponent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewComponent) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewComponent) UnmarshalBinary(b []byte) error { - var res NewComponent - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_config_repository.go b/client/models/new_config_repository.go deleted file mode 100644 index d1fc319c8..000000000 --- a/client/models/new_config_repository.go +++ /dev/null @@ -1,186 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewConfigRepository NewConfigRepository -// -// swagger:model NewConfigRepository -type NewConfigRepository struct { - - // branch - // Required: true - Branch *string `json:"branch"` - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // credential canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical *string `json:"credential_canonical"` - - // default - // Required: true - Default *bool `json:"default"` - - // name - // Required: true - Name *string `json:"name"` - - // url - // Required: true - // Pattern: ^((/|~)[^/]*)+.(\.git)|(([\w\]+@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(/)? - URL *string `json:"url"` -} - -// Validate validates this new config repository -func (m *NewConfigRepository) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBranch(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDefault(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewConfigRepository) validateBranch(formats strfmt.Registry) error { - - if err := validate.Required("branch", "body", m.Branch); err != nil { - return err - } - - return nil -} - -func (m *NewConfigRepository) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewConfigRepository) validateCredentialCanonical(formats strfmt.Registry) error { - - if err := validate.Required("credential_canonical", "body", m.CredentialCanonical); err != nil { - return err - } - - if err := validate.MinLength("credential_canonical", "body", *m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", *m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", *m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewConfigRepository) validateDefault(formats strfmt.Registry) error { - - if err := validate.Required("default", "body", m.Default); err != nil { - return err - } - - return nil -} - -func (m *NewConfigRepository) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *NewConfigRepository) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - if err := validate.Pattern("url", "body", *m.URL, `^((/|~)[^/]*)+.(\.git)|(([\w\]+@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(/)?`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new config repository based on context it is used -func (m *NewConfigRepository) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewConfigRepository) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewConfigRepository) UnmarshalBinary(b []byte) error { - var res NewConfigRepository - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_credential.go b/client/models/new_credential.go deleted file mode 100644 index 3b050763b..000000000 --- a/client/models/new_credential.go +++ /dev/null @@ -1,271 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewCredential Credential -// -// # Represents the Credential -// -// swagger:model NewCredential -type NewCredential struct { - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // description - Description string `json:"description,omitempty"` - - // name - // Required: true - Name *string `json:"name"` - - // User canonical that owns this credential. If omitted then the person creating this - // credential will be assigned as owner. When a user is the owner of a credential he has - // all the permissions on it. - // - Owner string `json:"owner,omitempty"` - - // path - // Required: true - // Pattern: [a-zA-z0-9_\-./] - Path *string `json:"path"` - - // raw - // Required: true - Raw *CredentialRaw `json:"raw"` - - // type - // Required: true - // Enum: ["ssh","aws","custom","azure","azure_storage","gcp","basic_auth","elasticsearch","swift","vmware"] - Type *string `json:"type"` -} - -// Validate validates this new credential -func (m *NewCredential) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePath(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRaw(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewCredential) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewCredential) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *NewCredential) validatePath(formats strfmt.Registry) error { - - if err := validate.Required("path", "body", m.Path); err != nil { - return err - } - - if err := validate.Pattern("path", "body", *m.Path, `[a-zA-z0-9_\-./]`); err != nil { - return err - } - - return nil -} - -func (m *NewCredential) validateRaw(formats strfmt.Registry) error { - - if err := validate.Required("raw", "body", m.Raw); err != nil { - return err - } - - if m.Raw != nil { - if err := m.Raw.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("raw") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("raw") - } - - return err - } - } - - return nil -} - -var newCredentialTypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["ssh","aws","custom","azure","azure_storage","gcp","basic_auth","elasticsearch","swift","vmware"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - newCredentialTypeTypePropEnum = append(newCredentialTypeTypePropEnum, v) - } -} - -const ( - - // NewCredentialTypeSSH captures enum value "ssh" - NewCredentialTypeSSH string = "ssh" - - // NewCredentialTypeAws captures enum value "aws" - NewCredentialTypeAws string = "aws" - - // NewCredentialTypeCustom captures enum value "custom" - NewCredentialTypeCustom string = "custom" - - // NewCredentialTypeAzure captures enum value "azure" - NewCredentialTypeAzure string = "azure" - - // NewCredentialTypeAzureStorage captures enum value "azure_storage" - NewCredentialTypeAzureStorage string = "azure_storage" - - // NewCredentialTypeGcp captures enum value "gcp" - NewCredentialTypeGcp string = "gcp" - - // NewCredentialTypeBasicAuth captures enum value "basic_auth" - NewCredentialTypeBasicAuth string = "basic_auth" - - // NewCredentialTypeElasticsearch captures enum value "elasticsearch" - NewCredentialTypeElasticsearch string = "elasticsearch" - - // NewCredentialTypeSwift captures enum value "swift" - NewCredentialTypeSwift string = "swift" - - // NewCredentialTypeVmware captures enum value "vmware" - NewCredentialTypeVmware string = "vmware" -) - -// prop value enum -func (m *NewCredential) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, newCredentialTypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NewCredential) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this new credential based on the context it is used -func (m *NewCredential) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateRaw(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewCredential) contextValidateRaw(ctx context.Context, formats strfmt.Registry) error { - - if m.Raw != nil { - - if err := m.Raw.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("raw") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("raw") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewCredential) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewCredential) UnmarshalBinary(b []byte) error { - var res NewCredential - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_environment.go b/client/models/new_environment.go deleted file mode 100644 index 0064b2b18..000000000 --- a/client/models/new_environment.go +++ /dev/null @@ -1,258 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewEnvironment NewEnvironment -// -// # Represent an entity necessary for environment creation -// -// swagger:model NewEnvironment -type NewEnvironment struct { - - // canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$ - Canonical string `json:"canonical,omitempty"` - - // Canonicals of cloud accounts to link. Omit or set to empty array to unlink all. - CloudAccountCanonicals []string `json:"cloud_account_canonicals"` - - // Optional description of the environment - // Max Length: 1000 - Description string `json:"description,omitempty"` - - // name - // Required: true - // Max Length: 100 - // Min Length: 1 - Name *string `json:"name"` - - // User canonical that owns this environment. If omitted then the person - // creating this environment will be assigned as owner. When a user is the - // owner of an environment it has all the permissions on it. - // - Owner string `json:"owner,omitempty"` - - // type - // Example: production - // Required: true - Type *string `json:"type"` - - // Environment variables to attach to the new environment. Keys must not contain dots and must include at least one alphanumeric character. Omit or pass an empty array to create the environment without variables. - Variables []*EnvironmentVariableItem `json:"variables"` -} - -// Validate validates this new environment -func (m *NewEnvironment) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudAccountCanonicals(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVariables(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewEnvironment) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$`); err != nil { - return err - } - - return nil -} - -func (m *NewEnvironment) validateCloudAccountCanonicals(formats strfmt.Registry) error { - if swag.IsZero(m.CloudAccountCanonicals) { // not required - return nil - } - - for i := 0; i < len(m.CloudAccountCanonicals); i++ { - - if err := validate.MinLength("cloud_account_canonicals"+"."+strconv.Itoa(i), "body", m.CloudAccountCanonicals[i], 3); err != nil { - return err - } - - if err := validate.MaxLength("cloud_account_canonicals"+"."+strconv.Itoa(i), "body", m.CloudAccountCanonicals[i], 100); err != nil { - return err - } - - } - - return nil -} - -func (m *NewEnvironment) validateDescription(formats strfmt.Registry) error { - if swag.IsZero(m.Description) { // not required - return nil - } - - if err := validate.MaxLength("description", "body", m.Description, 1000); err != nil { - return err - } - - return nil -} - -func (m *NewEnvironment) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 100); err != nil { - return err - } - - return nil -} - -func (m *NewEnvironment) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - return nil -} - -func (m *NewEnvironment) validateVariables(formats strfmt.Registry) error { - if swag.IsZero(m.Variables) { // not required - return nil - } - - for i := 0; i < len(m.Variables); i++ { - if swag.IsZero(m.Variables[i]) { // not required - continue - } - - if m.Variables[i] != nil { - if err := m.Variables[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("variables" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("variables" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this new environment based on the context it is used -func (m *NewEnvironment) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateVariables(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewEnvironment) contextValidateVariables(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Variables); i++ { - - if m.Variables[i] != nil { - - if swag.IsZero(m.Variables[i]) { // not required - return nil - } - - if err := m.Variables[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("variables" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("variables" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewEnvironment) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewEnvironment) UnmarshalBinary(b []byte) error { - var res NewEnvironment - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_environment_type.go b/client/models/new_environment_type.go deleted file mode 100644 index 3d042b3f7..000000000 --- a/client/models/new_environment_type.go +++ /dev/null @@ -1,132 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewEnvironmentType New Environment Type -// -// # Represent an entity necessary for environment type creation -// -// swagger:model NewEnvironmentType -type NewEnvironmentType struct { - - // canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-z]+(?:[\da-z\-._]+[\da-z]|[\da-z])$ - Canonical string `json:"canonical,omitempty"` - - // Color associated with this environment type - // Required: true - // Max Length: 64 - Color *string `json:"color"` - - // name - // Required: true - // Max Length: 255 - // Min Length: 1 - Name *string `json:"name"` -} - -// Validate validates this new environment type -func (m *NewEnvironmentType) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateColor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewEnvironmentType) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[\da-z]+(?:[\da-z\-._]+[\da-z]|[\da-z])$`); err != nil { - return err - } - - return nil -} - -func (m *NewEnvironmentType) validateColor(formats strfmt.Registry) error { - - if err := validate.Required("color", "body", m.Color); err != nil { - return err - } - - if err := validate.MaxLength("color", "body", *m.Color, 64); err != nil { - return err - } - - return nil -} - -func (m *NewEnvironmentType) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 255); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new environment type based on context it is used -func (m *NewEnvironmentType) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewEnvironmentType) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewEnvironmentType) UnmarshalBinary(b []byte) error { - var res NewEnvironmentType - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_event.go b/client/models/new_event.go deleted file mode 100644 index 287a38ec2..000000000 --- a/client/models/new_event.go +++ /dev/null @@ -1,343 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewEvent A new event -// -// A new event to register in the Cycloid platform. -// -// swagger:model NewEvent -type NewEvent struct { - - // The HTML color associated to the event. The valid colors are the ones listed in the CSS 2 specification: https://www.w3.org/TR/CSS2/syndata.html#value-def-color. Only the keyword are accepted, the hexadecimal values are not valid. - // Max Length: 20 - // Min Length: 3 - // Pattern: [a-z]+ - Color string `json:"color,omitempty"` - - // [A Font Awesome class name](https://fontawesome.com/icons) - // Min Length: 3 - Icon string `json:"icon,omitempty"` - - // The message associated to the event. - // Required: true - // Min Length: 1 - Message *string `json:"message"` - - // tThe severity associated to the event. - // Required: true - // Enum: ["info","warn","err","crit"] - Severity *string `json:"severity"` - - // The list of tags associated to the event. - // Required: true - Tags []*Tag `json:"tags"` - - // The title of the event. - // Required: true - // Min Length: 1 - Title *string `json:"title"` - - // The type of the event - // Required: true - // Enum: ["Cycloid","AWS","Monitoring","Custom"] - Type *string `json:"type"` -} - -// Validate validates this new event -func (m *NewEvent) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateColor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIcon(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSeverity(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTags(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTitle(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewEvent) validateColor(formats strfmt.Registry) error { - if swag.IsZero(m.Color) { // not required - return nil - } - - if err := validate.MinLength("color", "body", m.Color, 3); err != nil { - return err - } - - if err := validate.MaxLength("color", "body", m.Color, 20); err != nil { - return err - } - - if err := validate.Pattern("color", "body", m.Color, `[a-z]+`); err != nil { - return err - } - - return nil -} - -func (m *NewEvent) validateIcon(formats strfmt.Registry) error { - if swag.IsZero(m.Icon) { // not required - return nil - } - - if err := validate.MinLength("icon", "body", m.Icon, 3); err != nil { - return err - } - - return nil -} - -func (m *NewEvent) validateMessage(formats strfmt.Registry) error { - - if err := validate.Required("message", "body", m.Message); err != nil { - return err - } - - if err := validate.MinLength("message", "body", *m.Message, 1); err != nil { - return err - } - - return nil -} - -var newEventTypeSeverityPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["info","warn","err","crit"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - newEventTypeSeverityPropEnum = append(newEventTypeSeverityPropEnum, v) - } -} - -const ( - - // NewEventSeverityInfo captures enum value "info" - NewEventSeverityInfo string = "info" - - // NewEventSeverityWarn captures enum value "warn" - NewEventSeverityWarn string = "warn" - - // NewEventSeverityErr captures enum value "err" - NewEventSeverityErr string = "err" - - // NewEventSeverityCrit captures enum value "crit" - NewEventSeverityCrit string = "crit" -) - -// prop value enum -func (m *NewEvent) validateSeverityEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, newEventTypeSeverityPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NewEvent) validateSeverity(formats strfmt.Registry) error { - - if err := validate.Required("severity", "body", m.Severity); err != nil { - return err - } - - // value enum - if err := m.validateSeverityEnum("severity", "body", *m.Severity); err != nil { - return err - } - - return nil -} - -func (m *NewEvent) validateTags(formats strfmt.Registry) error { - - if err := validate.Required("tags", "body", m.Tags); err != nil { - return err - } - - for i := 0; i < len(m.Tags); i++ { - if swag.IsZero(m.Tags[i]) { // not required - continue - } - - if m.Tags[i] != nil { - if err := m.Tags[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("tags" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("tags" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *NewEvent) validateTitle(formats strfmt.Registry) error { - - if err := validate.Required("title", "body", m.Title); err != nil { - return err - } - - if err := validate.MinLength("title", "body", *m.Title, 1); err != nil { - return err - } - - return nil -} - -var newEventTypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["Cycloid","AWS","Monitoring","Custom"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - newEventTypeTypePropEnum = append(newEventTypeTypePropEnum, v) - } -} - -const ( - - // NewEventTypeCycloid captures enum value "Cycloid" - NewEventTypeCycloid string = "Cycloid" - - // NewEventTypeAWS captures enum value "AWS" - NewEventTypeAWS string = "AWS" - - // NewEventTypeMonitoring captures enum value "Monitoring" - NewEventTypeMonitoring string = "Monitoring" - - // NewEventTypeCustom captures enum value "Custom" - NewEventTypeCustom string = "Custom" -) - -// prop value enum -func (m *NewEvent) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, newEventTypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NewEvent) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this new event based on the context it is used -func (m *NewEvent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateTags(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewEvent) contextValidateTags(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Tags); i++ { - - if m.Tags[i] != nil { - - if swag.IsZero(m.Tags[i]) { // not required - return nil - } - - if err := m.Tags[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("tags" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("tags" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewEvent) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewEvent) UnmarshalBinary(b []byte) error { - var res NewEvent - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_external_backend.go b/client/models/new_external_backend.go deleted file mode 100644 index 893516c23..000000000 --- a/client/models/new_external_backend.go +++ /dev/null @@ -1,409 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - stderrors "errors" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewExternalBackend New External backend -// -// An external backend contains the configuration needed in order to be plugged into the Cycloid system. A backend is a general purpose concept, but Cycloid specifies which ones are supported and the list of those which are supported for every concrete feature. -// -// swagger:model NewExternalBackend -type NewExternalBackend struct { - - // component canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$ - ComponentCanonical string `json:"component_canonical,omitempty"` - - configurationField ExternalBackendConfiguration - - // The type of the credential must be one of: ["aws", "azure_storage", "elasticsearch", "gcp", "swift", "vmware"] - // - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical string `json:"credential_canonical,omitempty"` - - // Will mark this EB as default for the specific purpose - Default bool `json:"default,omitempty"` - - // environment canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$ - EnvironmentCanonical string `json:"environment_canonical,omitempty"` - - // project canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - ProjectCanonical string `json:"project_canonical,omitempty"` - - // purpose - // Required: true - // Enum: ["events","logs","remote_tfstate","cost_explorer"] - Purpose *string `json:"purpose"` -} - -// Configuration gets the configuration of this base type -func (m *NewExternalBackend) Configuration() ExternalBackendConfiguration { - return m.configurationField -} - -// SetConfiguration sets the configuration of this base type -func (m *NewExternalBackend) SetConfiguration(val ExternalBackendConfiguration) { - m.configurationField = val -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *NewExternalBackend) UnmarshalJSON(raw []byte) error { - var data struct { - ComponentCanonical string `json:"component_canonical,omitempty"` - - Configuration json.RawMessage `json:"configuration"` - - CredentialCanonical string `json:"credential_canonical,omitempty"` - - Default bool `json:"default,omitempty"` - - EnvironmentCanonical string `json:"environment_canonical,omitempty"` - - ProjectCanonical string `json:"project_canonical,omitempty"` - - Purpose *string `json:"purpose"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - propConfiguration, err := UnmarshalExternalBackendConfiguration(bytes.NewBuffer(data.Configuration), runtime.JSONConsumer()) - if err != nil && !stderrors.Is(err, io.EOF) { - return err - } - - var result NewExternalBackend - - // component_canonical - result.ComponentCanonical = data.ComponentCanonical - - // configuration - result.configurationField = propConfiguration - - // credential_canonical - result.CredentialCanonical = data.CredentialCanonical - - // default - result.Default = data.Default - - // environment_canonical - result.EnvironmentCanonical = data.EnvironmentCanonical - - // project_canonical - result.ProjectCanonical = data.ProjectCanonical - - // purpose - result.Purpose = data.Purpose - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m NewExternalBackend) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - ComponentCanonical string `json:"component_canonical,omitempty"` - - CredentialCanonical string `json:"credential_canonical,omitempty"` - - Default bool `json:"default,omitempty"` - - EnvironmentCanonical string `json:"environment_canonical,omitempty"` - - ProjectCanonical string `json:"project_canonical,omitempty"` - - Purpose *string `json:"purpose"` - }{ - - ComponentCanonical: m.ComponentCanonical, - - CredentialCanonical: m.CredentialCanonical, - - Default: m.Default, - - EnvironmentCanonical: m.EnvironmentCanonical, - - ProjectCanonical: m.ProjectCanonical, - - Purpose: m.Purpose, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Configuration ExternalBackendConfiguration `json:"configuration"` - }{ - - Configuration: m.configurationField, - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this new external backend -func (m *NewExternalBackend) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateComponentCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateConfiguration(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironmentCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjectCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePurpose(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewExternalBackend) validateComponentCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ComponentCanonical) { // not required - return nil - } - - if err := validate.MinLength("component_canonical", "body", m.ComponentCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("component_canonical", "body", m.ComponentCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("component_canonical", "body", m.ComponentCanonical, `^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$`); err != nil { - return err - } - - return nil -} - -func (m *NewExternalBackend) validateConfiguration(formats strfmt.Registry) error { - - if err := validate.Required("configuration", "body", m.Configuration()); err != nil { - return err - } - - if err := m.Configuration().Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -func (m *NewExternalBackend) validateCredentialCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.CredentialCanonical) { // not required - return nil - } - - if err := validate.MinLength("credential_canonical", "body", m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewExternalBackend) validateEnvironmentCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.EnvironmentCanonical) { // not required - return nil - } - - if err := validate.MinLength("environment_canonical", "body", m.EnvironmentCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("environment_canonical", "body", m.EnvironmentCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("environment_canonical", "body", m.EnvironmentCanonical, `^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$`); err != nil { - return err - } - - return nil -} - -func (m *NewExternalBackend) validateProjectCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ProjectCanonical) { // not required - return nil - } - - if err := validate.MinLength("project_canonical", "body", m.ProjectCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("project_canonical", "body", m.ProjectCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("project_canonical", "body", m.ProjectCanonical, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -var newExternalBackendTypePurposePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["events","logs","remote_tfstate","cost_explorer"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - newExternalBackendTypePurposePropEnum = append(newExternalBackendTypePurposePropEnum, v) - } -} - -const ( - - // NewExternalBackendPurposeEvents captures enum value "events" - NewExternalBackendPurposeEvents string = "events" - - // NewExternalBackendPurposeLogs captures enum value "logs" - NewExternalBackendPurposeLogs string = "logs" - - // NewExternalBackendPurposeRemoteTfstate captures enum value "remote_tfstate" - NewExternalBackendPurposeRemoteTfstate string = "remote_tfstate" - - // NewExternalBackendPurposeCostExplorer captures enum value "cost_explorer" - NewExternalBackendPurposeCostExplorer string = "cost_explorer" -) - -// prop value enum -func (m *NewExternalBackend) validatePurposeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, newExternalBackendTypePurposePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NewExternalBackend) validatePurpose(formats strfmt.Registry) error { - - if err := validate.Required("purpose", "body", m.Purpose); err != nil { - return err - } - - // value enum - if err := m.validatePurposeEnum("purpose", "body", *m.Purpose); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this new external backend based on the context it is used -func (m *NewExternalBackend) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateConfiguration(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewExternalBackend) contextValidateConfiguration(ctx context.Context, formats strfmt.Registry) error { - - if err := m.Configuration().ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewExternalBackend) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewExternalBackend) UnmarshalBinary(b []byte) error { - var res NewExternalBackend - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_infra_import.go b/client/models/new_infra_import.go deleted file mode 100644 index bb545150d..000000000 --- a/client/models/new_infra_import.go +++ /dev/null @@ -1,600 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - stderrors "errors" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewInfraImport New Infra Import -// -// # Entry that represents all the data needed to import a stack -// -// swagger:model NewInfraImport -type NewInfraImport struct { - - // component - Component *NewInfraImportComponent `json:"component,omitempty"` - - configurationField CloudProviderConfiguration - - // Credential that will be used to import from the provider - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical *string `json:"credential_canonical"` - - // environment - Environment *NewEnvironment `json:"environment,omitempty"` - - // external backend - ExternalBackend *NewInfraImportExternalBackend `json:"external_backend,omitempty"` - - // List of resources to import, these names are the ones on TF (ex: aws_instance). If not set then it means that all the resources will be imported - Include []string `json:"include"` - - // It's a KV where the key is the resource name and the value is the list (array) of attributes to include as part of the module - ModuleVariables map[string][]string `json:"module_variables,omitempty"` - - // project - Project *NewInfraImportProject `json:"project,omitempty"` - - // stack - // Required: true - Stack *NewServiceCatalog `json:"stack"` - - // List of tags to filter with format NAME:VALUE - Tags []string `json:"tags"` - - // List of resources to import via ID, those IDs are the ones documented on Terraform that are needed to Import. The format is 'aws_instance.ID' - Targets []string `json:"targets"` -} - -// Configuration gets the configuration of this base type -func (m *NewInfraImport) Configuration() CloudProviderConfiguration { - return m.configurationField -} - -// SetConfiguration sets the configuration of this base type -func (m *NewInfraImport) SetConfiguration(val CloudProviderConfiguration) { - m.configurationField = val -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *NewInfraImport) UnmarshalJSON(raw []byte) error { - var data struct { - Component *NewInfraImportComponent `json:"component,omitempty"` - - Configuration json.RawMessage `json:"configuration"` - - CredentialCanonical *string `json:"credential_canonical"` - - Environment *NewEnvironment `json:"environment,omitempty"` - - ExternalBackend *NewInfraImportExternalBackend `json:"external_backend,omitempty"` - - Include []string `json:"include"` - - ModuleVariables map[string][]string `json:"module_variables,omitempty"` - - Project *NewInfraImportProject `json:"project,omitempty"` - - Stack *NewServiceCatalog `json:"stack"` - - Tags []string `json:"tags"` - - Targets []string `json:"targets"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - propConfiguration, err := UnmarshalCloudProviderConfiguration(bytes.NewBuffer(data.Configuration), runtime.JSONConsumer()) - if err != nil && !stderrors.Is(err, io.EOF) { - return err - } - - var result NewInfraImport - - // component - result.Component = data.Component - - // configuration - result.configurationField = propConfiguration - - // credential_canonical - result.CredentialCanonical = data.CredentialCanonical - - // environment - result.Environment = data.Environment - - // external_backend - result.ExternalBackend = data.ExternalBackend - - // include - result.Include = data.Include - - // module_variables - result.ModuleVariables = data.ModuleVariables - - // project - result.Project = data.Project - - // stack - result.Stack = data.Stack - - // tags - result.Tags = data.Tags - - // targets - result.Targets = data.Targets - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m NewInfraImport) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - Component *NewInfraImportComponent `json:"component,omitempty"` - - CredentialCanonical *string `json:"credential_canonical"` - - Environment *NewEnvironment `json:"environment,omitempty"` - - ExternalBackend *NewInfraImportExternalBackend `json:"external_backend,omitempty"` - - Include []string `json:"include"` - - ModuleVariables map[string][]string `json:"module_variables,omitempty"` - - Project *NewInfraImportProject `json:"project,omitempty"` - - Stack *NewServiceCatalog `json:"stack"` - - Tags []string `json:"tags"` - - Targets []string `json:"targets"` - }{ - - Component: m.Component, - - CredentialCanonical: m.CredentialCanonical, - - Environment: m.Environment, - - ExternalBackend: m.ExternalBackend, - - Include: m.Include, - - ModuleVariables: m.ModuleVariables, - - Project: m.Project, - - Stack: m.Stack, - - Tags: m.Tags, - - Targets: m.Targets, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Configuration CloudProviderConfiguration `json:"configuration"` - }{ - - Configuration: m.configurationField, - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this new infra import -func (m *NewInfraImport) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateComponent(formats); err != nil { - res = append(res, err) - } - - if err := m.validateConfiguration(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironment(formats); err != nil { - res = append(res, err) - } - - if err := m.validateExternalBackend(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProject(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStack(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewInfraImport) validateComponent(formats strfmt.Registry) error { - if swag.IsZero(m.Component) { // not required - return nil - } - - if m.Component != nil { - if err := m.Component.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("component") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("component") - } - - return err - } - } - - return nil -} - -func (m *NewInfraImport) validateConfiguration(formats strfmt.Registry) error { - - if err := validate.Required("configuration", "body", m.Configuration()); err != nil { - return err - } - - if err := m.Configuration().Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -func (m *NewInfraImport) validateCredentialCanonical(formats strfmt.Registry) error { - - if err := validate.Required("credential_canonical", "body", m.CredentialCanonical); err != nil { - return err - } - - if err := validate.MinLength("credential_canonical", "body", *m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", *m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", *m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewInfraImport) validateEnvironment(formats strfmt.Registry) error { - if swag.IsZero(m.Environment) { // not required - return nil - } - - if m.Environment != nil { - if err := m.Environment.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment") - } - - return err - } - } - - return nil -} - -func (m *NewInfraImport) validateExternalBackend(formats strfmt.Registry) error { - if swag.IsZero(m.ExternalBackend) { // not required - return nil - } - - if m.ExternalBackend != nil { - if err := m.ExternalBackend.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("external_backend") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("external_backend") - } - - return err - } - } - - return nil -} - -func (m *NewInfraImport) validateProject(formats strfmt.Registry) error { - if swag.IsZero(m.Project) { // not required - return nil - } - - if m.Project != nil { - if err := m.Project.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project") - } - - return err - } - } - - return nil -} - -func (m *NewInfraImport) validateStack(formats strfmt.Registry) error { - - if err := validate.Required("stack", "body", m.Stack); err != nil { - return err - } - - if m.Stack != nil { - if err := m.Stack.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("stack") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("stack") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this new infra import based on the context it is used -func (m *NewInfraImport) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateComponent(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateConfiguration(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateEnvironment(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateExternalBackend(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateProject(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateStack(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewInfraImport) contextValidateComponent(ctx context.Context, formats strfmt.Registry) error { - - if m.Component != nil { - - if swag.IsZero(m.Component) { // not required - return nil - } - - if err := m.Component.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("component") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("component") - } - - return err - } - } - - return nil -} - -func (m *NewInfraImport) contextValidateConfiguration(ctx context.Context, formats strfmt.Registry) error { - - if err := m.Configuration().ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -func (m *NewInfraImport) contextValidateEnvironment(ctx context.Context, formats strfmt.Registry) error { - - if m.Environment != nil { - - if swag.IsZero(m.Environment) { // not required - return nil - } - - if err := m.Environment.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment") - } - - return err - } - } - - return nil -} - -func (m *NewInfraImport) contextValidateExternalBackend(ctx context.Context, formats strfmt.Registry) error { - - if m.ExternalBackend != nil { - - if swag.IsZero(m.ExternalBackend) { // not required - return nil - } - - if err := m.ExternalBackend.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("external_backend") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("external_backend") - } - - return err - } - } - - return nil -} - -func (m *NewInfraImport) contextValidateProject(ctx context.Context, formats strfmt.Registry) error { - - if m.Project != nil { - - if swag.IsZero(m.Project) { // not required - return nil - } - - if err := m.Project.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project") - } - - return err - } - } - - return nil -} - -func (m *NewInfraImport) contextValidateStack(ctx context.Context, formats strfmt.Registry) error { - - if m.Stack != nil { - - if err := m.Stack.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("stack") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("stack") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewInfraImport) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewInfraImport) UnmarshalBinary(b []byte) error { - var res NewInfraImport - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_infra_import_component.go b/client/models/new_infra_import_component.go deleted file mode 100644 index 645095c34..000000000 --- a/client/models/new_infra_import_component.go +++ /dev/null @@ -1,137 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewInfraImportComponent Create Component for the Infra Import -// -// The entity which represents the information of a new component. -// -// swagger:model NewInfraImportComponent -type NewInfraImportComponent struct { - - // canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$ - Canonical string `json:"canonical,omitempty"` - - // cloud provider canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CloudProviderCanonical *string `json:"cloud_provider_canonical"` - - // name - // Required: true - // Min Length: 1 - Name *string `json:"name"` -} - -// Validate validates this new infra import component -func (m *NewInfraImportComponent) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProviderCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewInfraImportComponent) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$`); err != nil { - return err - } - - return nil -} - -func (m *NewInfraImportComponent) validateCloudProviderCanonical(formats strfmt.Registry) error { - - if err := validate.Required("cloud_provider_canonical", "body", m.CloudProviderCanonical); err != nil { - return err - } - - if err := validate.MinLength("cloud_provider_canonical", "body", *m.CloudProviderCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("cloud_provider_canonical", "body", *m.CloudProviderCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("cloud_provider_canonical", "body", *m.CloudProviderCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewInfraImportComponent) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new infra import component based on context it is used -func (m *NewInfraImportComponent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewInfraImportComponent) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewInfraImportComponent) UnmarshalBinary(b []byte) error { - var res NewInfraImportComponent - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_infra_import_external_backend.go b/client/models/new_infra_import_external_backend.go deleted file mode 100644 index 6dc4aa3d1..000000000 --- a/client/models/new_infra_import_external_backend.go +++ /dev/null @@ -1,211 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - stderrors "errors" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewInfraImportExternalBackend New External backend -// -// An external backend contains the configuration needed in order to be plugged into the Cycloid system. A backend is a general purpose concept, but Cycloid specifies which ones are supported and the list of those which are supported for every concrete feature. -// -// swagger:model NewInfraImportExternalBackend -type NewInfraImportExternalBackend struct { - configurationField ExternalBackendConfiguration - - // credential canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical string `json:"credential_canonical,omitempty"` -} - -// Configuration gets the configuration of this base type -func (m *NewInfraImportExternalBackend) Configuration() ExternalBackendConfiguration { - return m.configurationField -} - -// SetConfiguration sets the configuration of this base type -func (m *NewInfraImportExternalBackend) SetConfiguration(val ExternalBackendConfiguration) { - m.configurationField = val -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *NewInfraImportExternalBackend) UnmarshalJSON(raw []byte) error { - var data struct { - Configuration json.RawMessage `json:"configuration"` - - CredentialCanonical string `json:"credential_canonical,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - propConfiguration, err := UnmarshalExternalBackendConfiguration(bytes.NewBuffer(data.Configuration), runtime.JSONConsumer()) - if err != nil && !stderrors.Is(err, io.EOF) { - return err - } - - var result NewInfraImportExternalBackend - - // configuration - result.configurationField = propConfiguration - - // credential_canonical - result.CredentialCanonical = data.CredentialCanonical - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m NewInfraImportExternalBackend) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - CredentialCanonical string `json:"credential_canonical,omitempty"` - }{ - - CredentialCanonical: m.CredentialCanonical, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Configuration ExternalBackendConfiguration `json:"configuration"` - }{ - - Configuration: m.configurationField, - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this new infra import external backend -func (m *NewInfraImportExternalBackend) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfiguration(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewInfraImportExternalBackend) validateConfiguration(formats strfmt.Registry) error { - - if err := validate.Required("configuration", "body", m.Configuration()); err != nil { - return err - } - - if err := m.Configuration().Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -func (m *NewInfraImportExternalBackend) validateCredentialCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.CredentialCanonical) { // not required - return nil - } - - if err := validate.MinLength("credential_canonical", "body", m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this new infra import external backend based on the context it is used -func (m *NewInfraImportExternalBackend) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateConfiguration(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewInfraImportExternalBackend) contextValidateConfiguration(ctx context.Context, formats strfmt.Registry) error { - - if err := m.Configuration().ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewInfraImportExternalBackend) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewInfraImportExternalBackend) UnmarshalBinary(b []byte) error { - var res NewInfraImportExternalBackend - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_infra_import_project.go b/client/models/new_infra_import_project.go deleted file mode 100644 index 6b56ad7cc..000000000 --- a/client/models/new_infra_import_project.go +++ /dev/null @@ -1,142 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewInfraImportProject Create Project for the Infra Import -// -// The entity which represents the information of a new project. -// -// swagger:model NewInfraImportProject -type NewInfraImportProject struct { - - // canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - Canonical string `json:"canonical,omitempty"` - - // config repository canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - ConfigRepositoryCanonical *string `json:"config_repository_canonical"` - - // A description regarding the project to help identify/remember details, - // implementation, purpose, etc. - // - Description string `json:"description,omitempty"` - - // name - // Required: true - // Min Length: 1 - Name *string `json:"name"` -} - -// Validate validates this new infra import project -func (m *NewInfraImportProject) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateConfigRepositoryCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewInfraImportProject) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -func (m *NewInfraImportProject) validateConfigRepositoryCanonical(formats strfmt.Registry) error { - - if err := validate.Required("config_repository_canonical", "body", m.ConfigRepositoryCanonical); err != nil { - return err - } - - if err := validate.MinLength("config_repository_canonical", "body", *m.ConfigRepositoryCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("config_repository_canonical", "body", *m.ConfigRepositoryCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("config_repository_canonical", "body", *m.ConfigRepositoryCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewInfraImportProject) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new infra import project based on context it is used -func (m *NewInfraImportProject) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewInfraImportProject) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewInfraImportProject) UnmarshalBinary(b []byte) error { - var res NewInfraImportProject - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_infra_policy.go b/client/models/new_infra_policy.go deleted file mode 100644 index e6d425ff1..000000000 --- a/client/models/new_infra_policy.go +++ /dev/null @@ -1,218 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewInfraPolicy Create InfraPolicy -// -// Create a new policy to control operations across infrastructure. -// -// swagger:model NewInfraPolicy -type NewInfraPolicy struct { - - // The body field is the code in plain text that defines the rules for the policy. - // Required: true - Body *string `json:"body"` - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // description - Description string `json:"description,omitempty"` - - // enabled - Enabled bool `json:"enabled,omitempty"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // User canonical that owns this InfraPolicy. When a user is the - // owner of an InfraPolicy it has all the permissions on it. - // - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Owner *string `json:"owner"` - - // severity - // Required: true - // Enum: ["critical","warning","advisory"] - Severity *string `json:"severity"` -} - -// Validate validates this new infra policy -func (m *NewInfraPolicy) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBody(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSeverity(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewInfraPolicy) validateBody(formats strfmt.Registry) error { - - if err := validate.Required("body", "body", m.Body); err != nil { - return err - } - - return nil -} - -func (m *NewInfraPolicy) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewInfraPolicy) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *NewInfraPolicy) validateOwner(formats strfmt.Registry) error { - - if err := validate.Required("owner", "body", m.Owner); err != nil { - return err - } - - if err := validate.MinLength("owner", "body", *m.Owner, 3); err != nil { - return err - } - - if err := validate.MaxLength("owner", "body", *m.Owner, 100); err != nil { - return err - } - - if err := validate.Pattern("owner", "body", *m.Owner, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -var newInfraPolicyTypeSeverityPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["critical","warning","advisory"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - newInfraPolicyTypeSeverityPropEnum = append(newInfraPolicyTypeSeverityPropEnum, v) - } -} - -const ( - - // NewInfraPolicySeverityCritical captures enum value "critical" - NewInfraPolicySeverityCritical string = "critical" - - // NewInfraPolicySeverityWarning captures enum value "warning" - NewInfraPolicySeverityWarning string = "warning" - - // NewInfraPolicySeverityAdvisory captures enum value "advisory" - NewInfraPolicySeverityAdvisory string = "advisory" -) - -// prop value enum -func (m *NewInfraPolicy) validateSeverityEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, newInfraPolicyTypeSeverityPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NewInfraPolicy) validateSeverity(formats strfmt.Registry) error { - - if err := validate.Required("severity", "body", m.Severity); err != nil { - return err - } - - // value enum - if err := m.validateSeverityEnum("severity", "body", *m.Severity); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new infra policy based on context it is used -func (m *NewInfraPolicy) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewInfraPolicy) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewInfraPolicy) UnmarshalBinary(b []byte) error { - var res NewInfraPolicy - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_inventory_resource.go b/client/models/new_inventory_resource.go deleted file mode 100644 index 18376147f..000000000 --- a/client/models/new_inventory_resource.go +++ /dev/null @@ -1,186 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewInventoryResource New Inventory Resource -// -// # The Resource of the Inventory representing an element of your infrastructure -// -// swagger:model NewInventoryResource -type NewInventoryResource struct { - - // The amount of cpu cores that it has in units - // Minimum: 0 - CPU *uint64 `json:"cpu,omitempty"` - - // List of attributes (key value object) of the Resource, can be anything - // Example: {"another":"one","custom":"attribute"} - CustomAttributes any `json:"custom_attributes,omitempty"` - - // A way to distinguish and categorize resources - // Example: my-label - // Required: true - Label *string `json:"label"` - - // The amount of memory that it has in MB - // Minimum: 0 - Memory *uint64 `json:"memory,omitempty"` - - // The name of the resource - // Required: true - Name *string `json:"name"` - - // The provider of the created Resource - // Required: true - Provider *string `json:"provider"` - - // The amount of storage that it has in MB - // Minimum: 0 - Storage *uint64 `json:"storage,omitempty"` - - // The type of the resource - // Required: true - Type *string `json:"type"` -} - -// Validate validates this new inventory resource -func (m *NewInventoryResource) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCPU(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLabel(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMemory(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStorage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewInventoryResource) validateCPU(formats strfmt.Registry) error { - if swag.IsZero(m.CPU) { // not required - return nil - } - - if err := validate.MinimumUint("cpu", "body", *m.CPU, 0, false); err != nil { - return err - } - - return nil -} - -func (m *NewInventoryResource) validateLabel(formats strfmt.Registry) error { - - if err := validate.Required("label", "body", m.Label); err != nil { - return err - } - - return nil -} - -func (m *NewInventoryResource) validateMemory(formats strfmt.Registry) error { - if swag.IsZero(m.Memory) { // not required - return nil - } - - if err := validate.MinimumUint("memory", "body", *m.Memory, 0, false); err != nil { - return err - } - - return nil -} - -func (m *NewInventoryResource) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *NewInventoryResource) validateProvider(formats strfmt.Registry) error { - - if err := validate.Required("provider", "body", m.Provider); err != nil { - return err - } - - return nil -} - -func (m *NewInventoryResource) validateStorage(formats strfmt.Registry) error { - if swag.IsZero(m.Storage) { // not required - return nil - } - - if err := validate.MinimumUint("storage", "body", *m.Storage, 0, false); err != nil { - return err - } - - return nil -} - -func (m *NewInventoryResource) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new inventory resource based on context it is used -func (m *NewInventoryResource) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewInventoryResource) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewInventoryResource) UnmarshalBinary(b []byte) error { - var res NewInventoryResource - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_k_p_i.go b/client/models/new_k_p_i.go deleted file mode 100644 index b46410f31..000000000 --- a/client/models/new_k_p_i.go +++ /dev/null @@ -1,247 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewKPI New KPI -// -// # A KPI's configuration that needs to be saved -// -// swagger:model NewKPI -type NewKPI struct { - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // The config represent some extra parameters which are required for the configuration of certain KPIs. Please refer to the documentation for more details. - // - Config any `json:"config,omitempty"` - - // description - Description string `json:"description,omitempty"` - - // job name - JobName string `json:"job_name,omitempty"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // pipeline name - PipelineName string `json:"pipeline_name,omitempty"` - - // type - // Required: true - // Enum: ["build_avg_time","build_frequency","build_history","code_coverage","time_to_release"] - Type *string `json:"type"` - - // widget - // Required: true - // Enum: ["bars","stackbars","doughnut","history","line","pie","summary"] - Widget *string `json:"widget"` -} - -// Validate validates this new k p i -func (m *NewKPI) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateWidget(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewKPI) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewKPI) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -var newKPITypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["build_avg_time","build_frequency","build_history","code_coverage","time_to_release"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - newKPITypeTypePropEnum = append(newKPITypeTypePropEnum, v) - } -} - -const ( - - // NewKPITypeBuildAvgTime captures enum value "build_avg_time" - NewKPITypeBuildAvgTime string = "build_avg_time" - - // NewKPITypeBuildFrequency captures enum value "build_frequency" - NewKPITypeBuildFrequency string = "build_frequency" - - // NewKPITypeBuildHistory captures enum value "build_history" - NewKPITypeBuildHistory string = "build_history" - - // NewKPITypeCodeCoverage captures enum value "code_coverage" - NewKPITypeCodeCoverage string = "code_coverage" - - // NewKPITypeTimeToRelease captures enum value "time_to_release" - NewKPITypeTimeToRelease string = "time_to_release" -) - -// prop value enum -func (m *NewKPI) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, newKPITypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NewKPI) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -var newKPITypeWidgetPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["bars","stackbars","doughnut","history","line","pie","summary"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - newKPITypeWidgetPropEnum = append(newKPITypeWidgetPropEnum, v) - } -} - -const ( - - // NewKPIWidgetBars captures enum value "bars" - NewKPIWidgetBars string = "bars" - - // NewKPIWidgetStackbars captures enum value "stackbars" - NewKPIWidgetStackbars string = "stackbars" - - // NewKPIWidgetDoughnut captures enum value "doughnut" - NewKPIWidgetDoughnut string = "doughnut" - - // NewKPIWidgetHistory captures enum value "history" - NewKPIWidgetHistory string = "history" - - // NewKPIWidgetLine captures enum value "line" - NewKPIWidgetLine string = "line" - - // NewKPIWidgetPie captures enum value "pie" - NewKPIWidgetPie string = "pie" - - // NewKPIWidgetSummary captures enum value "summary" - NewKPIWidgetSummary string = "summary" -) - -// prop value enum -func (m *NewKPI) validateWidgetEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, newKPITypeWidgetPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NewKPI) validateWidget(formats strfmt.Registry) error { - - if err := validate.Required("widget", "body", m.Widget); err != nil { - return err - } - - // value enum - if err := m.validateWidgetEnum("widget", "body", *m.Widget); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new k p i based on context it is used -func (m *NewKPI) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewKPI) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewKPI) UnmarshalBinary(b []byte) error { - var res NewKPI - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_licence.go b/client/models/new_licence.go deleted file mode 100644 index 73c2e231f..000000000 --- a/client/models/new_licence.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewLicence Licence -// -// # Object containing licence parameters -// -// swagger:model NewLicence -type NewLicence struct { - - // Licence's key in the JWT format - // Required: true - Key *string `json:"key"` -} - -// Validate validates this new licence -func (m *NewLicence) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateKey(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewLicence) validateKey(formats strfmt.Registry) error { - - if err := validate.Required("key", "body", m.Key); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new licence based on context it is used -func (m *NewLicence) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewLicence) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewLicence) UnmarshalBinary(b []byte) error { - var res NewLicence - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_member_invitation.go b/client/models/new_member_invitation.go deleted file mode 100644 index b302dd630..000000000 --- a/client/models/new_member_invitation.go +++ /dev/null @@ -1,107 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewMemberInvitation Invite user -// -// Send an invitation to a user to something. Something can be to create an account, to join to an organization, to join to a team, etc. API operation determines the operation to perform. -// -// swagger:model NewMemberInvitation -type NewMemberInvitation struct { - - // Invite user by email - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` - - // The role of the member. - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - RoleCanonical *string `json:"role_canonical"` -} - -// Validate validates this new member invitation -func (m *NewMemberInvitation) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRoleCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewMemberInvitation) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *NewMemberInvitation) validateRoleCanonical(formats strfmt.Registry) error { - - if err := validate.Required("role_canonical", "body", m.RoleCanonical); err != nil { - return err - } - - if err := validate.MinLength("role_canonical", "body", *m.RoleCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("role_canonical", "body", *m.RoleCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("role_canonical", "body", *m.RoleCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new member invitation based on context it is used -func (m *NewMemberInvitation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewMemberInvitation) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewMemberInvitation) UnmarshalBinary(b []byte) error { - var res NewMemberInvitation - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_o_auth_user.go b/client/models/new_o_auth_user.go deleted file mode 100644 index 20a114892..000000000 --- a/client/models/new_o_auth_user.go +++ /dev/null @@ -1,269 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewOAuthUser User's OAuth information -// -// # The User OAuth information -// -// swagger:model NewOAuthUser -type NewOAuthUser struct { - - // Code of a country the user is from in alpha-2 format - // Pattern: ^[A-Z]{2}$ - CountryCode string `json:"country_code,omitempty"` - - // email - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` - - // User's email has been verified - EmailVerified bool `json:"email_verified,omitempty"` - - // full name - // Required: true - // Max Length: 255 - // Min Length: 2 - FullName *string `json:"full_name"` - - // The field is used when a user signup from an invitation to an organization. Giving the token, the created user will be automatically added to the organization. - // Min Length: 5 - InvitationToken string `json:"invitation_token,omitempty"` - - // User's preferred language - // Enum: ["en","fr","es"] - Locale string `json:"locale,omitempty"` - - // organization canonical - OrganizationCanonical string `json:"organization_canonical,omitempty"` - - // picture url - // Format: uri - PictureURL strfmt.URI `json:"picture_url,omitempty"` - - // social id - // Required: true - SocialID *string `json:"social_id"` - - // username - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Username string `json:"username,omitempty"` -} - -// Validate validates this new o auth user -func (m *NewOAuthUser) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCountryCode(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFullName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInvitationToken(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLocale(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePictureURL(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSocialID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUsername(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewOAuthUser) validateCountryCode(formats strfmt.Registry) error { - if swag.IsZero(m.CountryCode) { // not required - return nil - } - - if err := validate.Pattern("country_code", "body", m.CountryCode, `^[A-Z]{2}$`); err != nil { - return err - } - - return nil -} - -func (m *NewOAuthUser) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *NewOAuthUser) validateFullName(formats strfmt.Registry) error { - - if err := validate.Required("full_name", "body", m.FullName); err != nil { - return err - } - - if err := validate.MinLength("full_name", "body", *m.FullName, 2); err != nil { - return err - } - - if err := validate.MaxLength("full_name", "body", *m.FullName, 255); err != nil { - return err - } - - return nil -} - -func (m *NewOAuthUser) validateInvitationToken(formats strfmt.Registry) error { - if swag.IsZero(m.InvitationToken) { // not required - return nil - } - - if err := validate.MinLength("invitation_token", "body", m.InvitationToken, 5); err != nil { - return err - } - - return nil -} - -var newOAuthUserTypeLocalePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["en","fr","es"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - newOAuthUserTypeLocalePropEnum = append(newOAuthUserTypeLocalePropEnum, v) - } -} - -const ( - - // NewOAuthUserLocaleEn captures enum value "en" - NewOAuthUserLocaleEn string = "en" - - // NewOAuthUserLocaleFr captures enum value "fr" - NewOAuthUserLocaleFr string = "fr" - - // NewOAuthUserLocaleEs captures enum value "es" - NewOAuthUserLocaleEs string = "es" -) - -// prop value enum -func (m *NewOAuthUser) validateLocaleEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, newOAuthUserTypeLocalePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NewOAuthUser) validateLocale(formats strfmt.Registry) error { - if swag.IsZero(m.Locale) { // not required - return nil - } - - // value enum - if err := m.validateLocaleEnum("locale", "body", m.Locale); err != nil { - return err - } - - return nil -} - -func (m *NewOAuthUser) validatePictureURL(formats strfmt.Registry) error { - if swag.IsZero(m.PictureURL) { // not required - return nil - } - - if err := validate.FormatOf("picture_url", "body", "uri", m.PictureURL.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *NewOAuthUser) validateSocialID(formats strfmt.Registry) error { - - if err := validate.Required("social_id", "body", m.SocialID); err != nil { - return err - } - - return nil -} - -func (m *NewOAuthUser) validateUsername(formats strfmt.Registry) error { - if swag.IsZero(m.Username) { // not required - return nil - } - - if err := validate.MinLength("username", "body", m.Username, 3); err != nil { - return err - } - - if err := validate.MaxLength("username", "body", m.Username, 100); err != nil { - return err - } - - if err := validate.Pattern("username", "body", m.Username, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new o auth user based on context it is used -func (m *NewOAuthUser) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewOAuthUser) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewOAuthUser) UnmarshalBinary(b []byte) error { - var res NewOAuthUser - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_organization.go b/client/models/new_organization.go deleted file mode 100644 index 6e8411ffe..000000000 --- a/client/models/new_organization.go +++ /dev/null @@ -1,105 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewOrganization Create Organization -// -// The entity which represents a new organization to create in the application. -// -// swagger:model NewOrganization -type NewOrganization struct { - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` -} - -// Validate validates this new organization -func (m *NewOrganization) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewOrganization) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewOrganization) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new organization based on context it is used -func (m *NewOrganization) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewOrganization) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewOrganization) UnmarshalBinary(b []byte) error { - var res NewOrganization - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_pipeline.go b/client/models/new_pipeline.go deleted file mode 100644 index 81e9699eb..000000000 --- a/client/models/new_pipeline.go +++ /dev/null @@ -1,94 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewPipeline Create Pipeline -// -// The entity which represents a new pipeline to create in the application. -// -// swagger:model NewPipeline -type NewPipeline struct { - - // Validate credentials manager variables in the pipeline config. - CheckCredentials bool `json:"check_credentials,omitempty"` - - // passed config - PassedConfig string `json:"passed_config,omitempty"` - - // pipeline name - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-._]+[a-z0-9]+$ - PipelineName *string `json:"pipeline_name"` - - // yaml vars - YamlVars string `json:"yaml_vars,omitempty"` -} - -// Validate validates this new pipeline -func (m *NewPipeline) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validatePipelineName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewPipeline) validatePipelineName(formats strfmt.Registry) error { - - if err := validate.Required("pipeline_name", "body", m.PipelineName); err != nil { - return err - } - - if err := validate.MinLength("pipeline_name", "body", *m.PipelineName, 3); err != nil { - return err - } - - if err := validate.MaxLength("pipeline_name", "body", *m.PipelineName, 100); err != nil { - return err - } - - if err := validate.Pattern("pipeline_name", "body", *m.PipelineName, `^[a-z0-9]+[a-z0-9\-._]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new pipeline based on context it is used -func (m *NewPipeline) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewPipeline) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewPipeline) UnmarshalBinary(b []byte) error { - var res NewPipeline - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_plugin.go b/client/models/new_plugin.go deleted file mode 100644 index b4250f149..000000000 --- a/client/models/new_plugin.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewPlugin New Plugin -// -// # The Plugin data needed to create it -// -// swagger:model NewPlugin -type NewPlugin struct { - - // Name assigned to the Repository - // Required: true - Name *string `json:"name"` -} - -// Validate validates this new plugin -func (m *NewPlugin) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewPlugin) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new plugin based on context it is used -func (m *NewPlugin) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewPlugin) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewPlugin) UnmarshalBinary(b []byte) error { - var res NewPlugin - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_plugin_install.go b/client/models/new_plugin_install.go deleted file mode 100644 index 0b54dbf21..000000000 --- a/client/models/new_plugin_install.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewPluginInstall New Plugin Install -// -// # The data needed to create a Plugin Install -// -// swagger:model NewPluginInstall -type NewPluginInstall struct { - - // Stack Forms syntax configuration - // Required: true - Configuration map[string]string `json:"configuration"` -} - -// Validate validates this new plugin install -func (m *NewPluginInstall) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfiguration(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewPluginInstall) validateConfiguration(formats strfmt.Registry) error { - - if err := validate.Required("configuration", "body", m.Configuration); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new plugin install based on context it is used -func (m *NewPluginInstall) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewPluginInstall) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewPluginInstall) UnmarshalBinary(b []byte) error { - var res NewPluginInstall - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_plugin_manager.go b/client/models/new_plugin_manager.go deleted file mode 100644 index bc63e46ae..000000000 --- a/client/models/new_plugin_manager.go +++ /dev/null @@ -1,95 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewPluginManager New Plugin Manager Invite -// -// # The Plugin Manager Invite data needed to create it -// -// swagger:model NewPluginManager -type NewPluginManager struct { - - // When true, performs full registration (requires authentication) - AutoRegister bool `json:"auto_register,omitempty"` - - // Name assigned to the Plugin Manager Instance - // Required: true - Name *string `json:"name"` - - // URL of the Plugin Version - // Required: true - // Format: uri - URL *strfmt.URI `json:"url"` -} - -// Validate validates this new plugin manager -func (m *NewPluginManager) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewPluginManager) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *NewPluginManager) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - if err := validate.FormatOf("url", "body", "uri", m.URL.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new plugin manager based on context it is used -func (m *NewPluginManager) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewPluginManager) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewPluginManager) UnmarshalBinary(b []byte) error { - var res NewPluginManager - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_plugin_registry.go b/client/models/new_plugin_registry.go deleted file mode 100644 index 04e6a5ad2..000000000 --- a/client/models/new_plugin_registry.go +++ /dev/null @@ -1,92 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewPluginRegistry New Plugin Registry -// -// # The Plugin Registry data needed to create it -// -// swagger:model NewPluginRegistry -type NewPluginRegistry struct { - - // Name assigned to the Repository - // Required: true - Name *string `json:"name"` - - // URL of the Plugin Registry - // Required: true - // Format: uri - URL *strfmt.URI `json:"url"` -} - -// Validate validates this new plugin registry -func (m *NewPluginRegistry) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewPluginRegistry) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *NewPluginRegistry) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - if err := validate.FormatOf("url", "body", "uri", m.URL.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new plugin registry based on context it is used -func (m *NewPluginRegistry) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewPluginRegistry) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewPluginRegistry) UnmarshalBinary(b []byte) error { - var res NewPluginRegistry - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_plugin_version.go b/client/models/new_plugin_version.go deleted file mode 100644 index 1c546114f..000000000 --- a/client/models/new_plugin_version.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewPluginVersion New Plugin -// -// # The Plugin data needed to create it -// -// swagger:model NewPluginVersion -type NewPluginVersion struct { - - // URL of the Plugin Version - // Required: true - URL *string `json:"url"` -} - -// Validate validates this new plugin version -func (m *NewPluginVersion) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewPluginVersion) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new plugin version based on context it is used -func (m *NewPluginVersion) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewPluginVersion) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewPluginVersion) UnmarshalBinary(b []byte) error { - var res NewPluginVersion - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_project.go b/client/models/new_project.go deleted file mode 100644 index e5a561f6a..000000000 --- a/client/models/new_project.go +++ /dev/null @@ -1,188 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewProject Create Project -// -// The entity which represents the information of a new project. -// -// swagger:model NewProject -type NewProject struct { - - // canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - Canonical string `json:"canonical,omitempty"` - - // color - // Max Length: 64 - Color string `json:"color,omitempty"` - - // config repository canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - ConfigRepositoryCanonical *string `json:"config_repository_canonical"` - - // A description regarding the project to help identify/remember details, - // implementation, purpose, etc. - // - Description string `json:"description,omitempty"` - - // icon - // Max Length: 64 - Icon string `json:"icon,omitempty"` - - // name - // Required: true - // Min Length: 1 - Name *string `json:"name"` - - // User canonical that owns this project. If omitted then the person - // creating this project will be assigned as owner. When a user is the - // owner of a project it has all the permissions on it. - // - Owner string `json:"owner,omitempty"` -} - -// Validate validates this new project -func (m *NewProject) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateColor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateConfigRepositoryCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIcon(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewProject) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -func (m *NewProject) validateColor(formats strfmt.Registry) error { - if swag.IsZero(m.Color) { // not required - return nil - } - - if err := validate.MaxLength("color", "body", m.Color, 64); err != nil { - return err - } - - return nil -} - -func (m *NewProject) validateConfigRepositoryCanonical(formats strfmt.Registry) error { - - if err := validate.Required("config_repository_canonical", "body", m.ConfigRepositoryCanonical); err != nil { - return err - } - - if err := validate.MinLength("config_repository_canonical", "body", *m.ConfigRepositoryCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("config_repository_canonical", "body", *m.ConfigRepositoryCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("config_repository_canonical", "body", *m.ConfigRepositoryCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewProject) validateIcon(formats strfmt.Registry) error { - if swag.IsZero(m.Icon) { // not required - return nil - } - - if err := validate.MaxLength("icon", "body", m.Icon, 64); err != nil { - return err - } - - return nil -} - -func (m *NewProject) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new project based on context it is used -func (m *NewProject) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewProject) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewProject) UnmarshalBinary(b []byte) error { - var res NewProject - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_role.go b/client/models/new_role.go deleted file mode 100644 index 1dcc01722..000000000 --- a/client/models/new_role.go +++ /dev/null @@ -1,192 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewRole New role access control -// -// New role represents the authorization level that a user has access to. A role contains a list of rules to define the access control. Note not all the entities supports roles access control; see the API endpoints to know which entities support them. -// -// swagger:model NewRole -type NewRole struct { - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // description - Description string `json:"description,omitempty"` - - // name - // Required: true - // Max Length: 100 - // Min Length: 3 - Name *string `json:"name"` - - // rules - // Required: true - Rules []*NewRule `json:"rules"` -} - -// Validate validates this new role -func (m *NewRole) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRules(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewRole) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewRole) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 100); err != nil { - return err - } - - return nil -} - -func (m *NewRole) validateRules(formats strfmt.Registry) error { - - if err := validate.Required("rules", "body", m.Rules); err != nil { - return err - } - - for i := 0; i < len(m.Rules); i++ { - if swag.IsZero(m.Rules[i]) { // not required - continue - } - - if m.Rules[i] != nil { - if err := m.Rules[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("rules" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("rules" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this new role based on the context it is used -func (m *NewRole) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateRules(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewRole) contextValidateRules(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Rules); i++ { - - if m.Rules[i] != nil { - - if swag.IsZero(m.Rules[i]) { // not required - return nil - } - - if err := m.Rules[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("rules" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("rules" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewRole) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewRole) UnmarshalBinary(b []byte) error { - var res NewRole - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_rule.go b/client/models/new_rule.go deleted file mode 100644 index 2e7e92b8b..000000000 --- a/client/models/new_rule.go +++ /dev/null @@ -1,123 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewRule NewRule -// -// NewRule represents an existing or new permission or constraint to access to an entity of the system. A Rule is aggregated into roles in order to be applied. -// -// swagger:model NewRule -type NewRule struct { - - // It can be the normal Policy.Code or contain globs like `*` or `**` - // Required: true - Action *string `json:"action"` - - // effect - // Required: true - // Enum: ["allow"] - Effect *string `json:"effect"` - - // It is the list of resources in which this Rule applies to, the format of it is the one on the Policy.Code but with the `canonical` of the entities like `organization:org-can:team:team-can` for an action of `organization:team:read` - Resources []string `json:"resources"` -} - -// Validate validates this new rule -func (m *NewRule) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAction(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEffect(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewRule) validateAction(formats strfmt.Registry) error { - - if err := validate.Required("action", "body", m.Action); err != nil { - return err - } - - return nil -} - -var newRuleTypeEffectPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["allow"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - newRuleTypeEffectPropEnum = append(newRuleTypeEffectPropEnum, v) - } -} - -const ( - - // NewRuleEffectAllow captures enum value "allow" - NewRuleEffectAllow string = "allow" -) - -// prop value enum -func (m *NewRule) validateEffectEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, newRuleTypeEffectPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NewRule) validateEffect(formats strfmt.Registry) error { - - if err := validate.Required("effect", "body", m.Effect); err != nil { - return err - } - - // value enum - if err := m.validateEffectEnum("effect", "body", *m.Effect); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new rule based on context it is used -func (m *NewRule) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewRule) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewRule) UnmarshalBinary(b []byte) error { - var res NewRule - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_service_catalog.go b/client/models/new_service_catalog.go deleted file mode 100644 index 363ba0cc4..000000000 --- a/client/models/new_service_catalog.go +++ /dev/null @@ -1,370 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewServiceCatalog NewServiceCatalog -// -// # Represents all information needed to create a new Service Catalog item -// -// swagger:model NewServiceCatalog -type NewServiceCatalog struct { - - // author - // Required: true - Author *string `json:"author"` - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // dependencies - Dependencies []*ServiceCatalogDependency `json:"dependencies"` - - // description - Description string `json:"description,omitempty"` - - // image - // Format: uri - Image strfmt.URI `json:"image,omitempty"` - - // keywords - // Required: true - Keywords []string `json:"keywords"` - - // name - // Required: true - Name *string `json:"name"` - - // service catalog source canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - ServiceCatalogSourceCanonical *string `json:"service_catalog_source_canonical"` - - // Team responsible for the maintenance of the underlying service catalogs - // - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - TeamCanonical string `json:"team_canonical,omitempty"` - - // technologies - Technologies []*ServiceCatalogTechnology `json:"technologies"` - - // visibility - Visibility string `json:"visibility,omitempty"` -} - -// Validate validates this new service catalog -func (m *NewServiceCatalog) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAuthor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDependencies(formats); err != nil { - res = append(res, err) - } - - if err := m.validateImage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateKeywords(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalogSourceCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTeamCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTechnologies(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewServiceCatalog) validateAuthor(formats strfmt.Registry) error { - - if err := validate.Required("author", "body", m.Author); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalog) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalog) validateDependencies(formats strfmt.Registry) error { - if swag.IsZero(m.Dependencies) { // not required - return nil - } - - for i := 0; i < len(m.Dependencies); i++ { - if swag.IsZero(m.Dependencies[i]) { // not required - continue - } - - if m.Dependencies[i] != nil { - if err := m.Dependencies[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("dependencies" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("dependencies" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *NewServiceCatalog) validateImage(formats strfmt.Registry) error { - if swag.IsZero(m.Image) { // not required - return nil - } - - if err := validate.FormatOf("image", "body", "uri", m.Image.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalog) validateKeywords(formats strfmt.Registry) error { - - if err := validate.Required("keywords", "body", m.Keywords); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalog) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalog) validateServiceCatalogSourceCanonical(formats strfmt.Registry) error { - - if err := validate.Required("service_catalog_source_canonical", "body", m.ServiceCatalogSourceCanonical); err != nil { - return err - } - - if err := validate.MinLength("service_catalog_source_canonical", "body", *m.ServiceCatalogSourceCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("service_catalog_source_canonical", "body", *m.ServiceCatalogSourceCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("service_catalog_source_canonical", "body", *m.ServiceCatalogSourceCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalog) validateTeamCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.TeamCanonical) { // not required - return nil - } - - if err := validate.MinLength("team_canonical", "body", m.TeamCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("team_canonical", "body", m.TeamCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("team_canonical", "body", m.TeamCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalog) validateTechnologies(formats strfmt.Registry) error { - if swag.IsZero(m.Technologies) { // not required - return nil - } - - for i := 0; i < len(m.Technologies); i++ { - if swag.IsZero(m.Technologies[i]) { // not required - continue - } - - if m.Technologies[i] != nil { - if err := m.Technologies[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("technologies" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("technologies" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this new service catalog based on the context it is used -func (m *NewServiceCatalog) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateDependencies(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateTechnologies(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewServiceCatalog) contextValidateDependencies(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Dependencies); i++ { - - if m.Dependencies[i] != nil { - - if swag.IsZero(m.Dependencies[i]) { // not required - return nil - } - - if err := m.Dependencies[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("dependencies" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("dependencies" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *NewServiceCatalog) contextValidateTechnologies(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Technologies); i++ { - - if m.Technologies[i] != nil { - - if swag.IsZero(m.Technologies[i]) { // not required - return nil - } - - if err := m.Technologies[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("technologies" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("technologies" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewServiceCatalog) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewServiceCatalog) UnmarshalBinary(b []byte) error { - var res NewServiceCatalog - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_service_catalog_from_template.go b/client/models/new_service_catalog_from_template.go deleted file mode 100644 index 98ccaf2d8..000000000 --- a/client/models/new_service_catalog_from_template.go +++ /dev/null @@ -1,203 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewServiceCatalogFromTemplate NewServiceCatalogFromTemplate -// -// # Represents the Service Catalog item -// -// swagger:model NewServiceCatalogFromTemplate -type NewServiceCatalogFromTemplate struct { - - // author - Author string `json:"author,omitempty"` - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // name - // Required: true - Name *string `json:"name"` - - // service catalog source canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - ServiceCatalogSourceCanonical *string `json:"service_catalog_source_canonical"` - - // Team responsible for the maintenance of the underlying service catalogs - // - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - TeamCanonical string `json:"team_canonical,omitempty"` - - // use case - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - UseCase *string `json:"use_case"` - - // visibility - Visibility string `json:"visibility,omitempty"` -} - -// Validate validates this new service catalog from template -func (m *NewServiceCatalogFromTemplate) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalogSourceCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTeamCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUseCase(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewServiceCatalogFromTemplate) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalogFromTemplate) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalogFromTemplate) validateServiceCatalogSourceCanonical(formats strfmt.Registry) error { - - if err := validate.Required("service_catalog_source_canonical", "body", m.ServiceCatalogSourceCanonical); err != nil { - return err - } - - if err := validate.MinLength("service_catalog_source_canonical", "body", *m.ServiceCatalogSourceCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("service_catalog_source_canonical", "body", *m.ServiceCatalogSourceCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("service_catalog_source_canonical", "body", *m.ServiceCatalogSourceCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalogFromTemplate) validateTeamCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.TeamCanonical) { // not required - return nil - } - - if err := validate.MinLength("team_canonical", "body", m.TeamCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("team_canonical", "body", m.TeamCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("team_canonical", "body", m.TeamCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalogFromTemplate) validateUseCase(formats strfmt.Registry) error { - - if err := validate.Required("use_case", "body", m.UseCase); err != nil { - return err - } - - if err := validate.MinLength("use_case", "body", *m.UseCase, 1); err != nil { - return err - } - - if err := validate.MaxLength("use_case", "body", *m.UseCase, 100); err != nil { - return err - } - - if err := validate.Pattern("use_case", "body", *m.UseCase, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new service catalog from template based on context it is used -func (m *NewServiceCatalogFromTemplate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewServiceCatalogFromTemplate) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewServiceCatalogFromTemplate) UnmarshalBinary(b []byte) error { - var res NewServiceCatalogFromTemplate - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_service_catalog_source.go b/client/models/new_service_catalog_source.go deleted file mode 100644 index 1be51e324..000000000 --- a/client/models/new_service_catalog_source.go +++ /dev/null @@ -1,209 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewServiceCatalogSource NewServiceCatalogSource -// -// swagger:model NewServiceCatalogSource -type NewServiceCatalogSource struct { - - // branch - // Required: true - Branch *string `json:"branch"` - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // credential canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical string `json:"credential_canonical,omitempty"` - - // name - // Required: true - Name *string `json:"name"` - - // User canonical that owns this service catalog source. If omitted then the person - // creating this service catalog source will be assigned as owner. When a user is the - // owner of a service catalog source they has all the permissions on it. - // - Owner string `json:"owner,omitempty"` - - // Team responsible for the maintenance of the underlying service catalogs - // - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - TeamCanonical string `json:"team_canonical,omitempty"` - - // url - // Required: true - // Pattern: ^((/|~)[^/]*)+.(\.git)|(([\w\]+@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(/)? - URL *string `json:"url"` - - // The visibility setting allows to specify which visibility will be applied to stacks in this catalog repository. - // This option is only applied during initial catalog repository creation, not for subsequent updates. - // - Visibility string `json:"visibility,omitempty"` -} - -// Validate validates this new service catalog source -func (m *NewServiceCatalogSource) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBranch(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTeamCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewServiceCatalogSource) validateBranch(formats strfmt.Registry) error { - - if err := validate.Required("branch", "body", m.Branch); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalogSource) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalogSource) validateCredentialCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.CredentialCanonical) { // not required - return nil - } - - if err := validate.MinLength("credential_canonical", "body", m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalogSource) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalogSource) validateTeamCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.TeamCanonical) { // not required - return nil - } - - if err := validate.MinLength("team_canonical", "body", m.TeamCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("team_canonical", "body", m.TeamCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("team_canonical", "body", m.TeamCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewServiceCatalogSource) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - if err := validate.Pattern("url", "body", *m.URL, `^((/|~)[^/]*)+.(\.git)|(([\w\]+@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(/)?`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new service catalog source based on context it is used -func (m *NewServiceCatalogSource) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewServiceCatalogSource) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewServiceCatalogSource) UnmarshalBinary(b []byte) error { - var res NewServiceCatalogSource - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_subscription.go b/client/models/new_subscription.go deleted file mode 100644 index fadd3b769..000000000 --- a/client/models/new_subscription.go +++ /dev/null @@ -1,85 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewSubscription New Subscription -// -// # It reflects the creation of a Subscription -// -// swagger:model NewSubscription -type NewSubscription struct { - - // plan canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - PlanCanonical *string `json:"plan_canonical"` -} - -// Validate validates this new subscription -func (m *NewSubscription) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validatePlanCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewSubscription) validatePlanCanonical(formats strfmt.Registry) error { - - if err := validate.Required("plan_canonical", "body", m.PlanCanonical); err != nil { - return err - } - - if err := validate.MinLength("plan_canonical", "body", *m.PlanCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("plan_canonical", "body", *m.PlanCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("plan_canonical", "body", *m.PlanCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new subscription based on context it is used -func (m *NewSubscription) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewSubscription) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewSubscription) UnmarshalBinary(b []byte) error { - var res NewSubscription - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_team.go b/client/models/new_team.go deleted file mode 100644 index 24c3e4407..000000000 --- a/client/models/new_team.go +++ /dev/null @@ -1,145 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewTeam Create Team -// -// The entity which represents the information of a new team. -// -// swagger:model NewTeam -type NewTeam struct { - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // User canonical that owns this team. If omitted then the person - // creating this team will be assigned as owner. When a user is the - // owner of a team it has all the permissions on it. - // - Owner string `json:"owner,omitempty"` - - // The roles to be assigned to a team. - // Required: true - RolesCanonical []string `json:"roles_canonical"` -} - -// Validate validates this new team -func (m *NewTeam) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRolesCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewTeam) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewTeam) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *NewTeam) validateRolesCanonical(formats strfmt.Registry) error { - - if err := validate.Required("roles_canonical", "body", m.RolesCanonical); err != nil { - return err - } - - for i := 0; i < len(m.RolesCanonical); i++ { - - if err := validate.MinLength("roles_canonical"+"."+strconv.Itoa(i), "body", m.RolesCanonical[i], 3); err != nil { - return err - } - - if err := validate.MaxLength("roles_canonical"+"."+strconv.Itoa(i), "body", m.RolesCanonical[i], 100); err != nil { - return err - } - - if err := validate.Pattern("roles_canonical"+"."+strconv.Itoa(i), "body", m.RolesCanonical[i], `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - } - - return nil -} - -// ContextValidate validates this new team based on context it is used -func (m *NewTeam) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewTeam) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewTeam) UnmarshalBinary(b []byte) error { - var res NewTeam - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_team_member_assignation.go b/client/models/new_team_member_assignation.go deleted file mode 100644 index 3d684f6b6..000000000 --- a/client/models/new_team_member_assignation.go +++ /dev/null @@ -1,78 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewTeamMemberAssignation Assign user -// -// Member is a user assigned to a Team. This is a good place to use oneOf property, but unfortunatelly we are still in 2.0, so the rule is: -// one of username or email must be given. In case if both are present, only the username is used to send the invite, -// because only one user can be added at the time. -// -// swagger:model NewTeamMemberAssignation -type NewTeamMemberAssignation struct { - - // Assign user by email (can be used for users who didn't accept the invitation yet and have no username) - // Format: email - Email strfmt.Email `json:"email,omitempty"` - - // Assign user by username - Username string `json:"username,omitempty"` -} - -// Validate validates this new team member assignation -func (m *NewTeamMemberAssignation) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewTeamMemberAssignation) validateEmail(formats strfmt.Registry) error { - if swag.IsZero(m.Email) { // not required - return nil - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new team member assignation based on context it is used -func (m *NewTeamMemberAssignation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewTeamMemberAssignation) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewTeamMemberAssignation) UnmarshalBinary(b []byte) error { - var res NewTeamMemberAssignation - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_user_account.go b/client/models/new_user_account.go deleted file mode 100644 index 1646647f4..000000000 --- a/client/models/new_user_account.go +++ /dev/null @@ -1,253 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewUserAccount Sign up -// -// Create a new user account. -// -// swagger:model NewUserAccount -type NewUserAccount struct { - - // Alpha-2 country code of a country the user is from - // Pattern: ^[A-Z]{2}$ - CountryCode string `json:"country_code,omitempty"` - - // email - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` - - // full name - // Required: true - // Max Length: 255 - // Min Length: 2 - FullName *string `json:"full_name"` - - // The field is used when a user signup from an invitation to an organization. Giving the token, the created user will be automatically added to the organization. - // Min Length: 5 - InvitationToken string `json:"invitation_token,omitempty"` - - // User's preferred language - // Enum: ["en","fr","es"] - Locale string `json:"locale,omitempty"` - - // password - // Required: true - // Min Length: 12 - // Format: password - Password *strfmt.Password `json:"password"` - - // username - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Username string `json:"username,omitempty"` -} - -// Validate validates this new user account -func (m *NewUserAccount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCountryCode(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFullName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInvitationToken(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLocale(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePassword(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUsername(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewUserAccount) validateCountryCode(formats strfmt.Registry) error { - if swag.IsZero(m.CountryCode) { // not required - return nil - } - - if err := validate.Pattern("country_code", "body", m.CountryCode, `^[A-Z]{2}$`); err != nil { - return err - } - - return nil -} - -func (m *NewUserAccount) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *NewUserAccount) validateFullName(formats strfmt.Registry) error { - - if err := validate.Required("full_name", "body", m.FullName); err != nil { - return err - } - - if err := validate.MinLength("full_name", "body", *m.FullName, 2); err != nil { - return err - } - - if err := validate.MaxLength("full_name", "body", *m.FullName, 255); err != nil { - return err - } - - return nil -} - -func (m *NewUserAccount) validateInvitationToken(formats strfmt.Registry) error { - if swag.IsZero(m.InvitationToken) { // not required - return nil - } - - if err := validate.MinLength("invitation_token", "body", m.InvitationToken, 5); err != nil { - return err - } - - return nil -} - -var newUserAccountTypeLocalePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["en","fr","es"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - newUserAccountTypeLocalePropEnum = append(newUserAccountTypeLocalePropEnum, v) - } -} - -const ( - - // NewUserAccountLocaleEn captures enum value "en" - NewUserAccountLocaleEn string = "en" - - // NewUserAccountLocaleFr captures enum value "fr" - NewUserAccountLocaleFr string = "fr" - - // NewUserAccountLocaleEs captures enum value "es" - NewUserAccountLocaleEs string = "es" -) - -// prop value enum -func (m *NewUserAccount) validateLocaleEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, newUserAccountTypeLocalePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NewUserAccount) validateLocale(formats strfmt.Registry) error { - if swag.IsZero(m.Locale) { // not required - return nil - } - - // value enum - if err := m.validateLocaleEnum("locale", "body", m.Locale); err != nil { - return err - } - - return nil -} - -func (m *NewUserAccount) validatePassword(formats strfmt.Registry) error { - - if err := validate.Required("password", "body", m.Password); err != nil { - return err - } - - if err := validate.MinLength("password", "body", m.Password.String(), 12); err != nil { - return err - } - - if err := validate.FormatOf("password", "body", "password", m.Password.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *NewUserAccount) validateUsername(formats strfmt.Registry) error { - if swag.IsZero(m.Username) { // not required - return nil - } - - if err := validate.MinLength("username", "body", m.Username, 3); err != nil { - return err - } - - if err := validate.MaxLength("username", "body", m.Username, 100); err != nil { - return err - } - - if err := validate.Pattern("username", "body", m.Username, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new user account based on context it is used -func (m *NewUserAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewUserAccount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewUserAccount) UnmarshalBinary(b []byte) error { - var res NewUserAccount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_watch_rule.go b/client/models/new_watch_rule.go deleted file mode 100644 index 288b23844..000000000 --- a/client/models/new_watch_rule.go +++ /dev/null @@ -1,253 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewWatchRule New Watch rule -// -// # The entity which represents the information of an Watch rule -// -// swagger:model NewWatchRule -type NewWatchRule struct { - - // canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical string `json:"canonical,omitempty"` - - // filters - // Required: true - // Min Items: 1 - Filters []*NewWatchRuleFilter `json:"filters"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // organization canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - OrganizationCanonical *string `json:"organization_canonical"` - - // project canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$ - ProjectCanonical string `json:"project_canonical,omitempty"` -} - -// Validate validates this new watch rule -func (m *NewWatchRule) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFilters(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOrganizationCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjectCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewWatchRule) validateCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.Canonical) { // not required - return nil - } - - if err := validate.MinLength("canonical", "body", m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewWatchRule) validateFilters(formats strfmt.Registry) error { - - if err := validate.Required("filters", "body", m.Filters); err != nil { - return err - } - - iFiltersSize := int64(len(m.Filters)) - - if err := validate.MinItems("filters", "body", iFiltersSize, 1); err != nil { - return err - } - - for i := 0; i < len(m.Filters); i++ { - if swag.IsZero(m.Filters[i]) { // not required - continue - } - - if m.Filters[i] != nil { - if err := m.Filters[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("filters" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("filters" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *NewWatchRule) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *NewWatchRule) validateOrganizationCanonical(formats strfmt.Registry) error { - - if err := validate.Required("organization_canonical", "body", m.OrganizationCanonical); err != nil { - return err - } - - if err := validate.MinLength("organization_canonical", "body", *m.OrganizationCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("organization_canonical", "body", *m.OrganizationCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("organization_canonical", "body", *m.OrganizationCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *NewWatchRule) validateProjectCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ProjectCanonical) { // not required - return nil - } - - if err := validate.MinLength("project_canonical", "body", m.ProjectCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("project_canonical", "body", m.ProjectCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("project_canonical", "body", m.ProjectCanonical, `^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this new watch rule based on the context it is used -func (m *NewWatchRule) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateFilters(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewWatchRule) contextValidateFilters(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Filters); i++ { - - if m.Filters[i] != nil { - - if swag.IsZero(m.Filters[i]) { // not required - return nil - } - - if err := m.Filters[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("filters" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("filters" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewWatchRule) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewWatchRule) UnmarshalBinary(b []byte) error { - var res NewWatchRule - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/new_watch_rule_filter.go b/client/models/new_watch_rule_filter.go deleted file mode 100644 index 4312b4c05..000000000 --- a/client/models/new_watch_rule_filter.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewWatchRuleFilter New Watch rule filter -// -// # The entity which represents the information of an Watch rule filter -// -// swagger:model NewWatchRuleFilter -type NewWatchRuleFilter struct { - - // * means the filter is applied to all the entities - // Required: true - Entity *string `json:"entity"` - - // * means the filter is applied to all the operations - // Required: true - Operation *string `json:"operation"` -} - -// Validate validates this new watch rule filter -func (m *NewWatchRuleFilter) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEntity(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOperation(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewWatchRuleFilter) validateEntity(formats strfmt.Registry) error { - - if err := validate.Required("entity", "body", m.Entity); err != nil { - return err - } - - return nil -} - -func (m *NewWatchRuleFilter) validateOperation(formats strfmt.Registry) error { - - if err := validate.Required("operation", "body", m.Operation); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this new watch rule filter based on context it is used -func (m *NewWatchRuleFilter) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NewWatchRuleFilter) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewWatchRuleFilter) UnmarshalBinary(b []byte) error { - var res NewWatchRuleFilter - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/notification.go b/client/models/notification.go deleted file mode 100644 index 5c7872130..000000000 --- a/client/models/notification.go +++ /dev/null @@ -1,205 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Notification Notification -// -// # The entity which represents the information of a Notification -// -// swagger:model Notification -type Notification struct { - - // created at - // Required: true - CreatedAt *uint64 `json:"created_at"` - - // event - // Required: true - Event *Event `json:"event"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // read at - ReadAt uint64 `json:"read_at,omitempty"` - - // updated at - // Required: true - UpdatedAt *uint64 `json:"updated_at"` - - // watch rule canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - WatchRuleCanonical string `json:"watch_rule_canonical,omitempty"` -} - -// Validate validates this notification -func (m *Notification) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEvent(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateWatchRuleCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Notification) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - return nil -} - -func (m *Notification) validateEvent(formats strfmt.Registry) error { - - if err := validate.Required("event", "body", m.Event); err != nil { - return err - } - - if m.Event != nil { - if err := m.Event.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("event") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("event") - } - - return err - } - } - - return nil -} - -func (m *Notification) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *Notification) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - return nil -} - -func (m *Notification) validateWatchRuleCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.WatchRuleCanonical) { // not required - return nil - } - - if err := validate.MinLength("watch_rule_canonical", "body", m.WatchRuleCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("watch_rule_canonical", "body", m.WatchRuleCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("watch_rule_canonical", "body", m.WatchRuleCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this notification based on the context it is used -func (m *Notification) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateEvent(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Notification) contextValidateEvent(ctx context.Context, formats strfmt.Registry) error { - - if m.Event != nil { - - if err := m.Event.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("event") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("event") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Notification) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Notification) UnmarshalBinary(b []byte) error { - var res Notification - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/notification_settings.go b/client/models/notification_settings.go deleted file mode 100644 index b15d71269..000000000 --- a/client/models/notification_settings.go +++ /dev/null @@ -1,124 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NotificationSettings User's notification settings -// -// swagger:model NotificationSettings -type NotificationSettings struct { - - // The frequency of the activity report. - // Required: true - // Enum: ["none","daily","weekly"] - ActivityReportFrequency *string `json:"activity_report_frequency"` - - // Automatically subscribe to the project updates when creating a new project. - // Required: true - WatchProjectsOnCreate *bool `json:"watch_projects_on_create"` -} - -// Validate validates this notification settings -func (m *NotificationSettings) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateActivityReportFrequency(formats); err != nil { - res = append(res, err) - } - - if err := m.validateWatchProjectsOnCreate(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -var notificationSettingsTypeActivityReportFrequencyPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["none","daily","weekly"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - notificationSettingsTypeActivityReportFrequencyPropEnum = append(notificationSettingsTypeActivityReportFrequencyPropEnum, v) - } -} - -const ( - - // NotificationSettingsActivityReportFrequencyNone captures enum value "none" - NotificationSettingsActivityReportFrequencyNone string = "none" - - // NotificationSettingsActivityReportFrequencyDaily captures enum value "daily" - NotificationSettingsActivityReportFrequencyDaily string = "daily" - - // NotificationSettingsActivityReportFrequencyWeekly captures enum value "weekly" - NotificationSettingsActivityReportFrequencyWeekly string = "weekly" -) - -// prop value enum -func (m *NotificationSettings) validateActivityReportFrequencyEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, notificationSettingsTypeActivityReportFrequencyPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *NotificationSettings) validateActivityReportFrequency(formats strfmt.Registry) error { - - if err := validate.Required("activity_report_frequency", "body", m.ActivityReportFrequency); err != nil { - return err - } - - // value enum - if err := m.validateActivityReportFrequencyEnum("activity_report_frequency", "body", *m.ActivityReportFrequency); err != nil { - return err - } - - return nil -} - -func (m *NotificationSettings) validateWatchProjectsOnCreate(formats strfmt.Registry) error { - - if err := validate.Required("watch_projects_on_create", "body", m.WatchProjectsOnCreate); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this notification settings based on context it is used -func (m *NotificationSettings) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *NotificationSettings) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NotificationSettings) UnmarshalBinary(b []byte) error { - var res NotificationSettings - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/on_failure_plan.go b/client/models/on_failure_plan.go deleted file mode 100644 index 6a36449f2..000000000 --- a/client/models/on_failure_plan.go +++ /dev/null @@ -1,173 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// OnFailurePlan OnFailurePlan -// -// The plan definition when the action has failed. -// -// swagger:model OnFailurePlan -type OnFailurePlan struct { - - // next - // Required: true - Next *Plan `json:"next"` - - // step - // Required: true - Step *Plan `json:"step"` -} - -// Validate validates this on failure plan -func (m *OnFailurePlan) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateNext(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStep(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *OnFailurePlan) validateNext(formats strfmt.Registry) error { - - if err := validate.Required("next", "body", m.Next); err != nil { - return err - } - - if m.Next != nil { - if err := m.Next.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next") - } - - return err - } - } - - return nil -} - -func (m *OnFailurePlan) validateStep(formats strfmt.Registry) error { - - if err := validate.Required("step", "body", m.Step); err != nil { - return err - } - - if m.Step != nil { - if err := m.Step.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("step") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("step") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this on failure plan based on the context it is used -func (m *OnFailurePlan) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateNext(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateStep(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *OnFailurePlan) contextValidateNext(ctx context.Context, formats strfmt.Registry) error { - - if m.Next != nil { - - if err := m.Next.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next") - } - - return err - } - } - - return nil -} - -func (m *OnFailurePlan) contextValidateStep(ctx context.Context, formats strfmt.Registry) error { - - if m.Step != nil { - - if err := m.Step.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("step") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("step") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *OnFailurePlan) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *OnFailurePlan) UnmarshalBinary(b []byte) error { - var res OnFailurePlan - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/on_success_plan.go b/client/models/on_success_plan.go deleted file mode 100644 index 2795ca7eb..000000000 --- a/client/models/on_success_plan.go +++ /dev/null @@ -1,173 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// OnSuccessPlan OnSuccessPlan -// -// The plan definition when the action has been successful. -// -// swagger:model OnSuccessPlan -type OnSuccessPlan struct { - - // next - // Required: true - Next *Plan `json:"next"` - - // step - // Required: true - Step *Plan `json:"step"` -} - -// Validate validates this on success plan -func (m *OnSuccessPlan) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateNext(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStep(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *OnSuccessPlan) validateNext(formats strfmt.Registry) error { - - if err := validate.Required("next", "body", m.Next); err != nil { - return err - } - - if m.Next != nil { - if err := m.Next.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next") - } - - return err - } - } - - return nil -} - -func (m *OnSuccessPlan) validateStep(formats strfmt.Registry) error { - - if err := validate.Required("step", "body", m.Step); err != nil { - return err - } - - if m.Step != nil { - if err := m.Step.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("step") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("step") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this on success plan based on the context it is used -func (m *OnSuccessPlan) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateNext(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateStep(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *OnSuccessPlan) contextValidateNext(ctx context.Context, formats strfmt.Registry) error { - - if m.Next != nil { - - if err := m.Next.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next") - } - - return err - } - } - - return nil -} - -func (m *OnSuccessPlan) contextValidateStep(ctx context.Context, formats strfmt.Registry) error { - - if m.Step != nil { - - if err := m.Step.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("step") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("step") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *OnSuccessPlan) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *OnSuccessPlan) UnmarshalBinary(b []byte) error { - var res OnSuccessPlan - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/organization.go b/client/models/organization.go deleted file mode 100644 index b012ce560..000000000 --- a/client/models/organization.go +++ /dev/null @@ -1,605 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Organization Organization -// -// The entity which holds all the direct information attached to an organization. -// -// swagger:model Organization -type Organization struct { - - // admins - Admins []*MemberOrg `json:"admins"` - - // appearance - Appearance *Appearance `json:"appearance,omitempty"` - - // blocked - // Required: true - Blocked []string `json:"blocked"` - - // can children create appearance - // Required: true - CanChildrenCreateAppearance *bool `json:"can_children_create_appearance"` - - // can children use dedicated authentication - // Required: true - CanChildrenUseDedicatedAuthentication *bool `json:"can_children_use_dedicated_authentication"` - - // can create appearance - // Required: true - CanCreateAppearance *bool `json:"can_create_appearance"` - - // can use dedicated authentication - // Required: true - CanUseDedicatedAuthentication *bool `json:"can_use_dedicated_authentication"` - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // ci port - // Required: true - CiPort *string `json:"ci_port"` - - // ci team name - // Required: true - CiTeamName *string `json:"ci_team_name"` - - // ci url - // Required: true - CiURL *string `json:"ci_url"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // has children - // Required: true - HasChildren *bool `json:"has_children"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // Defines if this organization is the root one on the platform or not - // Required: true - IsRoot *bool `json:"is_root"` - - // is using dedicated authentication - // Required: true - IsUsingDedicatedAuthentication *bool `json:"is_using_dedicated_authentication"` - - // mfa enabled - // Required: true - MfaEnabled *bool `json:"mfa_enabled"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // Canonical of the immediate parent organization. Omitted when this organization is root. - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - ParentCanonical *string `json:"parent_canonical,omitempty"` - - // When true, SSO users can only join the organization if they have been explicitly invited - SsoInviteOnly *bool `json:"sso_invite_only,omitempty"` - - // subscription - Subscription *Subscription `json:"subscription,omitempty"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` -} - -// Validate validates this organization -func (m *Organization) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAdmins(formats); err != nil { - res = append(res, err) - } - - if err := m.validateAppearance(formats); err != nil { - res = append(res, err) - } - - if err := m.validateBlocked(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanChildrenCreateAppearance(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanChildrenUseDedicatedAuthentication(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanCreateAppearance(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanUseDedicatedAuthentication(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCiPort(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCiTeamName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCiURL(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateHasChildren(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIsRoot(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIsUsingDedicatedAuthentication(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMfaEnabled(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateParentCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSubscription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Organization) validateAdmins(formats strfmt.Registry) error { - if swag.IsZero(m.Admins) { // not required - return nil - } - - for i := 0; i < len(m.Admins); i++ { - if swag.IsZero(m.Admins[i]) { // not required - continue - } - - if m.Admins[i] != nil { - if err := m.Admins[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("admins" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("admins" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Organization) validateAppearance(formats strfmt.Registry) error { - if swag.IsZero(m.Appearance) { // not required - return nil - } - - if m.Appearance != nil { - if err := m.Appearance.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("appearance") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("appearance") - } - - return err - } - } - - return nil -} - -func (m *Organization) validateBlocked(formats strfmt.Registry) error { - - if err := validate.Required("blocked", "body", m.Blocked); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateCanChildrenCreateAppearance(formats strfmt.Registry) error { - - if err := validate.Required("can_children_create_appearance", "body", m.CanChildrenCreateAppearance); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateCanChildrenUseDedicatedAuthentication(formats strfmt.Registry) error { - - if err := validate.Required("can_children_use_dedicated_authentication", "body", m.CanChildrenUseDedicatedAuthentication); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateCanCreateAppearance(formats strfmt.Registry) error { - - if err := validate.Required("can_create_appearance", "body", m.CanCreateAppearance); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateCanUseDedicatedAuthentication(formats strfmt.Registry) error { - - if err := validate.Required("can_use_dedicated_authentication", "body", m.CanUseDedicatedAuthentication); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateCiPort(formats strfmt.Registry) error { - - if err := validate.Required("ci_port", "body", m.CiPort); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateCiTeamName(formats strfmt.Registry) error { - - if err := validate.Required("ci_team_name", "body", m.CiTeamName); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateCiURL(formats strfmt.Registry) error { - - if err := validate.Required("ci_url", "body", m.CiURL); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateHasChildren(formats strfmt.Registry) error { - - if err := validate.Required("has_children", "body", m.HasChildren); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateIsRoot(formats strfmt.Registry) error { - - if err := validate.Required("is_root", "body", m.IsRoot); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateIsUsingDedicatedAuthentication(formats strfmt.Registry) error { - - if err := validate.Required("is_using_dedicated_authentication", "body", m.IsUsingDedicatedAuthentication); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateMfaEnabled(formats strfmt.Registry) error { - - if err := validate.Required("mfa_enabled", "body", m.MfaEnabled); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateParentCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ParentCanonical) { // not required - return nil - } - - if err := validate.MinLength("parent_canonical", "body", *m.ParentCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("parent_canonical", "body", *m.ParentCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("parent_canonical", "body", *m.ParentCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *Organization) validateSubscription(formats strfmt.Registry) error { - if swag.IsZero(m.Subscription) { // not required - return nil - } - - if m.Subscription != nil { - if err := m.Subscription.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("subscription") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("subscription") - } - - return err - } - } - - return nil -} - -func (m *Organization) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this organization based on the context it is used -func (m *Organization) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateAdmins(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateAppearance(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateSubscription(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Organization) contextValidateAdmins(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Admins); i++ { - - if m.Admins[i] != nil { - - if swag.IsZero(m.Admins[i]) { // not required - return nil - } - - if err := m.Admins[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("admins" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("admins" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Organization) contextValidateAppearance(ctx context.Context, formats strfmt.Registry) error { - - if m.Appearance != nil { - - if swag.IsZero(m.Appearance) { // not required - return nil - } - - if err := m.Appearance.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("appearance") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("appearance") - } - - return err - } - } - - return nil -} - -func (m *Organization) contextValidateSubscription(ctx context.Context, formats strfmt.Registry) error { - - if m.Subscription != nil { - - if swag.IsZero(m.Subscription) { // not required - return nil - } - - if err := m.Subscription.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("subscription") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("subscription") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Organization) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Organization) UnmarshalBinary(b []byte) error { - var res Organization - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/organization_messages.go b/client/models/organization_messages.go deleted file mode 100644 index 6daaf769a..000000000 --- a/client/models/organization_messages.go +++ /dev/null @@ -1,47 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// OrganizationMessages organization messages -// -// swagger:model OrganizationMessages -type OrganizationMessages struct { - - // creation restricted message - CreationRestrictedMessage *string `json:"creation_restricted_message,omitempty"` -} - -// Validate validates this organization messages -func (m *OrganizationMessages) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this organization messages based on context it is used -func (m *OrganizationMessages) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *OrganizationMessages) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *OrganizationMessages) UnmarshalBinary(b []byte) error { - var res OrganizationMessages - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/organization_naming_rules.go b/client/models/organization_naming_rules.go deleted file mode 100644 index 00c883678..000000000 --- a/client/models/organization_naming_rules.go +++ /dev/null @@ -1,173 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// OrganizationNamingRules OrganizationNamingRules -// -// # Naming validation rules applied to entities within an organization -// -// swagger:model OrganizationNamingRules -type OrganizationNamingRules struct { - - // Custom error message shown when a component canonical does not match the regex - // Max Length: 500 - ComponentMessage string `json:"component_message,omitempty"` - - // Regex pattern that component canonicals must match - // Max Length: 255 - ComponentRegex string `json:"component_regex,omitempty"` - - // Custom error message shown when an environment canonical does not match the regex - // Max Length: 500 - EnvMessage string `json:"env_message,omitempty"` - - // Regex pattern that environment canonicals must match - // Max Length: 255 - EnvRegex string `json:"env_regex,omitempty"` - - // Custom error message shown when a project canonical does not match the regex - // Max Length: 500 - ProjectMessage string `json:"project_message,omitempty"` - - // Regex pattern that project canonicals must match - // Max Length: 255 - ProjectRegex string `json:"project_regex,omitempty"` -} - -// Validate validates this organization naming rules -func (m *OrganizationNamingRules) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateComponentMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateComponentRegex(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvRegex(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjectMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjectRegex(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *OrganizationNamingRules) validateComponentMessage(formats strfmt.Registry) error { - if swag.IsZero(m.ComponentMessage) { // not required - return nil - } - - if err := validate.MaxLength("component_message", "body", m.ComponentMessage, 500); err != nil { - return err - } - - return nil -} - -func (m *OrganizationNamingRules) validateComponentRegex(formats strfmt.Registry) error { - if swag.IsZero(m.ComponentRegex) { // not required - return nil - } - - if err := validate.MaxLength("component_regex", "body", m.ComponentRegex, 255); err != nil { - return err - } - - return nil -} - -func (m *OrganizationNamingRules) validateEnvMessage(formats strfmt.Registry) error { - if swag.IsZero(m.EnvMessage) { // not required - return nil - } - - if err := validate.MaxLength("env_message", "body", m.EnvMessage, 500); err != nil { - return err - } - - return nil -} - -func (m *OrganizationNamingRules) validateEnvRegex(formats strfmt.Registry) error { - if swag.IsZero(m.EnvRegex) { // not required - return nil - } - - if err := validate.MaxLength("env_regex", "body", m.EnvRegex, 255); err != nil { - return err - } - - return nil -} - -func (m *OrganizationNamingRules) validateProjectMessage(formats strfmt.Registry) error { - if swag.IsZero(m.ProjectMessage) { // not required - return nil - } - - if err := validate.MaxLength("project_message", "body", m.ProjectMessage, 500); err != nil { - return err - } - - return nil -} - -func (m *OrganizationNamingRules) validateProjectRegex(formats strfmt.Registry) error { - if swag.IsZero(m.ProjectRegex) { // not required - return nil - } - - if err := validate.MaxLength("project_regex", "body", m.ProjectRegex, 255); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this organization naming rules based on context it is used -func (m *OrganizationNamingRules) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *OrganizationNamingRules) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *OrganizationNamingRules) UnmarshalBinary(b []byte) error { - var res OrganizationNamingRules - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/page_concourse.go b/client/models/page_concourse.go deleted file mode 100644 index fecddfb67..000000000 --- a/client/models/page_concourse.go +++ /dev/null @@ -1,102 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PageConcourse PageConcourse -// -// swagger:model PageConcourse -type PageConcourse struct { - - // The maximum number of entities to return - // Required: true - Limit *uint64 `json:"limit"` - - // Entities returned should have a higher timestamp than this one - // Required: true - Since *uint64 `json:"since"` - - // Entities returned should have a lower timestamp than this one - // Required: true - Until *uint64 `json:"until"` -} - -// Validate validates this page concourse -func (m *PageConcourse) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateLimit(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSince(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUntil(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PageConcourse) validateLimit(formats strfmt.Registry) error { - - if err := validate.Required("limit", "body", m.Limit); err != nil { - return err - } - - return nil -} - -func (m *PageConcourse) validateSince(formats strfmt.Registry) error { - - if err := validate.Required("since", "body", m.Since); err != nil { - return err - } - - return nil -} - -func (m *PageConcourse) validateUntil(formats strfmt.Registry) error { - - if err := validate.Required("until", "body", m.Until); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this page concourse based on context it is used -func (m *PageConcourse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PageConcourse) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PageConcourse) UnmarshalBinary(b []byte) error { - var res PageConcourse - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/pagination.go b/client/models/pagination.go deleted file mode 100644 index ebe791b24..000000000 --- a/client/models/pagination.go +++ /dev/null @@ -1,117 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Pagination Pagination -// -// swagger:model Pagination -type Pagination struct { - - // The index of the page sent (the first page is 1). - // Required: true - // Minimum: 1 - Index *uint64 `json:"index"` - - // The size of the page (the number of entities per page) - // Required: true - // Minimum: 0 - Size *uint64 `json:"size"` - - // The total number of items. - // Required: true - // Minimum: 0 - Total *uint64 `json:"total"` -} - -// Validate validates this pagination -func (m *Pagination) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateIndex(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSize(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTotal(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Pagination) validateIndex(formats strfmt.Registry) error { - - if err := validate.Required("index", "body", m.Index); err != nil { - return err - } - - if err := validate.MinimumUint("index", "body", *m.Index, 1, false); err != nil { - return err - } - - return nil -} - -func (m *Pagination) validateSize(formats strfmt.Registry) error { - - if err := validate.Required("size", "body", m.Size); err != nil { - return err - } - - if err := validate.MinimumUint("size", "body", *m.Size, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Pagination) validateTotal(formats strfmt.Registry) error { - - if err := validate.Required("total", "body", m.Total); err != nil { - return err - } - - if err := validate.MinimumUint("total", "body", *m.Total, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this pagination based on context it is used -func (m *Pagination) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *Pagination) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Pagination) UnmarshalBinary(b []byte) error { - var res Pagination - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/pagination_a_w_s.go b/client/models/pagination_a_w_s.go deleted file mode 100644 index efa9f94b5..000000000 --- a/client/models/pagination_a_w_s.go +++ /dev/null @@ -1,68 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PaginationAWS AWS Pagination -// -// swagger:model PaginationAWS -type PaginationAWS struct { - - // The token to retrieve the next page of results. Empty string when there isn't a next page. - // Required: true - Next *string `json:"next"` -} - -// Validate validates this pagination a w s -func (m *PaginationAWS) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateNext(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PaginationAWS) validateNext(formats strfmt.Registry) error { - - if err := validate.Required("next", "body", m.Next); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this pagination a w s based on context it is used -func (m *PaginationAWS) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PaginationAWS) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PaginationAWS) UnmarshalBinary(b []byte) error { - var res PaginationAWS - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/pagination_concourse.go b/client/models/pagination_concourse.go deleted file mode 100644 index 57d861654..000000000 --- a/client/models/pagination_concourse.go +++ /dev/null @@ -1,171 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PaginationConcourse PaginationConcourse -// -// swagger:model PaginationConcourse -type PaginationConcourse struct { - - // next - // Required: true - Next *PageConcourse `json:"next"` - - // previous - // Required: true - Previous *PageConcourse `json:"previous"` -} - -// Validate validates this pagination concourse -func (m *PaginationConcourse) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateNext(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePrevious(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PaginationConcourse) validateNext(formats strfmt.Registry) error { - - if err := validate.Required("next", "body", m.Next); err != nil { - return err - } - - if m.Next != nil { - if err := m.Next.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next") - } - - return err - } - } - - return nil -} - -func (m *PaginationConcourse) validatePrevious(formats strfmt.Registry) error { - - if err := validate.Required("previous", "body", m.Previous); err != nil { - return err - } - - if m.Previous != nil { - if err := m.Previous.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("previous") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("previous") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this pagination concourse based on the context it is used -func (m *PaginationConcourse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateNext(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidatePrevious(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PaginationConcourse) contextValidateNext(ctx context.Context, formats strfmt.Registry) error { - - if m.Next != nil { - - if err := m.Next.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next") - } - - return err - } - } - - return nil -} - -func (m *PaginationConcourse) contextValidatePrevious(ctx context.Context, formats strfmt.Registry) error { - - if m.Previous != nil { - - if err := m.Previous.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("previous") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("previous") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *PaginationConcourse) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PaginationConcourse) UnmarshalBinary(b []byte) error { - var res PaginationConcourse - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/pending_member_invitation.go b/client/models/pending_member_invitation.go deleted file mode 100644 index 52f9e4916..000000000 --- a/client/models/pending_member_invitation.go +++ /dev/null @@ -1,75 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PendingMemberInvitation PendingMemberInvitation -// -// # Contains the email used for the member invitation -// -// swagger:model PendingMemberInvitation -type PendingMemberInvitation struct { - - // email - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` -} - -// Validate validates this pending member invitation -func (m *PendingMemberInvitation) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PendingMemberInvitation) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this pending member invitation based on context it is used -func (m *PendingMemberInvitation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PendingMemberInvitation) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PendingMemberInvitation) UnmarshalBinary(b []byte) error { - var res PendingMemberInvitation - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/pin_comment.go b/client/models/pin_comment.go deleted file mode 100644 index d3dfe06cc..000000000 --- a/client/models/pin_comment.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PinComment PinComment -// -// # Represents a pin comment of a resource -// -// swagger:model PinComment -type PinComment struct { - - // pin comment - // Required: true - PinComment *string `json:"pin_comment"` -} - -// Validate validates this pin comment -func (m *PinComment) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validatePinComment(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PinComment) validatePinComment(formats strfmt.Registry) error { - - if err := validate.Required("pin_comment", "body", m.PinComment); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this pin comment based on context it is used -func (m *PinComment) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PinComment) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PinComment) UnmarshalBinary(b []byte) error { - var res PinComment - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/pipeline.go b/client/models/pipeline.go deleted file mode 100644 index ee9a92619..000000000 --- a/client/models/pipeline.go +++ /dev/null @@ -1,511 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Pipeline Pipeline -// -// The entity which represents a pipeline in the application. -// -// swagger:model Pipeline -type Pipeline struct { - - // archived - Archived bool `json:"archived,omitempty"` - - // component - // Required: true - Component *Component `json:"component"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // environment - // Required: true - Environment *Environment `json:"environment"` - - // groups - Groups []*GroupConfig `json:"groups"` - - // id - // Required: true - ID *uint64 `json:"id"` - - // jobs - // Required: true - Jobs []*Job `json:"jobs"` - - // name - // Required: true - Name *string `json:"name"` - - // paused - // Required: true - Paused *bool `json:"paused"` - - // project - // Required: true - Project *Project `json:"project"` - - // public - // Required: true - Public *bool `json:"public"` - - // started - Started bool `json:"started,omitempty"` - - // status - Status string `json:"status,omitempty"` - - // team name - // Required: true - TeamName *string `json:"team_name"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` -} - -// Validate validates this pipeline -func (m *Pipeline) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateComponent(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironment(formats); err != nil { - res = append(res, err) - } - - if err := m.validateGroups(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateJobs(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePaused(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProject(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePublic(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTeamName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Pipeline) validateComponent(formats strfmt.Registry) error { - - if err := validate.Required("component", "body", m.Component); err != nil { - return err - } - - if m.Component != nil { - if err := m.Component.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("component") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("component") - } - - return err - } - } - - return nil -} - -func (m *Pipeline) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Pipeline) validateEnvironment(formats strfmt.Registry) error { - - if err := validate.Required("environment", "body", m.Environment); err != nil { - return err - } - - if m.Environment != nil { - if err := m.Environment.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment") - } - - return err - } - } - - return nil -} - -func (m *Pipeline) validateGroups(formats strfmt.Registry) error { - if swag.IsZero(m.Groups) { // not required - return nil - } - - for i := 0; i < len(m.Groups); i++ { - if swag.IsZero(m.Groups[i]) { // not required - continue - } - - if m.Groups[i] != nil { - if err := m.Groups[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("groups" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("groups" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Pipeline) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - return nil -} - -func (m *Pipeline) validateJobs(formats strfmt.Registry) error { - - if err := validate.Required("jobs", "body", m.Jobs); err != nil { - return err - } - - for i := 0; i < len(m.Jobs); i++ { - if swag.IsZero(m.Jobs[i]) { // not required - continue - } - - if m.Jobs[i] != nil { - if err := m.Jobs[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("jobs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("jobs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Pipeline) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *Pipeline) validatePaused(formats strfmt.Registry) error { - - if err := validate.Required("paused", "body", m.Paused); err != nil { - return err - } - - return nil -} - -func (m *Pipeline) validateProject(formats strfmt.Registry) error { - - if err := validate.Required("project", "body", m.Project); err != nil { - return err - } - - if m.Project != nil { - if err := m.Project.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project") - } - - return err - } - } - - return nil -} - -func (m *Pipeline) validatePublic(formats strfmt.Registry) error { - - if err := validate.Required("public", "body", m.Public); err != nil { - return err - } - - return nil -} - -func (m *Pipeline) validateTeamName(formats strfmt.Registry) error { - - if err := validate.Required("team_name", "body", m.TeamName); err != nil { - return err - } - - return nil -} - -func (m *Pipeline) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this pipeline based on the context it is used -func (m *Pipeline) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateComponent(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateEnvironment(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateGroups(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateJobs(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateProject(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Pipeline) contextValidateComponent(ctx context.Context, formats strfmt.Registry) error { - - if m.Component != nil { - - if err := m.Component.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("component") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("component") - } - - return err - } - } - - return nil -} - -func (m *Pipeline) contextValidateEnvironment(ctx context.Context, formats strfmt.Registry) error { - - if m.Environment != nil { - - if err := m.Environment.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment") - } - - return err - } - } - - return nil -} - -func (m *Pipeline) contextValidateGroups(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Groups); i++ { - - if m.Groups[i] != nil { - - if swag.IsZero(m.Groups[i]) { // not required - return nil - } - - if err := m.Groups[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("groups" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("groups" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Pipeline) contextValidateJobs(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Jobs); i++ { - - if m.Jobs[i] != nil { - - if swag.IsZero(m.Jobs[i]) { // not required - return nil - } - - if err := m.Jobs[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("jobs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("jobs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Pipeline) contextValidateProject(ctx context.Context, formats strfmt.Registry) error { - - if m.Project != nil { - - if err := m.Project.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("project") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("project") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Pipeline) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Pipeline) UnmarshalBinary(b []byte) error { - var res Pipeline - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/pipeline_diff.go b/client/models/pipeline_diff.go deleted file mode 100644 index 7e94be464..000000000 --- a/client/models/pipeline_diff.go +++ /dev/null @@ -1,205 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PipelineDiff PipelineDiff -// -// Represents a diff element of a PipelineDiffs. -// -// swagger:model PipelineDiff -type PipelineDiff struct { - - // Represents the diff of all configuration line for an element - // Required: true - Diff []*PipelineDiffRecord `json:"diff"` - - // Represents the name of the element in a pipeline. For example the job name for jobs section - // Required: true - Name *string `json:"name"` - - // Represents the status of the element (added, removed, changed) - // Required: true - // Enum: ["added","removed","changed"] - Status *string `json:"status"` -} - -// Validate validates this pipeline diff -func (m *PipelineDiff) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateDiff(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PipelineDiff) validateDiff(formats strfmt.Registry) error { - - if err := validate.Required("diff", "body", m.Diff); err != nil { - return err - } - - for i := 0; i < len(m.Diff); i++ { - if swag.IsZero(m.Diff[i]) { // not required - continue - } - - if m.Diff[i] != nil { - if err := m.Diff[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("diff" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("diff" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PipelineDiff) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -var pipelineDiffTypeStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["added","removed","changed"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - pipelineDiffTypeStatusPropEnum = append(pipelineDiffTypeStatusPropEnum, v) - } -} - -const ( - - // PipelineDiffStatusAdded captures enum value "added" - PipelineDiffStatusAdded string = "added" - - // PipelineDiffStatusRemoved captures enum value "removed" - PipelineDiffStatusRemoved string = "removed" - - // PipelineDiffStatusChanged captures enum value "changed" - PipelineDiffStatusChanged string = "changed" -) - -// prop value enum -func (m *PipelineDiff) validateStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, pipelineDiffTypeStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *PipelineDiff) validateStatus(formats strfmt.Registry) error { - - if err := validate.Required("status", "body", m.Status); err != nil { - return err - } - - // value enum - if err := m.validateStatusEnum("status", "body", *m.Status); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this pipeline diff based on the context it is used -func (m *PipelineDiff) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateDiff(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PipelineDiff) contextValidateDiff(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Diff); i++ { - - if m.Diff[i] != nil { - - if swag.IsZero(m.Diff[i]) { // not required - return nil - } - - if err := m.Diff[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("diff" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("diff" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *PipelineDiff) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PipelineDiff) UnmarshalBinary(b []byte) error { - var res PipelineDiff - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/pipeline_diff_record.go b/client/models/pipeline_diff_record.go deleted file mode 100644 index 63f292efb..000000000 --- a/client/models/pipeline_diff_record.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PipelineDiffRecord PipelineDiffRecord -// -// # Represents a diff record of a pipeline diff -// -// swagger:model PipelineDiffRecord -type PipelineDiffRecord struct { - - // Represents the type of delta (added, removed, changed, equals) for the text line - // Required: true - DeltaType *string `json:"delta_type"` - - // Represents a text line in a pipeline configuration - // Required: true - Line *string `json:"line"` -} - -// Validate validates this pipeline diff record -func (m *PipelineDiffRecord) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateDeltaType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLine(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PipelineDiffRecord) validateDeltaType(formats strfmt.Registry) error { - - if err := validate.Required("delta_type", "body", m.DeltaType); err != nil { - return err - } - - return nil -} - -func (m *PipelineDiffRecord) validateLine(formats strfmt.Registry) error { - - if err := validate.Required("line", "body", m.Line); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this pipeline diff record based on context it is used -func (m *PipelineDiffRecord) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PipelineDiffRecord) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PipelineDiffRecord) UnmarshalBinary(b []byte) error { - var res PipelineDiffRecord - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/pipeline_diffs.go b/client/models/pipeline_diffs.go deleted file mode 100644 index a0115e55c..000000000 --- a/client/models/pipeline_diffs.go +++ /dev/null @@ -1,339 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// PipelineDiffs PipelineDiffs -// -// # Represents the diffs between two pipelines -// -// swagger:model PipelineDiffs -type PipelineDiffs struct { - - // groups - Groups []*PipelineDiff `json:"groups"` - - // jobs - Jobs []*PipelineDiff `json:"jobs"` - - // resource types - ResourceTypes []*PipelineDiff `json:"resource_types"` - - // resources - Resources []*PipelineDiff `json:"resources"` -} - -// Validate validates this pipeline diffs -func (m *PipelineDiffs) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateGroups(formats); err != nil { - res = append(res, err) - } - - if err := m.validateJobs(formats); err != nil { - res = append(res, err) - } - - if err := m.validateResourceTypes(formats); err != nil { - res = append(res, err) - } - - if err := m.validateResources(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PipelineDiffs) validateGroups(formats strfmt.Registry) error { - if swag.IsZero(m.Groups) { // not required - return nil - } - - for i := 0; i < len(m.Groups); i++ { - if swag.IsZero(m.Groups[i]) { // not required - continue - } - - if m.Groups[i] != nil { - if err := m.Groups[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("groups" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("groups" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PipelineDiffs) validateJobs(formats strfmt.Registry) error { - if swag.IsZero(m.Jobs) { // not required - return nil - } - - for i := 0; i < len(m.Jobs); i++ { - if swag.IsZero(m.Jobs[i]) { // not required - continue - } - - if m.Jobs[i] != nil { - if err := m.Jobs[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("jobs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("jobs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PipelineDiffs) validateResourceTypes(formats strfmt.Registry) error { - if swag.IsZero(m.ResourceTypes) { // not required - return nil - } - - for i := 0; i < len(m.ResourceTypes); i++ { - if swag.IsZero(m.ResourceTypes[i]) { // not required - continue - } - - if m.ResourceTypes[i] != nil { - if err := m.ResourceTypes[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("resource_types" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("resource_types" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PipelineDiffs) validateResources(formats strfmt.Registry) error { - if swag.IsZero(m.Resources) { // not required - return nil - } - - for i := 0; i < len(m.Resources); i++ { - if swag.IsZero(m.Resources[i]) { // not required - continue - } - - if m.Resources[i] != nil { - if err := m.Resources[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("resources" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("resources" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this pipeline diffs based on the context it is used -func (m *PipelineDiffs) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateGroups(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateJobs(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateResourceTypes(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateResources(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PipelineDiffs) contextValidateGroups(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Groups); i++ { - - if m.Groups[i] != nil { - - if swag.IsZero(m.Groups[i]) { // not required - return nil - } - - if err := m.Groups[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("groups" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("groups" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PipelineDiffs) contextValidateJobs(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Jobs); i++ { - - if m.Jobs[i] != nil { - - if swag.IsZero(m.Jobs[i]) { // not required - return nil - } - - if err := m.Jobs[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("jobs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("jobs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PipelineDiffs) contextValidateResourceTypes(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.ResourceTypes); i++ { - - if m.ResourceTypes[i] != nil { - - if swag.IsZero(m.ResourceTypes[i]) { // not required - return nil - } - - if err := m.ResourceTypes[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("resource_types" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("resource_types" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PipelineDiffs) contextValidateResources(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Resources); i++ { - - if m.Resources[i] != nil { - - if swag.IsZero(m.Resources[i]) { // not required - return nil - } - - if err := m.Resources[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("resources" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("resources" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *PipelineDiffs) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PipelineDiffs) UnmarshalBinary(b []byte) error { - var res PipelineDiffs - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/pipeline_status.go b/client/models/pipeline_status.go deleted file mode 100644 index 2d57e1194..000000000 --- a/client/models/pipeline_status.go +++ /dev/null @@ -1,184 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PipelineStatus PipelineStatus -// -// Pipeline status returned upon pipelines comparison between the one locally stored in the database and its counter part on git. -// -// swagger:model PipelineStatus -type PipelineStatus struct { - - // diffs - Diffs *PipelineDiffs `json:"diffs,omitempty"` - - // error - Error string `json:"error,omitempty"` - - // The state can vary depending on how far the comparison process went. There are 4 possible states which are: - // - unknown: one of the pipeline (database/git) couldn't be retrieved - // - sycned: both database & git pipelines are identical - // - out_of_sync: database & git pipelines have some differences - // - errored: both pipelines got retrieved but the comparison triggered an error - // Required: true - // Enum: ["unknown","synced","out_of_sync","errored"] - Synced *string `json:"synced"` -} - -// Validate validates this pipeline status -func (m *PipelineStatus) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateDiffs(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSynced(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PipelineStatus) validateDiffs(formats strfmt.Registry) error { - if swag.IsZero(m.Diffs) { // not required - return nil - } - - if m.Diffs != nil { - if err := m.Diffs.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("diffs") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("diffs") - } - - return err - } - } - - return nil -} - -var pipelineStatusTypeSyncedPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["unknown","synced","out_of_sync","errored"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - pipelineStatusTypeSyncedPropEnum = append(pipelineStatusTypeSyncedPropEnum, v) - } -} - -const ( - - // PipelineStatusSyncedUnknown captures enum value "unknown" - PipelineStatusSyncedUnknown string = "unknown" - - // PipelineStatusSyncedSynced captures enum value "synced" - PipelineStatusSyncedSynced string = "synced" - - // PipelineStatusSyncedOutOfSync captures enum value "out_of_sync" - PipelineStatusSyncedOutOfSync string = "out_of_sync" - - // PipelineStatusSyncedErrored captures enum value "errored" - PipelineStatusSyncedErrored string = "errored" -) - -// prop value enum -func (m *PipelineStatus) validateSyncedEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, pipelineStatusTypeSyncedPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *PipelineStatus) validateSynced(formats strfmt.Registry) error { - - if err := validate.Required("synced", "body", m.Synced); err != nil { - return err - } - - // value enum - if err := m.validateSyncedEnum("synced", "body", *m.Synced); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this pipeline status based on the context it is used -func (m *PipelineStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateDiffs(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PipelineStatus) contextValidateDiffs(ctx context.Context, formats strfmt.Registry) error { - - if m.Diffs != nil { - - if swag.IsZero(m.Diffs) { // not required - return nil - } - - if err := m.Diffs.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("diffs") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("diffs") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *PipelineStatus) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PipelineStatus) UnmarshalBinary(b []byte) error { - var res PipelineStatus - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/pipeline_variables.go b/client/models/pipeline_variables.go deleted file mode 100644 index e4a1733e6..000000000 --- a/client/models/pipeline_variables.go +++ /dev/null @@ -1,90 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PipelineVariables Pipeline variables -// -// The entity which contains pipeline's variables. -// -// swagger:model PipelineVariables -type PipelineVariables struct { - - // The has_saved_yaml_vars specifies whether the returned vars are from - // the saved ones or the sample ones. If the has_saved_yaml_vars is true, - // it means that the saved have been returned. - // - // Required: true - HasSavedYamlVars *bool `json:"has_saved_yaml_vars"` - - // yaml vars - // Required: true - YamlVars *string `json:"yaml_vars"` -} - -// Validate validates this pipeline variables -func (m *PipelineVariables) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateHasSavedYamlVars(formats); err != nil { - res = append(res, err) - } - - if err := m.validateYamlVars(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PipelineVariables) validateHasSavedYamlVars(formats strfmt.Registry) error { - - if err := validate.Required("has_saved_yaml_vars", "body", m.HasSavedYamlVars); err != nil { - return err - } - - return nil -} - -func (m *PipelineVariables) validateYamlVars(formats strfmt.Registry) error { - - if err := validate.Required("yaml_vars", "body", m.YamlVars); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this pipeline variables based on context it is used -func (m *PipelineVariables) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PipelineVariables) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PipelineVariables) UnmarshalBinary(b []byte) error { - var res PipelineVariables - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plan.go b/client/models/plan.go deleted file mode 100644 index c5c5b7097..000000000 --- a/client/models/plan.go +++ /dev/null @@ -1,695 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Plan Plan -// -// The plan is what represent a concourse build. -// -// swagger:model Plan -type Plan struct { - - // aggregate - Aggregate string `json:"aggregate,omitempty"` - - // attempts - Attempts []uint32 `json:"attempts"` - - // do - Do []*Plan `json:"do"` - - // ensure - Ensure *EnsurePlan `json:"ensure,omitempty"` - - // get - Get *GetPlan `json:"get,omitempty"` - - // id - // Required: true - ID *string `json:"id"` - - // on failure - OnFailure *OnFailurePlan `json:"on_failure,omitempty"` - - // on success - OnSuccess *OnSuccessPlan `json:"on_success,omitempty"` - - // put - Put *PutPlan `json:"put,omitempty"` - - // retry - Retry []*Plan `json:"retry"` - - // task - Task *TaskPlan `json:"task,omitempty"` - - // timeout - Timeout *TimeoutPlan `json:"timeout,omitempty"` - - // try - Try *TryPlan `json:"try,omitempty"` -} - -// Validate validates this plan -func (m *Plan) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateDo(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnsure(formats); err != nil { - res = append(res, err) - } - - if err := m.validateGet(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOnFailure(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOnSuccess(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePut(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRetry(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTask(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTimeout(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTry(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Plan) validateDo(formats strfmt.Registry) error { - if swag.IsZero(m.Do) { // not required - return nil - } - - for i := 0; i < len(m.Do); i++ { - if swag.IsZero(m.Do[i]) { // not required - continue - } - - if m.Do[i] != nil { - if err := m.Do[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("do" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("do" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Plan) validateEnsure(formats strfmt.Registry) error { - if swag.IsZero(m.Ensure) { // not required - return nil - } - - if m.Ensure != nil { - if err := m.Ensure.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("ensure") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("ensure") - } - - return err - } - } - - return nil -} - -func (m *Plan) validateGet(formats strfmt.Registry) error { - if swag.IsZero(m.Get) { // not required - return nil - } - - if m.Get != nil { - if err := m.Get.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("get") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("get") - } - - return err - } - } - - return nil -} - -func (m *Plan) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - return nil -} - -func (m *Plan) validateOnFailure(formats strfmt.Registry) error { - if swag.IsZero(m.OnFailure) { // not required - return nil - } - - if m.OnFailure != nil { - if err := m.OnFailure.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("on_failure") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("on_failure") - } - - return err - } - } - - return nil -} - -func (m *Plan) validateOnSuccess(formats strfmt.Registry) error { - if swag.IsZero(m.OnSuccess) { // not required - return nil - } - - if m.OnSuccess != nil { - if err := m.OnSuccess.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("on_success") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("on_success") - } - - return err - } - } - - return nil -} - -func (m *Plan) validatePut(formats strfmt.Registry) error { - if swag.IsZero(m.Put) { // not required - return nil - } - - if m.Put != nil { - if err := m.Put.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("put") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("put") - } - - return err - } - } - - return nil -} - -func (m *Plan) validateRetry(formats strfmt.Registry) error { - if swag.IsZero(m.Retry) { // not required - return nil - } - - for i := 0; i < len(m.Retry); i++ { - if swag.IsZero(m.Retry[i]) { // not required - continue - } - - if m.Retry[i] != nil { - if err := m.Retry[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("retry" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("retry" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Plan) validateTask(formats strfmt.Registry) error { - if swag.IsZero(m.Task) { // not required - return nil - } - - if m.Task != nil { - if err := m.Task.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("task") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("task") - } - - return err - } - } - - return nil -} - -func (m *Plan) validateTimeout(formats strfmt.Registry) error { - if swag.IsZero(m.Timeout) { // not required - return nil - } - - if m.Timeout != nil { - if err := m.Timeout.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("timeout") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("timeout") - } - - return err - } - } - - return nil -} - -func (m *Plan) validateTry(formats strfmt.Registry) error { - if swag.IsZero(m.Try) { // not required - return nil - } - - if m.Try != nil { - if err := m.Try.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("try") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("try") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this plan based on the context it is used -func (m *Plan) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateDo(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateEnsure(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateGet(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateOnFailure(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateOnSuccess(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidatePut(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateRetry(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateTask(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateTimeout(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateTry(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Plan) contextValidateDo(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Do); i++ { - - if m.Do[i] != nil { - - if swag.IsZero(m.Do[i]) { // not required - return nil - } - - if err := m.Do[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("do" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("do" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Plan) contextValidateEnsure(ctx context.Context, formats strfmt.Registry) error { - - if m.Ensure != nil { - - if swag.IsZero(m.Ensure) { // not required - return nil - } - - if err := m.Ensure.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("ensure") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("ensure") - } - - return err - } - } - - return nil -} - -func (m *Plan) contextValidateGet(ctx context.Context, formats strfmt.Registry) error { - - if m.Get != nil { - - if swag.IsZero(m.Get) { // not required - return nil - } - - if err := m.Get.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("get") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("get") - } - - return err - } - } - - return nil -} - -func (m *Plan) contextValidateOnFailure(ctx context.Context, formats strfmt.Registry) error { - - if m.OnFailure != nil { - - if swag.IsZero(m.OnFailure) { // not required - return nil - } - - if err := m.OnFailure.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("on_failure") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("on_failure") - } - - return err - } - } - - return nil -} - -func (m *Plan) contextValidateOnSuccess(ctx context.Context, formats strfmt.Registry) error { - - if m.OnSuccess != nil { - - if swag.IsZero(m.OnSuccess) { // not required - return nil - } - - if err := m.OnSuccess.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("on_success") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("on_success") - } - - return err - } - } - - return nil -} - -func (m *Plan) contextValidatePut(ctx context.Context, formats strfmt.Registry) error { - - if m.Put != nil { - - if swag.IsZero(m.Put) { // not required - return nil - } - - if err := m.Put.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("put") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("put") - } - - return err - } - } - - return nil -} - -func (m *Plan) contextValidateRetry(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Retry); i++ { - - if m.Retry[i] != nil { - - if swag.IsZero(m.Retry[i]) { // not required - return nil - } - - if err := m.Retry[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("retry" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("retry" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Plan) contextValidateTask(ctx context.Context, formats strfmt.Registry) error { - - if m.Task != nil { - - if swag.IsZero(m.Task) { // not required - return nil - } - - if err := m.Task.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("task") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("task") - } - - return err - } - } - - return nil -} - -func (m *Plan) contextValidateTimeout(ctx context.Context, formats strfmt.Registry) error { - - if m.Timeout != nil { - - if swag.IsZero(m.Timeout) { // not required - return nil - } - - if err := m.Timeout.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("timeout") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("timeout") - } - - return err - } - } - - return nil -} - -func (m *Plan) contextValidateTry(ctx context.Context, formats strfmt.Registry) error { - - if m.Try != nil { - - if swag.IsZero(m.Try) { // not required - return nil - } - - if err := m.Try.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("try") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("try") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Plan) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Plan) UnmarshalBinary(b []byte) error { - var res Plan - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plan_config.go b/client/models/plan_config.go deleted file mode 100644 index 0b3444400..000000000 --- a/client/models/plan_config.go +++ /dev/null @@ -1,291 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// PlanConfig PlanConfig -// -// The plan configuration when creating new build. -// -// swagger:model PlanConfig -type PlanConfig struct { - - // aggregate - Aggregate []*PlanConfig `json:"aggregate"` - - // conditions - Conditions []string `json:"conditions"` - - // do - Do []*PlanConfig `json:"do"` - - // get - Get string `json:"get,omitempty"` - - // params - Params map[string]any `json:"params,omitempty"` - - // passed - Passed []string `json:"passed"` - - // privileged - Privileged bool `json:"privileged,omitempty"` - - // put - Put string `json:"put,omitempty"` - - // raw name - RawName string `json:"raw_name,omitempty"` - - // raw trigger - RawTrigger bool `json:"raw_trigger,omitempty"` - - // resource - Resource string `json:"resource,omitempty"` - - // task - Task string `json:"task,omitempty"` - - // task config - TaskConfig *TaskConfig `json:"taskConfig,omitempty"` - - // task config path - TaskConfigPath string `json:"taskConfigPath,omitempty"` -} - -// Validate validates this plan config -func (m *PlanConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAggregate(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDo(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTaskConfig(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PlanConfig) validateAggregate(formats strfmt.Registry) error { - if swag.IsZero(m.Aggregate) { // not required - return nil - } - - for i := 0; i < len(m.Aggregate); i++ { - if swag.IsZero(m.Aggregate[i]) { // not required - continue - } - - if m.Aggregate[i] != nil { - if err := m.Aggregate[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("aggregate" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("aggregate" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PlanConfig) validateDo(formats strfmt.Registry) error { - if swag.IsZero(m.Do) { // not required - return nil - } - - for i := 0; i < len(m.Do); i++ { - if swag.IsZero(m.Do[i]) { // not required - continue - } - - if m.Do[i] != nil { - if err := m.Do[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("do" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("do" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PlanConfig) validateTaskConfig(formats strfmt.Registry) error { - if swag.IsZero(m.TaskConfig) { // not required - return nil - } - - if m.TaskConfig != nil { - if err := m.TaskConfig.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("taskConfig") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("taskConfig") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this plan config based on the context it is used -func (m *PlanConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateAggregate(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateDo(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateTaskConfig(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PlanConfig) contextValidateAggregate(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Aggregate); i++ { - - if m.Aggregate[i] != nil { - - if swag.IsZero(m.Aggregate[i]) { // not required - return nil - } - - if err := m.Aggregate[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("aggregate" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("aggregate" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PlanConfig) contextValidateDo(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Do); i++ { - - if m.Do[i] != nil { - - if swag.IsZero(m.Do[i]) { // not required - return nil - } - - if err := m.Do[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("do" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("do" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PlanConfig) contextValidateTaskConfig(ctx context.Context, formats strfmt.Registry) error { - - if m.TaskConfig != nil { - - if swag.IsZero(m.TaskConfig) { // not required - return nil - } - - if err := m.TaskConfig.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("taskConfig") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("taskConfig") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *PlanConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PlanConfig) UnmarshalBinary(b []byte) error { - var res PlanConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plugin.go b/client/models/plugin.go deleted file mode 100644 index eb13692f7..000000000 --- a/client/models/plugin.go +++ /dev/null @@ -1,356 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Plugin Plugin -// -// # The Plugin that holds all the Versions -// -// swagger:model Plugin -type Plugin struct { - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // install - Install *PluginInstall `json:"install,omitempty"` - - // latest - Latest *PluginVersion `json:"latest,omitempty"` - - // Name assigned to the Plugin - // Required: true - Name *string `json:"name"` - - // True when the local install has no corresponding registry plugin - // (e.g. the registry plugin was deleted out-of-band, or the registry is - // unreachable). When true, Latest/Version fields may be zero-valued and - // update operations will be rejected. Defaults to false. - // - Orphaned bool `json:"orphaned,omitempty"` - - // If the plugin is owned - // Required: true - Owned *bool `json:"owned"` - - // registry - // Required: true - Registry *PluginRegistry `json:"registry"` - - // The relation of the Plugin with the current component, if any - Relation *PluginRelation `json:"relation,omitempty"` -} - -// Validate validates this plugin -func (m *Plugin) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInstall(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLatest(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwned(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRegistry(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRelation(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Plugin) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *Plugin) validateInstall(formats strfmt.Registry) error { - if swag.IsZero(m.Install) { // not required - return nil - } - - if m.Install != nil { - if err := m.Install.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("install") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("install") - } - - return err - } - } - - return nil -} - -func (m *Plugin) validateLatest(formats strfmt.Registry) error { - if swag.IsZero(m.Latest) { // not required - return nil - } - - if m.Latest != nil { - if err := m.Latest.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("latest") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("latest") - } - - return err - } - } - - return nil -} - -func (m *Plugin) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *Plugin) validateOwned(formats strfmt.Registry) error { - - if err := validate.Required("owned", "body", m.Owned); err != nil { - return err - } - - return nil -} - -func (m *Plugin) validateRegistry(formats strfmt.Registry) error { - - if err := validate.Required("registry", "body", m.Registry); err != nil { - return err - } - - if m.Registry != nil { - if err := m.Registry.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("registry") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("registry") - } - - return err - } - } - - return nil -} - -func (m *Plugin) validateRelation(formats strfmt.Registry) error { - if swag.IsZero(m.Relation) { // not required - return nil - } - - if m.Relation != nil { - if err := m.Relation.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("relation") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("relation") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this plugin based on the context it is used -func (m *Plugin) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateInstall(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateLatest(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateRegistry(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateRelation(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Plugin) contextValidateInstall(ctx context.Context, formats strfmt.Registry) error { - - if m.Install != nil { - - if swag.IsZero(m.Install) { // not required - return nil - } - - if err := m.Install.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("install") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("install") - } - - return err - } - } - - return nil -} - -func (m *Plugin) contextValidateLatest(ctx context.Context, formats strfmt.Registry) error { - - if m.Latest != nil { - - if swag.IsZero(m.Latest) { // not required - return nil - } - - if err := m.Latest.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("latest") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("latest") - } - - return err - } - } - - return nil -} - -func (m *Plugin) contextValidateRegistry(ctx context.Context, formats strfmt.Registry) error { - - if m.Registry != nil { - - if err := m.Registry.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("registry") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("registry") - } - - return err - } - } - - return nil -} - -func (m *Plugin) contextValidateRelation(ctx context.Context, formats strfmt.Registry) error { - - if m.Relation != nil { - - if swag.IsZero(m.Relation) { // not required - return nil - } - - if err := m.Relation.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("relation") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("relation") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Plugin) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Plugin) UnmarshalBinary(b []byte) error { - var res Plugin - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plugin_install.go b/client/models/plugin_install.go deleted file mode 100644 index 89d7f7aff..000000000 --- a/client/models/plugin_install.go +++ /dev/null @@ -1,296 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PluginInstall Plugin Install -// -// # The Plugin Install data -// -// swagger:model PluginInstall -type PluginInstall struct { - - // Stack Forms syntax configuration - // Required: true - Configuration map[string]string `json:"configuration"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // Secret used by the frontend to generate webhooks for the Plugin - // Required: true - PmSecret *string `json:"pm_secret"` - - // Status of the Plugin deployment process on Plugin Manager - // Required: true - // Enum: ["pending","running","failed"] - Status *string `json:"status"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` - - // Unique identifier of the Plugin Install - // Required: true - // Format: uuid - UUID *strfmt.UUID `json:"uuid"` - - // version - Version *PluginVersion `json:"version,omitempty"` -} - -// Validate validates this plugin install -func (m *PluginInstall) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfiguration(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePmSecret(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUUID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginInstall) validateConfiguration(formats strfmt.Registry) error { - - if err := validate.Required("configuration", "body", m.Configuration); err != nil { - return err - } - - return nil -} - -func (m *PluginInstall) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *PluginInstall) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *PluginInstall) validatePmSecret(formats strfmt.Registry) error { - - if err := validate.Required("pm_secret", "body", m.PmSecret); err != nil { - return err - } - - return nil -} - -var pluginInstallTypeStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["pending","running","failed"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - pluginInstallTypeStatusPropEnum = append(pluginInstallTypeStatusPropEnum, v) - } -} - -const ( - - // PluginInstallStatusPending captures enum value "pending" - PluginInstallStatusPending string = "pending" - - // PluginInstallStatusRunning captures enum value "running" - PluginInstallStatusRunning string = "running" - - // PluginInstallStatusFailed captures enum value "failed" - PluginInstallStatusFailed string = "failed" -) - -// prop value enum -func (m *PluginInstall) validateStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, pluginInstallTypeStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *PluginInstall) validateStatus(formats strfmt.Registry) error { - - if err := validate.Required("status", "body", m.Status); err != nil { - return err - } - - // value enum - if err := m.validateStatusEnum("status", "body", *m.Status); err != nil { - return err - } - - return nil -} - -func (m *PluginInstall) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *PluginInstall) validateUUID(formats strfmt.Registry) error { - - if err := validate.Required("uuid", "body", m.UUID); err != nil { - return err - } - - if err := validate.FormatOf("uuid", "body", "uuid", m.UUID.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *PluginInstall) validateVersion(formats strfmt.Registry) error { - if swag.IsZero(m.Version) { // not required - return nil - } - - if m.Version != nil { - if err := m.Version.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("version") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("version") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this plugin install based on the context it is used -func (m *PluginInstall) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateVersion(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginInstall) contextValidateVersion(ctx context.Context, formats strfmt.Registry) error { - - if m.Version != nil { - - if swag.IsZero(m.Version) { // not required - return nil - } - - if err := m.Version.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("version") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("version") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *PluginInstall) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PluginInstall) UnmarshalBinary(b []byte) error { - var res PluginInstall - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plugin_install_deployment_log.go b/client/models/plugin_install_deployment_log.go deleted file mode 100644 index 4f394036e..000000000 --- a/client/models/plugin_install_deployment_log.go +++ /dev/null @@ -1,92 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PluginInstallDeploymentLog Plugin Install Deployment Log -// -// # Plugin Install deployment log entry -// -// swagger:model PluginInstallDeploymentLog -type PluginInstallDeploymentLog struct { - - // message - // Required: true - Message *string `json:"message"` - - // timestamp - // Required: true - // Format: date-time - Timestamp *strfmt.DateTime `json:"timestamp"` -} - -// Validate validates this plugin install deployment log -func (m *PluginInstallDeploymentLog) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTimestamp(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginInstallDeploymentLog) validateMessage(formats strfmt.Registry) error { - - if err := validate.Required("message", "body", m.Message); err != nil { - return err - } - - return nil -} - -func (m *PluginInstallDeploymentLog) validateTimestamp(formats strfmt.Registry) error { - - if err := validate.Required("timestamp", "body", m.Timestamp); err != nil { - return err - } - - if err := validate.FormatOf("timestamp", "body", "date-time", m.Timestamp.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this plugin install deployment log based on context it is used -func (m *PluginInstallDeploymentLog) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PluginInstallDeploymentLog) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PluginInstallDeploymentLog) UnmarshalBinary(b []byte) error { - var res PluginInstallDeploymentLog - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plugin_install_runtime_log.go b/client/models/plugin_install_runtime_log.go deleted file mode 100644 index f6766273e..000000000 --- a/client/models/plugin_install_runtime_log.go +++ /dev/null @@ -1,114 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PluginInstallRuntimeLog Plugin Install Runtime Log -// -// # Plugin Install runtime log entry -// -// swagger:model PluginInstallRuntimeLog -type PluginInstallRuntimeLog struct { - - // Log line number - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // Text of the log line - // Required: true - Message *string `json:"message"` - - // Timestamp of the log line - // Required: true - // Format: date-time - Timestamp *strfmt.DateTime `json:"timestamp"` -} - -// Validate validates this plugin install runtime log -func (m *PluginInstallRuntimeLog) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTimestamp(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginInstallRuntimeLog) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *PluginInstallRuntimeLog) validateMessage(formats strfmt.Registry) error { - - if err := validate.Required("message", "body", m.Message); err != nil { - return err - } - - return nil -} - -func (m *PluginInstallRuntimeLog) validateTimestamp(formats strfmt.Registry) error { - - if err := validate.Required("timestamp", "body", m.Timestamp); err != nil { - return err - } - - if err := validate.FormatOf("timestamp", "body", "date-time", m.Timestamp.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this plugin install runtime log based on context it is used -func (m *PluginInstallRuntimeLog) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PluginInstallRuntimeLog) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PluginInstallRuntimeLog) UnmarshalBinary(b []byte) error { - var res PluginInstallRuntimeLog - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plugin_logs.go b/client/models/plugin_logs.go deleted file mode 100644 index 037dfd016..000000000 --- a/client/models/plugin_logs.go +++ /dev/null @@ -1,199 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// PluginLogs Plugin Logs -// -// # Combined runtime and installation logs for a plugin install -// -// swagger:model PluginLogs -type PluginLogs struct { - - // Deployment logs from the plugin installation process - InstallLogs []*PluginInstallDeploymentLog `json:"install_logs"` - - // Output logs from the running plugin process - RuntimeLogs []*PluginInstallRuntimeLog `json:"runtime_logs"` -} - -// Validate validates this plugin logs -func (m *PluginLogs) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateInstallLogs(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRuntimeLogs(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginLogs) validateInstallLogs(formats strfmt.Registry) error { - if swag.IsZero(m.InstallLogs) { // not required - return nil - } - - for i := 0; i < len(m.InstallLogs); i++ { - if swag.IsZero(m.InstallLogs[i]) { // not required - continue - } - - if m.InstallLogs[i] != nil { - if err := m.InstallLogs[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("install_logs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("install_logs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PluginLogs) validateRuntimeLogs(formats strfmt.Registry) error { - if swag.IsZero(m.RuntimeLogs) { // not required - return nil - } - - for i := 0; i < len(m.RuntimeLogs); i++ { - if swag.IsZero(m.RuntimeLogs[i]) { // not required - continue - } - - if m.RuntimeLogs[i] != nil { - if err := m.RuntimeLogs[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("runtime_logs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("runtime_logs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this plugin logs based on the context it is used -func (m *PluginLogs) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateInstallLogs(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateRuntimeLogs(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginLogs) contextValidateInstallLogs(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.InstallLogs); i++ { - - if m.InstallLogs[i] != nil { - - if swag.IsZero(m.InstallLogs[i]) { // not required - return nil - } - - if err := m.InstallLogs[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("install_logs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("install_logs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *PluginLogs) contextValidateRuntimeLogs(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.RuntimeLogs); i++ { - - if m.RuntimeLogs[i] != nil { - - if swag.IsZero(m.RuntimeLogs[i]) { // not required - return nil - } - - if err := m.RuntimeLogs[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("runtime_logs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("runtime_logs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *PluginLogs) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PluginLogs) UnmarshalBinary(b []byte) error { - var res PluginLogs - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plugin_manager.go b/client/models/plugin_manager.go deleted file mode 100644 index ecde75da6..000000000 --- a/client/models/plugin_manager.go +++ /dev/null @@ -1,263 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PluginManager Plugin Manager -// -// # The Plugin Manager instance -// -// swagger:model PluginManager -type PluginManager struct { - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // Status of the Plugin Manager invitation - // Required: true - // Enum: ["pending","accepted"] - InviteStatus *string `json:"invite_status"` - - // Name assigned to the Plugin Manager Instance - // Required: true - Name *string `json:"name"` - - // Status of the Plugin Manager connection - // Required: true - // Enum: ["offline","connected"] - Status *string `json:"status"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` - - // URL of the Plugin Version - // Required: true - // Format: uri - URL *strfmt.URI `json:"url"` -} - -// Validate validates this plugin manager -func (m *PluginManager) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInviteStatus(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginManager) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *PluginManager) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -var pluginManagerTypeInviteStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["pending","accepted"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - pluginManagerTypeInviteStatusPropEnum = append(pluginManagerTypeInviteStatusPropEnum, v) - } -} - -const ( - - // PluginManagerInviteStatusPending captures enum value "pending" - PluginManagerInviteStatusPending string = "pending" - - // PluginManagerInviteStatusAccepted captures enum value "accepted" - PluginManagerInviteStatusAccepted string = "accepted" -) - -// prop value enum -func (m *PluginManager) validateInviteStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, pluginManagerTypeInviteStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *PluginManager) validateInviteStatus(formats strfmt.Registry) error { - - if err := validate.Required("invite_status", "body", m.InviteStatus); err != nil { - return err - } - - // value enum - if err := m.validateInviteStatusEnum("invite_status", "body", *m.InviteStatus); err != nil { - return err - } - - return nil -} - -func (m *PluginManager) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -var pluginManagerTypeStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["offline","connected"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - pluginManagerTypeStatusPropEnum = append(pluginManagerTypeStatusPropEnum, v) - } -} - -const ( - - // PluginManagerStatusOffline captures enum value "offline" - PluginManagerStatusOffline string = "offline" - - // PluginManagerStatusConnected captures enum value "connected" - PluginManagerStatusConnected string = "connected" -) - -// prop value enum -func (m *PluginManager) validateStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, pluginManagerTypeStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *PluginManager) validateStatus(formats strfmt.Registry) error { - - if err := validate.Required("status", "body", m.Status); err != nil { - return err - } - - // value enum - if err := m.validateStatusEnum("status", "body", *m.Status); err != nil { - return err - } - - return nil -} - -func (m *PluginManager) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *PluginManager) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - if err := validate.FormatOf("url", "body", "uri", m.URL.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this plugin manager based on context it is used -func (m *PluginManager) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PluginManager) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PluginManager) UnmarshalBinary(b []byte) error { - var res PluginManager - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plugin_registry.go b/client/models/plugin_registry.go deleted file mode 100644 index 4a6a3354b..000000000 --- a/client/models/plugin_registry.go +++ /dev/null @@ -1,228 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PluginRegistry Plugin Registry -// -// # The Plugin Registry that holds all the available Plugins -// -// swagger:model PluginRegistry -type PluginRegistry struct { - - // If you have access to create Plugins - // Required: true - Access *bool `json:"access"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // Name assigned to the Repository - // Required: true - Name *string `json:"name"` - - // Status of the Plugin Registry - // Required: true - // Enum: ["offline","connected"] - Status *string `json:"status"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` - - // URL of the Plugin Registry - // Required: true - // Format: uri - URL *strfmt.URI `json:"url"` -} - -// Validate validates this plugin registry -func (m *PluginRegistry) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAccess(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginRegistry) validateAccess(formats strfmt.Registry) error { - - if err := validate.Required("access", "body", m.Access); err != nil { - return err - } - - return nil -} - -func (m *PluginRegistry) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *PluginRegistry) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *PluginRegistry) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -var pluginRegistryTypeStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["offline","connected"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - pluginRegistryTypeStatusPropEnum = append(pluginRegistryTypeStatusPropEnum, v) - } -} - -const ( - - // PluginRegistryStatusOffline captures enum value "offline" - PluginRegistryStatusOffline string = "offline" - - // PluginRegistryStatusConnected captures enum value "connected" - PluginRegistryStatusConnected string = "connected" -) - -// prop value enum -func (m *PluginRegistry) validateStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, pluginRegistryTypeStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *PluginRegistry) validateStatus(formats strfmt.Registry) error { - - if err := validate.Required("status", "body", m.Status); err != nil { - return err - } - - // value enum - if err := m.validateStatusEnum("status", "body", *m.Status); err != nil { - return err - } - - return nil -} - -func (m *PluginRegistry) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *PluginRegistry) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - if err := validate.FormatOf("url", "body", "uri", m.URL.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this plugin registry based on context it is used -func (m *PluginRegistry) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PluginRegistry) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PluginRegistry) UnmarshalBinary(b []byte) error { - var res PluginRegistry - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plugin_relation.go b/client/models/plugin_relation.go deleted file mode 100644 index 551ad60c7..000000000 --- a/client/models/plugin_relation.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PluginRelation Plugin Relation -// -// # The relation between a Plugin and a Component -// -// swagger:model PluginRelation -type PluginRelation struct { - - // If the Plugin is enabled for the Component - // Required: true - Enabled *bool `json:"enabled"` - - // List of relations between a Plugin and a Component - // Required: true - Relations any `json:"relations"` -} - -// Validate validates this plugin relation -func (m *PluginRelation) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEnabled(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRelations(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginRelation) validateEnabled(formats strfmt.Registry) error { - - if err := validate.Required("enabled", "body", m.Enabled); err != nil { - return err - } - - return nil -} - -func (m *PluginRelation) validateRelations(formats strfmt.Registry) error { - - if m.Relations == nil { - return errors.Required("relations", "body", nil) - } - - return nil -} - -// ContextValidate validates this plugin relation based on context it is used -func (m *PluginRelation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PluginRelation) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PluginRelation) UnmarshalBinary(b []byte) error { - var res PluginRelation - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plugin_version.go b/client/models/plugin_version.go deleted file mode 100644 index b4b5dedad..000000000 --- a/client/models/plugin_version.go +++ /dev/null @@ -1,235 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PluginVersion Plugin -// -// # The Plugin that holds all the Versions -// -// swagger:model PluginVersion -type PluginVersion struct { - - // Stack Forms syntax configuration - Configuration []any `json:"configuration"` - - // The Description of the Plugin Version - Description string `json:"description,omitempty"` - - // If an error happen on the creation of the Version this will hold the info - Error string `json:"error,omitempty"` - - // Icon of the Plugin Version - // Format: uri - Icon strfmt.URI `json:"icon,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // Images to show the Plugin Version - Images []strfmt.URI `json:"images"` - - // Name assigned to the Plugin - // Required: true - Name *string `json:"name"` - - // Schema of the SQLite schema - Schema any `json:"schema,omitempty"` - - // Policies in which the Plugin Version is scoped - Scope []string `json:"scope"` - - // Status of the current Plugin Version creation process - // Required: true - // Enum: ["pending","processing","failed","success"] - Status *string `json:"status"` - - // URL of the Plugin Version - // Required: true - // Format: uri - URL *strfmt.URI `json:"url"` - - // List of default Widgets configuration - Widgets []any `json:"widgets"` -} - -// Validate validates this plugin version -func (m *PluginVersion) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateIcon(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateImages(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginVersion) validateIcon(formats strfmt.Registry) error { - if swag.IsZero(m.Icon) { // not required - return nil - } - - if err := validate.FormatOf("icon", "body", "uri", m.Icon.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *PluginVersion) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *PluginVersion) validateImages(formats strfmt.Registry) error { - if swag.IsZero(m.Images) { // not required - return nil - } - - for i := 0; i < len(m.Images); i++ { - - if err := validate.FormatOf("images"+"."+strconv.Itoa(i), "body", "uri", m.Images[i].String(), formats); err != nil { - return err - } - - } - - return nil -} - -func (m *PluginVersion) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -var pluginVersionTypeStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["pending","processing","failed","success"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - pluginVersionTypeStatusPropEnum = append(pluginVersionTypeStatusPropEnum, v) - } -} - -const ( - - // PluginVersionStatusPending captures enum value "pending" - PluginVersionStatusPending string = "pending" - - // PluginVersionStatusProcessing captures enum value "processing" - PluginVersionStatusProcessing string = "processing" - - // PluginVersionStatusFailed captures enum value "failed" - PluginVersionStatusFailed string = "failed" - - // PluginVersionStatusSuccess captures enum value "success" - PluginVersionStatusSuccess string = "success" -) - -// prop value enum -func (m *PluginVersion) validateStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, pluginVersionTypeStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *PluginVersion) validateStatus(formats strfmt.Registry) error { - - if err := validate.Required("status", "body", m.Status); err != nil { - return err - } - - // value enum - if err := m.validateStatusEnum("status", "body", *m.Status); err != nil { - return err - } - - return nil -} - -func (m *PluginVersion) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - if err := validate.FormatOf("url", "body", "uri", m.URL.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this plugin version based on context it is used -func (m *PluginVersion) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PluginVersion) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PluginVersion) UnmarshalBinary(b []byte) error { - var res PluginVersion - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plugin_version_log.go b/client/models/plugin_version_log.go deleted file mode 100644 index 8c4b0791c..000000000 --- a/client/models/plugin_version_log.go +++ /dev/null @@ -1,92 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PluginVersionLog PluginVersionLog -// -// # The Plugin Version Log info -// -// swagger:model PluginVersionLog -type PluginVersionLog struct { - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // Text of the log line - // Required: true - Message *string `json:"message"` -} - -// Validate validates this plugin version log -func (m *PluginVersionLog) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMessage(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginVersionLog) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *PluginVersionLog) validateMessage(formats strfmt.Registry) error { - - if err := validate.Required("message", "body", m.Message); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this plugin version log based on context it is used -func (m *PluginVersionLog) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PluginVersionLog) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PluginVersionLog) UnmarshalBinary(b []byte) error { - var res PluginVersionLog - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plugin_widget.go b/client/models/plugin_widget.go deleted file mode 100644 index 74a2d9252..000000000 --- a/client/models/plugin_widget.go +++ /dev/null @@ -1,141 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PluginWidget Plugin Widget -// -// # A widget associated with an installed Plugin -// -// swagger:model PluginWidget -type PluginWidget struct { - - // id - // Minimum: 1 - ID uint32 `json:"id,omitempty"` - - // Whether this is a default widget - // Required: true - IsDefault *bool `json:"is_default"` - - // Placement configuration of the widget - // Required: true - Placement any `json:"placement"` - - // Type of the widget - // Required: true - Type *string `json:"type"` - - // Widget configuration - // Required: true - Widget any `json:"widget"` -} - -// Validate validates this plugin widget -func (m *PluginWidget) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIsDefault(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePlacement(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateWidget(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginWidget) validateID(formats strfmt.Registry) error { - if swag.IsZero(m.ID) { // not required - return nil - } - - if err := validate.MinimumUint("id", "body", uint64(m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *PluginWidget) validateIsDefault(formats strfmt.Registry) error { - - if err := validate.Required("is_default", "body", m.IsDefault); err != nil { - return err - } - - return nil -} - -func (m *PluginWidget) validatePlacement(formats strfmt.Registry) error { - - if m.Placement == nil { - return errors.Required("placement", "body", nil) - } - - return nil -} - -func (m *PluginWidget) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - return nil -} - -func (m *PluginWidget) validateWidget(formats strfmt.Registry) error { - - if m.Widget == nil { - return errors.Required("widget", "body", nil) - } - - return nil -} - -// ContextValidate validates this plugin widget based on context it is used -func (m *PluginWidget) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PluginWidget) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PluginWidget) UnmarshalBinary(b []byte) error { - var res PluginWidget - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/plugin_widget_data.go b/client/models/plugin_widget_data.go deleted file mode 100644 index 3da79e885..000000000 --- a/client/models/plugin_widget_data.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PluginWidgetData Plugin Widget Data -// -// # The Plugin Widget query response data -// -// swagger:model PluginWidgetData -type PluginWidgetData struct { - - // Data returned from executing query on the plugin - // Required: true - Data []any `json:"data"` -} - -// Validate validates this plugin widget data -func (m *PluginWidgetData) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateData(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PluginWidgetData) validateData(formats strfmt.Registry) error { - - if err := validate.Required("data", "body", m.Data); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this plugin widget data based on context it is used -func (m *PluginWidgetData) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PluginWidgetData) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PluginWidgetData) UnmarshalBinary(b []byte) error { - var res PluginWidgetData - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/policy.go b/client/models/policy.go deleted file mode 100644 index 1cc80979d..000000000 --- a/client/models/policy.go +++ /dev/null @@ -1,167 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Policy Policy -// -// Policy represents a permission or constraint to access to an entity of the system. A policy is aggregated into roles in order to be applied. -// -// swagger:model Policy -type Policy struct { - - // code - // Required: true - // Max Length: 60 - // Min Length: 5 - // Pattern: (?:[a-z]+_)*[a-z]+(?::(?:[a-z]+_)*[a-z]+)*$ - Code *string `json:"code"` - - // created at - // Minimum: 0 - CreatedAt *uint64 `json:"created_at,omitempty"` - - // description - // Required: true - Description *string `json:"description"` - - // entities - Entities []string `json:"entities"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // updated at - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` -} - -// Validate validates this policy -func (m *Policy) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCode(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Policy) validateCode(formats strfmt.Registry) error { - - if err := validate.Required("code", "body", m.Code); err != nil { - return err - } - - if err := validate.MinLength("code", "body", *m.Code, 5); err != nil { - return err - } - - if err := validate.MaxLength("code", "body", *m.Code, 60); err != nil { - return err - } - - if err := validate.Pattern("code", "body", *m.Code, `(?:[a-z]+_)*[a-z]+(?::(?:[a-z]+_)*[a-z]+)*$`); err != nil { - return err - } - - return nil -} - -func (m *Policy) validateCreatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Policy) validateDescription(formats strfmt.Registry) error { - - if err := validate.Required("description", "body", m.Description); err != nil { - return err - } - - return nil -} - -func (m *Policy) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *Policy) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this policy based on context it is used -func (m *Policy) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *Policy) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Policy) UnmarshalBinary(b []byte) error { - var res Policy - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/preparation.go b/client/models/preparation.go deleted file mode 100644 index b8409c8a3..000000000 --- a/client/models/preparation.go +++ /dev/null @@ -1,170 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Preparation Preparation -// -// swagger:model Preparation -type Preparation struct { - - // build id - // Required: true - BuildID *string `json:"build_id"` - - // inputs - // Required: true - Inputs any `json:"inputs"` - - // inputs satisfied - // Required: true - InputsSatisfied any `json:"inputs_satisfied"` - - // max running builds - // Required: true - MaxRunningBuilds *string `json:"max_running_builds"` - - // missing input reasons - // Required: true - MissingInputReasons any `json:"missing_input_reasons"` - - // paused job - // Required: true - PausedJob *string `json:"paused_job"` - - // paused pipeline - // Required: true - PausedPipeline *string `json:"paused_pipeline"` -} - -// Validate validates this preparation -func (m *Preparation) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBuildID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInputs(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInputsSatisfied(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMaxRunningBuilds(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMissingInputReasons(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePausedJob(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePausedPipeline(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Preparation) validateBuildID(formats strfmt.Registry) error { - - if err := validate.Required("build_id", "body", m.BuildID); err != nil { - return err - } - - return nil -} - -func (m *Preparation) validateInputs(formats strfmt.Registry) error { - - if m.Inputs == nil { - return errors.Required("inputs", "body", nil) - } - - return nil -} - -func (m *Preparation) validateInputsSatisfied(formats strfmt.Registry) error { - - if m.InputsSatisfied == nil { - return errors.Required("inputs_satisfied", "body", nil) - } - - return nil -} - -func (m *Preparation) validateMaxRunningBuilds(formats strfmt.Registry) error { - - if err := validate.Required("max_running_builds", "body", m.MaxRunningBuilds); err != nil { - return err - } - - return nil -} - -func (m *Preparation) validateMissingInputReasons(formats strfmt.Registry) error { - - if m.MissingInputReasons == nil { - return errors.Required("missing_input_reasons", "body", nil) - } - - return nil -} - -func (m *Preparation) validatePausedJob(formats strfmt.Registry) error { - - if err := validate.Required("paused_job", "body", m.PausedJob); err != nil { - return err - } - - return nil -} - -func (m *Preparation) validatePausedPipeline(formats strfmt.Registry) error { - - if err := validate.Required("paused_pipeline", "body", m.PausedPipeline); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this preparation based on context it is used -func (m *Preparation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *Preparation) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Preparation) UnmarshalBinary(b []byte) error { - var res Preparation - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/project.go b/client/models/project.go deleted file mode 100644 index a66aa040c..000000000 --- a/client/models/project.go +++ /dev/null @@ -1,438 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Project Project -// -// The entity which represents the information of a project. -// -// swagger:model Project -type Project struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - Canonical *string `json:"canonical"` - - // color - // Required: true - // Max Length: 64 - Color *string `json:"color"` - - // config repository canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - ConfigRepositoryCanonical string `json:"config_repository_canonical,omitempty"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // description - Description string `json:"description,omitempty"` - - // environments - // Required: true - Environments []*Environment `json:"environments"` - - // favorite - Favorite bool `json:"favorite,omitempty"` - - // icon - // Required: true - // Max Length: 64 - Icon *string `json:"icon"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // name - // Required: true - // Min Length: 1 - Name *string `json:"name"` - - // Organization member that owns this project. When a user is the owner of a - // project it has all the permissions on it. - // In the event where the user has been deleted that field might be empty. - // - Owner *User `json:"owner,omitempty"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` - - // Aggregated value of the Environments Components Version.Status - VersionStatus []string `json:"version_status"` -} - -// Validate validates this project -func (m *Project) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateColor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateConfigRepositoryCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironments(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIcon(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersionStatus(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Project) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -func (m *Project) validateColor(formats strfmt.Registry) error { - - if err := validate.Required("color", "body", m.Color); err != nil { - return err - } - - if err := validate.MaxLength("color", "body", *m.Color, 64); err != nil { - return err - } - - return nil -} - -func (m *Project) validateConfigRepositoryCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ConfigRepositoryCanonical) { // not required - return nil - } - - if err := validate.MinLength("config_repository_canonical", "body", m.ConfigRepositoryCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("config_repository_canonical", "body", m.ConfigRepositoryCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("config_repository_canonical", "body", m.ConfigRepositoryCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *Project) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Project) validateEnvironments(formats strfmt.Registry) error { - - if err := validate.Required("environments", "body", m.Environments); err != nil { - return err - } - - for i := 0; i < len(m.Environments); i++ { - if swag.IsZero(m.Environments[i]) { // not required - continue - } - - if m.Environments[i] != nil { - if err := m.Environments[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environments" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environments" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Project) validateIcon(formats strfmt.Registry) error { - - if err := validate.Required("icon", "body", m.Icon); err != nil { - return err - } - - if err := validate.MaxLength("icon", "body", *m.Icon, 64); err != nil { - return err - } - - return nil -} - -func (m *Project) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *Project) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - return nil -} - -func (m *Project) validateOwner(formats strfmt.Registry) error { - if swag.IsZero(m.Owner) { // not required - return nil - } - - if m.Owner != nil { - if err := m.Owner.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *Project) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -var projectVersionStatusItemsEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["no_status","latest","active","deleted","outdated"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - projectVersionStatusItemsEnum = append(projectVersionStatusItemsEnum, v) - } -} - -func (m *Project) validateVersionStatusItemsEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, projectVersionStatusItemsEnum, true); err != nil { - return err - } - return nil -} - -func (m *Project) validateVersionStatus(formats strfmt.Registry) error { - if swag.IsZero(m.VersionStatus) { // not required - return nil - } - - for i := 0; i < len(m.VersionStatus); i++ { - - // value enum - if err := m.validateVersionStatusItemsEnum("version_status"+"."+strconv.Itoa(i), "body", m.VersionStatus[i]); err != nil { - return err - } - - } - - return nil -} - -// ContextValidate validate this project based on the context it is used -func (m *Project) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateEnvironments(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateOwner(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Project) contextValidateEnvironments(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Environments); i++ { - - if m.Environments[i] != nil { - - if swag.IsZero(m.Environments[i]) { // not required - return nil - } - - if err := m.Environments[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environments" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environments" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Project) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { - - if m.Owner != nil { - - if swag.IsZero(m.Owner) { // not required - return nil - } - - if err := m.Owner.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Project) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Project) UnmarshalBinary(b []byte) error { - var res Project - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/project_environment.go b/client/models/project_environment.go deleted file mode 100644 index 5f7e00e92..000000000 --- a/client/models/project_environment.go +++ /dev/null @@ -1,508 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ProjectEnvironment Project Environment -// -// Represent an environment linked to a project with its associated components. This extends the base Environment with project-specific relations. -// -// swagger:model ProjectEnvironment -type ProjectEnvironment struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$ - Canonical *string `json:"canonical"` - - // cloud accounts - CloudAccounts []*CloudAccountSimple `json:"cloud_accounts"` - - // components - Components []*Component `json:"components"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // Optional description of the environment - // Max Length: 1000 - Description string `json:"description,omitempty"` - - // environment type - EnvironmentType *EnvironmentType `json:"environment_type,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // The display name of the environment - // Max Length: 100 - // Min Length: 1 - Name string `json:"name,omitempty"` - - // Organization member that owns this environment. When a user is the owner of an - // environment it has all the permissions on it. - // In the event where the user has been deleted this field might be empty. - // - Owner *User `json:"owner,omitempty"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` - - // When the environment is returned alongside Project this will be set with the aggregated value of the Components Version.Status it has - VersionStatus []string `json:"version_status"` -} - -// Validate validates this project environment -func (m *ProjectEnvironment) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudAccounts(formats); err != nil { - res = append(res, err) - } - - if err := m.validateComponents(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironmentType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersionStatus(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ProjectEnvironment) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[\da-zA-Z]+(?:[\da-zA-Z\-._]+[\da-zA-Z]|[\da-zA-Z])$`); err != nil { - return err - } - - return nil -} - -func (m *ProjectEnvironment) validateCloudAccounts(formats strfmt.Registry) error { - if swag.IsZero(m.CloudAccounts) { // not required - return nil - } - - for i := 0; i < len(m.CloudAccounts); i++ { - if swag.IsZero(m.CloudAccounts[i]) { // not required - continue - } - - if m.CloudAccounts[i] != nil { - if err := m.CloudAccounts[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cloud_accounts" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cloud_accounts" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ProjectEnvironment) validateComponents(formats strfmt.Registry) error { - if swag.IsZero(m.Components) { // not required - return nil - } - - for i := 0; i < len(m.Components); i++ { - if swag.IsZero(m.Components[i]) { // not required - continue - } - - if m.Components[i] != nil { - if err := m.Components[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("components" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("components" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ProjectEnvironment) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *ProjectEnvironment) validateDescription(formats strfmt.Registry) error { - if swag.IsZero(m.Description) { // not required - return nil - } - - if err := validate.MaxLength("description", "body", m.Description, 1000); err != nil { - return err - } - - return nil -} - -func (m *ProjectEnvironment) validateEnvironmentType(formats strfmt.Registry) error { - if swag.IsZero(m.EnvironmentType) { // not required - return nil - } - - if m.EnvironmentType != nil { - if err := m.EnvironmentType.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment_type") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment_type") - } - - return err - } - } - - return nil -} - -func (m *ProjectEnvironment) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *ProjectEnvironment) validateName(formats strfmt.Registry) error { - if swag.IsZero(m.Name) { // not required - return nil - } - - if err := validate.MinLength("name", "body", m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", m.Name, 100); err != nil { - return err - } - - return nil -} - -func (m *ProjectEnvironment) validateOwner(formats strfmt.Registry) error { - if swag.IsZero(m.Owner) { // not required - return nil - } - - if m.Owner != nil { - if err := m.Owner.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *ProjectEnvironment) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -var projectEnvironmentVersionStatusItemsEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["no_status","latest","active","deleted","outdated"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - projectEnvironmentVersionStatusItemsEnum = append(projectEnvironmentVersionStatusItemsEnum, v) - } -} - -func (m *ProjectEnvironment) validateVersionStatusItemsEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, projectEnvironmentVersionStatusItemsEnum, true); err != nil { - return err - } - return nil -} - -func (m *ProjectEnvironment) validateVersionStatus(formats strfmt.Registry) error { - if swag.IsZero(m.VersionStatus) { // not required - return nil - } - - for i := 0; i < len(m.VersionStatus); i++ { - - // value enum - if err := m.validateVersionStatusItemsEnum("version_status"+"."+strconv.Itoa(i), "body", m.VersionStatus[i]); err != nil { - return err - } - - } - - return nil -} - -// ContextValidate validate this project environment based on the context it is used -func (m *ProjectEnvironment) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateCloudAccounts(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateComponents(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateEnvironmentType(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateOwner(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ProjectEnvironment) contextValidateCloudAccounts(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.CloudAccounts); i++ { - - if m.CloudAccounts[i] != nil { - - if swag.IsZero(m.CloudAccounts[i]) { // not required - return nil - } - - if err := m.CloudAccounts[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cloud_accounts" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cloud_accounts" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ProjectEnvironment) contextValidateComponents(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Components); i++ { - - if m.Components[i] != nil { - - if swag.IsZero(m.Components[i]) { // not required - return nil - } - - if err := m.Components[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("components" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("components" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ProjectEnvironment) contextValidateEnvironmentType(ctx context.Context, formats strfmt.Registry) error { - - if m.EnvironmentType != nil { - - if swag.IsZero(m.EnvironmentType) { // not required - return nil - } - - if err := m.EnvironmentType.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("environment_type") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("environment_type") - } - - return err - } - } - - return nil -} - -func (m *ProjectEnvironment) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { - - if m.Owner != nil { - - if swag.IsZero(m.Owner) { // not required - return nil - } - - if err := m.Owner.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ProjectEnvironment) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ProjectEnvironment) UnmarshalBinary(b []byte) error { - var res ProjectEnvironment - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/project_simple.go b/client/models/project_simple.go deleted file mode 100644 index 4ee4334e4..000000000 --- a/client/models/project_simple.go +++ /dev/null @@ -1,291 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ProjectSimple ProjectSimple -// -// The entity which represents minimal information of a project. -// -// swagger:model ProjectSimple -type ProjectSimple struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - Canonical *string `json:"canonical"` - - // color - // Required: true - // Max Length: 64 - Color *string `json:"color"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // description - Description string `json:"description,omitempty"` - - // favorite - Favorite bool `json:"favorite,omitempty"` - - // icon - // Required: true - // Max Length: 64 - Icon *string `json:"icon"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // name - // Required: true - // Min Length: 1 - Name *string `json:"name"` - - // Organization member that owns this project. When a user is the owner of a - // project it has all the permissions on it. - // In the event where the user has been deleted that field might be empty. - // - Owner *User `json:"owner,omitempty"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` -} - -// Validate validates this project simple -func (m *ProjectSimple) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateColor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIcon(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ProjectSimple) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -func (m *ProjectSimple) validateColor(formats strfmt.Registry) error { - - if err := validate.Required("color", "body", m.Color); err != nil { - return err - } - - if err := validate.MaxLength("color", "body", *m.Color, 64); err != nil { - return err - } - - return nil -} - -func (m *ProjectSimple) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *ProjectSimple) validateIcon(formats strfmt.Registry) error { - - if err := validate.Required("icon", "body", m.Icon); err != nil { - return err - } - - if err := validate.MaxLength("icon", "body", *m.Icon, 64); err != nil { - return err - } - - return nil -} - -func (m *ProjectSimple) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *ProjectSimple) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - return nil -} - -func (m *ProjectSimple) validateOwner(formats strfmt.Registry) error { - if swag.IsZero(m.Owner) { // not required - return nil - } - - if m.Owner != nil { - if err := m.Owner.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *ProjectSimple) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this project simple based on the context it is used -func (m *ProjectSimple) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateOwner(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ProjectSimple) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { - - if m.Owner != nil { - - if swag.IsZero(m.Owner) { // not required - return nil - } - - if err := m.Owner.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ProjectSimple) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ProjectSimple) UnmarshalBinary(b []byte) error { - var res ProjectSimple - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/public_build_input.go b/client/models/public_build_input.go deleted file mode 100644 index d768f9b79..000000000 --- a/client/models/public_build_input.go +++ /dev/null @@ -1,121 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PublicBuildInput PublicBuildInput -// -// # Represent the information of a build input -// -// swagger:model PublicBuildInput -type PublicBuildInput struct { - - // first occurrence - // Required: true - FirstOccurrence *bool `json:"first_occurrence"` - - // name - // Required: true - Name *string `json:"name"` - - // pipeline id - // Required: true - PipelineID *uint64 `json:"pipeline_id"` - - // version - // Required: true - Version map[string]string `json:"version"` -} - -// Validate validates this public build input -func (m *PublicBuildInput) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateFirstOccurrence(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePipelineID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PublicBuildInput) validateFirstOccurrence(formats strfmt.Registry) error { - - if err := validate.Required("first_occurrence", "body", m.FirstOccurrence); err != nil { - return err - } - - return nil -} - -func (m *PublicBuildInput) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *PublicBuildInput) validatePipelineID(formats strfmt.Registry) error { - - if err := validate.Required("pipeline_id", "body", m.PipelineID); err != nil { - return err - } - - return nil -} - -func (m *PublicBuildInput) validateVersion(formats strfmt.Registry) error { - - if err := validate.Required("version", "body", m.Version); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this public build input based on context it is used -func (m *PublicBuildInput) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PublicBuildInput) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PublicBuildInput) UnmarshalBinary(b []byte) error { - var res PublicBuildInput - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/public_build_output.go b/client/models/public_build_output.go deleted file mode 100644 index a2aadf924..000000000 --- a/client/models/public_build_output.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PublicBuildOutput PublicBuildOutput -// -// # Represents the information of a build output -// -// swagger:model PublicBuildOutput -type PublicBuildOutput struct { - - // name - // Required: true - Name *string `json:"name"` - - // version - // Required: true - Version map[string]string `json:"version"` -} - -// Validate validates this public build output -func (m *PublicBuildOutput) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PublicBuildOutput) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *PublicBuildOutput) validateVersion(formats strfmt.Registry) error { - - if err := validate.Required("version", "body", m.Version); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this public build output based on context it is used -func (m *PublicBuildOutput) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PublicBuildOutput) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PublicBuildOutput) UnmarshalBinary(b []byte) error { - var res PublicBuildOutput - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/public_plan.go b/client/models/public_plan.go deleted file mode 100644 index 55bdbf483..000000000 --- a/client/models/public_plan.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PublicPlan PublicPlan -// -// The public plan returned requesting a build plan. -// -// swagger:model PublicPlan -type PublicPlan struct { - - // plan - // Required: true - Plan any `json:"plan"` - - // schema - // Required: true - Schema *string `json:"schema"` -} - -// Validate validates this public plan -func (m *PublicPlan) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validatePlan(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSchema(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PublicPlan) validatePlan(formats strfmt.Registry) error { - - if m.Plan == nil { - return errors.Required("plan", "body", nil) - } - - return nil -} - -func (m *PublicPlan) validateSchema(formats strfmt.Registry) error { - - if err := validate.Required("schema", "body", m.Schema); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this public plan based on context it is used -func (m *PublicPlan) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *PublicPlan) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PublicPlan) UnmarshalBinary(b []byte) error { - var res PublicPlan - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/put_plan.go b/client/models/put_plan.go deleted file mode 100644 index cf9cc0779..000000000 --- a/client/models/put_plan.go +++ /dev/null @@ -1,198 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// PutPlan PutPlan -// -// The put plan following a plan. -// -// swagger:model PutPlan -type PutPlan struct { - - // name - Name string `json:"name,omitempty"` - - // params - Params map[string]any `json:"params,omitempty"` - - // resource - // Required: true - Resource *string `json:"resource"` - - // source - // Required: true - Source map[string]any `json:"source"` - - // tags - Tags []string `json:"tags"` - - // type - // Required: true - Type *string `json:"type"` - - // versioned resource types - VersionedResourceTypes []*VersionedResourceType `json:"versioned_resource_types"` -} - -// Validate validates this put plan -func (m *PutPlan) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateResource(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSource(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersionedResourceTypes(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PutPlan) validateResource(formats strfmt.Registry) error { - - if err := validate.Required("resource", "body", m.Resource); err != nil { - return err - } - - return nil -} - -func (m *PutPlan) validateSource(formats strfmt.Registry) error { - - if err := validate.Required("source", "body", m.Source); err != nil { - return err - } - - for k := range m.Source { - - if err := validate.Required("source"+"."+k, "body", m.Source[k]); err != nil { - return err - } - - } - - return nil -} - -func (m *PutPlan) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - return nil -} - -func (m *PutPlan) validateVersionedResourceTypes(formats strfmt.Registry) error { - if swag.IsZero(m.VersionedResourceTypes) { // not required - return nil - } - - for i := 0; i < len(m.VersionedResourceTypes); i++ { - if swag.IsZero(m.VersionedResourceTypes[i]) { // not required - continue - } - - if m.VersionedResourceTypes[i] != nil { - if err := m.VersionedResourceTypes[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("versioned_resource_types" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("versioned_resource_types" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this put plan based on the context it is used -func (m *PutPlan) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateVersionedResourceTypes(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *PutPlan) contextValidateVersionedResourceTypes(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.VersionedResourceTypes); i++ { - - if m.VersionedResourceTypes[i] != nil { - - if swag.IsZero(m.VersionedResourceTypes[i]) { // not required - return nil - } - - if err := m.VersionedResourceTypes[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("versioned_resource_types" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("versioned_resource_types" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *PutPlan) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *PutPlan) UnmarshalBinary(b []byte) error { - var res PutPlan - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/resource.go b/client/models/resource.go deleted file mode 100644 index 11efdee70..000000000 --- a/client/models/resource.go +++ /dev/null @@ -1,176 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Resource Resource -// -// The entity which represents a resource in the application. -// -// swagger:model Resource -type Resource struct { - - // build - Build *BuildSummary `json:"build,omitempty"` - - // icon - Icon string `json:"icon,omitempty"` - - // last checked - LastChecked uint64 `json:"last_checked,omitempty"` - - // name - // Required: true - Name *string `json:"name"` - - // pin comment - PinComment string `json:"pin_comment,omitempty"` - - // pinned in config - PinnedInConfig bool `json:"pinned_in_config,omitempty"` - - // pinned version - PinnedVersion map[string]string `json:"pinned_version,omitempty"` - - // pipeline id - PipelineID uint64 `json:"pipeline_id,omitempty"` - - // pipeline name - PipelineName string `json:"pipeline_name,omitempty"` - - // team name - TeamName string `json:"team_name,omitempty"` - - // type - // Required: true - Type *string `json:"type"` -} - -// Validate validates this resource -func (m *Resource) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBuild(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Resource) validateBuild(formats strfmt.Registry) error { - if swag.IsZero(m.Build) { // not required - return nil - } - - if m.Build != nil { - if err := m.Build.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("build") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("build") - } - - return err - } - } - - return nil -} - -func (m *Resource) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *Resource) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this resource based on the context it is used -func (m *Resource) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateBuild(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Resource) contextValidateBuild(ctx context.Context, formats strfmt.Registry) error { - - if m.Build != nil { - - if swag.IsZero(m.Build) { // not required - return nil - } - - if err := m.Build.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("build") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("build") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Resource) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Resource) UnmarshalBinary(b []byte) error { - var res Resource - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/resource_version.go b/client/models/resource_version.go deleted file mode 100644 index 2a89fb73d..000000000 --- a/client/models/resource_version.go +++ /dev/null @@ -1,181 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ResourceVersion ResourceVersion -// -// # Represent the outputs of a job -// -// swagger:model ResourceVersion -type ResourceVersion struct { - - // enabled - // Required: true - Enabled *bool `json:"enabled"` - - // id - // Required: true - ID *uint64 `json:"id"` - - // metadata - Metadata []*MetadataField `json:"metadata"` - - // version - // Required: true - Version map[string]string `json:"version"` -} - -// Validate validates this resource version -func (m *ResourceVersion) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEnabled(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMetadata(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ResourceVersion) validateEnabled(formats strfmt.Registry) error { - - if err := validate.Required("enabled", "body", m.Enabled); err != nil { - return err - } - - return nil -} - -func (m *ResourceVersion) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - return nil -} - -func (m *ResourceVersion) validateMetadata(formats strfmt.Registry) error { - if swag.IsZero(m.Metadata) { // not required - return nil - } - - for i := 0; i < len(m.Metadata); i++ { - if swag.IsZero(m.Metadata[i]) { // not required - continue - } - - if m.Metadata[i] != nil { - if err := m.Metadata[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("metadata" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("metadata" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ResourceVersion) validateVersion(formats strfmt.Registry) error { - - if err := validate.Required("version", "body", m.Version); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this resource version based on the context it is used -func (m *ResourceVersion) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateMetadata(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ResourceVersion) contextValidateMetadata(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Metadata); i++ { - - if m.Metadata[i] != nil { - - if swag.IsZero(m.Metadata[i]) { // not required - return nil - } - - if err := m.Metadata[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("metadata" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("metadata" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ResourceVersion) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ResourceVersion) UnmarshalBinary(b []byte) error { - var res ResourceVersion - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/role.go b/client/models/role.go deleted file mode 100644 index c1123904e..000000000 --- a/client/models/role.go +++ /dev/null @@ -1,287 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Role Role access control -// -// Role represents the authorization level that an user has to access to a specific entity of the system. A role contains a list of rules to define the access control. Note not all the entities supports roles access control; see the API endpoints to know which entities support them. -// -// swagger:model Role -type Role struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // created at - // Minimum: 0 - CreatedAt *uint64 `json:"created_at,omitempty"` - - // default - // Required: true - Default *bool `json:"default"` - - // description - // Required: true - Description *string `json:"description"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // name - // Required: true - // Max Length: 100 - // Min Length: 3 - Name *string `json:"name"` - - // rules - // Required: true - Rules []*Rule `json:"rules"` - - // updated at - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` -} - -// Validate validates this role -func (m *Role) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDefault(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRules(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Role) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *Role) validateCreatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Role) validateDefault(formats strfmt.Registry) error { - - if err := validate.Required("default", "body", m.Default); err != nil { - return err - } - - return nil -} - -func (m *Role) validateDescription(formats strfmt.Registry) error { - - if err := validate.Required("description", "body", m.Description); err != nil { - return err - } - - return nil -} - -func (m *Role) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *Role) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 100); err != nil { - return err - } - - return nil -} - -func (m *Role) validateRules(formats strfmt.Registry) error { - - if err := validate.Required("rules", "body", m.Rules); err != nil { - return err - } - - for i := 0; i < len(m.Rules); i++ { - if swag.IsZero(m.Rules[i]) { // not required - continue - } - - if m.Rules[i] != nil { - if err := m.Rules[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("rules" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("rules" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Role) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this role based on the context it is used -func (m *Role) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateRules(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Role) contextValidateRules(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Rules); i++ { - - if m.Rules[i] != nil { - - if swag.IsZero(m.Rules[i]) { // not required - return nil - } - - if err := m.Rules[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("rules" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("rules" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Role) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Role) UnmarshalBinary(b []byte) error { - var res Role - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/rule.go b/client/models/rule.go deleted file mode 100644 index 8779d9313..000000000 --- a/client/models/rule.go +++ /dev/null @@ -1,145 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Rule Rule -// -// # Rules define the specific access to the platform -// -// swagger:model Rule -type Rule struct { - - // It can be the normal Policy.Code or contain globs like `*` or `**` - // Required: true - Action *string `json:"action"` - - // effect - // Required: true - // Enum: ["allow"] - Effect *string `json:"effect"` - - // This is the id of the row from the database, but for blocking organizations we generate rules that are not in the database. When this happens the id is allowed to be 0. - // Required: true - // Minimum: 0 - ID *uint32 `json:"id"` - - // It is the list of resources in which this Rule applies to, the format of it is the one on the Policy.Code but with the `canonical` of the entities like `organization:org-can:team:team-can` for an action of `organization:team:read` - Resources []string `json:"resources"` -} - -// Validate validates this rule -func (m *Rule) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAction(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEffect(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Rule) validateAction(formats strfmt.Registry) error { - - if err := validate.Required("action", "body", m.Action); err != nil { - return err - } - - return nil -} - -var ruleTypeEffectPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["allow"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - ruleTypeEffectPropEnum = append(ruleTypeEffectPropEnum, v) - } -} - -const ( - - // RuleEffectAllow captures enum value "allow" - RuleEffectAllow string = "allow" -) - -// prop value enum -func (m *Rule) validateEffectEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, ruleTypeEffectPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *Rule) validateEffect(formats strfmt.Registry) error { - - if err := validate.Required("effect", "body", m.Effect); err != nil { - return err - } - - // value enum - if err := m.validateEffectEnum("effect", "body", *m.Effect); err != nil { - return err - } - - return nil -} - -func (m *Rule) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this rule based on context it is used -func (m *Rule) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *Rule) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Rule) UnmarshalBinary(b []byte) error { - var res Rule - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/s_c_config.go b/client/models/s_c_config.go deleted file mode 100644 index 2999c1380..000000000 --- a/client/models/s_c_config.go +++ /dev/null @@ -1,132 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// SCConfig SC Config -// -// # This entity is being used for automatic creation of SC config -// -// swagger:model SCConfig -type SCConfig struct { - - // Config files that will be created - // Required: true - Configs []*ConfigFile `json:"configs"` -} - -// Validate validates this s c config -func (m *SCConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfigs(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SCConfig) validateConfigs(formats strfmt.Registry) error { - - if err := validate.Required("configs", "body", m.Configs); err != nil { - return err - } - - for i := 0; i < len(m.Configs); i++ { - if swag.IsZero(m.Configs[i]) { // not required - continue - } - - if m.Configs[i] != nil { - if err := m.Configs[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this s c config based on the context it is used -func (m *SCConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateConfigs(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SCConfig) contextValidateConfigs(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Configs); i++ { - - if m.Configs[i] != nil { - - if swag.IsZero(m.Configs[i]) { // not required - return nil - } - - if err := m.Configs[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *SCConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *SCConfig) UnmarshalBinary(b []byte) error { - var res SCConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/s_c_config_custom_config.go b/client/models/s_c_config_custom_config.go deleted file mode 100644 index 8503f8ef0..000000000 --- a/client/models/s_c_config_custom_config.go +++ /dev/null @@ -1,149 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// SCConfigCustomConfig Custom Tech Configuration -// -// # Represents the Service Catalog Configuration for Custom Tech for a given Use Case -// -// swagger:model SCConfigCustomConfig -type SCConfigCustomConfig struct { - - // templates - // Required: true - Templates []*SCTemplateConfig `json:"templates"` - - // A path to a file holding selected values of variables (JSON format) - // Required: true - VarPath *string `json:"var_path"` -} - -// Validate validates this s c config custom config -func (m *SCConfigCustomConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateTemplates(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVarPath(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SCConfigCustomConfig) validateTemplates(formats strfmt.Registry) error { - - if err := validate.Required("templates", "body", m.Templates); err != nil { - return err - } - - for i := 0; i < len(m.Templates); i++ { - if swag.IsZero(m.Templates[i]) { // not required - continue - } - - if m.Templates[i] != nil { - if err := m.Templates[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("templates" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("templates" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *SCConfigCustomConfig) validateVarPath(formats strfmt.Registry) error { - - if err := validate.Required("var_path", "body", m.VarPath); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this s c config custom config based on the context it is used -func (m *SCConfigCustomConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateTemplates(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SCConfigCustomConfig) contextValidateTemplates(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Templates); i++ { - - if m.Templates[i] != nil { - - if swag.IsZero(m.Templates[i]) { // not required - return nil - } - - if err := m.Templates[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("templates" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("templates" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *SCConfigCustomConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *SCConfigCustomConfig) UnmarshalBinary(b []byte) error { - var res SCConfigCustomConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/s_c_config_form_data.go b/client/models/s_c_config_form_data.go deleted file mode 100644 index bfe2f0837..000000000 --- a/client/models/s_c_config_form_data.go +++ /dev/null @@ -1,99 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// SCConfigFormData Form Data -// -// # Represents the Data related to Forms that is stored in a SC Configuration for a given Use Case -// -// swagger:model SCConfigFormData -type SCConfigFormData map[string]map[string][]FormEntity - -// Validate validates this s c config form data -func (m SCConfigFormData) Validate(formats strfmt.Registry) error { - var res []error - - for k := range m { - - for kk := range m[k] { - - if err := validate.Required(k+"."+kk, "body", m[k][kk]); err != nil { - return err - } - - for i := 0; i < len(m[k][kk]); i++ { - - if err := m[k][kk][i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName(k + "." + kk + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName(k + "." + kk + "." + strconv.Itoa(i)) - } - - return err - } - - } - - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// ContextValidate validate this s c config form data based on the context it is used -func (m SCConfigFormData) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - for k := range m { - - for kk := range m[k] { - - for i := 0; i < len(m[k][kk]); i++ { - - if swag.IsZero(m[k][kk][i]) { // not required - return nil - } - - if err := m[k][kk][i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName(k + "." + kk + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName(k + "." + kk + "." + strconv.Itoa(i)) - } - - return err - } - - } - - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/client/models/s_c_config_path_config.go b/client/models/s_c_config_path_config.go deleted file mode 100644 index b5ab2ba03..000000000 --- a/client/models/s_c_config_path_config.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// SCConfigPathConfig Path Configuration -// -// # Represents a Configuration which holds Path and Content -// -// swagger:model SCConfigPathConfig -type SCConfigPathConfig struct { - - // content - // Required: true - Content *string `json:"content"` - - // path - // Required: true - Path *string `json:"path"` -} - -// Validate validates this s c config path config -func (m *SCConfigPathConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateContent(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePath(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SCConfigPathConfig) validateContent(formats strfmt.Registry) error { - - if err := validate.Required("content", "body", m.Content); err != nil { - return err - } - - return nil -} - -func (m *SCConfigPathConfig) validatePath(formats strfmt.Registry) error { - - if err := validate.Required("path", "body", m.Path); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this s c config path config based on context it is used -func (m *SCConfigPathConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *SCConfigPathConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *SCConfigPathConfig) UnmarshalBinary(b []byte) error { - var res SCConfigPathConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/s_c_config_path_dest_config.go b/client/models/s_c_config_path_dest_config.go deleted file mode 100644 index 49bdee975..000000000 --- a/client/models/s_c_config_path_dest_config.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// SCConfigPathDestConfig Path and Destination Configuration -// -// # Represents a Configuration which holds Path, Destination and Content -// -// swagger:model SCConfigPathDestConfig -type SCConfigPathDestConfig struct { - - // content - // Required: true - Content *string `json:"content"` - - // destination - // Required: true - Destination *string `json:"destination"` - - // path - // Required: true - Path *string `json:"path"` -} - -// Validate validates this s c config path dest config -func (m *SCConfigPathDestConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateContent(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDestination(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePath(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SCConfigPathDestConfig) validateContent(formats strfmt.Registry) error { - - if err := validate.Required("content", "body", m.Content); err != nil { - return err - } - - return nil -} - -func (m *SCConfigPathDestConfig) validateDestination(formats strfmt.Registry) error { - - if err := validate.Required("destination", "body", m.Destination); err != nil { - return err - } - - return nil -} - -func (m *SCConfigPathDestConfig) validatePath(formats strfmt.Registry) error { - - if err := validate.Required("path", "body", m.Path); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this s c config path dest config based on context it is used -func (m *SCConfigPathDestConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *SCConfigPathDestConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *SCConfigPathDestConfig) UnmarshalBinary(b []byte) error { - var res SCConfigPathDestConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/s_c_config_pipeline_config.go b/client/models/s_c_config_pipeline_config.go deleted file mode 100644 index f15c2e7db..000000000 --- a/client/models/s_c_config_pipeline_config.go +++ /dev/null @@ -1,173 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// SCConfigPipelineConfig Pipeline Configuration -// -// # Represents the Service Catalog Configuration for a Pipeline of a given Use Case -// -// swagger:model SCConfigPipelineConfig -type SCConfigPipelineConfig struct { - - // pipeline - // Required: true - Pipeline *SCConfigPathConfig `json:"pipeline"` - - // variables - // Required: true - Variables *SCConfigPathDestConfig `json:"variables"` -} - -// Validate validates this s c config pipeline config -func (m *SCConfigPipelineConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validatePipeline(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVariables(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SCConfigPipelineConfig) validatePipeline(formats strfmt.Registry) error { - - if err := validate.Required("pipeline", "body", m.Pipeline); err != nil { - return err - } - - if m.Pipeline != nil { - if err := m.Pipeline.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("pipeline") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("pipeline") - } - - return err - } - } - - return nil -} - -func (m *SCConfigPipelineConfig) validateVariables(formats strfmt.Registry) error { - - if err := validate.Required("variables", "body", m.Variables); err != nil { - return err - } - - if m.Variables != nil { - if err := m.Variables.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("variables") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("variables") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this s c config pipeline config based on the context it is used -func (m *SCConfigPipelineConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidatePipeline(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateVariables(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SCConfigPipelineConfig) contextValidatePipeline(ctx context.Context, formats strfmt.Registry) error { - - if m.Pipeline != nil { - - if err := m.Pipeline.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("pipeline") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("pipeline") - } - - return err - } - } - - return nil -} - -func (m *SCConfigPipelineConfig) contextValidateVariables(ctx context.Context, formats strfmt.Registry) error { - - if m.Variables != nil { - - if err := m.Variables.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("variables") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("variables") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *SCConfigPipelineConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *SCConfigPipelineConfig) UnmarshalBinary(b []byte) error { - var res SCConfigPipelineConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/s_c_config_tech_config.go b/client/models/s_c_config_tech_config.go deleted file mode 100644 index ef819a5cf..000000000 --- a/client/models/s_c_config_tech_config.go +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" -) - -// SCConfigTechConfig Tech Configuration -// -// # Represents the Service Catalog Configuration for a Technology of a given Use Case -// -// swagger:model SCConfigTechConfig -type SCConfigTechConfig map[string]SCConfigPathDestConfig - -// Validate validates this s c config tech config -func (m SCConfigTechConfig) Validate(formats strfmt.Registry) error { - var res []error - - for k := range m { - - if err := validate.Required(k, "body", m[k]); err != nil { - return err - } - if val, ok := m[k]; ok { - if err := val.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName(k) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName(k) - } - - return err - } - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// ContextValidate validate this s c config tech config based on the context it is used -func (m SCConfigTechConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - for k := range m { - - if val, ok := m[k]; ok { - if err := val.ContextValidate(ctx, formats); err != nil { - return err - } - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/client/models/s_c_optional_template_config.go b/client/models/s_c_optional_template_config.go deleted file mode 100644 index 6b0c146fc..000000000 --- a/client/models/s_c_optional_template_config.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// SCOptionalTemplateConfig An optional configuration of a single template -// -// Represents an optional configuration of a single template (defined by a Custom technology) -// -// swagger:model SCOptionalTemplateConfig -type SCOptionalTemplateConfig struct { - - // Informs whether the destination path is a file. If set to true, the input templates will be contatenated after the template execution and saved in the destination as a single file. - // It's false by default. - DestinationIsFile bool `json:"destination_is_file,omitempty"` -} - -// Validate validates this s c optional template config -func (m *SCOptionalTemplateConfig) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this s c optional template config based on context it is used -func (m *SCOptionalTemplateConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *SCOptionalTemplateConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *SCOptionalTemplateConfig) UnmarshalBinary(b []byte) error { - var res SCOptionalTemplateConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/s_c_template_config.go b/client/models/s_c_template_config.go deleted file mode 100644 index b220b4f81..000000000 --- a/client/models/s_c_template_config.go +++ /dev/null @@ -1,166 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// SCTemplateConfig A configuration of a single template -// -// Represents a Configuration of a single template (defined by a Custom technology) -// -// swagger:model SCTemplateConfig -type SCTemplateConfig struct { - - // config - Config *SCOptionalTemplateConfig `json:"config,omitempty"` - - // Holds the content of input files found in the Paths. - // The key is an input file and the value is the content of the file. - Content map[string]string `json:"content,omitempty"` - - // Destination path. By default, it's a directory, where the input files will be recreated maintaining the original file tree. - // This behavior can be changed by setting `destination_is_file` in optional configs to `true`. - // By doing that, the destination path will be treated as a file, not a directory. - // - // Required: true - Destination *string `json:"destination"` - - // Paths where common template helpers (parts) are located - Helpers []string `json:"helpers"` - - // Holds the content of the helpers found in Helpers paths. - // The key is a helper file path and the value is the content of the file. - HelpersContent map[string]string `json:"helpers_content,omitempty"` - - // Input Paths where the teplate files will be found - // Required: true - Paths []string `json:"paths"` -} - -// Validate validates this s c template config -func (m *SCTemplateConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfig(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDestination(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePaths(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SCTemplateConfig) validateConfig(formats strfmt.Registry) error { - if swag.IsZero(m.Config) { // not required - return nil - } - - if m.Config != nil { - if err := m.Config.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("config") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("config") - } - - return err - } - } - - return nil -} - -func (m *SCTemplateConfig) validateDestination(formats strfmt.Registry) error { - - if err := validate.Required("destination", "body", m.Destination); err != nil { - return err - } - - return nil -} - -func (m *SCTemplateConfig) validatePaths(formats strfmt.Registry) error { - - if err := validate.Required("paths", "body", m.Paths); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this s c template config based on the context it is used -func (m *SCTemplateConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateConfig(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SCTemplateConfig) contextValidateConfig(ctx context.Context, formats strfmt.Registry) error { - - if m.Config != nil { - - if swag.IsZero(m.Config) { // not required - return nil - } - - if err := m.Config.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("config") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("config") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *SCTemplateConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *SCTemplateConfig) UnmarshalBinary(b []byte) error { - var res SCTemplateConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/service_catalog.go b/client/models/service_catalog.go deleted file mode 100644 index 0f657a684..000000000 --- a/client/models/service_catalog.go +++ /dev/null @@ -1,741 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ServiceCatalog Service Catalog -// -// # Represents the Service Catalog item -// -// swagger:model ServiceCatalog -type ServiceCatalog struct { - - // author - // Required: true - Author *string `json:"author"` - - // Determines if given stack is a blueprint - Blueprint bool `json:"blueprint,omitempty"` - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // Cloud providers supported by the stack - CloudProviders []*CloudProvider `json:"cloud_providers"` - - // created at - // Minimum: 0 - CreatedAt *uint64 `json:"created_at,omitempty"` - - // Default version of the stack, based on the Catalog Repository branch - DefaultVersionBranch string `json:"default_version_branch,omitempty"` - - // dependencies - Dependencies []*ServiceCatalogDependency `json:"dependencies"` - - // description - Description string `json:"description,omitempty"` - - // Directory where the ServiceCatalog configuration is found. - // Required: true - Directory *string `json:"directory"` - - // Indicates if this stack can be configured with form's or not. Based on the presence or not of a valid .forms.yaml file since it's creation or last refresh. - // Required: true - FormEnabled *bool `json:"form_enabled"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // image - // Format: uri - Image strfmt.URI `json:"image,omitempty"` - - // The import process status. - // Enum: ["succeeded","failed","importing"] - ImportStatus string `json:"import_status,omitempty"` - - // keywords - // Required: true - Keywords []string `json:"keywords"` - - // Indicates if the stack uses the latest version - // Required: true - Latest *bool `json:"latest"` - - // name - // Required: true - Name *string `json:"name"` - - // Organization that the stack belongs to - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - OrganizationCanonical *string `json:"organization_canonical"` - - // Readme of the stack - Readme string `json:"readme,omitempty"` - - // ref - // Required: true - Ref *string `json:"ref"` - - // service catalog source canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - ServiceCatalogSourceCanonical string `json:"service_catalog_source_canonical,omitempty"` - - // Team that maintains the stack - Team *SimpleTeam `json:"team,omitempty"` - - // technologies - Technologies []*ServiceCatalogTechnology `json:"technologies"` - - // If 'true' the ServiceCatalog is from the main organization and can be trusted. - // Required: true - Trusted *bool `json:"trusted"` - - // updated at - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` - - // Version of the stack - // Required: true - Version *string `json:"version"` - - // visibility - // Required: true - Visibility *string `json:"visibility"` -} - -// Validate validates this service catalog -func (m *ServiceCatalog) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAuthor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProviders(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDependencies(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDirectory(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFormEnabled(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateImage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateImportStatus(formats); err != nil { - res = append(res, err) - } - - if err := m.validateKeywords(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLatest(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOrganizationCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRef(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalogSourceCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTeam(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTechnologies(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTrusted(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVisibility(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ServiceCatalog) validateAuthor(formats strfmt.Registry) error { - - if err := validate.Required("author", "body", m.Author); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateCloudProviders(formats strfmt.Registry) error { - if swag.IsZero(m.CloudProviders) { // not required - return nil - } - - for i := 0; i < len(m.CloudProviders); i++ { - if swag.IsZero(m.CloudProviders[i]) { // not required - continue - } - - if m.CloudProviders[i] != nil { - if err := m.CloudProviders[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cloud_providers" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cloud_providers" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalog) validateCreatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateDependencies(formats strfmt.Registry) error { - if swag.IsZero(m.Dependencies) { // not required - return nil - } - - for i := 0; i < len(m.Dependencies); i++ { - if swag.IsZero(m.Dependencies[i]) { // not required - continue - } - - if m.Dependencies[i] != nil { - if err := m.Dependencies[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("dependencies" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("dependencies" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalog) validateDirectory(formats strfmt.Registry) error { - - if err := validate.Required("directory", "body", m.Directory); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateFormEnabled(formats strfmt.Registry) error { - - if err := validate.Required("form_enabled", "body", m.FormEnabled); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateImage(formats strfmt.Registry) error { - if swag.IsZero(m.Image) { // not required - return nil - } - - if err := validate.FormatOf("image", "body", "uri", m.Image.String(), formats); err != nil { - return err - } - - return nil -} - -var serviceCatalogTypeImportStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["succeeded","failed","importing"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - serviceCatalogTypeImportStatusPropEnum = append(serviceCatalogTypeImportStatusPropEnum, v) - } -} - -const ( - - // ServiceCatalogImportStatusSucceeded captures enum value "succeeded" - ServiceCatalogImportStatusSucceeded string = "succeeded" - - // ServiceCatalogImportStatusFailed captures enum value "failed" - ServiceCatalogImportStatusFailed string = "failed" - - // ServiceCatalogImportStatusImporting captures enum value "importing" - ServiceCatalogImportStatusImporting string = "importing" -) - -// prop value enum -func (m *ServiceCatalog) validateImportStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, serviceCatalogTypeImportStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *ServiceCatalog) validateImportStatus(formats strfmt.Registry) error { - if swag.IsZero(m.ImportStatus) { // not required - return nil - } - - // value enum - if err := m.validateImportStatusEnum("import_status", "body", m.ImportStatus); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateKeywords(formats strfmt.Registry) error { - - if err := validate.Required("keywords", "body", m.Keywords); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateLatest(formats strfmt.Registry) error { - - if err := validate.Required("latest", "body", m.Latest); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateOrganizationCanonical(formats strfmt.Registry) error { - - if err := validate.Required("organization_canonical", "body", m.OrganizationCanonical); err != nil { - return err - } - - if err := validate.MinLength("organization_canonical", "body", *m.OrganizationCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("organization_canonical", "body", *m.OrganizationCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("organization_canonical", "body", *m.OrganizationCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateRef(formats strfmt.Registry) error { - - if err := validate.Required("ref", "body", m.Ref); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateServiceCatalogSourceCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ServiceCatalogSourceCanonical) { // not required - return nil - } - - if err := validate.MinLength("service_catalog_source_canonical", "body", m.ServiceCatalogSourceCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("service_catalog_source_canonical", "body", m.ServiceCatalogSourceCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("service_catalog_source_canonical", "body", m.ServiceCatalogSourceCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateTeam(formats strfmt.Registry) error { - if swag.IsZero(m.Team) { // not required - return nil - } - - if m.Team != nil { - if err := m.Team.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("team") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("team") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalog) validateTechnologies(formats strfmt.Registry) error { - if swag.IsZero(m.Technologies) { // not required - return nil - } - - for i := 0; i < len(m.Technologies); i++ { - if swag.IsZero(m.Technologies[i]) { // not required - continue - } - - if m.Technologies[i] != nil { - if err := m.Technologies[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("technologies" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("technologies" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalog) validateTrusted(formats strfmt.Registry) error { - - if err := validate.Required("trusted", "body", m.Trusted); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateVersion(formats strfmt.Registry) error { - - if err := validate.Required("version", "body", m.Version); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalog) validateVisibility(formats strfmt.Registry) error { - - if err := validate.Required("visibility", "body", m.Visibility); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this service catalog based on the context it is used -func (m *ServiceCatalog) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateCloudProviders(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateDependencies(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateTeam(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateTechnologies(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ServiceCatalog) contextValidateCloudProviders(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.CloudProviders); i++ { - - if m.CloudProviders[i] != nil { - - if swag.IsZero(m.CloudProviders[i]) { // not required - return nil - } - - if err := m.CloudProviders[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("cloud_providers" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("cloud_providers" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalog) contextValidateDependencies(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Dependencies); i++ { - - if m.Dependencies[i] != nil { - - if swag.IsZero(m.Dependencies[i]) { // not required - return nil - } - - if err := m.Dependencies[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("dependencies" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("dependencies" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalog) contextValidateTeam(ctx context.Context, formats strfmt.Registry) error { - - if m.Team != nil { - - if swag.IsZero(m.Team) { // not required - return nil - } - - if err := m.Team.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("team") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("team") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalog) contextValidateTechnologies(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Technologies); i++ { - - if m.Technologies[i] != nil { - - if swag.IsZero(m.Technologies[i]) { // not required - return nil - } - - if err := m.Technologies[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("technologies" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("technologies" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ServiceCatalog) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ServiceCatalog) UnmarshalBinary(b []byte) error { - var res ServiceCatalog - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/service_catalog_changes.go b/client/models/service_catalog_changes.go deleted file mode 100644 index 859309e78..000000000 --- a/client/models/service_catalog_changes.go +++ /dev/null @@ -1,416 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ServiceCatalogChanges ServiceCatalogChanges -// -// Represents list of service catalogs changes during the refresh of a service catalog source. Errored stacks are included in the corresponding field. The "details" field of the ErrorDetailsItem contains the stack canonical, if any. -// -// swagger:model ServiceCatalogChanges -type ServiceCatalogChanges struct { - - // created - // Required: true - Created []*ServiceCatalog `json:"created"` - - // deleted - // Required: true - Deleted []*ServiceCatalog `json:"deleted"` - - // errored - Errored []*ErrorDetailsItem `json:"errored"` - - // updated - // Required: true - Updated []*ServiceCatalog `json:"updated"` - - // versions - Versions []*ServiceCatalogSourceVersion `json:"versions"` -} - -// Validate validates this service catalog changes -func (m *ServiceCatalogChanges) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCreated(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDeleted(formats); err != nil { - res = append(res, err) - } - - if err := m.validateErrored(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdated(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersions(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ServiceCatalogChanges) validateCreated(formats strfmt.Registry) error { - - if err := validate.Required("created", "body", m.Created); err != nil { - return err - } - - for i := 0; i < len(m.Created); i++ { - if swag.IsZero(m.Created[i]) { // not required - continue - } - - if m.Created[i] != nil { - if err := m.Created[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("created" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("created" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalogChanges) validateDeleted(formats strfmt.Registry) error { - - if err := validate.Required("deleted", "body", m.Deleted); err != nil { - return err - } - - for i := 0; i < len(m.Deleted); i++ { - if swag.IsZero(m.Deleted[i]) { // not required - continue - } - - if m.Deleted[i] != nil { - if err := m.Deleted[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("deleted" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("deleted" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalogChanges) validateErrored(formats strfmt.Registry) error { - if swag.IsZero(m.Errored) { // not required - return nil - } - - for i := 0; i < len(m.Errored); i++ { - if swag.IsZero(m.Errored[i]) { // not required - continue - } - - if m.Errored[i] != nil { - if err := m.Errored[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("errored" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("errored" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalogChanges) validateUpdated(formats strfmt.Registry) error { - - if err := validate.Required("updated", "body", m.Updated); err != nil { - return err - } - - for i := 0; i < len(m.Updated); i++ { - if swag.IsZero(m.Updated[i]) { // not required - continue - } - - if m.Updated[i] != nil { - if err := m.Updated[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("updated" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("updated" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalogChanges) validateVersions(formats strfmt.Registry) error { - if swag.IsZero(m.Versions) { // not required - return nil - } - - for i := 0; i < len(m.Versions); i++ { - if swag.IsZero(m.Versions[i]) { // not required - continue - } - - if m.Versions[i] != nil { - if err := m.Versions[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("versions" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("versions" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this service catalog changes based on the context it is used -func (m *ServiceCatalogChanges) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateCreated(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateDeleted(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateErrored(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateUpdated(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateVersions(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ServiceCatalogChanges) contextValidateCreated(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Created); i++ { - - if m.Created[i] != nil { - - if swag.IsZero(m.Created[i]) { // not required - return nil - } - - if err := m.Created[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("created" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("created" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalogChanges) contextValidateDeleted(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Deleted); i++ { - - if m.Deleted[i] != nil { - - if swag.IsZero(m.Deleted[i]) { // not required - return nil - } - - if err := m.Deleted[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("deleted" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("deleted" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalogChanges) contextValidateErrored(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Errored); i++ { - - if m.Errored[i] != nil { - - if swag.IsZero(m.Errored[i]) { // not required - return nil - } - - if err := m.Errored[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("errored" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("errored" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalogChanges) contextValidateUpdated(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Updated); i++ { - - if m.Updated[i] != nil { - - if swag.IsZero(m.Updated[i]) { // not required - return nil - } - - if err := m.Updated[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("updated" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("updated" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalogChanges) contextValidateVersions(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Versions); i++ { - - if m.Versions[i] != nil { - - if swag.IsZero(m.Versions[i]) { // not required - return nil - } - - if err := m.Versions[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("versions" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("versions" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ServiceCatalogChanges) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ServiceCatalogChanges) UnmarshalBinary(b []byte) error { - var res ServiceCatalogChanges - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/service_catalog_config.go b/client/models/service_catalog_config.go deleted file mode 100644 index 59e5fd300..000000000 --- a/client/models/service_catalog_config.go +++ /dev/null @@ -1,397 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ServiceCatalogConfig Use Case Configuration -// -// # Represents the Service Catalog Configuration for a given Use Case -// -// swagger:model ServiceCatalogConfig -type ServiceCatalogConfig struct { - - // ansible - Ansible SCConfigTechConfig `json:"ansible,omitempty"` - - // cloud provider - // Required: true - CloudProvider *string `json:"cloud_provider"` - - // custom - Custom *SCConfigCustomConfig `json:"custom,omitempty"` - - // description - // Required: true - Description *string `json:"description"` - - // forms - Forms *FormUseCase `json:"forms,omitempty"` - - // name - // Required: true - Name *string `json:"name"` - - // pipeline - // Required: true - Pipeline *SCConfigPipelineConfig `json:"pipeline"` - - // terraform - Terraform SCConfigTechConfig `json:"terraform,omitempty"` -} - -// Validate validates this service catalog config -func (m *ServiceCatalogConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAnsible(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloudProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCustom(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateForms(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePipeline(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTerraform(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ServiceCatalogConfig) validateAnsible(formats strfmt.Registry) error { - if swag.IsZero(m.Ansible) { // not required - return nil - } - - if m.Ansible != nil { - if err := m.Ansible.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("ansible") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("ansible") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalogConfig) validateCloudProvider(formats strfmt.Registry) error { - - if err := validate.Required("cloud_provider", "body", m.CloudProvider); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogConfig) validateCustom(formats strfmt.Registry) error { - if swag.IsZero(m.Custom) { // not required - return nil - } - - if m.Custom != nil { - if err := m.Custom.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("custom") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("custom") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalogConfig) validateDescription(formats strfmt.Registry) error { - - if err := validate.Required("description", "body", m.Description); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogConfig) validateForms(formats strfmt.Registry) error { - if swag.IsZero(m.Forms) { // not required - return nil - } - - if m.Forms != nil { - if err := m.Forms.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("forms") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("forms") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalogConfig) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogConfig) validatePipeline(formats strfmt.Registry) error { - - if err := validate.Required("pipeline", "body", m.Pipeline); err != nil { - return err - } - - if m.Pipeline != nil { - if err := m.Pipeline.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("pipeline") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("pipeline") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalogConfig) validateTerraform(formats strfmt.Registry) error { - if swag.IsZero(m.Terraform) { // not required - return nil - } - - if m.Terraform != nil { - if err := m.Terraform.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("terraform") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("terraform") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this service catalog config based on the context it is used -func (m *ServiceCatalogConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateAnsible(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateCustom(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateForms(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidatePipeline(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateTerraform(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ServiceCatalogConfig) contextValidateAnsible(ctx context.Context, formats strfmt.Registry) error { - - if swag.IsZero(m.Ansible) { // not required - return nil - } - - if err := m.Ansible.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("ansible") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("ansible") - } - - return err - } - - return nil -} - -func (m *ServiceCatalogConfig) contextValidateCustom(ctx context.Context, formats strfmt.Registry) error { - - if m.Custom != nil { - - if swag.IsZero(m.Custom) { // not required - return nil - } - - if err := m.Custom.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("custom") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("custom") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalogConfig) contextValidateForms(ctx context.Context, formats strfmt.Registry) error { - - if m.Forms != nil { - - if swag.IsZero(m.Forms) { // not required - return nil - } - - if err := m.Forms.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("forms") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("forms") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalogConfig) contextValidatePipeline(ctx context.Context, formats strfmt.Registry) error { - - if m.Pipeline != nil { - - if err := m.Pipeline.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("pipeline") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("pipeline") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalogConfig) contextValidateTerraform(ctx context.Context, formats strfmt.Registry) error { - - if swag.IsZero(m.Terraform) { // not required - return nil - } - - if err := m.Terraform.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("terraform") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("terraform") - } - - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ServiceCatalogConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ServiceCatalogConfig) UnmarshalBinary(b []byte) error { - var res ServiceCatalogConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/service_catalog_configs.go b/client/models/service_catalog_configs.go deleted file mode 100644 index f62733e2b..000000000 --- a/client/models/service_catalog_configs.go +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" -) - -// ServiceCatalogConfigs Service Catalog Configurations -// -// # Represents the Service Catalog Configuration assigned per Use case -// -// swagger:model ServiceCatalogConfigs -type ServiceCatalogConfigs map[string]ServiceCatalogConfig - -// Validate validates this service catalog configs -func (m ServiceCatalogConfigs) Validate(formats strfmt.Registry) error { - var res []error - - for k := range m { - - if err := validate.Required(k, "body", m[k]); err != nil { - return err - } - if val, ok := m[k]; ok { - if err := val.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName(k) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName(k) - } - - return err - } - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// ContextValidate validate this service catalog configs based on the context it is used -func (m ServiceCatalogConfigs) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - for k := range m { - - if val, ok := m[k]; ok { - if err := val.ContextValidate(ctx, formats); err != nil { - return err - } - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/client/models/service_catalog_dependencies_validation_result.go b/client/models/service_catalog_dependencies_validation_result.go deleted file mode 100644 index f9a9dc0da..000000000 --- a/client/models/service_catalog_dependencies_validation_result.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ServiceCatalogDependenciesValidationResult ServiceCatalogValidationResult -// -// The result of the Service Catalog dependencies validation. If errors and warnings are empty then it means that the dependencies are respected. -// -// swagger:model ServiceCatalogDependenciesValidationResult -type ServiceCatalogDependenciesValidationResult struct { - - // errors - // Required: true - Errors []string `json:"errors"` - - // warnings - // Required: true - Warnings []string `json:"warnings"` -} - -// Validate validates this service catalog dependencies validation result -func (m *ServiceCatalogDependenciesValidationResult) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateErrors(formats); err != nil { - res = append(res, err) - } - - if err := m.validateWarnings(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ServiceCatalogDependenciesValidationResult) validateErrors(formats strfmt.Registry) error { - - if err := validate.Required("errors", "body", m.Errors); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogDependenciesValidationResult) validateWarnings(formats strfmt.Registry) error { - - if err := validate.Required("warnings", "body", m.Warnings); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this service catalog dependencies validation result based on context it is used -func (m *ServiceCatalogDependenciesValidationResult) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *ServiceCatalogDependenciesValidationResult) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ServiceCatalogDependenciesValidationResult) UnmarshalBinary(b []byte) error { - var res ServiceCatalogDependenciesValidationResult - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/service_catalog_dependency.go b/client/models/service_catalog_dependency.go deleted file mode 100644 index ac47d70bf..000000000 --- a/client/models/service_catalog_dependency.go +++ /dev/null @@ -1,52 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// ServiceCatalogDependency ServiceCatalogDependency -// -// # Service Catalog Dependency identifies ServiceCatalog being dependency of other -// -// swagger:model ServiceCatalogDependency -type ServiceCatalogDependency struct { - - // ref - Ref string `json:"ref,omitempty"` - - // required - Required bool `json:"required,omitempty"` -} - -// Validate validates this service catalog dependency -func (m *ServiceCatalogDependency) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this service catalog dependency based on context it is used -func (m *ServiceCatalogDependency) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *ServiceCatalogDependency) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ServiceCatalogDependency) UnmarshalBinary(b []byte) error { - var res ServiceCatalogDependency - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/service_catalog_source.go b/client/models/service_catalog_source.go deleted file mode 100644 index ec5b59cdf..000000000 --- a/client/models/service_catalog_source.go +++ /dev/null @@ -1,455 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ServiceCatalogSource ServiceCatalogSource -// -// swagger:model ServiceCatalogSource -type ServiceCatalogSource struct { - - // branch - Branch string `json:"branch,omitempty"` - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // Represents map of service catalogs changes during the update of a service catalog source. Used only for update action on a service catalog source. - Changes *ServiceCatalogChanges `json:"changes,omitempty"` - - // created at - // Minimum: 0 - CreatedAt *uint64 `json:"created_at,omitempty"` - - // credential canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical string `json:"credential_canonical,omitempty"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // name - // Required: true - Name *string `json:"name"` - - // Organization member that owns this service catalog source. When a user is the owner of a - // service catalog source they has all the permissions on it. - // In the event where the user has been deleted this field might be empty. - // - // Required: true - Owner *User `json:"owner"` - - // The last time the Service Catalog Source was (successfully) refreshed. - // Minimum: 0 - RefreshedAt *uint64 `json:"refreshed_at,omitempty"` - - // Represents list of service catalogs in the service catalog source. Not used during update action on a service catalog source. - ServiceCatalogs []*ServiceCatalog `json:"service_catalogs"` - - // stack count - // Required: true - // Minimum: 0 - StackCount *uint32 `json:"stack_count"` - - // updated at - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` - - // url - // Required: true - // Pattern: ^((/|~)[^/]*)+.(\.git)|(([\w\]+@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(/)? - URL *string `json:"url"` -} - -// Validate validates this service catalog source -func (m *ServiceCatalogSource) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateChanges(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRefreshedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalogs(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStackCount(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ServiceCatalogSource) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogSource) validateChanges(formats strfmt.Registry) error { - if swag.IsZero(m.Changes) { // not required - return nil - } - - if m.Changes != nil { - if err := m.Changes.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("changes") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("changes") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalogSource) validateCreatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogSource) validateCredentialCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.CredentialCanonical) { // not required - return nil - } - - if err := validate.MinLength("credential_canonical", "body", m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogSource) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogSource) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogSource) validateOwner(formats strfmt.Registry) error { - - if err := validate.Required("owner", "body", m.Owner); err != nil { - return err - } - - if m.Owner != nil { - if err := m.Owner.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalogSource) validateRefreshedAt(formats strfmt.Registry) error { - if swag.IsZero(m.RefreshedAt) { // not required - return nil - } - - if err := validate.MinimumUint("refreshed_at", "body", *m.RefreshedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogSource) validateServiceCatalogs(formats strfmt.Registry) error { - if swag.IsZero(m.ServiceCatalogs) { // not required - return nil - } - - for i := 0; i < len(m.ServiceCatalogs); i++ { - if swag.IsZero(m.ServiceCatalogs[i]) { // not required - continue - } - - if m.ServiceCatalogs[i] != nil { - if err := m.ServiceCatalogs[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("service_catalogs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("service_catalogs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *ServiceCatalogSource) validateStackCount(formats strfmt.Registry) error { - - if err := validate.Required("stack_count", "body", m.StackCount); err != nil { - return err - } - - if err := validate.MinimumUint("stack_count", "body", uint64(*m.StackCount), 0, false); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogSource) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogSource) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - if err := validate.Pattern("url", "body", *m.URL, `^((/|~)[^/]*)+.(\.git)|(([\w\]+@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(/)?`); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this service catalog source based on the context it is used -func (m *ServiceCatalogSource) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateChanges(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateOwner(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateServiceCatalogs(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ServiceCatalogSource) contextValidateChanges(ctx context.Context, formats strfmt.Registry) error { - - if m.Changes != nil { - - if swag.IsZero(m.Changes) { // not required - return nil - } - - if err := m.Changes.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("changes") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("changes") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalogSource) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { - - if m.Owner != nil { - - if err := m.Owner.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *ServiceCatalogSource) contextValidateServiceCatalogs(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.ServiceCatalogs); i++ { - - if m.ServiceCatalogs[i] != nil { - - if swag.IsZero(m.ServiceCatalogs[i]) { // not required - return nil - } - - if err := m.ServiceCatalogs[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("service_catalogs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("service_catalogs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *ServiceCatalogSource) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ServiceCatalogSource) UnmarshalBinary(b []byte) error { - var res ServiceCatalogSource - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/service_catalog_source_version.go b/client/models/service_catalog_source_version.go deleted file mode 100644 index 5b653fcb4..000000000 --- a/client/models/service_catalog_source_version.go +++ /dev/null @@ -1,259 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// ServiceCatalogSourceVersion Version -// -// # Version of a SCS for the Stacks -// -// swagger:model ServiceCatalogSourceVersion -type ServiceCatalogSourceVersion struct { - - // Last commit hash that references it - // Required: true - // Min Length: 1 - CommitHash *string `json:"commit_hash"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // If it's the latest - // Required: true - IsLatest *bool `json:"is_latest"` - - // Name of the version - // Required: true - Name *string `json:"name"` - - // Status of the version - // Required: true - // Enum: ["no_status","active","deleted","outdated"] - Status *string `json:"status"` - - // Type of the version - // Required: true - // Enum: ["tag","branch"] - Type *string `json:"type"` - - // How many stacks use it - // Required: true - Usage *int64 `json:"usage"` -} - -// Validate validates this service catalog source version -func (m *ServiceCatalogSourceVersion) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCommitHash(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIsLatest(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStatus(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUsage(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *ServiceCatalogSourceVersion) validateCommitHash(formats strfmt.Registry) error { - - if err := validate.Required("commit_hash", "body", m.CommitHash); err != nil { - return err - } - - if err := validate.MinLength("commit_hash", "body", *m.CommitHash, 1); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogSourceVersion) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogSourceVersion) validateIsLatest(formats strfmt.Registry) error { - - if err := validate.Required("is_latest", "body", m.IsLatest); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogSourceVersion) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -var serviceCatalogSourceVersionTypeStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["no_status","active","deleted","outdated"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - serviceCatalogSourceVersionTypeStatusPropEnum = append(serviceCatalogSourceVersionTypeStatusPropEnum, v) - } -} - -const ( - - // ServiceCatalogSourceVersionStatusNoStatus captures enum value "no_status" - ServiceCatalogSourceVersionStatusNoStatus string = "no_status" - - // ServiceCatalogSourceVersionStatusActive captures enum value "active" - ServiceCatalogSourceVersionStatusActive string = "active" - - // ServiceCatalogSourceVersionStatusDeleted captures enum value "deleted" - ServiceCatalogSourceVersionStatusDeleted string = "deleted" - - // ServiceCatalogSourceVersionStatusOutdated captures enum value "outdated" - ServiceCatalogSourceVersionStatusOutdated string = "outdated" -) - -// prop value enum -func (m *ServiceCatalogSourceVersion) validateStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, serviceCatalogSourceVersionTypeStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *ServiceCatalogSourceVersion) validateStatus(formats strfmt.Registry) error { - - if err := validate.Required("status", "body", m.Status); err != nil { - return err - } - - // value enum - if err := m.validateStatusEnum("status", "body", *m.Status); err != nil { - return err - } - - return nil -} - -var serviceCatalogSourceVersionTypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["tag","branch"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - serviceCatalogSourceVersionTypeTypePropEnum = append(serviceCatalogSourceVersionTypeTypePropEnum, v) - } -} - -const ( - - // ServiceCatalogSourceVersionTypeTag captures enum value "tag" - ServiceCatalogSourceVersionTypeTag string = "tag" - - // ServiceCatalogSourceVersionTypeBranch captures enum value "branch" - ServiceCatalogSourceVersionTypeBranch string = "branch" -) - -// prop value enum -func (m *ServiceCatalogSourceVersion) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, serviceCatalogSourceVersionTypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *ServiceCatalogSourceVersion) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -func (m *ServiceCatalogSourceVersion) validateUsage(formats strfmt.Registry) error { - - if err := validate.Required("usage", "body", m.Usage); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this service catalog source version based on context it is used -func (m *ServiceCatalogSourceVersion) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *ServiceCatalogSourceVersion) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ServiceCatalogSourceVersion) UnmarshalBinary(b []byte) error { - var res ServiceCatalogSourceVersion - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/service_catalog_technology.go b/client/models/service_catalog_technology.go deleted file mode 100644 index 7baf8d85b..000000000 --- a/client/models/service_catalog_technology.go +++ /dev/null @@ -1,52 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// ServiceCatalogTechnology ServiceCatalogTechnology -// -// # ServiceCatalogTechnology is a Technology of the Service Catalog -// -// swagger:model ServiceCatalogTechnology -type ServiceCatalogTechnology struct { - - // technology - Technology string `json:"technology,omitempty"` - - // version - Version string `json:"version,omitempty"` -} - -// Validate validates this service catalog technology -func (m *ServiceCatalogTechnology) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this service catalog technology based on context it is used -func (m *ServiceCatalogTechnology) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *ServiceCatalogTechnology) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ServiceCatalogTechnology) UnmarshalBinary(b []byte) error { - var res ServiceCatalogTechnology - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/simple_member_org.go b/client/models/simple_member_org.go deleted file mode 100644 index b42d24a39..000000000 --- a/client/models/simple_member_org.go +++ /dev/null @@ -1,212 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// SimpleMemberOrg Simplified model of a member of an organization -// -// Simplified model of a member of an organization. The member is 'accepted' and have an associated user account. -// -// swagger:model SimpleMemberOrg -type SimpleMemberOrg struct { - - // When the user became a member. - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // Primary email - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` - - // full name - FullName string `json:"full_name,omitempty"` - - // Member ID (different from the user ID) - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // When the user logged in last time. - // Minimum: 0 - LastLoginAt *uint64 `json:"last_login_at,omitempty"` - - // picture url - // Format: uri - PictureURL strfmt.URI `json:"picture_url,omitempty"` - - // When the user had the role modified. - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` - - // username - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Username string `json:"username,omitempty"` -} - -// Validate validates this simple member org -func (m *SimpleMemberOrg) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLastLoginAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePictureURL(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUsername(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SimpleMemberOrg) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *SimpleMemberOrg) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *SimpleMemberOrg) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *SimpleMemberOrg) validateLastLoginAt(formats strfmt.Registry) error { - if swag.IsZero(m.LastLoginAt) { // not required - return nil - } - - if err := validate.MinimumUint("last_login_at", "body", *m.LastLoginAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *SimpleMemberOrg) validatePictureURL(formats strfmt.Registry) error { - if swag.IsZero(m.PictureURL) { // not required - return nil - } - - if err := validate.FormatOf("picture_url", "body", "uri", m.PictureURL.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *SimpleMemberOrg) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *SimpleMemberOrg) validateUsername(formats strfmt.Registry) error { - if swag.IsZero(m.Username) { // not required - return nil - } - - if err := validate.MinLength("username", "body", m.Username, 3); err != nil { - return err - } - - if err := validate.MaxLength("username", "body", m.Username, 100); err != nil { - return err - } - - if err := validate.Pattern("username", "body", m.Username, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this simple member org based on context it is used -func (m *SimpleMemberOrg) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *SimpleMemberOrg) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *SimpleMemberOrg) UnmarshalBinary(b []byte) error { - var res SimpleMemberOrg - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/simple_team.go b/client/models/simple_team.go deleted file mode 100644 index 3bd4be599..000000000 --- a/client/models/simple_team.go +++ /dev/null @@ -1,241 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// SimpleTeam SimpleTeam -// -// The entity which represents the information of a team a bit simplified. -// -// swagger:model SimpleTeam -type SimpleTeam struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // Organization member that owns this team. When a user is the owner of a - // team it has all the permissions on it. - // In the event where the user has been deleted this field might be empty. - // - Owner *User `json:"owner,omitempty"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` -} - -// Validate validates this simple team -func (m *SimpleTeam) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SimpleTeam) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *SimpleTeam) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *SimpleTeam) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *SimpleTeam) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *SimpleTeam) validateOwner(formats strfmt.Registry) error { - if swag.IsZero(m.Owner) { // not required - return nil - } - - if m.Owner != nil { - if err := m.Owner.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *SimpleTeam) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this simple team based on the context it is used -func (m *SimpleTeam) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateOwner(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SimpleTeam) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { - - if m.Owner != nil { - - if swag.IsZero(m.Owner) { // not required - return nil - } - - if err := m.Owner.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *SimpleTeam) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *SimpleTeam) UnmarshalBinary(b []byte) error { - var res SimpleTeam - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/stack_use_case.go b/client/models/stack_use_case.go deleted file mode 100644 index 8fdcb13ce..000000000 --- a/client/models/stack_use_case.go +++ /dev/null @@ -1,130 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// StackUseCase Stack Use Case -// -// # The entity which represents the information of a Stack Use Case -// -// swagger:model StackUseCase -type StackUseCase struct { - - // cloud provider - // Min Length: 1 - CloudProvider string `json:"cloud_provider,omitempty"` - - // description - Description string `json:"description,omitempty"` - - // name - // Required: true - // Min Length: 1 - Name *string `json:"name"` - - // use case - // Required: true - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - UseCase *string `json:"use_case"` -} - -// Validate validates this stack use case -func (m *StackUseCase) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCloudProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUseCase(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *StackUseCase) validateCloudProvider(formats strfmt.Registry) error { - if swag.IsZero(m.CloudProvider) { // not required - return nil - } - - if err := validate.MinLength("cloud_provider", "body", m.CloudProvider, 1); err != nil { - return err - } - - return nil -} - -func (m *StackUseCase) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - return nil -} - -func (m *StackUseCase) validateUseCase(formats strfmt.Registry) error { - - if err := validate.Required("use_case", "body", m.UseCase); err != nil { - return err - } - - if err := validate.MinLength("use_case", "body", *m.UseCase, 1); err != nil { - return err - } - - if err := validate.MaxLength("use_case", "body", *m.UseCase, 100); err != nil { - return err - } - - if err := validate.Pattern("use_case", "body", *m.UseCase, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this stack use case based on context it is used -func (m *StackUseCase) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *StackUseCase) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *StackUseCase) UnmarshalBinary(b []byte) error { - var res StackUseCase - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/state.go b/client/models/state.go deleted file mode 100644 index 753c4d038..000000000 --- a/client/models/state.go +++ /dev/null @@ -1,144 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// State State -// -// # The State of an Inventory of the Project's environment -// -// swagger:model State -type State struct { - - // lineage - Lineage string `json:"lineage,omitempty"` - - // outputs - Outputs any `json:"outputs,omitempty"` - - // resources - Resources []*StateResource `json:"resources"` - - // serial - Serial uint32 `json:"serial,omitempty"` - - // terraform version - TerraformVersion string `json:"terraform_version,omitempty"` - - // version - Version uint32 `json:"version,omitempty"` -} - -// Validate validates this state -func (m *State) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateResources(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *State) validateResources(formats strfmt.Registry) error { - if swag.IsZero(m.Resources) { // not required - return nil - } - - for i := 0; i < len(m.Resources); i++ { - if swag.IsZero(m.Resources[i]) { // not required - continue - } - - if m.Resources[i] != nil { - if err := m.Resources[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("resources" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("resources" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this state based on the context it is used -func (m *State) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateResources(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *State) contextValidateResources(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Resources); i++ { - - if m.Resources[i] != nil { - - if swag.IsZero(m.Resources[i]) { // not required - return nil - } - - if err := m.Resources[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("resources" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("resources" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *State) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *State) UnmarshalBinary(b []byte) error { - var res State - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/state_lock.go b/client/models/state_lock.go deleted file mode 100644 index 6ef835867..000000000 --- a/client/models/state_lock.go +++ /dev/null @@ -1,64 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// StateLock State Lock -// -// # The Lock management of a State in the Inventory of the Project's environment -// -// swagger:model StateLock -type StateLock struct { - - // created - Created string `json:"created,omitempty"` - - // id - ID string `json:"id,omitempty"` - - // info - Info string `json:"info,omitempty"` - - // operation - Operation string `json:"operation,omitempty"` - - // version - Version string `json:"version,omitempty"` - - // who - Who string `json:"who,omitempty"` -} - -// Validate validates this state lock -func (m *StateLock) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this state lock based on context it is used -func (m *StateLock) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *StateLock) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *StateLock) UnmarshalBinary(b []byte) error { - var res StateLock - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/state_resource.go b/client/models/state_resource.go deleted file mode 100644 index b4cdc3e32..000000000 --- a/client/models/state_resource.go +++ /dev/null @@ -1,180 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// StateResource State Resource -// -// # The Resource of a State in the Inventory of the Project's environment -// -// swagger:model StateResource -type StateResource struct { - - // Category of the resource type - Category string `json:"category,omitempty"` - - // Full description of the resource type documentation - Description string `json:"description,omitempty"` - - // Image of the resource type - // Format: uri - Image strfmt.URI `json:"image,omitempty"` - - // instances - Instances []*StateResourceInstances `json:"instances"` - - // Set of keywords to categorize the resource type - Keywords []string `json:"keywords"` - - // mode - Mode string `json:"mode,omitempty"` - - // module - Module string `json:"module,omitempty"` - - // name - Name string `json:"name,omitempty"` - - // Project canonical in which this resource is used - ProjectCanonical string `json:"project_canonical,omitempty"` - - // provider - Provider string `json:"provider,omitempty"` - - // Short description of the resource type documentation - ShortDescription string `json:"short_description,omitempty"` - - // type - Type string `json:"type,omitempty"` -} - -// Validate validates this state resource -func (m *StateResource) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateImage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateInstances(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *StateResource) validateImage(formats strfmt.Registry) error { - if swag.IsZero(m.Image) { // not required - return nil - } - - if err := validate.FormatOf("image", "body", "uri", m.Image.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *StateResource) validateInstances(formats strfmt.Registry) error { - if swag.IsZero(m.Instances) { // not required - return nil - } - - for i := 0; i < len(m.Instances); i++ { - if swag.IsZero(m.Instances[i]) { // not required - continue - } - - if m.Instances[i] != nil { - if err := m.Instances[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("instances" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("instances" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this state resource based on the context it is used -func (m *StateResource) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateInstances(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *StateResource) contextValidateInstances(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Instances); i++ { - - if m.Instances[i] != nil { - - if swag.IsZero(m.Instances[i]) { // not required - return nil - } - - if err := m.Instances[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("instances" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("instances" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *StateResource) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *StateResource) UnmarshalBinary(b []byte) error { - var res StateResource - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/state_resource_instances.go b/client/models/state_resource_instances.go deleted file mode 100644 index b5d092b72..000000000 --- a/client/models/state_resource_instances.go +++ /dev/null @@ -1,52 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// StateResourceInstances State Resource Instances -// -// # The Instances inside Resources of a State in the Inventory of the Project's environment -// -// swagger:model StateResourceInstances -type StateResourceInstances struct { - - // attributes - Attributes any `json:"attributes,omitempty"` - - // custom attributes - CustomAttributes any `json:"custom_attributes,omitempty"` -} - -// Validate validates this state resource instances -func (m *StateResourceInstances) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this state resource instances based on context it is used -func (m *StateResourceInstances) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *StateResourceInstances) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *StateResourceInstances) UnmarshalBinary(b []byte) error { - var res StateResourceInstances - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/subscription.go b/client/models/subscription.go deleted file mode 100644 index 0cece71b3..000000000 --- a/client/models/subscription.go +++ /dev/null @@ -1,179 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Subscription Subscription -// -// It reflects the relation between an Organization and a Plan which -// could be the Free Trial or others, for more info check https://www.cycloid.io/pricing -// -// swagger:model Subscription -type Subscription struct { - - // current members - // Minimum: 0 - CurrentMembers *uint64 `json:"current_members,omitempty"` - - // expires at - // Required: true - // Minimum: 0 - ExpiresAt *uint64 `json:"expires_at"` - - // members count - // Minimum: 0 - MembersCount *uint64 `json:"members_count,omitempty"` - - // plan - // Required: true - Plan *SubscriptionPlan `json:"plan"` -} - -// Validate validates this subscription -func (m *Subscription) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCurrentMembers(formats); err != nil { - res = append(res, err) - } - - if err := m.validateExpiresAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMembersCount(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePlan(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Subscription) validateCurrentMembers(formats strfmt.Registry) error { - if swag.IsZero(m.CurrentMembers) { // not required - return nil - } - - if err := validate.MinimumUint("current_members", "body", *m.CurrentMembers, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Subscription) validateExpiresAt(formats strfmt.Registry) error { - - if err := validate.Required("expires_at", "body", m.ExpiresAt); err != nil { - return err - } - - if err := validate.MinimumUint("expires_at", "body", *m.ExpiresAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Subscription) validateMembersCount(formats strfmt.Registry) error { - if swag.IsZero(m.MembersCount) { // not required - return nil - } - - if err := validate.MinimumUint("members_count", "body", *m.MembersCount, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Subscription) validatePlan(formats strfmt.Registry) error { - - if err := validate.Required("plan", "body", m.Plan); err != nil { - return err - } - - if m.Plan != nil { - if err := m.Plan.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("plan") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("plan") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this subscription based on the context it is used -func (m *Subscription) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidatePlan(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Subscription) contextValidatePlan(ctx context.Context, formats strfmt.Registry) error { - - if m.Plan != nil { - - if err := m.Plan.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("plan") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("plan") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Subscription) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Subscription) UnmarshalBinary(b []byte) error { - var res Subscription - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/subscription_plan.go b/client/models/subscription_plan.go deleted file mode 100644 index 3c7f1ae52..000000000 --- a/client/models/subscription_plan.go +++ /dev/null @@ -1,107 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// SubscriptionPlan SubscriptionPlan -// -// # It reflects the Plan used for the subscription -// -// swagger:model SubscriptionPlan -type SubscriptionPlan struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` -} - -// Validate validates this subscription plan -func (m *SubscriptionPlan) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SubscriptionPlan) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *SubscriptionPlan) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this subscription plan based on context it is used -func (m *SubscriptionPlan) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *SubscriptionPlan) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *SubscriptionPlan) UnmarshalBinary(b []byte) error { - var res SubscriptionPlan - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/summary.go b/client/models/summary.go deleted file mode 100644 index a4e3802a7..000000000 --- a/client/models/summary.go +++ /dev/null @@ -1,204 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Summary Summary of the organization -// -// swagger:model Summary -type Summary struct { - - // config repositories - // Required: true - ConfigRepositories *uint64 `json:"config_repositories"` - - // credentials - // Required: true - Credentials *uint64 `json:"credentials"` - - // pipelines - // Required: true - Pipelines *uint64 `json:"pipelines"` - - // projects - // Required: true - Projects *uint64 `json:"projects"` - - // roles - // Required: true - Roles *uint64 `json:"roles"` - - // service catalog sources - // Required: true - ServiceCatalogSources *uint64 `json:"service_catalog_sources"` - - // service catalogs - // Required: true - ServiceCatalogs *uint64 `json:"service_catalogs"` - - // teams - // Required: true - Teams *uint64 `json:"teams"` - - // users - // Required: true - Users *uint64 `json:"users"` -} - -// Validate validates this summary -func (m *Summary) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfigRepositories(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentials(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePipelines(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjects(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRoles(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalogSources(formats); err != nil { - res = append(res, err) - } - - if err := m.validateServiceCatalogs(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTeams(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUsers(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Summary) validateConfigRepositories(formats strfmt.Registry) error { - - if err := validate.Required("config_repositories", "body", m.ConfigRepositories); err != nil { - return err - } - - return nil -} - -func (m *Summary) validateCredentials(formats strfmt.Registry) error { - - if err := validate.Required("credentials", "body", m.Credentials); err != nil { - return err - } - - return nil -} - -func (m *Summary) validatePipelines(formats strfmt.Registry) error { - - if err := validate.Required("pipelines", "body", m.Pipelines); err != nil { - return err - } - - return nil -} - -func (m *Summary) validateProjects(formats strfmt.Registry) error { - - if err := validate.Required("projects", "body", m.Projects); err != nil { - return err - } - - return nil -} - -func (m *Summary) validateRoles(formats strfmt.Registry) error { - - if err := validate.Required("roles", "body", m.Roles); err != nil { - return err - } - - return nil -} - -func (m *Summary) validateServiceCatalogSources(formats strfmt.Registry) error { - - if err := validate.Required("service_catalog_sources", "body", m.ServiceCatalogSources); err != nil { - return err - } - - return nil -} - -func (m *Summary) validateServiceCatalogs(formats strfmt.Registry) error { - - if err := validate.Required("service_catalogs", "body", m.ServiceCatalogs); err != nil { - return err - } - - return nil -} - -func (m *Summary) validateTeams(formats strfmt.Registry) error { - - if err := validate.Required("teams", "body", m.Teams); err != nil { - return err - } - - return nil -} - -func (m *Summary) validateUsers(formats strfmt.Registry) error { - - if err := validate.Required("users", "body", m.Users); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this summary based on context it is used -func (m *Summary) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *Summary) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Summary) UnmarshalBinary(b []byte) error { - var res Summary - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/swift_remote_t_f_state.go b/client/models/swift_remote_t_f_state.go deleted file mode 100644 index 6ca801985..000000000 --- a/client/models/swift_remote_t_f_state.go +++ /dev/null @@ -1,222 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// SwiftRemoteTFState Deprecated. Please use SwiftStorage. -// Representation of Swift remote tf state for external backend. -// Must be matched with a credential of the "swift" type. -// -// swagger:model SwiftRemoteTFState -type SwiftRemoteTFState struct { - - // The Swift container containing objects - // - // Required: true - Container *string `json:"container"` - - // The swift object uniquely identifying an object in a container - // - Object string `json:"object,omitempty"` - - // The Swift region where the resource exists - // - // Required: true - Region *string `json:"region"` - - // Set this to `true` to not verify SSL certificates - // - SkipVerifySsl bool `json:"skip_verify_ssl,omitempty"` -} - -// Engine gets the engine of this subtype -func (m *SwiftRemoteTFState) Engine() string { - return "SwiftRemoteTFState" -} - -// SetEngine sets the engine of this subtype -func (m *SwiftRemoteTFState) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *SwiftRemoteTFState) UnmarshalJSON(raw []byte) error { - var data struct { - - // The Swift container containing objects - // - // Required: true - Container *string `json:"container"` - - // The swift object uniquely identifying an object in a container - // - Object string `json:"object,omitempty"` - - // The Swift region where the resource exists - // - // Required: true - Region *string `json:"region"` - - // Set this to `true` to not verify SSL certificates - // - SkipVerifySsl bool `json:"skip_verify_ssl,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result SwiftRemoteTFState - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.Container = data.Container - result.Object = data.Object - result.Region = data.Region - result.SkipVerifySsl = data.SkipVerifySsl - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m SwiftRemoteTFState) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The Swift container containing objects - // - // Required: true - Container *string `json:"container"` - - // The swift object uniquely identifying an object in a container - // - Object string `json:"object,omitempty"` - - // The Swift region where the resource exists - // - // Required: true - Region *string `json:"region"` - - // Set this to `true` to not verify SSL certificates - // - SkipVerifySsl bool `json:"skip_verify_ssl,omitempty"` - }{ - - Container: m.Container, - - Object: m.Object, - - Region: m.Region, - - SkipVerifySsl: m.SkipVerifySsl, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this swift remote t f state -func (m *SwiftRemoteTFState) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateContainer(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRegion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SwiftRemoteTFState) validateContainer(formats strfmt.Registry) error { - - if err := validate.Required("container", "body", m.Container); err != nil { - return err - } - - return nil -} - -func (m *SwiftRemoteTFState) validateRegion(formats strfmt.Registry) error { - - if err := validate.Required("region", "body", m.Region); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this swift remote t f state based on the context it is used -func (m *SwiftRemoteTFState) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *SwiftRemoteTFState) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *SwiftRemoteTFState) UnmarshalBinary(b []byte) error { - var res SwiftRemoteTFState - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/swift_storage.go b/client/models/swift_storage.go deleted file mode 100644 index 1f4122fd4..000000000 --- a/client/models/swift_storage.go +++ /dev/null @@ -1,224 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// SwiftStorage Representation of Swift remote tf state for external backend. -// Must be matched with a credential of the "swift" type. -// -// swagger:model SwiftStorage -type SwiftStorage struct { - - // The Swift container containing objects - // - // Required: true - Container *string `json:"container"` - - // The swift object uniquely identifying an object in a container, - // will be required if the EB is not default - // - Object string `json:"object,omitempty"` - - // The Swift region where the resource exists - // - // Required: true - Region *string `json:"region"` - - // Set this to `true` to not verify SSL certificates - // - SkipVerifySsl bool `json:"skip_verify_ssl,omitempty"` -} - -// Engine gets the engine of this subtype -func (m *SwiftStorage) Engine() string { - return "SwiftStorage" -} - -// SetEngine sets the engine of this subtype -func (m *SwiftStorage) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *SwiftStorage) UnmarshalJSON(raw []byte) error { - var data struct { - - // The Swift container containing objects - // - // Required: true - Container *string `json:"container"` - - // The swift object uniquely identifying an object in a container, - // will be required if the EB is not default - // - Object string `json:"object,omitempty"` - - // The Swift region where the resource exists - // - // Required: true - Region *string `json:"region"` - - // Set this to `true` to not verify SSL certificates - // - SkipVerifySsl bool `json:"skip_verify_ssl,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result SwiftStorage - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.Container = data.Container - result.Object = data.Object - result.Region = data.Region - result.SkipVerifySsl = data.SkipVerifySsl - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m SwiftStorage) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // The Swift container containing objects - // - // Required: true - Container *string `json:"container"` - - // The swift object uniquely identifying an object in a container, - // will be required if the EB is not default - // - Object string `json:"object,omitempty"` - - // The Swift region where the resource exists - // - // Required: true - Region *string `json:"region"` - - // Set this to `true` to not verify SSL certificates - // - SkipVerifySsl bool `json:"skip_verify_ssl,omitempty"` - }{ - - Container: m.Container, - - Object: m.Object, - - Region: m.Region, - - SkipVerifySsl: m.SkipVerifySsl, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this swift storage -func (m *SwiftStorage) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateContainer(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRegion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *SwiftStorage) validateContainer(formats strfmt.Registry) error { - - if err := validate.Required("container", "body", m.Container); err != nil { - return err - } - - return nil -} - -func (m *SwiftStorage) validateRegion(formats strfmt.Registry) error { - - if err := validate.Required("region", "body", m.Region); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this swift storage based on the context it is used -func (m *SwiftStorage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *SwiftStorage) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *SwiftStorage) UnmarshalBinary(b []byte) error { - var res SwiftStorage - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/tag.go b/client/models/tag.go deleted file mode 100644 index 00a9f2096..000000000 --- a/client/models/tag.go +++ /dev/null @@ -1,107 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Tag Key and value pair -// -// Key and value pair defined with the widely adopted name, tag. -// -// swagger:model Tag -type Tag struct { - - // key - // Required: true - // Max Length: 254 - // Min Length: 1 - Key *string `json:"key"` - - // value - // Required: true - // Max Length: 254 - // Pattern: ^(?:[\w\-+=.:/@ ]*)$ - Value *string `json:"value"` -} - -// Validate validates this tag -func (m *Tag) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateKey(formats); err != nil { - res = append(res, err) - } - - if err := m.validateValue(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Tag) validateKey(formats strfmt.Registry) error { - - if err := validate.Required("key", "body", m.Key); err != nil { - return err - } - - if err := validate.MinLength("key", "body", *m.Key, 1); err != nil { - return err - } - - if err := validate.MaxLength("key", "body", *m.Key, 254); err != nil { - return err - } - - return nil -} - -func (m *Tag) validateValue(formats strfmt.Registry) error { - - if err := validate.Required("value", "body", m.Value); err != nil { - return err - } - - if err := validate.MaxLength("value", "body", *m.Value, 254); err != nil { - return err - } - - if err := validate.Pattern("value", "body", *m.Value, `^(?:[\w\-+=.:/@ ]*)$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this tag based on context it is used -func (m *Tag) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *Tag) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Tag) UnmarshalBinary(b []byte) error { - var res Tag - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/task_config.go b/client/models/task_config.go deleted file mode 100644 index e8ea85894..000000000 --- a/client/models/task_config.go +++ /dev/null @@ -1,200 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// TaskConfig TaskConfig -// -// The configuration of a concourse task. -// -// swagger:model TaskConfig -type TaskConfig struct { - - // image - Image string `json:"image,omitempty"` - - // inputs - Inputs []*TaskInputConfig `json:"inputs"` - - // params - Params map[string]string `json:"params,omitempty"` - - // platform - Platform string `json:"platform,omitempty"` - - // run - Run *TaskRunConfig `json:"run,omitempty"` - - // tags - Tags []string `json:"tags"` -} - -// Validate validates this task config -func (m *TaskConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateInputs(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRun(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TaskConfig) validateInputs(formats strfmt.Registry) error { - if swag.IsZero(m.Inputs) { // not required - return nil - } - - for i := 0; i < len(m.Inputs); i++ { - if swag.IsZero(m.Inputs[i]) { // not required - continue - } - - if m.Inputs[i] != nil { - if err := m.Inputs[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("inputs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("inputs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *TaskConfig) validateRun(formats strfmt.Registry) error { - if swag.IsZero(m.Run) { // not required - return nil - } - - if m.Run != nil { - if err := m.Run.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("run") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("run") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this task config based on the context it is used -func (m *TaskConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateInputs(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateRun(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TaskConfig) contextValidateInputs(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Inputs); i++ { - - if m.Inputs[i] != nil { - - if swag.IsZero(m.Inputs[i]) { // not required - return nil - } - - if err := m.Inputs[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("inputs" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("inputs" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *TaskConfig) contextValidateRun(ctx context.Context, formats strfmt.Registry) error { - - if m.Run != nil { - - if swag.IsZero(m.Run) { // not required - return nil - } - - if err := m.Run.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("run") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("run") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *TaskConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TaskConfig) UnmarshalBinary(b []byte) error { - var res TaskConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/task_input_config.go b/client/models/task_input_config.go deleted file mode 100644 index 2786ff5fd..000000000 --- a/client/models/task_input_config.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TaskInputConfig TaskInputConfig -// -// The configuration of inputs for concourse tasks. -// -// swagger:model TaskInputConfig -type TaskInputConfig struct { - - // name - // Required: true - Name *string `json:"name"` - - // path - Path string `json:"path,omitempty"` -} - -// Validate validates this task input config -func (m *TaskInputConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TaskInputConfig) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this task input config based on context it is used -func (m *TaskInputConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *TaskInputConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TaskInputConfig) UnmarshalBinary(b []byte) error { - var res TaskInputConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/task_plan.go b/client/models/task_plan.go deleted file mode 100644 index cbf664b8e..000000000 --- a/client/models/task_plan.go +++ /dev/null @@ -1,227 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TaskPlan TaskPlan -// -// The task plan. -// -// swagger:model TaskPlan -type TaskPlan struct { - - // config - Config *TaskConfig `json:"config,omitempty"` - - // config path - ConfigPath string `json:"config_path,omitempty"` - - // image artifact name - ImageArtifactName string `json:"image_artifact_name,omitempty"` - - // input mapping - InputMapping map[string]string `json:"input_mapping,omitempty"` - - // name - Name string `json:"name,omitempty"` - - // output mapping - OutputMapping map[string]string `json:"output_mapping,omitempty"` - - // params - Params map[string]any `json:"params,omitempty"` - - // privileged - // Required: true - Privileged *bool `json:"privileged"` - - // tags - Tags []string `json:"tags"` - - // versioned resource types - VersionedResourceTypes []*VersionedResourceType `json:"versioned_resource_types"` -} - -// Validate validates this task plan -func (m *TaskPlan) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfig(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePrivileged(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersionedResourceTypes(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TaskPlan) validateConfig(formats strfmt.Registry) error { - if swag.IsZero(m.Config) { // not required - return nil - } - - if m.Config != nil { - if err := m.Config.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("config") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("config") - } - - return err - } - } - - return nil -} - -func (m *TaskPlan) validatePrivileged(formats strfmt.Registry) error { - - if err := validate.Required("privileged", "body", m.Privileged); err != nil { - return err - } - - return nil -} - -func (m *TaskPlan) validateVersionedResourceTypes(formats strfmt.Registry) error { - if swag.IsZero(m.VersionedResourceTypes) { // not required - return nil - } - - for i := 0; i < len(m.VersionedResourceTypes); i++ { - if swag.IsZero(m.VersionedResourceTypes[i]) { // not required - continue - } - - if m.VersionedResourceTypes[i] != nil { - if err := m.VersionedResourceTypes[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("versioned_resource_types" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("versioned_resource_types" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this task plan based on the context it is used -func (m *TaskPlan) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateConfig(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateVersionedResourceTypes(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TaskPlan) contextValidateConfig(ctx context.Context, formats strfmt.Registry) error { - - if m.Config != nil { - - if swag.IsZero(m.Config) { // not required - return nil - } - - if err := m.Config.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("config") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("config") - } - - return err - } - } - - return nil -} - -func (m *TaskPlan) contextValidateVersionedResourceTypes(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.VersionedResourceTypes); i++ { - - if m.VersionedResourceTypes[i] != nil { - - if swag.IsZero(m.VersionedResourceTypes[i]) { // not required - return nil - } - - if err := m.VersionedResourceTypes[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("versioned_resource_types" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("versioned_resource_types" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *TaskPlan) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TaskPlan) UnmarshalBinary(b []byte) error { - var res TaskPlan - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/task_run_config.go b/client/models/task_run_config.go deleted file mode 100644 index 25da74fb7..000000000 --- a/client/models/task_run_config.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TaskRunConfig TaskRunConfig -// -// The configuration of a concourse task-run. -// -// swagger:model TaskRunConfig -type TaskRunConfig struct { - - // args - Args []string `json:"args"` - - // path - // Min Length: 3 - Path string `json:"path,omitempty"` -} - -// Validate validates this task run config -func (m *TaskRunConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validatePath(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TaskRunConfig) validatePath(formats strfmt.Registry) error { - if swag.IsZero(m.Path) { // not required - return nil - } - - if err := validate.MinLength("path", "body", m.Path, 3); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this task run config based on context it is used -func (m *TaskRunConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *TaskRunConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TaskRunConfig) UnmarshalBinary(b []byte) error { - var res TaskRunConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/team.go b/client/models/team.go deleted file mode 100644 index 1b2144521..000000000 --- a/client/models/team.go +++ /dev/null @@ -1,417 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Team Team -// -// The entity which represents the information of a team. -// -// swagger:model Team -type Team struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // The total count of members of the team. - // Required: true - MemberCount *uint32 `json:"member_count"` - - // Preview of the list of team members, limited to 6 members. - // Required: true - // Max Items: 6 - MembersPreview []*MemberTeam `json:"members_preview"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // Organization member that owns this team. When a user is the owner of a - // team it has all the permissions on it. - // In the event where the user has been deleted this field might be empty. - // - Owner *User `json:"owner,omitempty"` - - // roles - // Required: true - // Min Items: 1 - Roles []*Role `json:"roles"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` -} - -// Validate validates this team -func (m *Team) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMemberCount(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMembersPreview(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRoles(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Team) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *Team) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *Team) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *Team) validateMemberCount(formats strfmt.Registry) error { - - if err := validate.Required("member_count", "body", m.MemberCount); err != nil { - return err - } - - return nil -} - -func (m *Team) validateMembersPreview(formats strfmt.Registry) error { - - if err := validate.Required("members_preview", "body", m.MembersPreview); err != nil { - return err - } - - iMembersPreviewSize := int64(len(m.MembersPreview)) - - if err := validate.MaxItems("members_preview", "body", iMembersPreviewSize, 6); err != nil { - return err - } - - for i := 0; i < len(m.MembersPreview); i++ { - if swag.IsZero(m.MembersPreview[i]) { // not required - continue - } - - if m.MembersPreview[i] != nil { - if err := m.MembersPreview[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("members_preview" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("members_preview" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Team) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *Team) validateOwner(formats strfmt.Registry) error { - if swag.IsZero(m.Owner) { // not required - return nil - } - - if m.Owner != nil { - if err := m.Owner.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *Team) validateRoles(formats strfmt.Registry) error { - - if err := validate.Required("roles", "body", m.Roles); err != nil { - return err - } - - iRolesSize := int64(len(m.Roles)) - - if err := validate.MinItems("roles", "body", iRolesSize, 1); err != nil { - return err - } - - for i := 0; i < len(m.Roles); i++ { - if swag.IsZero(m.Roles[i]) { // not required - continue - } - - if m.Roles[i] != nil { - if err := m.Roles[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("roles" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("roles" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Team) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this team based on the context it is used -func (m *Team) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateMembersPreview(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateOwner(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateRoles(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Team) contextValidateMembersPreview(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.MembersPreview); i++ { - - if m.MembersPreview[i] != nil { - - if swag.IsZero(m.MembersPreview[i]) { // not required - return nil - } - - if err := m.MembersPreview[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("members_preview" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("members_preview" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *Team) contextValidateOwner(ctx context.Context, formats strfmt.Registry) error { - - if m.Owner != nil { - - if swag.IsZero(m.Owner) { // not required - return nil - } - - if err := m.Owner.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("owner") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("owner") - } - - return err - } - } - - return nil -} - -func (m *Team) contextValidateRoles(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Roles); i++ { - - if m.Roles[i] != nil { - - if swag.IsZero(m.Roles[i]) { // not required - return nil - } - - if err := m.Roles[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("roles" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("roles" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Team) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Team) UnmarshalBinary(b []byte) error { - var res Team - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/terraform_h_c_l_config.go b/client/models/terraform_h_c_l_config.go deleted file mode 100644 index 1fd9c0062..000000000 --- a/client/models/terraform_h_c_l_config.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TerraformHCLConfig TerraformHCLConfig -// -// # The HCL config for Terraform -// -// swagger:model TerraformHCLConfig -type TerraformHCLConfig struct { - - // config - // Required: true - Config *string `json:"config"` -} - -// Validate validates this terraform h c l config -func (m *TerraformHCLConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfig(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TerraformHCLConfig) validateConfig(formats strfmt.Registry) error { - - if err := validate.Required("config", "body", m.Config); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this terraform h c l config based on context it is used -func (m *TerraformHCLConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *TerraformHCLConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TerraformHCLConfig) UnmarshalBinary(b []byte) error { - var res TerraformHCLConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/terraform_image.go b/client/models/terraform_image.go deleted file mode 100644 index 8bea3cc14..000000000 --- a/client/models/terraform_image.go +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TerraformImage TerraformImage -// -// # The Image from the TF structure -// -// swagger:model TerraformImage -type TerraformImage struct { - - // image - // Required: true - // Format: byte - Image *strfmt.Base64 `json:"image"` -} - -// Validate validates this terraform image -func (m *TerraformImage) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateImage(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TerraformImage) validateImage(formats strfmt.Registry) error { - - if err := validate.Required("image", "body", m.Image); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this terraform image based on context it is used -func (m *TerraformImage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *TerraformImage) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TerraformImage) UnmarshalBinary(b []byte) error { - var res TerraformImage - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/terraform_json_config.go b/client/models/terraform_json_config.go deleted file mode 100644 index c581f6ef4..000000000 --- a/client/models/terraform_json_config.go +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// TerraformJSONConfig TerraformJSONConfig -// -// # The JSON config for Terraform -// -// swagger:model TerraformJSONConfig -type TerraformJSONConfig struct { - - // config - // Required: true - Config any `json:"config"` -} - -// Validate validates this terraform JSON config -func (m *TerraformJSONConfig) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfig(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TerraformJSONConfig) validateConfig(formats strfmt.Registry) error { - - if m.Config == nil { - return errors.Required("config", "body", nil) - } - - return nil -} - -// ContextValidate validates this terraform JSON config based on context it is used -func (m *TerraformJSONConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *TerraformJSONConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TerraformJSONConfig) UnmarshalBinary(b []byte) error { - var res TerraformJSONConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/terraform_json_diagram.go b/client/models/terraform_json_diagram.go deleted file mode 100644 index 6bfafcea2..000000000 --- a/client/models/terraform_json_diagram.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// TerraformJSONDiagram TerraformDiagram -// -// # The JSON Diagram structure -// -// swagger:model TerraformJSONDiagram -type TerraformJSONDiagram any diff --git a/client/models/terraform_plan_input.go b/client/models/terraform_plan_input.go deleted file mode 100644 index 6f7139ea0..000000000 --- a/client/models/terraform_plan_input.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TerraformPlanInput TerraformPlanInput -// -// Input for endpoints that require a Terraform plan. -// -// swagger:model TerraformPlanInput -type TerraformPlanInput struct { - - // Terraform plan file in escaped JSON format. See more: https://www.terraform.io/internals/json-format - // Required: true - Tfplan *string `json:"tfplan"` -} - -// Validate validates this terraform plan input -func (m *TerraformPlanInput) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateTfplan(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TerraformPlanInput) validateTfplan(formats strfmt.Registry) error { - - if err := validate.Required("tfplan", "body", m.Tfplan); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this terraform plan input based on context it is used -func (m *TerraformPlanInput) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *TerraformPlanInput) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TerraformPlanInput) UnmarshalBinary(b []byte) error { - var res TerraformPlanInput - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/terraform_provider.go b/client/models/terraform_provider.go deleted file mode 100644 index f0905035d..000000000 --- a/client/models/terraform_provider.go +++ /dev/null @@ -1,148 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TerraformProvider Provider -// -// # Provider of infrastructure -// -// swagger:model TerraformProvider -type TerraformProvider struct { - - // abbreviation - // Required: true - Abbreviation *string `json:"abbreviation"` - - // canonical - // Required: true - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // cloud - // Required: true - Cloud *bool `json:"cloud"` - - // name - // Required: true - Name *string `json:"name"` - - // schema - // Required: true - Schema any `json:"schema"` -} - -// Validate validates this terraform provider -func (m *TerraformProvider) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAbbreviation(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloud(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSchema(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TerraformProvider) validateAbbreviation(formats strfmt.Registry) error { - - if err := validate.Required("abbreviation", "body", m.Abbreviation); err != nil { - return err - } - - return nil -} - -func (m *TerraformProvider) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *TerraformProvider) validateCloud(formats strfmt.Registry) error { - - if err := validate.Required("cloud", "body", m.Cloud); err != nil { - return err - } - - return nil -} - -func (m *TerraformProvider) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *TerraformProvider) validateSchema(formats strfmt.Registry) error { - - if m.Schema == nil { - return errors.Required("schema", "body", nil) - } - - return nil -} - -// ContextValidate validates this terraform provider based on context it is used -func (m *TerraformProvider) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *TerraformProvider) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TerraformProvider) UnmarshalBinary(b []byte) error { - var res TerraformProvider - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/terraform_provider_resource.go b/client/models/terraform_provider_resource.go deleted file mode 100644 index a40f3e765..000000000 --- a/client/models/terraform_provider_resource.go +++ /dev/null @@ -1,282 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TerraformProviderResource Resource -// -// # A Resource of a Provider -// -// swagger:model TerraformProviderResource -type TerraformProviderResource struct { - - // attributes - // Required: true - Attributes *TerraformProviderResourceAttributes `json:"attributes"` - - // canonical - // Required: true - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // category - // Required: true - Category *string `json:"category"` - - // description - // Required: true - Description *string `json:"description"` - - // image - // Format: uri - Image strfmt.URI `json:"image,omitempty"` - - // is edge - // Required: true - IsEdge *bool `json:"is_edge"` - - // is node - // Required: true - IsNode *bool `json:"is_node"` - - // keywords - // Required: true - Keywords []string `json:"keywords"` - - // schema - // Required: true - Schema any `json:"schema"` - - // short description - // Required: true - ShortDescription *string `json:"short_description"` -} - -// Validate validates this terraform provider resource -func (m *TerraformProviderResource) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAttributes(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCategory(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateImage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIsEdge(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIsNode(formats); err != nil { - res = append(res, err) - } - - if err := m.validateKeywords(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSchema(formats); err != nil { - res = append(res, err) - } - - if err := m.validateShortDescription(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TerraformProviderResource) validateAttributes(formats strfmt.Registry) error { - - if err := validate.Required("attributes", "body", m.Attributes); err != nil { - return err - } - - if m.Attributes != nil { - if err := m.Attributes.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("attributes") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("attributes") - } - - return err - } - } - - return nil -} - -func (m *TerraformProviderResource) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResource) validateCategory(formats strfmt.Registry) error { - - if err := validate.Required("category", "body", m.Category); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResource) validateDescription(formats strfmt.Registry) error { - - if err := validate.Required("description", "body", m.Description); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResource) validateImage(formats strfmt.Registry) error { - if swag.IsZero(m.Image) { // not required - return nil - } - - if err := validate.FormatOf("image", "body", "uri", m.Image.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResource) validateIsEdge(formats strfmt.Registry) error { - - if err := validate.Required("is_edge", "body", m.IsEdge); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResource) validateIsNode(formats strfmt.Registry) error { - - if err := validate.Required("is_node", "body", m.IsNode); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResource) validateKeywords(formats strfmt.Registry) error { - - if err := validate.Required("keywords", "body", m.Keywords); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResource) validateSchema(formats strfmt.Registry) error { - - if m.Schema == nil { - return errors.Required("schema", "body", nil) - } - - return nil -} - -func (m *TerraformProviderResource) validateShortDescription(formats strfmt.Registry) error { - - if err := validate.Required("short_description", "body", m.ShortDescription); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this terraform provider resource based on the context it is used -func (m *TerraformProviderResource) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateAttributes(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TerraformProviderResource) contextValidateAttributes(ctx context.Context, formats strfmt.Registry) error { - - if m.Attributes != nil { - - if err := m.Attributes.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("attributes") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("attributes") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *TerraformProviderResource) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TerraformProviderResource) UnmarshalBinary(b []byte) error { - var res TerraformProviderResource - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/terraform_provider_resource_attributes.go b/client/models/terraform_provider_resource_attributes.go deleted file mode 100644 index c9c3a84db..000000000 --- a/client/models/terraform_provider_resource_attributes.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// TerraformProviderResourceAttributes ResourceAttributes -// -// # Holds specific logic of some attributes -// -// swagger:model TerraformProviderResourceAttributes -type TerraformProviderResourceAttributes struct { - - // important - Important []string `json:"important"` - - // Is a KV where the K is the resource possible value and the Value is the normalized value of it. The current possible values are "unknown", "pending", "running", "stopping" - NormalizedStatus any `json:"normalized_status,omitempty"` - - // status - Status string `json:"status,omitempty"` -} - -// Validate validates this terraform provider resource attributes -func (m *TerraformProviderResourceAttributes) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this terraform provider resource attributes based on context it is used -func (m *TerraformProviderResourceAttributes) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *TerraformProviderResourceAttributes) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TerraformProviderResourceAttributes) UnmarshalBinary(b []byte) error { - var res TerraformProviderResourceAttributes - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/terraform_provider_resource_simple.go b/client/models/terraform_provider_resource_simple.go deleted file mode 100644 index b97a67b4d..000000000 --- a/client/models/terraform_provider_resource_simple.go +++ /dev/null @@ -1,265 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TerraformProviderResourceSimple ResourceSimple -// -// # A Resource of a Provider without the config -// -// swagger:model TerraformProviderResourceSimple -type TerraformProviderResourceSimple struct { - - // attributes - // Required: true - Attributes *TerraformProviderResourceAttributes `json:"attributes"` - - // canonical - // Required: true - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // category - // Required: true - Category *string `json:"category"` - - // description - // Required: true - Description *string `json:"description"` - - // image - // Format: uri - Image strfmt.URI `json:"image,omitempty"` - - // is edge - // Required: true - IsEdge *bool `json:"is_edge"` - - // is node - // Required: true - IsNode *bool `json:"is_node"` - - // keywords - // Required: true - Keywords []string `json:"keywords"` - - // short description - // Required: true - ShortDescription *string `json:"short_description"` -} - -// Validate validates this terraform provider resource simple -func (m *TerraformProviderResourceSimple) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAttributes(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCategory(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateImage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIsEdge(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIsNode(formats); err != nil { - res = append(res, err) - } - - if err := m.validateKeywords(formats); err != nil { - res = append(res, err) - } - - if err := m.validateShortDescription(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TerraformProviderResourceSimple) validateAttributes(formats strfmt.Registry) error { - - if err := validate.Required("attributes", "body", m.Attributes); err != nil { - return err - } - - if m.Attributes != nil { - if err := m.Attributes.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("attributes") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("attributes") - } - - return err - } - } - - return nil -} - -func (m *TerraformProviderResourceSimple) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResourceSimple) validateCategory(formats strfmt.Registry) error { - - if err := validate.Required("category", "body", m.Category); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResourceSimple) validateDescription(formats strfmt.Registry) error { - - if err := validate.Required("description", "body", m.Description); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResourceSimple) validateImage(formats strfmt.Registry) error { - if swag.IsZero(m.Image) { // not required - return nil - } - - if err := validate.FormatOf("image", "body", "uri", m.Image.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResourceSimple) validateIsEdge(formats strfmt.Registry) error { - - if err := validate.Required("is_edge", "body", m.IsEdge); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResourceSimple) validateIsNode(formats strfmt.Registry) error { - - if err := validate.Required("is_node", "body", m.IsNode); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResourceSimple) validateKeywords(formats strfmt.Registry) error { - - if err := validate.Required("keywords", "body", m.Keywords); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderResourceSimple) validateShortDescription(formats strfmt.Registry) error { - - if err := validate.Required("short_description", "body", m.ShortDescription); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this terraform provider resource simple based on the context it is used -func (m *TerraformProviderResourceSimple) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateAttributes(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TerraformProviderResourceSimple) contextValidateAttributes(ctx context.Context, formats strfmt.Registry) error { - - if m.Attributes != nil { - - if err := m.Attributes.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("attributes") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("attributes") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *TerraformProviderResourceSimple) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TerraformProviderResourceSimple) UnmarshalBinary(b []byte) error { - var res TerraformProviderResourceSimple - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/terraform_provider_simple.go b/client/models/terraform_provider_simple.go deleted file mode 100644 index 992a74b15..000000000 --- a/client/models/terraform_provider_simple.go +++ /dev/null @@ -1,131 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TerraformProviderSimple TerraformProviderSimple -// -// # Provider of infrastructure without the config -// -// swagger:model TerraformProviderSimple -type TerraformProviderSimple struct { - - // abbreviation - // Required: true - Abbreviation *string `json:"abbreviation"` - - // canonical - // Required: true - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // cloud - // Required: true - Cloud *bool `json:"cloud"` - - // name - // Required: true - Name *string `json:"name"` -} - -// Validate validates this terraform provider simple -func (m *TerraformProviderSimple) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateAbbreviation(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCloud(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TerraformProviderSimple) validateAbbreviation(formats strfmt.Registry) error { - - if err := validate.Required("abbreviation", "body", m.Abbreviation); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderSimple) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderSimple) validateCloud(formats strfmt.Registry) error { - - if err := validate.Required("cloud", "body", m.Cloud); err != nil { - return err - } - - return nil -} - -func (m *TerraformProviderSimple) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this terraform provider simple based on context it is used -func (m *TerraformProviderSimple) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *TerraformProviderSimple) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TerraformProviderSimple) UnmarshalBinary(b []byte) error { - var res TerraformProviderSimple - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/terraform_validation_result.go b/client/models/terraform_validation_result.go deleted file mode 100644 index cb895aa4d..000000000 --- a/client/models/terraform_validation_result.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TerraformValidationResult TerraformValidationResult -// -// # The result of the validation, if errors is empty means that is correct -// -// swagger:model TerraformValidationResult -type TerraformValidationResult struct { - - // errors - // Required: true - Errors []string `json:"errors"` -} - -// Validate validates this terraform validation result -func (m *TerraformValidationResult) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateErrors(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TerraformValidationResult) validateErrors(formats strfmt.Registry) error { - - if err := validate.Required("errors", "body", m.Errors); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this terraform validation result based on context it is used -func (m *TerraformValidationResult) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *TerraformValidationResult) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TerraformValidationResult) UnmarshalBinary(b []byte) error { - var res TerraformValidationResult - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/test_connection_credential.go b/client/models/test_connection_credential.go deleted file mode 100644 index 47222eccf..000000000 --- a/client/models/test_connection_credential.go +++ /dev/null @@ -1,187 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TestConnectionCredential Test Connection Credential -// -// Inline credential data for testing an external backend connection. The credential is not stored. -// -// swagger:model TestConnectionCredential -type TestConnectionCredential struct { - - // raw - // Required: true - Raw *CredentialRaw `json:"raw"` - - // type - // Required: true - // Enum: ["aws","azure","azure_storage","gcp","basic_auth","elasticsearch","swift","vmware"] - Type *string `json:"type"` -} - -// Validate validates this test connection credential -func (m *TestConnectionCredential) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateRaw(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TestConnectionCredential) validateRaw(formats strfmt.Registry) error { - - if err := validate.Required("raw", "body", m.Raw); err != nil { - return err - } - - if m.Raw != nil { - if err := m.Raw.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("raw") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("raw") - } - - return err - } - } - - return nil -} - -var testConnectionCredentialTypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["aws","azure","azure_storage","gcp","basic_auth","elasticsearch","swift","vmware"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - testConnectionCredentialTypeTypePropEnum = append(testConnectionCredentialTypeTypePropEnum, v) - } -} - -const ( - - // TestConnectionCredentialTypeAws captures enum value "aws" - TestConnectionCredentialTypeAws string = "aws" - - // TestConnectionCredentialTypeAzure captures enum value "azure" - TestConnectionCredentialTypeAzure string = "azure" - - // TestConnectionCredentialTypeAzureStorage captures enum value "azure_storage" - TestConnectionCredentialTypeAzureStorage string = "azure_storage" - - // TestConnectionCredentialTypeGcp captures enum value "gcp" - TestConnectionCredentialTypeGcp string = "gcp" - - // TestConnectionCredentialTypeBasicAuth captures enum value "basic_auth" - TestConnectionCredentialTypeBasicAuth string = "basic_auth" - - // TestConnectionCredentialTypeElasticsearch captures enum value "elasticsearch" - TestConnectionCredentialTypeElasticsearch string = "elasticsearch" - - // TestConnectionCredentialTypeSwift captures enum value "swift" - TestConnectionCredentialTypeSwift string = "swift" - - // TestConnectionCredentialTypeVmware captures enum value "vmware" - TestConnectionCredentialTypeVmware string = "vmware" -) - -// prop value enum -func (m *TestConnectionCredential) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, testConnectionCredentialTypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *TestConnectionCredential) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this test connection credential based on the context it is used -func (m *TestConnectionCredential) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateRaw(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TestConnectionCredential) contextValidateRaw(ctx context.Context, formats strfmt.Registry) error { - - if m.Raw != nil { - - if err := m.Raw.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("raw") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("raw") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *TestConnectionCredential) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TestConnectionCredential) UnmarshalBinary(b []byte) error { - var res TestConnectionCredential - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/test_external_backend_connection_input.go b/client/models/test_external_backend_connection_input.go deleted file mode 100644 index 196ebe48b..000000000 --- a/client/models/test_external_backend_connection_input.go +++ /dev/null @@ -1,302 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - stderrors "errors" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TestExternalBackendConnectionInput Test External Backend Connection Input -// -// Configuration to test an external backend connection without creating it. -// -// swagger:model TestExternalBackendConnectionInput -type TestExternalBackendConnectionInput struct { - configurationField ExternalBackendConfiguration - - // credential - // Required: true - Credential *TestConnectionCredential `json:"credential"` - - // purpose - // Required: true - // Enum: ["logs","remote_tfstate","cost_explorer"] - Purpose *string `json:"purpose"` -} - -// Configuration gets the configuration of this base type -func (m *TestExternalBackendConnectionInput) Configuration() ExternalBackendConfiguration { - return m.configurationField -} - -// SetConfiguration sets the configuration of this base type -func (m *TestExternalBackendConnectionInput) SetConfiguration(val ExternalBackendConfiguration) { - m.configurationField = val -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *TestExternalBackendConnectionInput) UnmarshalJSON(raw []byte) error { - var data struct { - Configuration json.RawMessage `json:"configuration"` - - Credential *TestConnectionCredential `json:"credential"` - - Purpose *string `json:"purpose"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - propConfiguration, err := UnmarshalExternalBackendConfiguration(bytes.NewBuffer(data.Configuration), runtime.JSONConsumer()) - if err != nil && !stderrors.Is(err, io.EOF) { - return err - } - - var result TestExternalBackendConnectionInput - - // configuration - result.configurationField = propConfiguration - - // credential - result.Credential = data.Credential - - // purpose - result.Purpose = data.Purpose - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m TestExternalBackendConnectionInput) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - Credential *TestConnectionCredential `json:"credential"` - - Purpose *string `json:"purpose"` - }{ - - Credential: m.Credential, - - Purpose: m.Purpose, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Configuration ExternalBackendConfiguration `json:"configuration"` - }{ - - Configuration: m.configurationField, - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this test external backend connection input -func (m *TestExternalBackendConnectionInput) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfiguration(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredential(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePurpose(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TestExternalBackendConnectionInput) validateConfiguration(formats strfmt.Registry) error { - - if err := validate.Required("configuration", "body", m.Configuration()); err != nil { - return err - } - - if err := m.Configuration().Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -func (m *TestExternalBackendConnectionInput) validateCredential(formats strfmt.Registry) error { - - if err := validate.Required("credential", "body", m.Credential); err != nil { - return err - } - - if m.Credential != nil { - if err := m.Credential.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("credential") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("credential") - } - - return err - } - } - - return nil -} - -var testExternalBackendConnectionInputTypePurposePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["logs","remote_tfstate","cost_explorer"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - testExternalBackendConnectionInputTypePurposePropEnum = append(testExternalBackendConnectionInputTypePurposePropEnum, v) - } -} - -const ( - - // TestExternalBackendConnectionInputPurposeLogs captures enum value "logs" - TestExternalBackendConnectionInputPurposeLogs string = "logs" - - // TestExternalBackendConnectionInputPurposeRemoteTfstate captures enum value "remote_tfstate" - TestExternalBackendConnectionInputPurposeRemoteTfstate string = "remote_tfstate" - - // TestExternalBackendConnectionInputPurposeCostExplorer captures enum value "cost_explorer" - TestExternalBackendConnectionInputPurposeCostExplorer string = "cost_explorer" -) - -// prop value enum -func (m *TestExternalBackendConnectionInput) validatePurposeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, testExternalBackendConnectionInputTypePurposePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *TestExternalBackendConnectionInput) validatePurpose(formats strfmt.Registry) error { - - if err := validate.Required("purpose", "body", m.Purpose); err != nil { - return err - } - - // value enum - if err := m.validatePurposeEnum("purpose", "body", *m.Purpose); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this test external backend connection input based on the context it is used -func (m *TestExternalBackendConnectionInput) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateConfiguration(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateCredential(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TestExternalBackendConnectionInput) contextValidateConfiguration(ctx context.Context, formats strfmt.Registry) error { - - if err := m.Configuration().ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -func (m *TestExternalBackendConnectionInput) contextValidateCredential(ctx context.Context, formats strfmt.Registry) error { - - if m.Credential != nil { - - if err := m.Credential.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("credential") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("credential") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *TestExternalBackendConnectionInput) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TestExternalBackendConnectionInput) UnmarshalBinary(b []byte) error { - var res TestExternalBackendConnectionInput - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/timeout_plan.go b/client/models/timeout_plan.go deleted file mode 100644 index 81098776c..000000000 --- a/client/models/timeout_plan.go +++ /dev/null @@ -1,173 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TimeoutPlan EnsurePlan -// -// The plan to ensure to be run. -// -// swagger:model TimeoutPlan -type TimeoutPlan struct { - - // next - // Required: true - Next *Plan `json:"next"` - - // step - // Required: true - Step *Plan `json:"step"` -} - -// Validate validates this timeout plan -func (m *TimeoutPlan) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateNext(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStep(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TimeoutPlan) validateNext(formats strfmt.Registry) error { - - if err := validate.Required("next", "body", m.Next); err != nil { - return err - } - - if m.Next != nil { - if err := m.Next.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next") - } - - return err - } - } - - return nil -} - -func (m *TimeoutPlan) validateStep(formats strfmt.Registry) error { - - if err := validate.Required("step", "body", m.Step); err != nil { - return err - } - - if m.Step != nil { - if err := m.Step.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("step") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("step") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this timeout plan based on the context it is used -func (m *TimeoutPlan) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateNext(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateStep(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TimeoutPlan) contextValidateNext(ctx context.Context, formats strfmt.Registry) error { - - if m.Next != nil { - - if err := m.Next.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next") - } - - return err - } - } - - return nil -} - -func (m *TimeoutPlan) contextValidateStep(ctx context.Context, formats strfmt.Registry) error { - - if m.Step != nil { - - if err := m.Step.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("step") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("step") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *TimeoutPlan) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TimeoutPlan) UnmarshalBinary(b []byte) error { - var res TimeoutPlan - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/try_plan.go b/client/models/try_plan.go deleted file mode 100644 index 15e75e1c6..000000000 --- a/client/models/try_plan.go +++ /dev/null @@ -1,173 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TryPlan EnsurePlan -// -// The plan to ensure to be run. -// -// swagger:model TryPlan -type TryPlan struct { - - // next - // Required: true - Next *Plan `json:"next"` - - // step - // Required: true - Step *Plan `json:"step"` -} - -// Validate validates this try plan -func (m *TryPlan) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateNext(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStep(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TryPlan) validateNext(formats strfmt.Registry) error { - - if err := validate.Required("next", "body", m.Next); err != nil { - return err - } - - if m.Next != nil { - if err := m.Next.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next") - } - - return err - } - } - - return nil -} - -func (m *TryPlan) validateStep(formats strfmt.Registry) error { - - if err := validate.Required("step", "body", m.Step); err != nil { - return err - } - - if m.Step != nil { - if err := m.Step.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("step") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("step") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this try plan based on the context it is used -func (m *TryPlan) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateNext(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateStep(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TryPlan) contextValidateNext(ctx context.Context, formats strfmt.Registry) error { - - if m.Next != nil { - - if err := m.Next.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("next") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("next") - } - - return err - } - } - - return nil -} - -func (m *TryPlan) contextValidateStep(ctx context.Context, formats strfmt.Registry) error { - - if m.Step != nil { - - if err := m.Step.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("step") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("step") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *TryPlan) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TryPlan) UnmarshalBinary(b []byte) error { - var res TryPlan - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_api_key.go b/client/models/update_api_key.go deleted file mode 100644 index 8ef6bdc5a..000000000 --- a/client/models/update_api_key.go +++ /dev/null @@ -1,85 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateAPIKey Update API key -// -// The entity which represents the information of the API key to be updated. -// The API key rules are immutable and cannot be changed. -// -// swagger:model UpdateAPIKey -type UpdateAPIKey struct { - - // description - Description string `json:"description,omitempty"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // User canonical that owns this API key. Only the owner or an - // organization admin can update such a field. When a user is the owner - // of a API key it has all the permission on it. - // - Owner string `json:"owner,omitempty"` -} - -// Validate validates this update API key -func (m *UpdateAPIKey) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateAPIKey) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update API key based on context it is used -func (m *UpdateAPIKey) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateAPIKey) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateAPIKey) UnmarshalBinary(b []byte) error { - var res UpdateAPIKey - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_cloud_account.go b/client/models/update_cloud_account.go deleted file mode 100644 index 74760da7c..000000000 --- a/client/models/update_cloud_account.go +++ /dev/null @@ -1,115 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateCloudAccount Update Cloud Account -// -// Update an existing Cloud Account. -// -// swagger:model UpdateCloudAccount -type UpdateCloudAccount struct { - - // Canonical of the credential to use. If omitted, the credential remains unchanged. - // Required: true - // Max Length: 100 - // Min Length: 3 - CredentialCanonical *string `json:"credential_canonical"` - - // An optional description for the cloud account - Description string `json:"description,omitempty"` - - // A user-defined name for the cloud account - // Required: true - // Max Length: 255 - // Min Length: 1 - Name *string `json:"name"` - - // User canonical that owns this cloud account. If omitted, ownership - // remains unchanged. - // - Owner string `json:"owner,omitempty"` -} - -// Validate validates this update cloud account -func (m *UpdateCloudAccount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateCloudAccount) validateCredentialCanonical(formats strfmt.Registry) error { - - if err := validate.Required("credential_canonical", "body", m.CredentialCanonical); err != nil { - return err - } - - if err := validate.MinLength("credential_canonical", "body", *m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", *m.CredentialCanonical, 100); err != nil { - return err - } - - return nil -} - -func (m *UpdateCloudAccount) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 255); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update cloud account based on context it is used -func (m *UpdateCloudAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateCloudAccount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateCloudAccount) UnmarshalBinary(b []byte) error { - var res UpdateCloudAccount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_cloud_account_finops.go b/client/models/update_cloud_account_finops.go deleted file mode 100644 index 1e9b82ecb..000000000 --- a/client/models/update_cloud_account_finops.go +++ /dev/null @@ -1,194 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateCloudAccountFinops Update Cloud Account FinOps -// -// Enable or disable FinOps (Cloud Cost Management) for a cloud account. -// -// swagger:model UpdateCloudAccountFinops -type UpdateCloudAccountFinops struct { - - // Required when finops_enabled is true. The CCM account configuration. - FinopsConfig *NewCloudCostManagementAccount `json:"finops_config,omitempty"` - - // Optional when finops_enabled is true. A dedicated credential for cost ingestion. When omitted, the cloud account's access credential is reused. Must be empty when finops_enabled is false. - FinopsCredential *NewCloudAccountCredential `json:"finops_credential,omitempty"` - - // Whether FinOps should be enabled for this cloud account - // Required: true - FinopsEnabled *bool `json:"finops_enabled"` -} - -// Validate validates this update cloud account finops -func (m *UpdateCloudAccountFinops) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateFinopsConfig(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFinopsCredential(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFinopsEnabled(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateCloudAccountFinops) validateFinopsConfig(formats strfmt.Registry) error { - if swag.IsZero(m.FinopsConfig) { // not required - return nil - } - - if m.FinopsConfig != nil { - if err := m.FinopsConfig.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("finops_config") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("finops_config") - } - - return err - } - } - - return nil -} - -func (m *UpdateCloudAccountFinops) validateFinopsCredential(formats strfmt.Registry) error { - if swag.IsZero(m.FinopsCredential) { // not required - return nil - } - - if m.FinopsCredential != nil { - if err := m.FinopsCredential.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("finops_credential") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("finops_credential") - } - - return err - } - } - - return nil -} - -func (m *UpdateCloudAccountFinops) validateFinopsEnabled(formats strfmt.Registry) error { - - if err := validate.Required("finops_enabled", "body", m.FinopsEnabled); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this update cloud account finops based on the context it is used -func (m *UpdateCloudAccountFinops) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateFinopsConfig(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateFinopsCredential(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateCloudAccountFinops) contextValidateFinopsConfig(ctx context.Context, formats strfmt.Registry) error { - - if m.FinopsConfig != nil { - - if swag.IsZero(m.FinopsConfig) { // not required - return nil - } - - if err := m.FinopsConfig.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("finops_config") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("finops_config") - } - - return err - } - } - - return nil -} - -func (m *UpdateCloudAccountFinops) contextValidateFinopsCredential(ctx context.Context, formats strfmt.Registry) error { - - if m.FinopsCredential != nil { - - if swag.IsZero(m.FinopsCredential) { // not required - return nil - } - - if err := m.FinopsCredential.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("finops_credential") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("finops_credential") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateCloudAccountFinops) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateCloudAccountFinops) UnmarshalBinary(b []byte) error { - var res UpdateCloudAccountFinops - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_cloud_cost_management_account.go b/client/models/update_cloud_cost_management_account.go deleted file mode 100644 index 8a814d093..000000000 --- a/client/models/update_cloud_cost_management_account.go +++ /dev/null @@ -1,119 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateCloudCostManagementAccount Update CloudCostManagementAccount -// -// Update a Cloud Cost Management account to connect CP. -// -// swagger:model UpdateCloudCostManagementAccount -type UpdateCloudCostManagementAccount struct { - - // external backend - // Required: true - ExternalBackend *UpdateExternalBackend `json:"external_backend"` - - // A user-defined name for the account - Name string `json:"name,omitempty"` -} - -// Validate validates this update cloud cost management account -func (m *UpdateCloudCostManagementAccount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateExternalBackend(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateCloudCostManagementAccount) validateExternalBackend(formats strfmt.Registry) error { - - if err := validate.Required("external_backend", "body", m.ExternalBackend); err != nil { - return err - } - - if m.ExternalBackend != nil { - if err := m.ExternalBackend.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("external_backend") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("external_backend") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this update cloud cost management account based on the context it is used -func (m *UpdateCloudCostManagementAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateExternalBackend(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateCloudCostManagementAccount) contextValidateExternalBackend(ctx context.Context, formats strfmt.Registry) error { - - if m.ExternalBackend != nil { - - if err := m.ExternalBackend.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("external_backend") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("external_backend") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateCloudCostManagementAccount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateCloudCostManagementAccount) UnmarshalBinary(b []byte) error { - var res UpdateCloudCostManagementAccount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_cloud_cost_management_linked_account.go b/client/models/update_cloud_cost_management_linked_account.go deleted file mode 100644 index 2f61935b0..000000000 --- a/client/models/update_cloud_cost_management_linked_account.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateCloudCostManagementLinkedAccount Update CloudCostManagementLinkedAccount -// -// Attributes of a CCM linked accout that can be updated by a user. -// -// swagger:model UpdateCloudCostManagementLinkedAccount -type UpdateCloudCostManagementLinkedAccount struct { - - // name - // Required: true - Name *string `json:"name"` -} - -// Validate validates this update cloud cost management linked account -func (m *UpdateCloudCostManagementLinkedAccount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateCloudCostManagementLinkedAccount) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update cloud cost management linked account based on context it is used -func (m *UpdateCloudCostManagementLinkedAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateCloudCostManagementLinkedAccount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateCloudCostManagementLinkedAccount) UnmarshalBinary(b []byte) error { - var res UpdateCloudCostManagementLinkedAccount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_cloud_cost_management_tag_mapping.go b/client/models/update_cloud_cost_management_tag_mapping.go deleted file mode 100644 index 1f8e47796..000000000 --- a/client/models/update_cloud_cost_management_tag_mapping.go +++ /dev/null @@ -1,64 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// UpdateCloudCostManagementTagMapping Create or Update CloudCostManagementTagMapping -// -// # Create or Update a Cloud Cost Management tag mapping for projects and environments -// -// swagger:model UpdateCloudCostManagementTagMapping -type UpdateCloudCostManagementTagMapping struct { - - // component regex - ComponentRegex string `json:"component_regex,omitempty"` - - // component tags - ComponentTags []string `json:"component_tags"` - - // environment regex - EnvironmentRegex string `json:"environment_regex,omitempty"` - - // environment tags - EnvironmentTags []string `json:"environment_tags"` - - // project regex - ProjectRegex string `json:"project_regex,omitempty"` - - // project tags - ProjectTags []string `json:"project_tags"` -} - -// Validate validates this update cloud cost management tag mapping -func (m *UpdateCloudCostManagementTagMapping) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this update cloud cost management tag mapping based on context it is used -func (m *UpdateCloudCostManagementTagMapping) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateCloudCostManagementTagMapping) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateCloudCostManagementTagMapping) UnmarshalBinary(b []byte) error { - var res UpdateCloudCostManagementTagMapping - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_component.go b/client/models/update_component.go deleted file mode 100644 index 7ac68b3e9..000000000 --- a/client/models/update_component.go +++ /dev/null @@ -1,78 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateComponent Update Component -// -// The entity which represents the information of a component to update. -// -// swagger:model UpdateComponent -type UpdateComponent struct { - - // description - Description string `json:"description,omitempty"` - - // name - // Required: true - // Min Length: 1 - Name *string `json:"name"` -} - -// Validate validates this update component -func (m *UpdateComponent) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateComponent) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update component based on context it is used -func (m *UpdateComponent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateComponent) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateComponent) UnmarshalBinary(b []byte) error { - var res UpdateComponent - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_config_repository.go b/client/models/update_config_repository.go deleted file mode 100644 index 5ccacc25c..000000000 --- a/client/models/update_config_repository.go +++ /dev/null @@ -1,156 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateConfigRepository UpdateConfigRepository -// -// swagger:model UpdateConfigRepository -type UpdateConfigRepository struct { - - // branch - // Required: true - Branch *string `json:"branch"` - - // credential canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical *string `json:"credential_canonical"` - - // default - // Required: true - Default *bool `json:"default"` - - // name - // Required: true - Name *string `json:"name"` - - // url - // Required: true - // Pattern: ^((/|~)[^/]*)+.(\.git)|(([\w\]+@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(/)? - URL *string `json:"url"` -} - -// Validate validates this update config repository -func (m *UpdateConfigRepository) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBranch(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDefault(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateConfigRepository) validateBranch(formats strfmt.Registry) error { - - if err := validate.Required("branch", "body", m.Branch); err != nil { - return err - } - - return nil -} - -func (m *UpdateConfigRepository) validateCredentialCanonical(formats strfmt.Registry) error { - - if err := validate.Required("credential_canonical", "body", m.CredentialCanonical); err != nil { - return err - } - - if err := validate.MinLength("credential_canonical", "body", *m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", *m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", *m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *UpdateConfigRepository) validateDefault(formats strfmt.Registry) error { - - if err := validate.Required("default", "body", m.Default); err != nil { - return err - } - - return nil -} - -func (m *UpdateConfigRepository) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *UpdateConfigRepository) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - if err := validate.Pattern("url", "body", *m.URL, `^((/|~)[^/]*)+.(\.git)|(([\w\]+@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(/)?`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update config repository based on context it is used -func (m *UpdateConfigRepository) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateConfigRepository) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateConfigRepository) UnmarshalBinary(b []byte) error { - var res UpdateConfigRepository - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_credential.go b/client/models/update_credential.go deleted file mode 100644 index 800baa55c..000000000 --- a/client/models/update_credential.go +++ /dev/null @@ -1,269 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateCredential Credential -// -// # Represents the Credential -// -// swagger:model UpdateCredential -type UpdateCredential struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // description - Description string `json:"description,omitempty"` - - // name - // Required: true - Name *string `json:"name"` - - // User canonical that owns this credential. When a user is the owner of a credential he has - // all the permissions on it. - // - Owner string `json:"owner,omitempty"` - - // path - // Required: true - // Pattern: [a-zA-z0-9_\-./] - Path *string `json:"path"` - - // raw - // Required: true - Raw *CredentialRaw `json:"raw"` - - // type - // Required: true - // Enum: ["ssh","aws","custom","azure","azure_storage","gcp","basic_auth","elasticsearch","vmware"] - Type *string `json:"type"` -} - -// Validate validates this update credential -func (m *UpdateCredential) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePath(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRaw(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateCredential) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *UpdateCredential) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *UpdateCredential) validatePath(formats strfmt.Registry) error { - - if err := validate.Required("path", "body", m.Path); err != nil { - return err - } - - if err := validate.Pattern("path", "body", *m.Path, `[a-zA-z0-9_\-./]`); err != nil { - return err - } - - return nil -} - -func (m *UpdateCredential) validateRaw(formats strfmt.Registry) error { - - if err := validate.Required("raw", "body", m.Raw); err != nil { - return err - } - - if m.Raw != nil { - if err := m.Raw.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("raw") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("raw") - } - - return err - } - } - - return nil -} - -var updateCredentialTypeTypePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["ssh","aws","custom","azure","azure_storage","gcp","basic_auth","elasticsearch","vmware"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - updateCredentialTypeTypePropEnum = append(updateCredentialTypeTypePropEnum, v) - } -} - -const ( - - // UpdateCredentialTypeSSH captures enum value "ssh" - UpdateCredentialTypeSSH string = "ssh" - - // UpdateCredentialTypeAws captures enum value "aws" - UpdateCredentialTypeAws string = "aws" - - // UpdateCredentialTypeCustom captures enum value "custom" - UpdateCredentialTypeCustom string = "custom" - - // UpdateCredentialTypeAzure captures enum value "azure" - UpdateCredentialTypeAzure string = "azure" - - // UpdateCredentialTypeAzureStorage captures enum value "azure_storage" - UpdateCredentialTypeAzureStorage string = "azure_storage" - - // UpdateCredentialTypeGcp captures enum value "gcp" - UpdateCredentialTypeGcp string = "gcp" - - // UpdateCredentialTypeBasicAuth captures enum value "basic_auth" - UpdateCredentialTypeBasicAuth string = "basic_auth" - - // UpdateCredentialTypeElasticsearch captures enum value "elasticsearch" - UpdateCredentialTypeElasticsearch string = "elasticsearch" - - // UpdateCredentialTypeVmware captures enum value "vmware" - UpdateCredentialTypeVmware string = "vmware" -) - -// prop value enum -func (m *UpdateCredential) validateTypeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, updateCredentialTypeTypePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *UpdateCredential) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - // value enum - if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this update credential based on the context it is used -func (m *UpdateCredential) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateRaw(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateCredential) contextValidateRaw(ctx context.Context, formats strfmt.Registry) error { - - if m.Raw != nil { - - if err := m.Raw.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("raw") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("raw") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateCredential) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateCredential) UnmarshalBinary(b []byte) error { - var res UpdateCredential - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_environment.go b/client/models/update_environment.go deleted file mode 100644 index 8f580a774..000000000 --- a/client/models/update_environment.go +++ /dev/null @@ -1,228 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateEnvironment Update Environment -// -// # Represent an entity necessary for environment update -// -// swagger:model UpdateEnvironment -type UpdateEnvironment struct { - - // Canonicals of cloud accounts to link. Omit or set to empty array to unlink all. - CloudAccountCanonicals []string `json:"cloud_account_canonicals"` - - // Optional description of the environment - // Max Length: 1000 - Description string `json:"description,omitempty"` - - // name - // Required: true - // Max Length: 100 - // Min Length: 1 - Name *string `json:"name"` - - // User canonical that owns this environment. Only the owner or an - // organization admin can update this field. When a user is the owner - // of an environment it has all the permissions on it. - // - Owner string `json:"owner,omitempty"` - - // type - // Example: production - // Required: true - Type *string `json:"type"` - - // Full replacement list of environment variables. Omit the field to leave existing variables untouched; pass an empty array to wipe all variables; pass a non-empty array to replace them. - Variables []*EnvironmentVariableItem `json:"variables"` -} - -// Validate validates this update environment -func (m *UpdateEnvironment) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCloudAccountCanonicals(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVariables(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateEnvironment) validateCloudAccountCanonicals(formats strfmt.Registry) error { - if swag.IsZero(m.CloudAccountCanonicals) { // not required - return nil - } - - for i := 0; i < len(m.CloudAccountCanonicals); i++ { - - if err := validate.MinLength("cloud_account_canonicals"+"."+strconv.Itoa(i), "body", m.CloudAccountCanonicals[i], 3); err != nil { - return err - } - - if err := validate.MaxLength("cloud_account_canonicals"+"."+strconv.Itoa(i), "body", m.CloudAccountCanonicals[i], 100); err != nil { - return err - } - - } - - return nil -} - -func (m *UpdateEnvironment) validateDescription(formats strfmt.Registry) error { - if swag.IsZero(m.Description) { // not required - return nil - } - - if err := validate.MaxLength("description", "body", m.Description, 1000); err != nil { - return err - } - - return nil -} - -func (m *UpdateEnvironment) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 100); err != nil { - return err - } - - return nil -} - -func (m *UpdateEnvironment) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - return nil -} - -func (m *UpdateEnvironment) validateVariables(formats strfmt.Registry) error { - if swag.IsZero(m.Variables) { // not required - return nil - } - - for i := 0; i < len(m.Variables); i++ { - if swag.IsZero(m.Variables[i]) { // not required - continue - } - - if m.Variables[i] != nil { - if err := m.Variables[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("variables" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("variables" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// ContextValidate validate this update environment based on the context it is used -func (m *UpdateEnvironment) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateVariables(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateEnvironment) contextValidateVariables(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Variables); i++ { - - if m.Variables[i] != nil { - - if swag.IsZero(m.Variables[i]) { // not required - return nil - } - - if err := m.Variables[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("variables" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("variables" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateEnvironment) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateEnvironment) UnmarshalBinary(b []byte) error { - var res UpdateEnvironment - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_environment_type.go b/client/models/update_environment_type.go deleted file mode 100644 index f2d08c7c6..000000000 --- a/client/models/update_environment_type.go +++ /dev/null @@ -1,102 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateEnvironmentType Update Environment Type -// -// # Represent an entity necessary for environment type update -// -// swagger:model UpdateEnvironmentType -type UpdateEnvironmentType struct { - - // Color associated with this environment type - // Required: true - // Max Length: 64 - Color *string `json:"color"` - - // name - // Required: true - // Max Length: 255 - // Min Length: 1 - Name *string `json:"name"` -} - -// Validate validates this update environment type -func (m *UpdateEnvironmentType) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateColor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateEnvironmentType) validateColor(formats strfmt.Registry) error { - - if err := validate.Required("color", "body", m.Color); err != nil { - return err - } - - if err := validate.MaxLength("color", "body", *m.Color, 64); err != nil { - return err - } - - return nil -} - -func (m *UpdateEnvironmentType) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - if err := validate.MaxLength("name", "body", *m.Name, 255); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update environment type based on context it is used -func (m *UpdateEnvironmentType) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateEnvironmentType) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateEnvironmentType) UnmarshalBinary(b []byte) error { - var res UpdateEnvironmentType - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_external_backend.go b/client/models/update_external_backend.go deleted file mode 100644 index 5972305c3..000000000 --- a/client/models/update_external_backend.go +++ /dev/null @@ -1,438 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - stderrors "errors" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateExternalBackend Update External backend -// -// An external backend contains the configuration needed in order to be plugged into the Cycloid system. A backend is a general purpose concept, but Cycloid specifies which ones are supported and the list of those which are supported for every concrete feature. -// -// swagger:model UpdateExternalBackend -type UpdateExternalBackend struct { - - // component canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$ - ComponentCanonical string `json:"component_canonical,omitempty"` - - configurationField ExternalBackendConfiguration - - // The type of the credential must be one of: ["aws", "azure_storage", "elasticsearch", "gcp", "swift", "vmware"] - // - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical string `json:"credential_canonical,omitempty"` - - // Will mark this EB as default for the specific purpose - Default bool `json:"default,omitempty"` - - // environment canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: ^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$ - EnvironmentCanonical string `json:"environment_canonical,omitempty"` - - // id - // Minimum: 1 - ID uint32 `json:"id,omitempty"` - - // project canonical - // Max Length: 100 - // Min Length: 1 - // Pattern: (^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$) - ProjectCanonical string `json:"project_canonical,omitempty"` - - // purpose - // Required: true - // Enum: ["events","logs","remote_tfstate","cost_explorer"] - Purpose *string `json:"purpose"` -} - -// Configuration gets the configuration of this base type -func (m *UpdateExternalBackend) Configuration() ExternalBackendConfiguration { - return m.configurationField -} - -// SetConfiguration sets the configuration of this base type -func (m *UpdateExternalBackend) SetConfiguration(val ExternalBackendConfiguration) { - m.configurationField = val -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *UpdateExternalBackend) UnmarshalJSON(raw []byte) error { - var data struct { - ComponentCanonical string `json:"component_canonical,omitempty"` - - Configuration json.RawMessage `json:"configuration"` - - CredentialCanonical string `json:"credential_canonical,omitempty"` - - Default bool `json:"default,omitempty"` - - EnvironmentCanonical string `json:"environment_canonical,omitempty"` - - ID uint32 `json:"id,omitempty"` - - ProjectCanonical string `json:"project_canonical,omitempty"` - - Purpose *string `json:"purpose"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - propConfiguration, err := UnmarshalExternalBackendConfiguration(bytes.NewBuffer(data.Configuration), runtime.JSONConsumer()) - if err != nil && !stderrors.Is(err, io.EOF) { - return err - } - - var result UpdateExternalBackend - - // component_canonical - result.ComponentCanonical = data.ComponentCanonical - - // configuration - result.configurationField = propConfiguration - - // credential_canonical - result.CredentialCanonical = data.CredentialCanonical - - // default - result.Default = data.Default - - // environment_canonical - result.EnvironmentCanonical = data.EnvironmentCanonical - - // id - result.ID = data.ID - - // project_canonical - result.ProjectCanonical = data.ProjectCanonical - - // purpose - result.Purpose = data.Purpose - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m UpdateExternalBackend) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - ComponentCanonical string `json:"component_canonical,omitempty"` - - CredentialCanonical string `json:"credential_canonical,omitempty"` - - Default bool `json:"default,omitempty"` - - EnvironmentCanonical string `json:"environment_canonical,omitempty"` - - ID uint32 `json:"id,omitempty"` - - ProjectCanonical string `json:"project_canonical,omitempty"` - - Purpose *string `json:"purpose"` - }{ - - ComponentCanonical: m.ComponentCanonical, - - CredentialCanonical: m.CredentialCanonical, - - Default: m.Default, - - EnvironmentCanonical: m.EnvironmentCanonical, - - ID: m.ID, - - ProjectCanonical: m.ProjectCanonical, - - Purpose: m.Purpose, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Configuration ExternalBackendConfiguration `json:"configuration"` - }{ - - Configuration: m.configurationField, - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this update external backend -func (m *UpdateExternalBackend) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateComponentCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateConfiguration(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvironmentCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjectCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePurpose(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateExternalBackend) validateComponentCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ComponentCanonical) { // not required - return nil - } - - if err := validate.MinLength("component_canonical", "body", m.ComponentCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("component_canonical", "body", m.ComponentCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("component_canonical", "body", m.ComponentCanonical, `^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$`); err != nil { - return err - } - - return nil -} - -func (m *UpdateExternalBackend) validateConfiguration(formats strfmt.Registry) error { - - if err := validate.Required("configuration", "body", m.Configuration()); err != nil { - return err - } - - if err := m.Configuration().Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -func (m *UpdateExternalBackend) validateCredentialCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.CredentialCanonical) { // not required - return nil - } - - if err := validate.MinLength("credential_canonical", "body", m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *UpdateExternalBackend) validateEnvironmentCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.EnvironmentCanonical) { // not required - return nil - } - - if err := validate.MinLength("environment_canonical", "body", m.EnvironmentCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("environment_canonical", "body", m.EnvironmentCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("environment_canonical", "body", m.EnvironmentCanonical, `^[\da-zA-Z]+(?:(?:[\da-zA-Z\-._]+)?[\da-zA-Z])?$`); err != nil { - return err - } - - return nil -} - -func (m *UpdateExternalBackend) validateID(formats strfmt.Registry) error { - if swag.IsZero(m.ID) { // not required - return nil - } - - if err := validate.MinimumUint("id", "body", uint64(m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *UpdateExternalBackend) validateProjectCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ProjectCanonical) { // not required - return nil - } - - if err := validate.MinLength("project_canonical", "body", m.ProjectCanonical, 1); err != nil { - return err - } - - if err := validate.MaxLength("project_canonical", "body", m.ProjectCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("project_canonical", "body", m.ProjectCanonical, `(^[a-z0-9]+(([a-z0-9\-_]+)?[a-z0-9]+)?$)`); err != nil { - return err - } - - return nil -} - -var updateExternalBackendTypePurposePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["events","logs","remote_tfstate","cost_explorer"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - updateExternalBackendTypePurposePropEnum = append(updateExternalBackendTypePurposePropEnum, v) - } -} - -const ( - - // UpdateExternalBackendPurposeEvents captures enum value "events" - UpdateExternalBackendPurposeEvents string = "events" - - // UpdateExternalBackendPurposeLogs captures enum value "logs" - UpdateExternalBackendPurposeLogs string = "logs" - - // UpdateExternalBackendPurposeRemoteTfstate captures enum value "remote_tfstate" - UpdateExternalBackendPurposeRemoteTfstate string = "remote_tfstate" - - // UpdateExternalBackendPurposeCostExplorer captures enum value "cost_explorer" - UpdateExternalBackendPurposeCostExplorer string = "cost_explorer" -) - -// prop value enum -func (m *UpdateExternalBackend) validatePurposeEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, updateExternalBackendTypePurposePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *UpdateExternalBackend) validatePurpose(formats strfmt.Registry) error { - - if err := validate.Required("purpose", "body", m.Purpose); err != nil { - return err - } - - // value enum - if err := m.validatePurposeEnum("purpose", "body", *m.Purpose); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this update external backend based on the context it is used -func (m *UpdateExternalBackend) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateConfiguration(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateExternalBackend) contextValidateConfiguration(ctx context.Context, formats strfmt.Registry) error { - - if err := m.Configuration().ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("configuration") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("configuration") - } - - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateExternalBackend) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateExternalBackend) UnmarshalBinary(b []byte) error { - var res UpdateExternalBackend - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_infra_policy.go b/client/models/update_infra_policy.go deleted file mode 100644 index 65cc96c6d..000000000 --- a/client/models/update_infra_policy.go +++ /dev/null @@ -1,208 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateInfraPolicy Update InfraPolicy -// -// Update a policy to control operations across infrastructure. -// -// swagger:model UpdateInfraPolicy -type UpdateInfraPolicy struct { - - // The body field is the code in plain text that defines the rules for the policy. - // Required: true - Body *string `json:"body"` - - // description - // Required: true - Description *string `json:"description"` - - // enabled - // Required: true - Enabled *bool `json:"enabled"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // User canonical that owns this InfraPolicy. When a user is the - // owner of an InfraPolicy it has all the permissions on it. - // In the event where the Owner has been deleted then a new one can be assigned - // or an empty canonical is allowed to not reset it. - // - // Required: true - // Max Length: 100 - Owner *string `json:"owner"` - - // severity - // Required: true - // Enum: ["critical","warning","advisory"] - Severity *string `json:"severity"` -} - -// Validate validates this update infra policy -func (m *UpdateInfraPolicy) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateBody(formats); err != nil { - res = append(res, err) - } - - if err := m.validateDescription(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnabled(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOwner(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSeverity(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateInfraPolicy) validateBody(formats strfmt.Registry) error { - - if err := validate.Required("body", "body", m.Body); err != nil { - return err - } - - return nil -} - -func (m *UpdateInfraPolicy) validateDescription(formats strfmt.Registry) error { - - if err := validate.Required("description", "body", m.Description); err != nil { - return err - } - - return nil -} - -func (m *UpdateInfraPolicy) validateEnabled(formats strfmt.Registry) error { - - if err := validate.Required("enabled", "body", m.Enabled); err != nil { - return err - } - - return nil -} - -func (m *UpdateInfraPolicy) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *UpdateInfraPolicy) validateOwner(formats strfmt.Registry) error { - - if err := validate.Required("owner", "body", m.Owner); err != nil { - return err - } - - if err := validate.MaxLength("owner", "body", *m.Owner, 100); err != nil { - return err - } - - return nil -} - -var updateInfraPolicyTypeSeverityPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["critical","warning","advisory"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - updateInfraPolicyTypeSeverityPropEnum = append(updateInfraPolicyTypeSeverityPropEnum, v) - } -} - -const ( - - // UpdateInfraPolicySeverityCritical captures enum value "critical" - UpdateInfraPolicySeverityCritical string = "critical" - - // UpdateInfraPolicySeverityWarning captures enum value "warning" - UpdateInfraPolicySeverityWarning string = "warning" - - // UpdateInfraPolicySeverityAdvisory captures enum value "advisory" - UpdateInfraPolicySeverityAdvisory string = "advisory" -) - -// prop value enum -func (m *UpdateInfraPolicy) validateSeverityEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, updateInfraPolicyTypeSeverityPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *UpdateInfraPolicy) validateSeverity(formats strfmt.Registry) error { - - if err := validate.Required("severity", "body", m.Severity); err != nil { - return err - } - - // value enum - if err := m.validateSeverityEnum("severity", "body", *m.Severity); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update infra policy based on context it is used -func (m *UpdateInfraPolicy) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateInfraPolicy) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateInfraPolicy) UnmarshalBinary(b []byte) error { - var res UpdateInfraPolicy - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_organization.go b/client/models/update_organization.go deleted file mode 100644 index ce13f534e..000000000 --- a/client/models/update_organization.go +++ /dev/null @@ -1,93 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateOrganization Update Organization -// -// The entity which represents the information of an organization to be updated. -// -// swagger:model UpdateOrganization -type UpdateOrganization struct { - - // can children create appearance - CanChildrenCreateAppearance bool `json:"can_children_create_appearance,omitempty"` - - // can children use dedicated authentication - CanChildrenUseDedicatedAuthentication bool `json:"can_children_use_dedicated_authentication,omitempty"` - - // Message displayed to users when organization creation is restricted - CreationRestrictedMessage *string `json:"creation_restricted_message,omitempty"` - - // is using dedicated authentication - IsUsingDedicatedAuthentication bool `json:"is_using_dedicated_authentication,omitempty"` - - // mfa enabled - MfaEnabled bool `json:"mfa_enabled,omitempty"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // When true, SSO users can only join the organization if they have been explicitly invited - SsoInviteOnly *bool `json:"sso_invite_only,omitempty"` -} - -// Validate validates this update organization -func (m *UpdateOrganization) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateOrganization) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update organization based on context it is used -func (m *UpdateOrganization) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateOrganization) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateOrganization) UnmarshalBinary(b []byte) error { - var res UpdateOrganization - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_organization_messages.go b/client/models/update_organization_messages.go deleted file mode 100644 index f9ec374f0..000000000 --- a/client/models/update_organization_messages.go +++ /dev/null @@ -1,47 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// UpdateOrganizationMessages update organization messages -// -// swagger:model UpdateOrganizationMessages -type UpdateOrganizationMessages struct { - - // creation restricted message - CreationRestrictedMessage *string `json:"creation_restricted_message,omitempty"` -} - -// Validate validates this update organization messages -func (m *UpdateOrganizationMessages) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this update organization messages based on context it is used -func (m *UpdateOrganizationMessages) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateOrganizationMessages) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateOrganizationMessages) UnmarshalBinary(b []byte) error { - var res UpdateOrganizationMessages - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_organization_naming_rules.go b/client/models/update_organization_naming_rules.go deleted file mode 100644 index 72a2537c5..000000000 --- a/client/models/update_organization_naming_rules.go +++ /dev/null @@ -1,173 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateOrganizationNamingRules UpdateOrganizationNamingRules -// -// # Naming validation rules to apply to entities within an organization -// -// swagger:model UpdateOrganizationNamingRules -type UpdateOrganizationNamingRules struct { - - // Custom error message shown when a component canonical does not match the regex - // Max Length: 500 - ComponentMessage string `json:"component_message,omitempty"` - - // Regex pattern that component canonicals must match - // Max Length: 255 - ComponentRegex string `json:"component_regex,omitempty"` - - // Custom error message shown when an environment canonical does not match the regex - // Max Length: 500 - EnvMessage string `json:"env_message,omitempty"` - - // Regex pattern that environment canonicals must match - // Max Length: 255 - EnvRegex string `json:"env_regex,omitempty"` - - // Custom error message shown when a project canonical does not match the regex - // Max Length: 500 - ProjectMessage string `json:"project_message,omitempty"` - - // Regex pattern that project canonicals must match - // Max Length: 255 - ProjectRegex string `json:"project_regex,omitempty"` -} - -// Validate validates this update organization naming rules -func (m *UpdateOrganizationNamingRules) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateComponentMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateComponentRegex(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEnvRegex(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjectMessage(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjectRegex(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateOrganizationNamingRules) validateComponentMessage(formats strfmt.Registry) error { - if swag.IsZero(m.ComponentMessage) { // not required - return nil - } - - if err := validate.MaxLength("component_message", "body", m.ComponentMessage, 500); err != nil { - return err - } - - return nil -} - -func (m *UpdateOrganizationNamingRules) validateComponentRegex(formats strfmt.Registry) error { - if swag.IsZero(m.ComponentRegex) { // not required - return nil - } - - if err := validate.MaxLength("component_regex", "body", m.ComponentRegex, 255); err != nil { - return err - } - - return nil -} - -func (m *UpdateOrganizationNamingRules) validateEnvMessage(formats strfmt.Registry) error { - if swag.IsZero(m.EnvMessage) { // not required - return nil - } - - if err := validate.MaxLength("env_message", "body", m.EnvMessage, 500); err != nil { - return err - } - - return nil -} - -func (m *UpdateOrganizationNamingRules) validateEnvRegex(formats strfmt.Registry) error { - if swag.IsZero(m.EnvRegex) { // not required - return nil - } - - if err := validate.MaxLength("env_regex", "body", m.EnvRegex, 255); err != nil { - return err - } - - return nil -} - -func (m *UpdateOrganizationNamingRules) validateProjectMessage(formats strfmt.Registry) error { - if swag.IsZero(m.ProjectMessage) { // not required - return nil - } - - if err := validate.MaxLength("project_message", "body", m.ProjectMessage, 500); err != nil { - return err - } - - return nil -} - -func (m *UpdateOrganizationNamingRules) validateProjectRegex(formats strfmt.Registry) error { - if swag.IsZero(m.ProjectRegex) { // not required - return nil - } - - if err := validate.MaxLength("project_regex", "body", m.ProjectRegex, 255); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update organization naming rules based on context it is used -func (m *UpdateOrganizationNamingRules) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateOrganizationNamingRules) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateOrganizationNamingRules) UnmarshalBinary(b []byte) error { - var res UpdateOrganizationNamingRules - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_pipeline.go b/client/models/update_pipeline.go deleted file mode 100644 index 8b840b812..000000000 --- a/client/models/update_pipeline.go +++ /dev/null @@ -1,64 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// UpdatePipeline Update Pipeline -// -// The entity which represents a new pipeline config to update in the -// application. -// If the refresh_from_git is requested, the passed_config is ignored -// and the new pipeline config and vars are retrieved from git instead. -// If the refresh_from_git is set to false (default), the passed_config is required -// and is used to update the pipeline config. The passed_config is NOT templated. -// -// swagger:model UpdatePipeline -type UpdatePipeline struct { - - // check credentials - CheckCredentials bool `json:"check_credentials,omitempty"` - - // Already templated 'final' pipeline config that is used to perform 'live updates'. - // What you pass here is what you get. - PassedConfig string `json:"passed_config,omitempty"` - - // If set to true, the new pipeline content and vars are retrieved from git and templated. - RefreshFromGit *bool `json:"refresh_from_git,omitempty"` - - // yaml vars - YamlVars string `json:"yaml_vars,omitempty"` -} - -// Validate validates this update pipeline -func (m *UpdatePipeline) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this update pipeline based on context it is used -func (m *UpdatePipeline) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdatePipeline) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdatePipeline) UnmarshalBinary(b []byte) error { - var res UpdatePipeline - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_plugin.go b/client/models/update_plugin.go deleted file mode 100644 index 0fc046d63..000000000 --- a/client/models/update_plugin.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdatePlugin Update Plugin -// -// # The Plugin data needed to update it -// -// swagger:model UpdatePlugin -type UpdatePlugin struct { - - // Name assigned to the Plugin - // Required: true - Name *string `json:"name"` -} - -// Validate validates this update plugin -func (m *UpdatePlugin) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdatePlugin) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update plugin based on context it is used -func (m *UpdatePlugin) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdatePlugin) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdatePlugin) UnmarshalBinary(b []byte) error { - var res UpdatePlugin - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_plugin_install.go b/client/models/update_plugin_install.go deleted file mode 100644 index 6cd12c943..000000000 --- a/client/models/update_plugin_install.go +++ /dev/null @@ -1,92 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdatePluginInstall Update Plugin Install -// -// # The data needed to update a Plugin Install to a new Plugin Version -// -// swagger:model UpdatePluginInstall -type UpdatePluginInstall struct { - - // Stack Forms syntax configuration - // Required: true - Configuration map[string]string `json:"configuration"` - - // ID of the new Plugin Version of the Plugin on the Plugin Registry - // Required: true - // Minimum: 1 - PluginVersionID *uint32 `json:"plugin_version_id"` -} - -// Validate validates this update plugin install -func (m *UpdatePluginInstall) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateConfiguration(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePluginVersionID(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdatePluginInstall) validateConfiguration(formats strfmt.Registry) error { - - if err := validate.Required("configuration", "body", m.Configuration); err != nil { - return err - } - - return nil -} - -func (m *UpdatePluginInstall) validatePluginVersionID(formats strfmt.Registry) error { - - if err := validate.Required("plugin_version_id", "body", m.PluginVersionID); err != nil { - return err - } - - if err := validate.MinimumUint("plugin_version_id", "body", uint64(*m.PluginVersionID), 1, false); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update plugin install based on context it is used -func (m *UpdatePluginInstall) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdatePluginInstall) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdatePluginInstall) UnmarshalBinary(b []byte) error { - var res UpdatePluginInstall - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_plugin_manager.go b/client/models/update_plugin_manager.go deleted file mode 100644 index c3a90fe70..000000000 --- a/client/models/update_plugin_manager.go +++ /dev/null @@ -1,106 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdatePluginManager Update Plugin Manager instance -// -// # The Plugin Manager instance data needed to update it -// -// swagger:model UpdatePluginManager -type UpdatePluginManager struct { - - // Invite status to be set by the Plugin Manager update - // Required: true - // Enum: ["accepted","rejected"] - InviteStatus *string `json:"invite_status"` -} - -// Validate validates this update plugin manager -func (m *UpdatePluginManager) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateInviteStatus(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -var updatePluginManagerTypeInviteStatusPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["accepted","rejected"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - updatePluginManagerTypeInviteStatusPropEnum = append(updatePluginManagerTypeInviteStatusPropEnum, v) - } -} - -const ( - - // UpdatePluginManagerInviteStatusAccepted captures enum value "accepted" - UpdatePluginManagerInviteStatusAccepted string = "accepted" - - // UpdatePluginManagerInviteStatusRejected captures enum value "rejected" - UpdatePluginManagerInviteStatusRejected string = "rejected" -) - -// prop value enum -func (m *UpdatePluginManager) validateInviteStatusEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, updatePluginManagerTypeInviteStatusPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *UpdatePluginManager) validateInviteStatus(formats strfmt.Registry) error { - - if err := validate.Required("invite_status", "body", m.InviteStatus); err != nil { - return err - } - - // value enum - if err := m.validateInviteStatusEnum("invite_status", "body", *m.InviteStatus); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update plugin manager based on context it is used -func (m *UpdatePluginManager) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdatePluginManager) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdatePluginManager) UnmarshalBinary(b []byte) error { - var res UpdatePluginManager - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_plugin_registry.go b/client/models/update_plugin_registry.go deleted file mode 100644 index 371469e9e..000000000 --- a/client/models/update_plugin_registry.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdatePluginRegistry Update Plugin Registry -// -// # The Plugin Registry data needed to update it -// -// swagger:model UpdatePluginRegistry -type UpdatePluginRegistry struct { - - // Name assigned to the Repository - // Required: true - Name *string `json:"name"` -} - -// Validate validates this update plugin registry -func (m *UpdatePluginRegistry) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdatePluginRegistry) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update plugin registry based on context it is used -func (m *UpdatePluginRegistry) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdatePluginRegistry) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdatePluginRegistry) UnmarshalBinary(b []byte) error { - var res UpdatePluginRegistry - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_project.go b/client/models/update_project.go deleted file mode 100644 index cdd121fb1..000000000 --- a/client/models/update_project.go +++ /dev/null @@ -1,229 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateProject Update Project -// -// The entity which represents the information of the project to be updated. -// -// swagger:model UpdateProject -type UpdateProject struct { - - // The cloud provider canonical that this project is using - between the - // supported ones. - // - // Enum: ["aws","google","azurerm","flexibleengine","openstack"] - CloudProvider string `json:"cloud_provider,omitempty"` - - // color - // Max Length: 64 - Color string `json:"color,omitempty"` - - // The config_repository_canonical points to new Config Repository the project - // will be using. If this value is filled and it's different from the - // current one, the whole project will be migrated to new CR, meaning - // configuration files will also be moved. - // If the project didn't have config_repository_canonical set, this action will - // only attach the project to the CR, it won't create/move any files. - // In order to be sure everything works, make sure the - // config_repository_canonical is pointing at the CR with the same git - // repository that was used during project creation. - // Although the config_repository_canonical is not marked as required, - // it's actually required for projects that are already using CR. This - // field not being required is only for compatibility with older projects, - // which are not having CR yet. - // - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - ConfigRepositoryCanonical string `json:"config_repository_canonical,omitempty"` - - // description - Description string `json:"description,omitempty"` - - // icon - // Max Length: 64 - Icon string `json:"icon,omitempty"` - - // name - // Required: true - // Min Length: 1 - Name *string `json:"name"` - - // User canonical that owns this project. Only the owner or an - // organization admin can update such a field. When a user is the owner - // of a project it has all the permission on it. - // - Owner string `json:"owner,omitempty"` -} - -// Validate validates this update project -func (m *UpdateProject) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCloudProvider(formats); err != nil { - res = append(res, err) - } - - if err := m.validateColor(formats); err != nil { - res = append(res, err) - } - - if err := m.validateConfigRepositoryCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateIcon(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -var updateProjectTypeCloudProviderPropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["aws","google","azurerm","flexibleengine","openstack"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - updateProjectTypeCloudProviderPropEnum = append(updateProjectTypeCloudProviderPropEnum, v) - } -} - -const ( - - // UpdateProjectCloudProviderAws captures enum value "aws" - UpdateProjectCloudProviderAws string = "aws" - - // UpdateProjectCloudProviderGoogle captures enum value "google" - UpdateProjectCloudProviderGoogle string = "google" - - // UpdateProjectCloudProviderAzurerm captures enum value "azurerm" - UpdateProjectCloudProviderAzurerm string = "azurerm" - - // UpdateProjectCloudProviderFlexibleengine captures enum value "flexibleengine" - UpdateProjectCloudProviderFlexibleengine string = "flexibleengine" - - // UpdateProjectCloudProviderOpenstack captures enum value "openstack" - UpdateProjectCloudProviderOpenstack string = "openstack" -) - -// prop value enum -func (m *UpdateProject) validateCloudProviderEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, updateProjectTypeCloudProviderPropEnum, true); err != nil { - return err - } - return nil -} - -func (m *UpdateProject) validateCloudProvider(formats strfmt.Registry) error { - if swag.IsZero(m.CloudProvider) { // not required - return nil - } - - // value enum - if err := m.validateCloudProviderEnum("cloud_provider", "body", m.CloudProvider); err != nil { - return err - } - - return nil -} - -func (m *UpdateProject) validateColor(formats strfmt.Registry) error { - if swag.IsZero(m.Color) { // not required - return nil - } - - if err := validate.MaxLength("color", "body", m.Color, 64); err != nil { - return err - } - - return nil -} - -func (m *UpdateProject) validateConfigRepositoryCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ConfigRepositoryCanonical) { // not required - return nil - } - - if err := validate.MinLength("config_repository_canonical", "body", m.ConfigRepositoryCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("config_repository_canonical", "body", m.ConfigRepositoryCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("config_repository_canonical", "body", m.ConfigRepositoryCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *UpdateProject) validateIcon(formats strfmt.Registry) error { - if swag.IsZero(m.Icon) { // not required - return nil - } - - if err := validate.MaxLength("icon", "body", m.Icon, 64); err != nil { - return err - } - - return nil -} - -func (m *UpdateProject) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update project based on context it is used -func (m *UpdateProject) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateProject) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateProject) UnmarshalBinary(b []byte) error { - var res UpdateProject - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_service_catalog.go b/client/models/update_service_catalog.go deleted file mode 100644 index 4df9fa9ab..000000000 --- a/client/models/update_service_catalog.go +++ /dev/null @@ -1,101 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateServiceCatalog UpdateServiceCatalog -// -// # Represents the Service Catalog item to be updated -// -// swagger:model UpdateServiceCatalog -type UpdateServiceCatalog struct { - - // Team responsible for the maintenance of the underlying service catalogs - // - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - TeamCanonical string `json:"team_canonical,omitempty"` - - // visibility - // Required: true - Visibility *string `json:"visibility"` -} - -// Validate validates this update service catalog -func (m *UpdateServiceCatalog) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateTeamCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVisibility(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateServiceCatalog) validateTeamCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.TeamCanonical) { // not required - return nil - } - - if err := validate.MinLength("team_canonical", "body", m.TeamCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("team_canonical", "body", m.TeamCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("team_canonical", "body", m.TeamCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *UpdateServiceCatalog) validateVisibility(formats strfmt.Registry) error { - - if err := validate.Required("visibility", "body", m.Visibility); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update service catalog based on context it is used -func (m *UpdateServiceCatalog) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateServiceCatalog) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateServiceCatalog) UnmarshalBinary(b []byte) error { - var res UpdateServiceCatalog - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_service_catalog_source.go b/client/models/update_service_catalog_source.go deleted file mode 100644 index 336d71fd5..000000000 --- a/client/models/update_service_catalog_source.go +++ /dev/null @@ -1,129 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateServiceCatalogSource UpdateServiceCatalogSource -// -// swagger:model UpdateServiceCatalogSource -type UpdateServiceCatalogSource struct { - - // branch - Branch string `json:"branch,omitempty"` - - // credential canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - CredentialCanonical string `json:"credential_canonical,omitempty"` - - // name - // Required: true - Name *string `json:"name"` - - // User canonical that owns this service catalog source. If omitted then the person - // creating this service catalog source will be assigned as owner. When a user is the - // owner of a service catalog source they has all the permissions on it. - // - Owner string `json:"owner,omitempty"` - - // url - // Required: true - // Pattern: ^((/|~)[^/]*)+.(\.git)|(([\w\]+@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(/)? - URL *string `json:"url"` -} - -// Validate validates this update service catalog source -func (m *UpdateServiceCatalogSource) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCredentialCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateURL(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateServiceCatalogSource) validateCredentialCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.CredentialCanonical) { // not required - return nil - } - - if err := validate.MinLength("credential_canonical", "body", m.CredentialCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("credential_canonical", "body", m.CredentialCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("credential_canonical", "body", m.CredentialCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *UpdateServiceCatalogSource) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *UpdateServiceCatalogSource) validateURL(formats strfmt.Registry) error { - - if err := validate.Required("url", "body", m.URL); err != nil { - return err - } - - if err := validate.Pattern("url", "body", *m.URL, `^((/|~)[^/]*)+.(\.git)|(([\w\]+@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(/)?`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update service catalog source based on context it is used -func (m *UpdateServiceCatalogSource) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateServiceCatalogSource) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateServiceCatalogSource) UnmarshalBinary(b []byte) error { - var res UpdateServiceCatalogSource - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_team.go b/client/models/update_team.go deleted file mode 100644 index e639077b2..000000000 --- a/client/models/update_team.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateTeam Update Team -// -// The entity which represents the information of the team to be updated. -// -// swagger:model UpdateTeam -type UpdateTeam struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // User canonical that owns this team. Only the owner or an - // organization admin can update this field. When a user is the owner - // of a team it has all the permission on it. - // - Owner string `json:"owner,omitempty"` - - // The roles to be re-assigned to a team. - // Required: true - RolesCanonical []string `json:"roles_canonical"` -} - -// Validate validates this update team -func (m *UpdateTeam) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateRolesCanonical(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateTeam) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *UpdateTeam) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *UpdateTeam) validateRolesCanonical(formats strfmt.Registry) error { - - if err := validate.Required("roles_canonical", "body", m.RolesCanonical); err != nil { - return err - } - - for i := 0; i < len(m.RolesCanonical); i++ { - - if err := validate.MinLength("roles_canonical"+"."+strconv.Itoa(i), "body", m.RolesCanonical[i], 3); err != nil { - return err - } - - if err := validate.MaxLength("roles_canonical"+"."+strconv.Itoa(i), "body", m.RolesCanonical[i], 100); err != nil { - return err - } - - if err := validate.Pattern("roles_canonical"+"."+strconv.Itoa(i), "body", m.RolesCanonical[i], `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - } - - return nil -} - -// ContextValidate validates this update team based on context it is used -func (m *UpdateTeam) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateTeam) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateTeam) UnmarshalBinary(b []byte) error { - var res UpdateTeam - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_user_account.go b/client/models/update_user_account.go deleted file mode 100644 index d03e4ab0c..000000000 --- a/client/models/update_user_account.go +++ /dev/null @@ -1,461 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateUserAccount Update user's account -// -// The user's account information of the authenticated user to be updated. The username is not editable and is used to match the user account. Emails and password can be omitted if they don't have to be updated, because we can now if they have been sent or not although go-swagger doesn't currently support `PATCH` updates (see [comment](https://github.com/cycloidio/youdeploy-http-api/pull/71#issuecomment-321894076)), we do for this one with this 2 properties because they are good for the user, specially for the `password_update` one. In order to detect if they have been sent or not, we check if the length of array of emails is 0 (if it's sent, then the length MUST be greater than 0 as specified with minItems) and in case of the `password_update` field if it's `nil` or not. If the 'picture_url' is not send then it's removed from the user as it implies that it has deleted it, and also because we do not support partial updates -// -// swagger:model UpdateUserAccount -type UpdateUserAccount struct { - - // Code of a country the user is from in alpha-2 format - // Pattern: ^[A-Z]{2}$ - CountryCode string `json:"country_code,omitempty"` - - // emails - // Min Items: 1 - Emails []*UpdateUserAccountEmail `json:"emails"` - - // full name - // Required: true - // Max Length: 255 - // Min Length: 2 - FullName *string `json:"full_name"` - - // User's preferred language - // Required: true - // Enum: ["en","fr","es"] - Locale *string `json:"locale"` - - // mfa enabled - // Required: true - MfaEnabled *bool `json:"mfa_enabled"` - - // password update - PasswordUpdate *UpdateUserAccountPasswordUpdate `json:"password_update,omitempty"` - - // picture url - // Format: uri - PictureURL strfmt.URI `json:"picture_url,omitempty"` - - // Used to identify the user. Not editable. - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Username *string `json:"username"` -} - -// Validate validates this update user account -func (m *UpdateUserAccount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCountryCode(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEmails(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFullName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLocale(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMfaEnabled(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePasswordUpdate(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePictureURL(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUsername(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateUserAccount) validateCountryCode(formats strfmt.Registry) error { - if swag.IsZero(m.CountryCode) { // not required - return nil - } - - if err := validate.Pattern("country_code", "body", m.CountryCode, `^[A-Z]{2}$`); err != nil { - return err - } - - return nil -} - -func (m *UpdateUserAccount) validateEmails(formats strfmt.Registry) error { - if swag.IsZero(m.Emails) { // not required - return nil - } - - iEmailsSize := int64(len(m.Emails)) - - if err := validate.MinItems("emails", "body", iEmailsSize, 1); err != nil { - return err - } - - for i := 0; i < len(m.Emails); i++ { - if swag.IsZero(m.Emails[i]) { // not required - continue - } - - if m.Emails[i] != nil { - if err := m.Emails[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("emails" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("emails" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *UpdateUserAccount) validateFullName(formats strfmt.Registry) error { - - if err := validate.Required("full_name", "body", m.FullName); err != nil { - return err - } - - if err := validate.MinLength("full_name", "body", *m.FullName, 2); err != nil { - return err - } - - if err := validate.MaxLength("full_name", "body", *m.FullName, 255); err != nil { - return err - } - - return nil -} - -var updateUserAccountTypeLocalePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["en","fr","es"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - updateUserAccountTypeLocalePropEnum = append(updateUserAccountTypeLocalePropEnum, v) - } -} - -const ( - - // UpdateUserAccountLocaleEn captures enum value "en" - UpdateUserAccountLocaleEn string = "en" - - // UpdateUserAccountLocaleFr captures enum value "fr" - UpdateUserAccountLocaleFr string = "fr" - - // UpdateUserAccountLocaleEs captures enum value "es" - UpdateUserAccountLocaleEs string = "es" -) - -// prop value enum -func (m *UpdateUserAccount) validateLocaleEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, updateUserAccountTypeLocalePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *UpdateUserAccount) validateLocale(formats strfmt.Registry) error { - - if err := validate.Required("locale", "body", m.Locale); err != nil { - return err - } - - // value enum - if err := m.validateLocaleEnum("locale", "body", *m.Locale); err != nil { - return err - } - - return nil -} - -func (m *UpdateUserAccount) validateMfaEnabled(formats strfmt.Registry) error { - - if err := validate.Required("mfa_enabled", "body", m.MfaEnabled); err != nil { - return err - } - - return nil -} - -func (m *UpdateUserAccount) validatePasswordUpdate(formats strfmt.Registry) error { - if swag.IsZero(m.PasswordUpdate) { // not required - return nil - } - - if m.PasswordUpdate != nil { - if err := m.PasswordUpdate.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("password_update") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("password_update") - } - - return err - } - } - - return nil -} - -func (m *UpdateUserAccount) validatePictureURL(formats strfmt.Registry) error { - if swag.IsZero(m.PictureURL) { // not required - return nil - } - - if err := validate.FormatOf("picture_url", "body", "uri", m.PictureURL.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *UpdateUserAccount) validateUsername(formats strfmt.Registry) error { - - if err := validate.Required("username", "body", m.Username); err != nil { - return err - } - - if err := validate.MinLength("username", "body", *m.Username, 3); err != nil { - return err - } - - if err := validate.MaxLength("username", "body", *m.Username, 100); err != nil { - return err - } - - if err := validate.Pattern("username", "body", *m.Username, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this update user account based on the context it is used -func (m *UpdateUserAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateEmails(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidatePasswordUpdate(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateUserAccount) contextValidateEmails(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Emails); i++ { - - if m.Emails[i] != nil { - - if swag.IsZero(m.Emails[i]) { // not required - return nil - } - - if err := m.Emails[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("emails" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("emails" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *UpdateUserAccount) contextValidatePasswordUpdate(ctx context.Context, formats strfmt.Registry) error { - - if m.PasswordUpdate != nil { - - if swag.IsZero(m.PasswordUpdate) { // not required - return nil - } - - if err := m.PasswordUpdate.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("password_update") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("password_update") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateUserAccount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateUserAccount) UnmarshalBinary(b []byte) error { - var res UpdateUserAccount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} - -// UpdateUserAccountPasswordUpdate The update password requires to confirm the old password. -// -// swagger:model UpdateUserAccountPasswordUpdate -type UpdateUserAccountPasswordUpdate struct { - - // current - // Required: true - // Min Length: 8 - // Format: password - Current *strfmt.Password `json:"current"` - - // new - // Required: true - // Min Length: 8 - // Format: password - New *strfmt.Password `json:"new"` -} - -// Validate validates this update user account password update -func (m *UpdateUserAccountPasswordUpdate) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCurrent(formats); err != nil { - res = append(res, err) - } - - if err := m.validateNew(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateUserAccountPasswordUpdate) validateCurrent(formats strfmt.Registry) error { - - if err := validate.Required("password_update"+"."+"current", "body", m.Current); err != nil { - return err - } - - if err := validate.MinLength("password_update"+"."+"current", "body", m.Current.String(), 8); err != nil { - return err - } - - if err := validate.FormatOf("password_update"+"."+"current", "body", "password", m.Current.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *UpdateUserAccountPasswordUpdate) validateNew(formats strfmt.Registry) error { - - if err := validate.Required("password_update"+"."+"new", "body", m.New); err != nil { - return err - } - - if err := validate.MinLength("password_update"+"."+"new", "body", m.New.String(), 8); err != nil { - return err - } - - if err := validate.FormatOf("password_update"+"."+"new", "body", "password", m.New.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update user account password update based on context it is used -func (m *UpdateUserAccountPasswordUpdate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateUserAccountPasswordUpdate) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateUserAccountPasswordUpdate) UnmarshalBinary(b []byte) error { - var res UpdateUserAccountPasswordUpdate - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_user_account_email.go b/client/models/update_user_account_email.go deleted file mode 100644 index 37f9c3f31..000000000 --- a/client/models/update_user_account_email.go +++ /dev/null @@ -1,92 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateUserAccountEmail User's email -// -// The email address of a user to be updated. -// -// swagger:model UpdateUserAccountEmail -type UpdateUserAccountEmail struct { - - // email - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` - - // This values are set by the application to indicate the purpose of the email address. At least there is always one which is the primary. - // Required: true - Purpose *string `json:"purpose"` -} - -// Validate validates this update user account email -func (m *UpdateUserAccountEmail) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePurpose(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateUserAccountEmail) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *UpdateUserAccountEmail) validatePurpose(formats strfmt.Registry) error { - - if err := validate.Required("purpose", "body", m.Purpose); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this update user account email based on context it is used -func (m *UpdateUserAccountEmail) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateUserAccountEmail) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateUserAccountEmail) UnmarshalBinary(b []byte) error { - var res UpdateUserAccountEmail - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/update_watch_rule.go b/client/models/update_watch_rule.go deleted file mode 100644 index f104688b9..000000000 --- a/client/models/update_watch_rule.go +++ /dev/null @@ -1,169 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UpdateWatchRule Update Watch rule -// -// # The entity which represents the information of a Watch rule -// -// swagger:model UpdateWatchRule -type UpdateWatchRule struct { - - // filters - Filters []*NewWatchRuleFilter `json:"filters"` - - // muted - // Required: true - Muted *bool `json:"muted"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` -} - -// Validate validates this update watch rule -func (m *UpdateWatchRule) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateFilters(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMuted(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateWatchRule) validateFilters(formats strfmt.Registry) error { - if swag.IsZero(m.Filters) { // not required - return nil - } - - for i := 0; i < len(m.Filters); i++ { - if swag.IsZero(m.Filters[i]) { // not required - continue - } - - if m.Filters[i] != nil { - if err := m.Filters[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("filters" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("filters" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *UpdateWatchRule) validateMuted(formats strfmt.Registry) error { - - if err := validate.Required("muted", "body", m.Muted); err != nil { - return err - } - - return nil -} - -func (m *UpdateWatchRule) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this update watch rule based on the context it is used -func (m *UpdateWatchRule) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateFilters(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UpdateWatchRule) contextValidateFilters(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Filters); i++ { - - if m.Filters[i] != nil { - - if swag.IsZero(m.Filters[i]) { // not required - return nil - } - - if err := m.Filters[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("filters" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("filters" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *UpdateWatchRule) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UpdateWatchRule) UnmarshalBinary(b []byte) error { - var res UpdateWatchRule - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/user.go b/client/models/user.go deleted file mode 100644 index f62c90917..000000000 --- a/client/models/user.go +++ /dev/null @@ -1,287 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// User Basic info of a user -// -// A summary of a user to be used in places where only the basic information are need or are enough. -// -// swagger:model User -type User struct { - - // Code of a country the user is from in alpha-2 format - // Pattern: ^[A-Z]{2}$ - CountryCode string `json:"country_code,omitempty"` - - // When the user became a member. - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // User's primary email. - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` - - // full name - // Required: true - FullName *string `json:"full_name"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // When the user logged in last time. - // Minimum: 0 - LastLoginAt *uint64 `json:"last_login_at,omitempty"` - - // The local that the user prefer. - // Required: true - // Pattern: ^[a-z]{2}(?:-[a-z][a-z])?$ - Locale *string `json:"locale"` - - // mfa enabled - // Required: true - MfaEnabled *bool `json:"mfa_enabled"` - - // picture url - // Format: uri - PictureURL strfmt.URI `json:"picture_url,omitempty"` - - // When the user had the role modified. - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at,omitempty"` - - // username - // Required: true - // Max Length: 30 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Username *string `json:"username"` -} - -// Validate validates this user -func (m *User) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCountryCode(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFullName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLastLoginAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLocale(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMfaEnabled(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePictureURL(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUsername(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *User) validateCountryCode(formats strfmt.Registry) error { - if swag.IsZero(m.CountryCode) { // not required - return nil - } - - if err := validate.Pattern("country_code", "body", m.CountryCode, `^[A-Z]{2}$`); err != nil { - return err - } - - return nil -} - -func (m *User) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *User) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *User) validateFullName(formats strfmt.Registry) error { - - if err := validate.Required("full_name", "body", m.FullName); err != nil { - return err - } - - return nil -} - -func (m *User) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *User) validateLastLoginAt(formats strfmt.Registry) error { - if swag.IsZero(m.LastLoginAt) { // not required - return nil - } - - if err := validate.MinimumUint("last_login_at", "body", *m.LastLoginAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *User) validateLocale(formats strfmt.Registry) error { - - if err := validate.Required("locale", "body", m.Locale); err != nil { - return err - } - - if err := validate.Pattern("locale", "body", *m.Locale, `^[a-z]{2}(?:-[a-z][a-z])?$`); err != nil { - return err - } - - return nil -} - -func (m *User) validateMfaEnabled(formats strfmt.Registry) error { - - if err := validate.Required("mfa_enabled", "body", m.MfaEnabled); err != nil { - return err - } - - return nil -} - -func (m *User) validatePictureURL(formats strfmt.Registry) error { - if swag.IsZero(m.PictureURL) { // not required - return nil - } - - if err := validate.FormatOf("picture_url", "body", "uri", m.PictureURL.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *User) validateUpdatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *User) validateUsername(formats strfmt.Registry) error { - - if err := validate.Required("username", "body", m.Username); err != nil { - return err - } - - if err := validate.MinLength("username", "body", *m.Username, 3); err != nil { - return err - } - - if err := validate.MaxLength("username", "body", *m.Username, 30); err != nil { - return err - } - - if err := validate.Pattern("username", "body", *m.Username, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this user based on context it is used -func (m *User) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *User) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *User) UnmarshalBinary(b []byte) error { - var res User - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/user_account.go b/client/models/user_account.go deleted file mode 100644 index 286ab0490..000000000 --- a/client/models/user_account.go +++ /dev/null @@ -1,419 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - "encoding/json" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UserAccount User's account -// -// The user's account contains information related with the authenticated user. -// -// swagger:model UserAccount -type UserAccount struct { - - // country - Country *Country `json:"country,omitempty"` - - // created at - // Required: true - // Minimum: 0 - CreatedAt *uint64 `json:"created_at"` - - // emails - // Required: true - // Min Items: 1 - Emails []*UserAccountEmail `json:"emails"` - - // full name - // Required: true - // Max Length: 255 - // Min Length: 2 - FullName *string `json:"full_name"` - - // guide - Guide UserGuide `json:"guide,omitempty"` - - // last login - // Required: true - // Minimum: 0 - LastLogin *uint64 `json:"last_login"` - - // User's preferred language - // Required: true - // Enum: ["en","fr","es"] - Locale *string `json:"locale"` - - // mfa enabled - // Required: true - MfaEnabled *bool `json:"mfa_enabled"` - - // picture url - // Format: uri - PictureURL strfmt.URI `json:"picture_url,omitempty"` - - // updated at - // Required: true - // Minimum: 0 - UpdatedAt *uint64 `json:"updated_at"` - - // username - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Username *string `json:"username"` -} - -// Validate validates this user account -func (m *UserAccount) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCountry(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEmails(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFullName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLastLogin(formats); err != nil { - res = append(res, err) - } - - if err := m.validateLocale(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMfaEnabled(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePictureURL(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUsername(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UserAccount) validateCountry(formats strfmt.Registry) error { - if swag.IsZero(m.Country) { // not required - return nil - } - - if m.Country != nil { - if err := m.Country.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("country") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("country") - } - - return err - } - } - - return nil -} - -func (m *UserAccount) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *UserAccount) validateEmails(formats strfmt.Registry) error { - - if err := validate.Required("emails", "body", m.Emails); err != nil { - return err - } - - iEmailsSize := int64(len(m.Emails)) - - if err := validate.MinItems("emails", "body", iEmailsSize, 1); err != nil { - return err - } - - for i := 0; i < len(m.Emails); i++ { - if swag.IsZero(m.Emails[i]) { // not required - continue - } - - if m.Emails[i] != nil { - if err := m.Emails[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("emails" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("emails" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *UserAccount) validateFullName(formats strfmt.Registry) error { - - if err := validate.Required("full_name", "body", m.FullName); err != nil { - return err - } - - if err := validate.MinLength("full_name", "body", *m.FullName, 2); err != nil { - return err - } - - if err := validate.MaxLength("full_name", "body", *m.FullName, 255); err != nil { - return err - } - - return nil -} - -func (m *UserAccount) validateLastLogin(formats strfmt.Registry) error { - - if err := validate.Required("last_login", "body", m.LastLogin); err != nil { - return err - } - - if err := validate.MinimumUint("last_login", "body", *m.LastLogin, 0, false); err != nil { - return err - } - - return nil -} - -var userAccountTypeLocalePropEnum []any - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["en","fr","es"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - userAccountTypeLocalePropEnum = append(userAccountTypeLocalePropEnum, v) - } -} - -const ( - - // UserAccountLocaleEn captures enum value "en" - UserAccountLocaleEn string = "en" - - // UserAccountLocaleFr captures enum value "fr" - UserAccountLocaleFr string = "fr" - - // UserAccountLocaleEs captures enum value "es" - UserAccountLocaleEs string = "es" -) - -// prop value enum -func (m *UserAccount) validateLocaleEnum(path, location string, value string) error { - if err := validate.EnumCase(path, location, value, userAccountTypeLocalePropEnum, true); err != nil { - return err - } - return nil -} - -func (m *UserAccount) validateLocale(formats strfmt.Registry) error { - - if err := validate.Required("locale", "body", m.Locale); err != nil { - return err - } - - // value enum - if err := m.validateLocaleEnum("locale", "body", *m.Locale); err != nil { - return err - } - - return nil -} - -func (m *UserAccount) validateMfaEnabled(formats strfmt.Registry) error { - - if err := validate.Required("mfa_enabled", "body", m.MfaEnabled); err != nil { - return err - } - - return nil -} - -func (m *UserAccount) validatePictureURL(formats strfmt.Registry) error { - if swag.IsZero(m.PictureURL) { // not required - return nil - } - - if err := validate.FormatOf("picture_url", "body", "uri", m.PictureURL.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *UserAccount) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - if err := validate.MinimumUint("updated_at", "body", *m.UpdatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *UserAccount) validateUsername(formats strfmt.Registry) error { - - if err := validate.Required("username", "body", m.Username); err != nil { - return err - } - - if err := validate.MinLength("username", "body", *m.Username, 3); err != nil { - return err - } - - if err := validate.MaxLength("username", "body", *m.Username, 100); err != nil { - return err - } - - if err := validate.Pattern("username", "body", *m.Username, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this user account based on the context it is used -func (m *UserAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateCountry(ctx, formats); err != nil { - res = append(res, err) - } - - if err := m.contextValidateEmails(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UserAccount) contextValidateCountry(ctx context.Context, formats strfmt.Registry) error { - - if m.Country != nil { - - if swag.IsZero(m.Country) { // not required - return nil - } - - if err := m.Country.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("country") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("country") - } - - return err - } - } - - return nil -} - -func (m *UserAccount) contextValidateEmails(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Emails); i++ { - - if m.Emails[i] != nil { - - if swag.IsZero(m.Emails[i]) { // not required - return nil - } - - if err := m.Emails[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("emails" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("emails" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *UserAccount) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UserAccount) UnmarshalBinary(b []byte) error { - var res UserAccount - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/user_account_email.go b/client/models/user_account_email.go deleted file mode 100644 index 49edcc6a4..000000000 --- a/client/models/user_account_email.go +++ /dev/null @@ -1,129 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UserAccountEmail User's email -// -// The email address of a user. -// -// swagger:model UserAccountEmail -type UserAccountEmail struct { - - // created at - // Minimum: 0 - CreatedAt *uint64 `json:"created_at,omitempty"` - - // email - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` - - // This values are set by the application to indicate the purpose of the email address. At least there is always one which is the primary. - // Required: true - Purpose *string `json:"purpose"` - - // verified - // Required: true - Verified *bool `json:"verified"` -} - -// Validate validates this user account email -func (m *UserAccountEmail) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePurpose(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVerified(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UserAccountEmail) validateCreatedAt(formats strfmt.Registry) error { - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.MinimumUint("created_at", "body", *m.CreatedAt, 0, false); err != nil { - return err - } - - return nil -} - -func (m *UserAccountEmail) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *UserAccountEmail) validatePurpose(formats strfmt.Registry) error { - - if err := validate.Required("purpose", "body", m.Purpose); err != nil { - return err - } - - return nil -} - -func (m *UserAccountEmail) validateVerified(formats strfmt.Registry) error { - - if err := validate.Required("verified", "body", m.Verified); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this user account email based on context it is used -func (m *UserAccountEmail) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UserAccountEmail) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UserAccountEmail) UnmarshalBinary(b []byte) error { - var res UserAccountEmail - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/user_email.go b/client/models/user_email.go deleted file mode 100644 index 92cfc6be5..000000000 --- a/client/models/user_email.go +++ /dev/null @@ -1,75 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UserEmail User email address -// -// # The user's email address -// -// swagger:model UserEmail -type UserEmail struct { - - // email - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` -} - -// Validate validates this user email -func (m *UserEmail) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UserEmail) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this user email based on context it is used -func (m *UserEmail) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UserEmail) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UserEmail) UnmarshalBinary(b []byte) error { - var res UserEmail - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/user_guide.go b/client/models/user_guide.go deleted file mode 100644 index 79c07cdb9..000000000 --- a/client/models/user_guide.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// UserGuide User guide JSON schema -// -// # The user's guide progress JSON schema -// -// swagger:model UserGuide -type UserGuide any diff --git a/client/models/user_login.go b/client/models/user_login.go deleted file mode 100644 index 5827ea9e9..000000000 --- a/client/models/user_login.go +++ /dev/null @@ -1,132 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UserLogin Log in -// -// Validate the user to access to the application. The user can login with the primary email address. -// -// swagger:model UserLogin -type UserLogin struct { - - // email - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` - - // organization canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - OrganizationCanonical string `json:"organization_canonical,omitempty"` - - // password - // Required: true - // Min Length: 8 - // Format: password - Password *strfmt.Password `json:"password"` -} - -// Validate validates this user login -func (m *UserLogin) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOrganizationCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePassword(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UserLogin) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *UserLogin) validateOrganizationCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.OrganizationCanonical) { // not required - return nil - } - - if err := validate.MinLength("organization_canonical", "body", m.OrganizationCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("organization_canonical", "body", m.OrganizationCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("organization_canonical", "body", m.OrganizationCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *UserLogin) validatePassword(formats strfmt.Registry) error { - - if err := validate.Required("password", "body", m.Password); err != nil { - return err - } - - if err := validate.MinLength("password", "body", m.Password.String(), 8); err != nil { - return err - } - - if err := validate.FormatOf("password", "body", "password", m.Password.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this user login based on context it is used -func (m *UserLogin) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UserLogin) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UserLogin) UnmarshalBinary(b []byte) error { - var res UserLogin - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/user_o_auth.go b/client/models/user_o_auth.go deleted file mode 100644 index 233c9a44c..000000000 --- a/client/models/user_o_auth.go +++ /dev/null @@ -1,120 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// UserOAuth User's OAuth information -// -// The User OAuth information, if it's on the platform it'll return the 'token' to login, if not the 'user' to show to the user -// -// swagger:model UserOAuth -type UserOAuth struct { - - // Is the JWT of the platform user - Token string `json:"token,omitempty"` - - // user - User *NewOAuthUser `json:"user,omitempty"` -} - -// Validate validates this user o auth -func (m *UserOAuth) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateUser(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UserOAuth) validateUser(formats strfmt.Registry) error { - if swag.IsZero(m.User) { // not required - return nil - } - - if m.User != nil { - if err := m.User.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("user") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("user") - } - - return err - } - } - - return nil -} - -// ContextValidate validate this user o auth based on the context it is used -func (m *UserOAuth) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateUser(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UserOAuth) contextValidateUser(ctx context.Context, formats strfmt.Registry) error { - - if m.User != nil { - - if swag.IsZero(m.User) { // not required - return nil - } - - if err := m.User.ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("user") - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("user") - } - - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *UserOAuth) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UserOAuth) UnmarshalBinary(b []byte) error { - var res UserOAuth - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/user_password_reset_req.go b/client/models/user_password_reset_req.go deleted file mode 100644 index 83de50ee7..000000000 --- a/client/models/user_password_reset_req.go +++ /dev/null @@ -1,75 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UserPasswordResetReq User password reset request -// -// Request to send a token for allowing the user to reset its current password. -// -// swagger:model UserPasswordResetReq -type UserPasswordResetReq struct { - - // the email address must be the primary email of the user. - // Required: true - // Format: email - Email *strfmt.Email `json:"email"` -} - -// Validate validates this user password reset req -func (m *UserPasswordResetReq) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateEmail(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UserPasswordResetReq) validateEmail(formats strfmt.Registry) error { - - if err := validate.Required("email", "body", m.Email); err != nil { - return err - } - - if err := validate.FormatOf("email", "body", "email", m.Email.String(), formats); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this user password reset req based on context it is used -func (m *UserPasswordResetReq) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UserPasswordResetReq) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UserPasswordResetReq) UnmarshalBinary(b []byte) error { - var res UserPasswordResetReq - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/user_password_reset_update.go b/client/models/user_password_reset_update.go deleted file mode 100644 index 508683ed2..000000000 --- a/client/models/user_password_reset_update.go +++ /dev/null @@ -1,102 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UserPasswordResetUpdate User password reset update -// -// Reset the current user password to the one provided. The user must have a valid token for the resetting password action. -// -// swagger:model UserPasswordResetUpdate -type UserPasswordResetUpdate struct { - - // password - // Required: true - // Min Length: 12 - // Format: password - Password *strfmt.Password `json:"password"` - - // token - // Required: true - // Min Length: 1 - Token *string `json:"token"` -} - -// Validate validates this user password reset update -func (m *UserPasswordResetUpdate) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validatePassword(formats); err != nil { - res = append(res, err) - } - - if err := m.validateToken(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UserPasswordResetUpdate) validatePassword(formats strfmt.Registry) error { - - if err := validate.Required("password", "body", m.Password); err != nil { - return err - } - - if err := validate.MinLength("password", "body", m.Password.String(), 12); err != nil { - return err - } - - if err := validate.FormatOf("password", "body", "password", m.Password.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *UserPasswordResetUpdate) validateToken(formats strfmt.Registry) error { - - if err := validate.Required("token", "body", m.Token); err != nil { - return err - } - - if err := validate.MinLength("token", "body", *m.Token, 1); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this user password reset update based on context it is used -func (m *UserPasswordResetUpdate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *UserPasswordResetUpdate) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UserPasswordResetUpdate) UnmarshalBinary(b []byte) error { - var res UserPasswordResetUpdate - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/user_session.go b/client/models/user_session.go deleted file mode 100644 index fa6037e5a..000000000 --- a/client/models/user_session.go +++ /dev/null @@ -1,155 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// UserSession User's session -// -// The JWT which allows the user to access to the application. -// -// swagger:model UserSession -type UserSession struct { - - // owns - // Required: true - Owns []string `json:"owns"` - - // permissions - // Required: true - Permissions map[string]Rule `json:"permissions"` - - // token - // Required: true - Token *string `json:"token"` -} - -// Validate validates this user session -func (m *UserSession) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateOwns(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePermissions(formats); err != nil { - res = append(res, err) - } - - if err := m.validateToken(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UserSession) validateOwns(formats strfmt.Registry) error { - - if err := validate.Required("owns", "body", m.Owns); err != nil { - return err - } - - return nil -} - -func (m *UserSession) validatePermissions(formats strfmt.Registry) error { - - if err := validate.Required("permissions", "body", m.Permissions); err != nil { - return err - } - - for k := range m.Permissions { - - if err := validate.Required("permissions"+"."+k, "body", m.Permissions[k]); err != nil { - return err - } - if val, ok := m.Permissions[k]; ok { - if err := val.Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("permissions" + "." + k) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("permissions" + "." + k) - } - - return err - } - } - - } - - return nil -} - -func (m *UserSession) validateToken(formats strfmt.Registry) error { - - if err := validate.Required("token", "body", m.Token); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this user session based on the context it is used -func (m *UserSession) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidatePermissions(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *UserSession) contextValidatePermissions(ctx context.Context, formats strfmt.Registry) error { - - if err := validate.Required("permissions", "body", m.Permissions); err != nil { - return err - } - - for k := range m.Permissions { - - if val, ok := m.Permissions[k]; ok { - if err := val.ContextValidate(ctx, formats); err != nil { - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *UserSession) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *UserSession) UnmarshalBinary(b []byte) error { - var res UserSession - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/v_mware_vsphere.go b/client/models/v_mware_vsphere.go deleted file mode 100644 index 52c76f3e0..000000000 --- a/client/models/v_mware_vsphere.go +++ /dev/null @@ -1,158 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// VMwareVsphere Representation of VMwareVsphere external backend. -// Must be matched with a credential of the "vmware" type. -// -// swagger:model VMwareVsphere -type VMwareVsphere struct { - - // Whether verification of SSL certificate should be disabled. - // - AllowUnverifiedSsl bool `json:"allow_unverified_ssl,omitempty"` - - // FQDN or IP address of the vCenter server. - // - Server string `json:"server,omitempty"` -} - -// Engine gets the engine of this subtype -func (m *VMwareVsphere) Engine() string { - return "VMwareVsphere" -} - -// SetEngine sets the engine of this subtype -func (m *VMwareVsphere) SetEngine(val string) { -} - -// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure -func (m *VMwareVsphere) UnmarshalJSON(raw []byte) error { - var data struct { - - // Whether verification of SSL certificate should be disabled. - // - AllowUnverifiedSsl bool `json:"allow_unverified_ssl,omitempty"` - - // FQDN or IP address of the vCenter server. - // - Server string `json:"server,omitempty"` - } - buf := bytes.NewBuffer(raw) - dec := json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&data); err != nil { - return err - } - - var base struct { - /* Just the base type fields. Used for unmashalling polymorphic types.*/ - - Engine string `json:"engine"` - } - buf = bytes.NewBuffer(raw) - dec = json.NewDecoder(buf) - dec.UseNumber() - - if err := dec.Decode(&base); err != nil { - return err - } - - var result VMwareVsphere - - if base.Engine != result.Engine() { - /* Not the type we're looking for. */ - return errors.New(422, "invalid engine value: %q", base.Engine) - } - - result.AllowUnverifiedSsl = data.AllowUnverifiedSsl - result.Server = data.Server - - *m = result - - return nil -} - -// MarshalJSON marshals this object with a polymorphic type to a JSON structure -func (m VMwareVsphere) MarshalJSON() ([]byte, error) { - var b1, b2, b3 []byte - var err error - b1, err = json.Marshal(struct { - - // Whether verification of SSL certificate should be disabled. - // - AllowUnverifiedSsl bool `json:"allow_unverified_ssl,omitempty"` - - // FQDN or IP address of the vCenter server. - // - Server string `json:"server,omitempty"` - }{ - - AllowUnverifiedSsl: m.AllowUnverifiedSsl, - - Server: m.Server, - }) - if err != nil { - return nil, err - } - b2, err = json.Marshal(struct { - Engine string `json:"engine"` - }{ - - Engine: m.Engine(), - }) - if err != nil { - return nil, err - } - - return swag.ConcatJSON(b1, b2, b3), nil -} - -// Validate validates this v mware vsphere -func (m *VMwareVsphere) Validate(formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// ContextValidate validate this v mware vsphere based on the context it is used -func (m *VMwareVsphere) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *VMwareVsphere) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *VMwareVsphere) UnmarshalBinary(b []byte) error { - var res VMwareVsphere - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/version_config.go b/client/models/version_config.go deleted file mode 100644 index ccff8e95a..000000000 --- a/client/models/version_config.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" -) - -// VersionConfig VersionConfig -// -// The entity which represents a version configuration in the application. -// -// swagger:model VersionConfig -type VersionConfig struct { - - // every - Every bool `json:"every,omitempty"` - - // latest - Latest bool `json:"latest,omitempty"` - - // pinned - Pinned map[string]string `json:"pinned,omitempty"` -} - -// Validate validates this version config -func (m *VersionConfig) Validate(formats strfmt.Registry) error { - return nil -} - -// ContextValidate validates this version config based on context it is used -func (m *VersionConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *VersionConfig) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *VersionConfig) UnmarshalBinary(b []byte) error { - var res VersionConfig - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/versioned_resource_type.go b/client/models/versioned_resource_type.go deleted file mode 100644 index c66e43fc7..000000000 --- a/client/models/versioned_resource_type.go +++ /dev/null @@ -1,180 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// VersionedResourceType VersionedResourceType -// -// The versioned resources type. -// -// swagger:model VersionedResourceType -type VersionedResourceType struct { - - // id - // Required: true - ID *uint32 `json:"id"` - - // name - // Required: true - Name *string `json:"name"` - - // privileged - // Required: true - Privileged *bool `json:"privileged"` - - // source - // Required: true - Source map[string]any `json:"source"` - - // tags - // Required: true - Tags map[string]string `json:"tags"` - - // type - // Required: true - Type *string `json:"type"` - - // version - // Required: true - Version map[string]string `json:"version"` -} - -// Validate validates this versioned resource type -func (m *VersionedResourceType) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePrivileged(formats); err != nil { - res = append(res, err) - } - - if err := m.validateSource(formats); err != nil { - res = append(res, err) - } - - if err := m.validateTags(formats); err != nil { - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *VersionedResourceType) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - return nil -} - -func (m *VersionedResourceType) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *VersionedResourceType) validatePrivileged(formats strfmt.Registry) error { - - if err := validate.Required("privileged", "body", m.Privileged); err != nil { - return err - } - - return nil -} - -func (m *VersionedResourceType) validateSource(formats strfmt.Registry) error { - - if err := validate.Required("source", "body", m.Source); err != nil { - return err - } - - for k := range m.Source { - - if err := validate.Required("source"+"."+k, "body", m.Source[k]); err != nil { - return err - } - - } - - return nil -} - -func (m *VersionedResourceType) validateTags(formats strfmt.Registry) error { - - if err := validate.Required("tags", "body", m.Tags); err != nil { - return err - } - - return nil -} - -func (m *VersionedResourceType) validateType(formats strfmt.Registry) error { - - if err := validate.Required("type", "body", m.Type); err != nil { - return err - } - - return nil -} - -func (m *VersionedResourceType) validateVersion(formats strfmt.Registry) error { - - if err := validate.Required("version", "body", m.Version); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this versioned resource type based on context it is used -func (m *VersionedResourceType) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *VersionedResourceType) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *VersionedResourceType) UnmarshalBinary(b []byte) error { - var res VersionedResourceType - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/watch_rule.go b/client/models/watch_rule.go deleted file mode 100644 index b9293c906..000000000 --- a/client/models/watch_rule.go +++ /dev/null @@ -1,321 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - stderrors "errors" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// WatchRule Watch rule -// -// # The entity which represents the information of a Watch rule -// -// swagger:model WatchRule -type WatchRule struct { - - // canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - Canonical *string `json:"canonical"` - - // created at - // Required: true - CreatedAt *uint64 `json:"created_at"` - - // filters - // Required: true - Filters []*WatchRuleFilter `json:"filters"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // muted - // Required: true - Muted *bool `json:"muted"` - - // name - // Required: true - // Min Length: 3 - Name *string `json:"name"` - - // organization canonical - // Required: true - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - OrganizationCanonical *string `json:"organization_canonical"` - - // project canonical - // Max Length: 100 - // Min Length: 3 - // Pattern: ^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$ - ProjectCanonical string `json:"project_canonical,omitempty"` - - // updated at - // Required: true - UpdatedAt *uint64 `json:"updated_at"` -} - -// Validate validates this watch rule -func (m *WatchRule) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateFilters(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateMuted(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOrganizationCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateProjectCanonical(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *WatchRule) validateCanonical(formats strfmt.Registry) error { - - if err := validate.Required("canonical", "body", m.Canonical); err != nil { - return err - } - - if err := validate.MinLength("canonical", "body", *m.Canonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("canonical", "body", *m.Canonical, 100); err != nil { - return err - } - - if err := validate.Pattern("canonical", "body", *m.Canonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *WatchRule) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - return nil -} - -func (m *WatchRule) validateFilters(formats strfmt.Registry) error { - - if err := validate.Required("filters", "body", m.Filters); err != nil { - return err - } - - for i := 0; i < len(m.Filters); i++ { - if swag.IsZero(m.Filters[i]) { // not required - continue - } - - if m.Filters[i] != nil { - if err := m.Filters[i].Validate(formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("filters" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("filters" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -func (m *WatchRule) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *WatchRule) validateMuted(formats strfmt.Registry) error { - - if err := validate.Required("muted", "body", m.Muted); err != nil { - return err - } - - return nil -} - -func (m *WatchRule) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - if err := validate.MinLength("name", "body", *m.Name, 3); err != nil { - return err - } - - return nil -} - -func (m *WatchRule) validateOrganizationCanonical(formats strfmt.Registry) error { - - if err := validate.Required("organization_canonical", "body", m.OrganizationCanonical); err != nil { - return err - } - - if err := validate.MinLength("organization_canonical", "body", *m.OrganizationCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("organization_canonical", "body", *m.OrganizationCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("organization_canonical", "body", *m.OrganizationCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *WatchRule) validateProjectCanonical(formats strfmt.Registry) error { - if swag.IsZero(m.ProjectCanonical) { // not required - return nil - } - - if err := validate.MinLength("project_canonical", "body", m.ProjectCanonical, 3); err != nil { - return err - } - - if err := validate.MaxLength("project_canonical", "body", m.ProjectCanonical, 100); err != nil { - return err - } - - if err := validate.Pattern("project_canonical", "body", m.ProjectCanonical, `^[a-z0-9]+[a-z0-9\-_]+[a-z0-9]+$`); err != nil { - return err - } - - return nil -} - -func (m *WatchRule) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - return nil -} - -// ContextValidate validate this watch rule based on the context it is used -func (m *WatchRule) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - var res []error - - if err := m.contextValidateFilters(ctx, formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *WatchRule) contextValidateFilters(ctx context.Context, formats strfmt.Registry) error { - - for i := 0; i < len(m.Filters); i++ { - - if m.Filters[i] != nil { - - if swag.IsZero(m.Filters[i]) { // not required - return nil - } - - if err := m.Filters[i].ContextValidate(ctx, formats); err != nil { - ve := new(errors.Validation) - if stderrors.As(err, &ve) { - return ve.ValidateName("filters" + "." + strconv.Itoa(i)) - } - ce := new(errors.CompositeError) - if stderrors.As(err, &ce) { - return ce.ValidateName("filters" + "." + strconv.Itoa(i)) - } - - return err - } - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *WatchRule) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *WatchRule) UnmarshalBinary(b []byte) error { - var res WatchRule - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/watch_rule_filter.go b/client/models/watch_rule_filter.go deleted file mode 100644 index f3b9b41fd..000000000 --- a/client/models/watch_rule_filter.go +++ /dev/null @@ -1,143 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// WatchRuleFilter Watch rule filter -// -// # The entity which represents the information of a Watch rule filter -// -// swagger:model WatchRuleFilter -type WatchRuleFilter struct { - - // created at - // Required: true - CreatedAt *uint64 `json:"created_at"` - - // * means the filter is applied to all the entities - // Required: true - Entity *string `json:"entity"` - - // id - // Required: true - // Minimum: 1 - ID *uint32 `json:"id"` - - // * means the filter is applied to all the operations - // Required: true - Operation *string `json:"operation"` - - // updated at - // Required: true - UpdatedAt *uint64 `json:"updated_at"` -} - -// Validate validates this watch rule filter -func (m *WatchRuleFilter) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCreatedAt(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEntity(formats); err != nil { - res = append(res, err) - } - - if err := m.validateID(formats); err != nil { - res = append(res, err) - } - - if err := m.validateOperation(formats); err != nil { - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *WatchRuleFilter) validateCreatedAt(formats strfmt.Registry) error { - - if err := validate.Required("created_at", "body", m.CreatedAt); err != nil { - return err - } - - return nil -} - -func (m *WatchRuleFilter) validateEntity(formats strfmt.Registry) error { - - if err := validate.Required("entity", "body", m.Entity); err != nil { - return err - } - - return nil -} - -func (m *WatchRuleFilter) validateID(formats strfmt.Registry) error { - - if err := validate.Required("id", "body", m.ID); err != nil { - return err - } - - if err := validate.MinimumUint("id", "body", uint64(*m.ID), 1, false); err != nil { - return err - } - - return nil -} - -func (m *WatchRuleFilter) validateOperation(formats strfmt.Registry) error { - - if err := validate.Required("operation", "body", m.Operation); err != nil { - return err - } - - return nil -} - -func (m *WatchRuleFilter) validateUpdatedAt(formats strfmt.Registry) error { - - if err := validate.Required("updated_at", "body", m.UpdatedAt); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this watch rule filter based on context it is used -func (m *WatchRuleFilter) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *WatchRuleFilter) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *WatchRuleFilter) UnmarshalBinary(b []byte) error { - var res WatchRuleFilter - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/models/worker.go b/client/models/worker.go deleted file mode 100644 index dbf082c23..000000000 --- a/client/models/worker.go +++ /dev/null @@ -1,195 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -import ( - "context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Worker Worker -// -// The entity which represents a worker in the application. -// -// swagger:model Worker -type Worker struct { - - // active containers - // Required: true - ActiveContainers *uint64 `json:"active_containers"` - - // active volumes - // Required: true - ActiveVolumes *uint64 `json:"active_volumes"` - - // ephemeral - // Required: true - Ephemeral *bool `json:"ephemeral"` - - // name - // Required: true - Name *string `json:"name"` - - // platform - // Required: true - Platform *string `json:"platform"` - - // start time - // Required: true - StartTime *uint64 `json:"start_time"` - - // state - // Required: true - State *string `json:"state"` - - // tags - Tags []string `json:"tags"` - - // team - Team string `json:"team,omitempty"` - - // version - // Required: true - Version *string `json:"version"` -} - -// Validate validates this worker -func (m *Worker) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateActiveContainers(formats); err != nil { - res = append(res, err) - } - - if err := m.validateActiveVolumes(formats); err != nil { - res = append(res, err) - } - - if err := m.validateEphemeral(formats); err != nil { - res = append(res, err) - } - - if err := m.validateName(formats); err != nil { - res = append(res, err) - } - - if err := m.validatePlatform(formats); err != nil { - res = append(res, err) - } - - if err := m.validateStartTime(formats); err != nil { - res = append(res, err) - } - - if err := m.validateState(formats); err != nil { - res = append(res, err) - } - - if err := m.validateVersion(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Worker) validateActiveContainers(formats strfmt.Registry) error { - - if err := validate.Required("active_containers", "body", m.ActiveContainers); err != nil { - return err - } - - return nil -} - -func (m *Worker) validateActiveVolumes(formats strfmt.Registry) error { - - if err := validate.Required("active_volumes", "body", m.ActiveVolumes); err != nil { - return err - } - - return nil -} - -func (m *Worker) validateEphemeral(formats strfmt.Registry) error { - - if err := validate.Required("ephemeral", "body", m.Ephemeral); err != nil { - return err - } - - return nil -} - -func (m *Worker) validateName(formats strfmt.Registry) error { - - if err := validate.Required("name", "body", m.Name); err != nil { - return err - } - - return nil -} - -func (m *Worker) validatePlatform(formats strfmt.Registry) error { - - if err := validate.Required("platform", "body", m.Platform); err != nil { - return err - } - - return nil -} - -func (m *Worker) validateStartTime(formats strfmt.Registry) error { - - if err := validate.Required("start_time", "body", m.StartTime); err != nil { - return err - } - - return nil -} - -func (m *Worker) validateState(formats strfmt.Registry) error { - - if err := validate.Required("state", "body", m.State); err != nil { - return err - } - - return nil -} - -func (m *Worker) validateVersion(formats strfmt.Registry) error { - - if err := validate.Required("version", "body", m.Version); err != nil { - return err - } - - return nil -} - -// ContextValidate validates this worker based on context it is used -func (m *Worker) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} - -// MarshalBinary interface implementation -func (m *Worker) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Worker) UnmarshalBinary(b []byte) error { - var res Worker - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/client/version b/client/version deleted file mode 100644 index ffad31c96..000000000 --- a/client/version +++ /dev/null @@ -1 +0,0 @@ -v6.10.25 diff --git a/cmd/cycloid/apikey/cmd.go b/cmd/cycloid/apikey/cmd.go deleted file mode 100644 index 5a8372dba..000000000 --- a/cmd/cycloid/apikey/cmd.go +++ /dev/null @@ -1,26 +0,0 @@ -package apikey - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "api-key", - Aliases: []string{ - "api-keys", - }, - Example: `cy api-key [create|list|get|delete]`, - Short: "Manage organization API keys", - Args: cobra.NoArgs, - } - - cmd.AddCommand( - NewDeleteCommand(), - NewGetCommand(), - NewListCommand(), - NewCreateCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/apikey/create.go b/cmd/cycloid/apikey/create.go deleted file mode 100644 index d5ee82be5..000000000 --- a/cmd/cycloid/apikey/create.go +++ /dev/null @@ -1,105 +0,0 @@ -package apikey - -import ( - "encoding/json" - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -// NewCreateCommand returns the cobra command holding -// the create API key subcommand -func NewCreateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "create", - Args: cobra.NoArgs, - Short: "create an API key", - Example: `# Create an admin API key -cy --org myOrg api-key create --canonical "admin-api-key" --owner "Admin" --rules '[{"action": "organization:**", "effect": "allow", "resources": []}]' - -# Recreate an existing API key with new rules -cy --org myOrg api-key create --canonical "admin-api-key" --rules '[...]' --recreate`, - RunE: create, - } - - cyargs.AddAPIKeyNameFlag(cmd) - cyargs.AddAPIKeyCanonicalFlag(cmd) - cyargs.AddOwnerFlag(cmd) - cyargs.AddAPIKeyRulesFlag(cmd) - cyargs.AddDescriptionFlag(cmd) - cmd.Flags().Bool("recreate", false, "delete the API key if it already exists and create a new one with the provided settings") - - return cmd -} - -// create the generated tokens -func create(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - apiKey, _ := cyargs.GetAPIKeyCanonical(cmd) - apiKeyName, _ := cyargs.GetAPIKeyName(cmd) - if apiKey == "" && apiKeyName == "" { - return fmt.Errorf("missing either --canonical or --name flags") - } - - if apiKey == "" { - apiKey = common.GenerateCanonical(apiKeyName) - } - - if apiKeyName == "" { - apiKeyName = apiKey - } - - recreate, err := cmd.Flags().GetBool("recreate") - if err != nil { - return err - } - - owner, err := cyargs.GetOwner(cmd) - if err != nil { - return err - } - - rules, err := cyargs.GetAPIKeyRules(cmd) - if err != nil { - return err - } - - description, err := cyargs.GetAPIKeyDescription(cmd) - if err != nil { - return err - } - - var rulesModel []*models.NewRule - err = json.Unmarshal([]byte(rules), &rulesModel) - if err != nil { - return fmt.Errorf("failed to read rules argument as JSON: %w", err) - } - - _, _, getErr := m.GetAPIKey(org, apiKey) - if getErr == nil { - if !recreate { - return fmt.Errorf("API key %q already exists; use --recreate to delete and recreate it", apiKey) - } - _, err := m.DeleteAPIKey(org, apiKey) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to delete existing API key before recreation", printer.Options{}) - } - } - - key, _, err := m.CreateAPIKey(org, apiKey, description, owner, &apiKeyName, rulesModel) - return cyout.PrintWithOptions(cmd, key, err, "unable to create API key", printer.Options{}) -} diff --git a/cmd/cycloid/apikey/delete.go b/cmd/cycloid/apikey/delete.go deleted file mode 100644 index a787074d5..000000000 --- a/cmd/cycloid/apikey/delete.go +++ /dev/null @@ -1,77 +0,0 @@ -package apikey - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -// NewDeleteCommand returns the cobra command holding -// the delete API key subcommand -func NewDeleteCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "delete [canonical...]", - Aliases: []string{"rm"}, - Args: cyargs.RequireArgsOrFlag("canonical"), - ValidArgsFunction: cyargs.CompleteAPIKeyCanonical, - Short: "delete an API key", - Example: `# delete the API key 'my-key' in the org my-org - cy --org my-org api-key delete my-key - - # delete multiple API keys at once - cy --org my-org api-key delete key-one key-two - - # delete using the deprecated --canonical flag - cy --org my-org api-key delete --canonical my-key`, - RunE: remove, - } - - // Keep --canonical for backward compatibility - can := cyargs.AddAPIKeyCanonicalFlag(cmd) - _ = cmd.Flags().MarkHidden(can) - - return cmd -} - -// remove will send the DELETE request to the API in order to -// delete a generated token -func remove(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return fmt.Errorf("unable to get org flag: %w", err) - } - - if can, err := cyargs.GetAPIKeyCanonical(cmd); err != nil { - return fmt.Errorf("unable to get canonical flag: %w", err) - } else if can != "" { - found := false - for _, a := range args { - if a == can { - found = true - break - } - } - if !found { - args = append(args, can) - } - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - deleted := make([]string, 0, len(args)) - for _, canonical := range args { - _, err = m.DeleteAPIKey(org, canonical) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to delete API key "+canonical, printer.Options{}) - } - deleted = append(deleted, canonical) - } - return cyout.PrintWithOptions(cmd, deleted, nil, "", printer.Options{Columns: []string{"Canonical"}}) -} diff --git a/cmd/cycloid/apikey/get.go b/cmd/cycloid/apikey/get.go deleted file mode 100644 index c0891d15b..000000000 --- a/cmd/cycloid/apikey/get.go +++ /dev/null @@ -1,84 +0,0 @@ -package apikey - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -// NewGetCommand returns the cobra command holding -// the get API key subcommand -func NewGetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get [canonical...]", - Args: cyargs.RequireArgsOrFlag("canonical"), - ValidArgsFunction: cyargs.CompleteAPIKeyCanonical, - Short: "get API key", - Example: ` - # get API key 'my-key' in the org my-org - cy --org my-org api-key get my-key - - # get multiple API keys - cy --org my-org api-key get key-one key-two - - # get using the deprecated --canonical flag - cy --org my-org api-key get --canonical my-key -`, - RunE: get, - } - - // Keep --canonical for backward compatibility - can := cyargs.AddAPIKeyCanonicalFlag(cmd) - _ = cmd.Flags().MarkHidden(can) - cyout.RegisterModel(cmd, models.APIKey{}) - - return cmd -} - -// get will send the GET request to the API in order to -// get the generated token -func get(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return fmt.Errorf("unable to get org flag: %w", err) - } - - if can, err := cyargs.GetAPIKeyCanonical(cmd); err != nil { - return fmt.Errorf("unable to get canonical flag: %w", err) - } else if can != "" { - found := false - for _, a := range args { - if a == can { - found = true - break - } - } - if !found { - args = append(args, can) - } - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - if len(args) == 1 { - key, _, err := m.GetAPIKey(org, args[0]) - return cyout.PrintWithOptions(cmd, key, err, "unable to get API key", apiKeyTableOptions) - } - - results := make([]*models.APIKey, 0, len(args)) - for _, canonical := range args { - key, _, err := m.GetAPIKey(org, canonical) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to get API key "+canonical, apiKeyTableOptions) - } - results = append(results, key) - } - return cyout.PrintWithOptions(cmd, results, nil, "", apiKeyTableOptions) -} diff --git a/cmd/cycloid/apikey/list.go b/cmd/cycloid/apikey/list.go deleted file mode 100644 index 8b90bbafe..000000000 --- a/cmd/cycloid/apikey/list.go +++ /dev/null @@ -1,46 +0,0 @@ -package apikey - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var apiKeyTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "LastSeven", "LastUsed"}, - Identifier: "Canonical", -} - -// NewListCommand returns the cobra command holding -// the list API key subcommand -func NewListCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "list API keys", - Example: `# list API keys in the org my-org -cy api-key list --org my-org`, - RunE: list, - } - cyout.RegisterModel(cmd, models.APIKey{}) - return cmd -} - -// list the generated tokens -func list(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - keys, _, err := m.ListAPIKeys(org) - return cyout.PrintWithOptions(cmd, keys, err, "unable to list API keys", apiKeyTableOptions) -} diff --git a/cmd/cycloid/beta/bootstrap_first_org/bootstrap.go b/cmd/cycloid/beta/bootstrap_first_org/bootstrap.go deleted file mode 100644 index f417627b0..000000000 --- a/cmd/cycloid/beta/bootstrap_first_org/bootstrap.go +++ /dev/null @@ -1,83 +0,0 @@ -package bootstrapfirstorg - -import ( - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var bootstrapTableOptions = printer.Options{ - Columns: []string{"Org", "Username", "Email", "Token", "APIKey", "CredentialCanonical"}, - Transform: func(obj interface{}) map[string]string { - data, ok := obj.(*middleware.FirstOrgData) - if !ok || data == nil { - return nil - } - - row := map[string]string{ - "Org": data.Org, - "Username": data.Username, - "Email": data.Email, - "Token": maskSecret(data.Token), - "Password": maskSecret(data.Password), - } - if data.APIKey != nil { - row["APIKey"] = maskSecret(*data.APIKey) - } - if data.CredentialCanonical != nil { - row["CredentialCanonical"] = *data.CredentialCanonical - } - return row - }, -} - -func bootstrap(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - username, err := cmd.Flags().GetString("username") - if err != nil { - return err - } - fullName, err := cmd.Flags().GetString("full-name") - if err != nil { - return err - } - email, err := cmd.Flags().GetString("email") - if err != nil { - return err - } - password, err := cyargs.GetBootstrapPassword(cmd) - if err != nil { - return err - } - licence, err := cyargs.GetLicence(cmd) - if err != nil { - return err - } - apiKeyCanonical, err := cyargs.GetBootstrapAPIKeyCanonical(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, _, err := m.InitFirstOrg(org, username, fullName, email, password, licence, apiKeyCanonical) - return cyout.PrintWithOptions(cmd, result, err, "failed to bootstrap first organization", bootstrapTableOptions) -} - -func maskSecret(value string) string { - if len(value) <= 5 { - return strings.Repeat("*", len(value)) - } - return "***" + value[len(value)-5:] -} diff --git a/cmd/cycloid/beta/bootstrap_first_org/cmd.go b/cmd/cycloid/beta/bootstrap_first_org/cmd.go deleted file mode 100644 index db05dc8bc..000000000 --- a/cmd/cycloid/beta/bootstrap_first_org/cmd.go +++ /dev/null @@ -1,42 +0,0 @@ -package bootstrapfirstorg - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/internal/cyargs" -) - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "bootstrap-first-org", - Short: "Bootstrap the first organization on a fresh Cycloid install", - Long: `Bootstrap the very first organization on a fresh Cycloid install. - -Chains: - 1. POST /user — signup (ignores 409 if user already exists) - 2. POST /user/login — login with email + password - 3. POST /organizations — create the org (ignores 409 if it already exists) - 4. GET /user/refresh_token?organization_canonical= - — refresh token to get org scope - 5. POST /organizations//licence — activate the licence - -Optionally, when --api-key-canonical is set: - 6. Creates an admin api-key under that canonical - 7. Stores it in a custom credential under the same canonical - -Intended for first-install bootstrap or fully scripted environment recreation. -All steps tolerate "already exists" responses, so re-running is safe. - -This command is BETA — output shape and flag names may change.`, - Args: cobra.NoArgs, - RunE: bootstrap, - } - - cyargs.AddBootstrapUserFlags(cmd) - cyargs.AddLicenceFlag(cmd) - cyargs.AddLicenceFileFlag(cmd) - cyargs.AddBootstrapAPIKeyCanonicalFlag(cmd) - cmd.MarkFlagsMutuallyExclusive("licence", "licence-file") - - return cmd -} diff --git a/cmd/cycloid/beta/cmd.go b/cmd/cycloid/beta/cmd.go deleted file mode 100644 index f3828bb79..000000000 --- a/cmd/cycloid/beta/cmd.go +++ /dev/null @@ -1,23 +0,0 @@ -package beta - -import ( - "github.com/spf13/cobra" - - bootstrapfirstorg "github.com/cycloidio/cycloid-cli/cmd/cycloid/beta/bootstrap_first_org" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/beta/config" -) - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "beta", - Short: "Experimental commands.", - Long: `Experimental Cycloid commands. -Those commands are feature in testing, retro-compatibility is not guaranteed.`, - } - - cmd.AddCommand( - config.NewCommands(), - bootstrapfirstorg.NewCommands(), - ) - return cmd -} diff --git a/cmd/cycloid/beta/config/cmd.go b/cmd/cycloid/beta/config/cmd.go deleted file mode 100644 index 6b611aa05..000000000 --- a/cmd/cycloid/beta/config/cmd.go +++ /dev/null @@ -1,15 +0,0 @@ -package config - -import "github.com/spf13/cobra" - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "config", - Short: "Configuration related commands", - Aliases: []string{"cfg"}, - } - cmd.AddCommand( - NewInterpolateCmd(), - ) - return cmd -} diff --git a/cmd/cycloid/beta/config/interpolate.go b/cmd/cycloid/beta/config/interpolate.go deleted file mode 100644 index d22466d21..000000000 --- a/cmd/cycloid/beta/config/interpolate.go +++ /dev/null @@ -1,75 +0,0 @@ -package config - -import ( - "fmt" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewInterpolateCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: `interpolate -s service:catalog -u use_case -p project -e env -c component -v '{"section": {"group": {"var": "my_var"}}}'`, - Args: cobra.NoArgs, - Short: "Generate a set of configs based on the forms input but without creating anything", - RunE: interpolate, - } - - cyargs.AddUseCaseFlag(cmd) - cyargs.AddStackRefFlag(cmd) - cyargs.AddCyContext(cmd) - cyargs.AddStackFormsInputFlags(cmd) - cyargs.AddStackVersionFlags(cmd) - return cmd -} - -func interpolate(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - useCase, err := cyargs.GetUseCase(cmd) - if err != nil { - return err - } - - stackRef, err := cyargs.GetStackRef(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // Resolve stack version: --stack-version (new) or legacy flags. - tag, branch, hash, err := cyargs.ResolveStackVersionArg(cmd, m, org, stackRef) - if err != nil { - return errors.Wrap(err, "failed to read stack version flags") - } - - // Get default to stacks - stackConfig, _, err := m.GetComponentStackConfig(org, project, env, component, useCase, tag, branch, hash) - if err != nil { - return err - } - - useCaseConfig, err := common.FormUseCaseToFormVars(stackConfig, useCase) - if err != nil { - return fmt.Errorf("failed to parse default value for stack %q with use-case %q: %w", stackRef, useCase, err) - } - - inputs, err := cyargs.GetStackformsVars(cmd, useCaseConfig) - if err != nil { - return err - } - - config, _, err := m.InterpolateFormsConfig(org, project, env, component, stackRef, useCase, inputs) - return cyout.PrintWithOptions(cmd, config, err, "failed to interpolate config", printer.Options{}) -} diff --git a/cmd/cycloid/catalogrepositories/cmd.go b/cmd/cycloid/catalogrepositories/cmd.go deleted file mode 100644 index 50d8ef354..000000000 --- a/cmd/cycloid/catalogrepositories/cmd.go +++ /dev/null @@ -1,26 +0,0 @@ -package catalogrepositories - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - var cmd = &cobra.Command{ - Use: "catalog-repository", - Aliases: []string{ - "catalog-repo", - "catalog-repositories", - "cr", - }, - Short: "Manage the catalog repositories", - } - - cmd.AddCommand(NewCreateCommand(), - NewUpdateCommand(), - NewDeleteCommand(), - NewListCommand(), - NewGetCommand(), - NewRefreshCommand()) - - return cmd -} diff --git a/cmd/cycloid/catalogrepositories/create.go b/cmd/cycloid/catalogrepositories/create.go deleted file mode 100644 index 534d35c98..000000000 --- a/cmd/cycloid/catalogrepositories/create.go +++ /dev/null @@ -1,150 +0,0 @@ -package catalogrepositories - -import ( - stderrors "errors" - "fmt" - "net/http" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "create", - Args: cobra.NoArgs, - Short: "create a catalog repository", - Example: ` - # create a catalog repository using credential canonical 123, branch 'stacks' and git URL - cy --org my-org catalog-repo create --branch stacks --cred my-cred --url "git@github.com:my/repo.git" --name my-catalog-name - - # create a catalog repository using public git repository - cy --org my-org catalog-repo create --branch stacks --url "https://github.com:my/repo.git" --name my-catalog-name - - # create and immediately re-index all branches/tags so they are resolvable (fixes branch-stack presence race) - cy --org my-org catalog-repo create --branch stacks --url "git@github.com:my/repo.git" --name my-catalog-name --refresh -`, - RunE: createCatalogRepository, - } - - cyargs.AddRepoCredFlag(cmd) - cmd.MarkFlagRequired(cyargs.AddNameFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddRepoBranchFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddRepoURLFlag(cmd)) - cyargs.AddCatalogRepoCanonicalFlag(cmd) - - cmd.Flags().String("visibility", "", "set the stacks base visibility in the catalog. accepted values are 'local', 'shared' or 'hidden' (default: local)") - cmd.Flags().String("team", "", "set the team canonical to be set as maintener of the stacks") - cmd.Flags().Bool("update", false, "update the catalog repository if it already exists") - cmd.Flags().Bool("refresh", true, "trigger a synchronous version re-index after create (or update) to make all branches and tags immediately resolvable") - - return cmd -} - -// /organizations/{organization_canonical}/service_catalog_sources -// post: createServiceCatalogSource -// Creates a Service catalog source -func createCatalogRepository(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - canonical, err := cyargs.GetCatalogRepoCanonical(cmd) - if err != nil { - return err - } - - displayName, repoCanonical, err := middleware.NameOrCanonical(&name, &canonical) - if err != nil { - return err - } - - url, err := cyargs.GetRepoURL(cmd) - if err != nil { - return err - } - - branch, err := cyargs.GetRepoBranch(cmd) - if err != nil { - return err - } - - cred, err := cyargs.GetRepoCred(cmd) - if err != nil { - return err - } - - visibility, err := cmd.Flags().GetString("visibility") - if err != nil { - return err - } - - teamCanonical, err := cmd.Flags().GetString("team") - if err != nil { - return err - } - - update, err := cmd.Flags().GetBool("update") - if err != nil { - return err - } - - refresh, err := cmd.Flags().GetBool("refresh") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - _, _, getErr := m.GetCatalogRepository(org, repoCanonical) - exists := getErr == nil - if getErr != nil { - var apiErr *middleware.APIResponseError - if !stderrors.As(getErr, &apiErr) || apiErr.StatusCode != http.StatusNotFound { - return cyout.PrintWithOptions(cmd, nil, getErr, "failed to check if catalog repository exists", printer.Options{}) - } - } - - if exists && !update { - return cyout.PrintWithOptions(cmd, nil, - fmt.Errorf("catalog repository %q already exists; use --update or `cy catalog-repo update`", repoCanonical), - "unable to create catalog repository", printer.Options{}) - } - - var cr *models.ServiceCatalogSource - if exists { - cr, _, err = m.UpdateCatalogRepository(org, repoCanonical, displayName, url, branch, cred, nil) - } else { - cr, _, err = m.CreateCatalogRepository(org, displayName, url, branch, cred, visibility, teamCanonical) - } - if err != nil { - errMsg := "unable to create catalog repository" - if exists { - errMsg = "unable to update catalog repository" - } - return cyout.PrintWithOptions(cmd, nil, err, errMsg, printer.Options{}) - } - - if refresh { - if _, _, refreshErr := m.RefreshCatalogRepositoryVersions(org, repoCanonical); refreshErr != nil { - // Print the successful create/update result before returning the refresh error - _ = cyout.PrintWithOptions(cmd, cr, nil, "", printer.Options{}) - return cyout.PrintWithOptions(cmd, nil, refreshErr, "unable to refresh catalog repository versions", printer.Options{}) - } - } - - return cyout.PrintWithOptions(cmd, cr, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/catalogrepositories/delete.go b/cmd/cycloid/catalogrepositories/delete.go deleted file mode 100644 index d0fad678a..000000000 --- a/cmd/cycloid/catalogrepositories/delete.go +++ /dev/null @@ -1,73 +0,0 @@ -package catalogrepositories - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewDeleteCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "delete [canonical...]", - Aliases: []string{"rm"}, - Args: cyargs.RequireArgsOrFlag("canonical"), - ValidArgsFunction: cyargs.CompleteCatalogRepository, - Short: "delete a catalog repository", - Example: ` - # delete a catalog repository by canonical - cy --org my-org catalog-repo delete my-catalog-repository - - # delete multiple catalog repositories at once - cy --org my-org catalog-repo delete repo-one repo-two - - # delete using the deprecated --canonical flag - cy --org my-org catalog-repo delete --canonical my-catalog-repository -`, - RunE: deleteCatalogRepository, - } - - // Keep --canonical for backward compatibility - can := cyargs.AddCatalogRepoCanonicalFlag(cmd) - _ = cmd.Flags().MarkHidden(can) - - return cmd -} - -func deleteCatalogRepository(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - if can, err := cyargs.GetCatalogRepoCanonical(cmd); err != nil { - return err - } else if can != "" { - found := false - for _, a := range args { - if a == can { - found = true - break - } - } - if !found { - args = append(args, can) - } - } - - deleted := make([]string, 0, len(args)) - for _, canonical := range args { - _, err = m.DeleteCatalogRepository(org, canonical) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to delete catalog repository "+canonical, printer.Options{}) - } - deleted = append(deleted, canonical) - } - return cyout.PrintWithOptions(cmd, deleted, nil, "", printer.Options{Columns: []string{"Canonical"}}) -} diff --git a/cmd/cycloid/catalogrepositories/get.go b/cmd/cycloid/catalogrepositories/get.go deleted file mode 100644 index a544d7fc6..000000000 --- a/cmd/cycloid/catalogrepositories/get.go +++ /dev/null @@ -1,78 +0,0 @@ -package catalogrepositories - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewGetCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get [canonical...]", - Args: cyargs.RequireArgsOrFlag("canonical"), - ValidArgsFunction: cyargs.CompleteCatalogRepository, - Short: "get a catalog repository", - Example: ` - # get a catalog repository by canonical - cy --org my-org catalog-repo get my-catalog-repository - - # get a catalog repository using the deprecated --canonical flag - cy --org my-org catalog-repo get --canonical my-catalog-repository - - # get multiple catalog repositories at once - cy --org my-org catalog-repo get repo-one repo-two -`, - RunE: getCatalogRepository, - } - - // Keep --canonical for backward compatibility - can := cyargs.AddCatalogRepoCanonicalFlag(cmd) - _ = cmd.Flags().MarkHidden(can) - cyout.RegisterModel(cmd, models.ServiceCatalogSource{}) - - return cmd -} - -func getCatalogRepository(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - if can, err := cyargs.GetCatalogRepoCanonical(cmd); err != nil { - return err - } else if can != "" { - found := false - for _, a := range args { - if a == can { - found = true - break - } - } - if !found { - args = append(args, can) - } - } - - if len(args) == 1 { - cr, _, err := m.GetCatalogRepository(org, args[0]) - return cyout.PrintWithOptions(cmd, cr, err, "unable to get catalog repository", catalogSourceTableOptions) - } - - results := make([]*models.ServiceCatalogSource, 0, len(args)) - for _, can := range args { - cr, _, err := m.GetCatalogRepository(org, can) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to get catalog repository "+can, catalogSourceTableOptions) - } - results = append(results, cr) - } - return cyout.PrintWithOptions(cmd, results, nil, "", catalogSourceTableOptions) -} diff --git a/cmd/cycloid/catalogrepositories/list.go b/cmd/cycloid/catalogrepositories/list.go deleted file mode 100644 index 7d9a53fa2..000000000 --- a/cmd/cycloid/catalogrepositories/list.go +++ /dev/null @@ -1,45 +0,0 @@ -package catalogrepositories - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var catalogSourceTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "URL", "Branch", "StackCount"}, - Identifier: "Canonical", -} - -func NewListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "list the catalog repositories", - Example: ` - # list the catalog repositories in the org 'my-org' and display the result in JSON format - cy --org my-org cr list -o json -`, - RunE: listCatalogRepositories, - } - cyout.RegisterModel(cmd, models.ServiceCatalogSource{}) - return cmd -} - -func listCatalogRepositories(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - crs, _, err := m.ListCatalogRepositories(org) - return cyout.PrintWithOptions(cmd, crs, err, "unable to list catalog repositories", catalogSourceTableOptions) -} diff --git a/cmd/cycloid/catalogrepositories/refresh.go b/cmd/cycloid/catalogrepositories/refresh.go deleted file mode 100644 index b2b5d456a..000000000 --- a/cmd/cycloid/catalogrepositories/refresh.go +++ /dev/null @@ -1,72 +0,0 @@ -package catalogrepositories - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewRefreshCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "refresh [canonical...]", - Args: cyargs.RequireArgsOrFlag("canonical"), - ValidArgsFunction: cyargs.CompleteCatalogRepository, - Short: "refresh one or more catalog repositories", - Long: "refresh action can be used if the .cycloid.yml definition has been updated", - Example: ` - # refresh a catalog repository by canonical - cy --org my-org catalog-repo refresh my-catalog-repository - - # refresh multiple catalog repositories at once - cy --org my-org catalog-repo refresh repo-one repo-two - - # refresh using the deprecated --canonical flag - cy --org my-org catalog-repo refresh --canonical my-catalog-repository -`, - RunE: refreshCatalogRepository, - } - - // Keep --canonical for backward compatibility - can := cyargs.AddCatalogRepoCanonicalFlag(cmd) - _ = cmd.Flags().MarkHidden(can) - - return cmd -} - -func refreshCatalogRepository(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - // Support --canonical for backward compat; positional args take precedence - if len(args) == 0 { - can, err := cyargs.GetCatalogRepoCanonical(cmd) - if err != nil { - return err - } - args = []string{can} - } - - if len(args) == 1 { - cr, _, err := m.RefreshCatalogRepository(org, args[0]) - return cyout.PrintWithOptions(cmd, cr, err, "unable to refresh catalog repository", printer.Options{}) - } - - results := make([]interface{}, 0, len(args)) - for _, can := range args { - cr, _, err := m.RefreshCatalogRepository(org, can) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to refresh catalog repository "+can, printer.Options{}) - } - results = append(results, cr) - } - return cyout.PrintWithOptions(cmd, results, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/catalogrepositories/update.go b/cmd/cycloid/catalogrepositories/update.go deleted file mode 100644 index 6defed5e6..000000000 --- a/cmd/cycloid/catalogrepositories/update.go +++ /dev/null @@ -1,91 +0,0 @@ -package catalogrepositories - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUpdateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "update", - Args: cobra.NoArgs, - Short: "update a catalog repository", - Example: ` - # update a catalog repository - cy --org my-org cr update --branch my-branch --cred my-cred --url "git@github.com:my/repo.git" --name my-catalog-name --canonical my-catalog-repository - - # update and immediately re-index all branches/tags so they are resolvable - cy --org my-org cr update --branch my-branch --url "git@github.com:my/repo.git" --name my-catalog-name --canonical my-catalog-repository --refresh -`, - RunE: updateCatalogRepository, - } - - cmd.MarkFlagRequired(cyargs.AddCatalogRepoCanonicalFlag(cmd)) - cyargs.AddRepoCredFlag(cmd) - cmd.MarkFlagRequired(cyargs.AddNameFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddRepoBranchFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddRepoURLFlag(cmd)) - cmd.Flags().Bool("refresh", true, "trigger a synchronous version re-index after update to make all branches and tags immediately resolvable") - - return cmd -} - -func updateCatalogRepository(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - can, err := cyargs.GetCatalogRepoCanonical(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - url, err := cyargs.GetRepoURL(cmd) - if err != nil { - return err - } - - branch, err := cyargs.GetRepoBranch(cmd) - if err != nil { - return err - } - - cred, err := cyargs.GetRepoCred(cmd) - if err != nil { - return err - } - - refresh, err := cmd.Flags().GetBool("refresh") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - cr, _, err := m.UpdateCatalogRepository(org, can, name, url, branch, cred, nil) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to update catalog repository", printer.Options{}) - } - - if refresh { - if _, _, refreshErr := m.RefreshCatalogRepositoryVersions(org, can); refreshErr != nil { - // Print the successful update result before returning the refresh error - _ = cyout.PrintWithOptions(cmd, cr, nil, "", printer.Options{}) - return cyout.PrintWithOptions(cmd, nil, refreshErr, "unable to refresh catalog repository versions", printer.Options{}) - } - } - - return cyout.PrintWithOptions(cmd, cr, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/cloudaccounts/cmd.go b/cmd/cycloid/cloudaccounts/cmd.go deleted file mode 100644 index 33c7944f4..000000000 --- a/cmd/cycloid/cloudaccounts/cmd.go +++ /dev/null @@ -1,55 +0,0 @@ -package cloudaccounts - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "cloud-account", - Aliases: []string{"cloud-accounts", "cloudaccount", "ca"}, - Short: "Manage cloud accounts", - } - - cmd.AddCommand( - NewCreateCommand(), - NewUpdateCommand(), - NewGetCommand(), - NewDeleteCommand(), - NewListCommand(), - ) - return cmd -} - -var cloudAccountTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "CloudProvider"}, - Identifier: "Canonical", - Transform: func(obj interface{}) map[string]string { - account, ok := obj.(*models.CloudAccountDetail) - if !ok { - if simple, ok := obj.(*models.CloudAccount); ok { - account = &models.CloudAccountDetail{CloudAccount: *simple} - } else { - return map[string]string{} - } - } - canonical, name, provider := "", "", "" - if account.Canonical != nil { - canonical = *account.Canonical - } - if account.Name != nil { - name = *account.Name - } - if account.CloudProvider != nil { - provider = *account.CloudProvider - } - return map[string]string{ - "Canonical": canonical, - "Name": name, - "CloudProvider": provider, - } - }, -} diff --git a/cmd/cycloid/cloudaccounts/cmd_test.go b/cmd/cycloid/cloudaccounts/cmd_test.go deleted file mode 100644 index 7d9e14f9e..000000000 --- a/cmd/cycloid/cloudaccounts/cmd_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package cloudaccounts - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestCloudAccountsCommandTree(t *testing.T) { - t.Parallel() - root := NewCommands() - assert.Equal(t, "cloud-account", root.Name()) - - names := make(map[string]int) - for _, c := range root.Commands() { - names[c.Name()]++ - } - - require.Equal(t, 1, names["list"]) - require.Equal(t, 1, names["get"]) - require.Equal(t, 1, names["create"]) - require.Equal(t, 1, names["update"]) - require.Equal(t, 1, names["delete"]) -} - -func TestCloudAccountCreateFlags(t *testing.T) { - t.Parallel() - cmd := NewCreateCommand() - - require.NotNil(t, cmd.Flags().Lookup("cloud-provider"), "cloud-provider flag must be registered") - require.NotNil(t, cmd.Flags().Lookup("credential"), "credential flag must be registered") - require.NotNil(t, cmd.Flags().Lookup("new-credential"), "new-credential flag must be registered") -} - -func TestCloudAccountCreateHasUpdateFlag(t *testing.T) { - t.Parallel() - cmd := NewCreateCommand() - f := cmd.Flags().Lookup("update") - require.NotNil(t, f, "create must carry --update for upsert") - assert.Equal(t, "bool", f.Value.Type()) -} - -func TestCloudAccountUpdateNoUpdateFlag(t *testing.T) { - t.Parallel() - cmd := NewUpdateCommand() - // update subcommand is always an update; no upsert --update flag - assert.Nil(t, cmd.Flags().Lookup("update")) -} - -func TestCloudAccountUpdateRequiresCanonical(t *testing.T) { - t.Parallel() - cmd := NewUpdateCommand() - f := cmd.Flags().Lookup("cloud-account") - require.NotNil(t, f, "update must require --cloud-account (canonical)") -} - -func TestCloudAccountNameFallsBackToCanonical(t *testing.T) { - t.Parallel() - // cloudAccountName() is exercised via the cobra command flags; verify - // the function directly: when --name is empty it should use --cloud-account. - cmd := NewCreateCommand() - require.NoError(t, cmd.Flags().Set("cloud-account", "my-canonical")) - require.NoError(t, cmd.Flags().Set("cloud-provider", "aws")) - - name, err := cloudAccountName(cmd) - require.NoError(t, err) - assert.Equal(t, "my-canonical", name, "name must fall back to canonical when --name is absent") -} diff --git a/cmd/cycloid/cloudaccounts/create.go b/cmd/cycloid/cloudaccounts/create.go deleted file mode 100644 index a01b719d8..000000000 --- a/cmd/cycloid/cloudaccounts/create.go +++ /dev/null @@ -1,137 +0,0 @@ -package cloudaccounts - -import ( - stderrors "errors" - "fmt" - "net/http" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "create", - Short: "Create a cloud account", - Example: `cy --org my-org cloud-account create --cloud-account my-aws --name "My AWS" --cloud-provider aws --credential my-aws-cred`, - RunE: create, - Args: cobra.NoArgs, - } - - cmd.MarkFlagsOneRequired( - cyargs.AddNameFlag(cmd), - cyargs.AddCloudAccountFlag(cmd), - ) - cmd.MarkFlagRequired(cyargs.AddCloudProviderFlag(cmd)) - cyargs.AddExistingCredentialFlag(cmd) - cyargs.AddNewCredentialTypeFlag(cmd) - cyargs.AddDescriptionFlag(cmd) - cyargs.AddOwnerFlag(cmd) - addCredentialFlags(cmd) - cyargs.AddUpdateFlag(cmd, "update the cloud account if it already exists") - return cmd -} - -func create(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - name, err := cloudAccountName(cmd) - if err != nil { - return err - } - - canonical, err := cyargs.GetCloudAccount(cmd) - if err != nil { - return err - } - name, canonical, err = middleware.NameOrCanonical(&name, &canonical) - if err != nil { - return err - } - - cloudProviderPtr, err := cyargs.GetCloudProvider(cmd) - if err != nil { - return err - } - if cloudProviderPtr == nil || *cloudProviderPtr == "" { - return fmt.Errorf("cloud-provider is required") - } - cloudProvider := *cloudProviderPtr - - existingCredential, err := cyargs.GetExistingCredential(cmd) - if err != nil { - return err - } - newCredentialType, err := cyargs.GetNewCredentialType(cmd) - if err != nil { - return err - } - if existingCredential != "" && newCredentialType != "" { - return fmt.Errorf("cannot use --credential and --new-credential at the same time") - } - if existingCredential == "" && newCredentialType == "" { - return fmt.Errorf("either --credential or --new-credential must be set") - } - - description, err := cyargs.GetDescription(cmd) - if err != nil { - return err - } - owner, err := cyargs.GetOwner(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - if cyargs.GetUpdate(cmd) { - _, _, getErr := m.GetCloudAccount(org, canonical) - if getErr == nil { - return updateCloudAccount(cmd, args) - } - var apiErr *middleware.APIResponseError - if !stderrors.As(getErr, &apiErr) || apiErr.StatusCode != http.StatusNotFound { - return cyout.PrintWithOptions(cmd, nil, getErr, "failed to check existing cloud account", printer.Options{}) - } - } - - var result *models.CloudAccount - if newCredentialType != "" { - accessCredential, buildErr := buildAccessCredential(cmd, newCredentialType, name+" access", "") - if buildErr != nil { - return buildErr - } - body := &models.NewCloudAccountWithCredentials{ - Canonical: canonical, - Name: ptr.Ptr(name), - CloudProvider: ptr.Ptr(cloudProvider), - Description: description, - Owner: owner, - AccessCredential: accessCredential, - } - result, _, err = m.CreateCloudAccountWithCredentials(org, body) - } else { - body := &models.NewCloudAccount{ - Canonical: canonical, - Name: ptr.Ptr(name), - CloudProvider: ptr.Ptr(cloudProvider), - CredentialCanonical: ptr.Ptr(existingCredential), - Description: description, - Owner: owner, - } - result, _, err = m.CreateCloudAccount(org, body) - } - - return cyout.PrintWithOptions(cmd, result, err, "failed to create cloud account", cloudAccountTableOptions) -} diff --git a/cmd/cycloid/cloudaccounts/credential.go b/cmd/cycloid/cloudaccounts/credential.go deleted file mode 100644 index c2ae13703..000000000 --- a/cmd/cycloid/cloudaccounts/credential.go +++ /dev/null @@ -1,90 +0,0 @@ -package cloudaccounts - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/credentials" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -// addCredentialFlags wires every flag a credential type might need on a -// cloud-account command. It delegates to the shared credentials package so -// the supported flag set stays in sync with `cy credential` subcommands. -func addCredentialFlags(cmd *cobra.Command) { - credentials.AddAllRawFlags(cmd) -} - -// createInlineCredential creates a standalone Credential for an existing -// cloud account (used by `cy cloud-account update --new-credential …`). -func createInlineCredential(cmd *cobra.Command, m middleware.Middleware, org, credType, name string) (*models.Credential, error) { - raw, err := credentials.BuildCredentialRaw(cmd, credType) - if err != nil { - return nil, err - } - - // path/canonical/description are user-friendly hints, missing values are - // fine: GetCredentialPath/Canonical only error on type mismatch (cobra - // guarantees the flags we registered are strings), so the discarded err - // is unreachable and we keep the local code path readable. - description, _ := cyargs.GetDescription(cmd) - path, _ := cyargs.GetCredentialPath(cmd) - canonical, _ := cyargs.GetCredentialCanonical(cmd) - - cred, _, err := m.CreateCredential(org, name, credType, raw, path, canonical, description) - if err != nil { - return nil, err - } - - return cred, nil -} - -// buildAccessCredential builds an inline credential payload to send alongside -// a cloud-account create call (atomic POST /cloud_accounts/with_credentials). -func buildAccessCredential(cmd *cobra.Command, credType, name, canonical string) (*models.NewCloudAccountCredential, error) { - raw, err := credentials.BuildCredentialRaw(cmd, credType) - if err != nil { - return nil, err - } - - description, err := cyargs.GetDescription(cmd) - if err != nil { - return nil, err - } - - path, _ := cyargs.GetCredentialPath(cmd) - - credential := &models.NewCloudAccountCredential{ - Name: ptr.Ptr(name), - Type: ptr.Ptr(credType), - Raw: raw, - Description: description, - } - if canonical != "" { - credential.Canonical = canonical - } - if path != "" { - credential.Path = path - } - - return credential, nil -} - -func cloudAccountName(cmd *cobra.Command) (string, error) { - name, err := cyargs.GetName(cmd) - if err != nil { - return "", err - } - - if name == "" { - canonical, err := cyargs.GetCloudAccount(cmd) - if err != nil { - return "", err - } - name = canonical - } - - return name, nil -} diff --git a/cmd/cycloid/cloudaccounts/delete.go b/cmd/cycloid/cloudaccounts/delete.go deleted file mode 100644 index a9532ea22..000000000 --- a/cmd/cycloid/cloudaccounts/delete.go +++ /dev/null @@ -1,42 +0,0 @@ -package cloudaccounts - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewDeleteCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "delete [...]", - Short: "Delete cloud accounts", - RunE: deleteCloudAccount, - Args: cobra.MinimumNArgs(1), - ValidArgsFunction: cyargs.CompleteCloudAccount, - } - - return cmd -} - -func deleteCloudAccount(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - for _, canonical := range args { - if _, err := m.DeleteCloudAccount(org, canonical); err != nil { - return cyout.Print(cmd, nil, err, "failed to delete cloud account "+canonical) - } - fmt.Fprintf(cmd.OutOrStdout(), "deleted %s\n", canonical) - } - return nil -} diff --git a/cmd/cycloid/cloudaccounts/get.go b/cmd/cycloid/cloudaccounts/get.go deleted file mode 100644 index 7cc958f5c..000000000 --- a/cmd/cycloid/cloudaccounts/get.go +++ /dev/null @@ -1,49 +0,0 @@ -package cloudaccounts - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewGetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get [...]", - Short: "Get cloud account details", - RunE: get, - Args: cobra.MinimumNArgs(1), - ValidArgsFunction: cyargs.CompleteCloudAccount, - } - - cyout.RegisterModel(cmd, models.CloudAccountDetail{}) - return cmd -} - -func get(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - if len(args) == 1 { - account, _, err := m.GetCloudAccount(org, args[0]) - return cyout.PrintWithOptions(cmd, account, err, "failed to get cloud account", cloudAccountTableOptions) - } - - results := make([]*models.CloudAccountDetail, 0, len(args)) - for _, canonical := range args { - account, _, err := m.GetCloudAccount(org, canonical) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "failed to get cloud account "+canonical, cloudAccountTableOptions) - } - results = append(results, account) - } - return cyout.PrintWithOptions(cmd, results, nil, "", cloudAccountTableOptions) -} diff --git a/cmd/cycloid/cloudaccounts/list.go b/cmd/cycloid/cloudaccounts/list.go deleted file mode 100644 index 224f57f8e..000000000 --- a/cmd/cycloid/cloudaccounts/list.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudaccounts - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewListCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "list", - Short: "List cloud accounts", - RunE: list, - Args: cobra.NoArgs, - } - - cyout.RegisterModel(cmd, models.CloudAccountDetail{}) - return cmd -} - -func list(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - accounts, _, err := m.ListCloudAccounts(org) - return cyout.PrintWithOptions(cmd, accounts, err, "failed to list cloud accounts", cloudAccountTableOptions) -} diff --git a/cmd/cycloid/cloudaccounts/update.go b/cmd/cycloid/cloudaccounts/update.go deleted file mode 100644 index bc4c8b7a6..000000000 --- a/cmd/cycloid/cloudaccounts/update.go +++ /dev/null @@ -1,97 +0,0 @@ -package cloudaccounts - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/internal/utils" -) - -func NewUpdateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "update", - Short: "Update a cloud account", - RunE: updateCloudAccount, - Args: cobra.NoArgs, - } - - cmd.MarkFlagRequired(cyargs.AddCloudAccountFlag(cmd)) - cyargs.AddNameFlag(cmd) - cyargs.AddExistingCredentialFlag(cmd) - cyargs.AddNewCredentialTypeFlag(cmd) - cyargs.AddDescriptionFlag(cmd) - cyargs.AddOwnerFlag(cmd) - addCredentialFlags(cmd) - return cmd -} - -func updateCloudAccount(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - canonical, err := cyargs.GetCloudAccount(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - current, _, err := m.GetCloudAccount(org, canonical) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "cloud account not found", cloudAccountTableOptions) - } - - // Flag readers below ignore their err return on purpose: cobra guarantees - // these flags are registered as the right type, so GetString/GetBool can - // only fail on a programmer mistake (wrong type lookup), not user input. - // Treating them as best-effort lookups keeps the PATCH-style merge readable. - name, _ := cyargs.GetName(cmd) - description, _ := cyargs.GetDescription(cmd) - owner, _ := cyargs.GetOwner(cmd) - existingCredential, _ := cyargs.GetExistingCredential(cmd) - newCredentialType, _ := cyargs.GetNewCredentialType(cmd) - if existingCredential != "" && newCredentialType != "" { - return fmt.Errorf("cannot use --credential and --new-credential at the same time") - } - - body := &models.UpdateCloudAccount{ - Name: ptr.Ptr(utils.CoalesceNonZero(name, ptr.Value(current.Name))), - } - if cyargs.IsSet(cmd, "description") { - body.Description = description - } else { - body.Description = current.Description - } - if cyargs.IsSet(cmd, "owner") { - body.Owner = owner - } else if current.Owner != nil && current.Owner.Username != nil { - body.Owner = *current.Owner.Username - } - - switch { - case newCredentialType != "": - credName := utils.CoalesceNonZero(name, ptr.Value(current.Name)) + " access" - credential, err := createInlineCredential(cmd, m, org, newCredentialType, credName) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "failed to create inline credential", cloudAccountTableOptions) - } - body.CredentialCanonical = credential.Canonical - case cyargs.IsSet(cmd, "credential"): - body.CredentialCanonical = ptr.Ptr(existingCredential) - case current.Credential != nil && current.Credential.Canonical != nil: - body.CredentialCanonical = current.Credential.Canonical - } - - result, _, err := m.UpdateCloudAccount(org, canonical, body) - return cyout.PrintWithOptions(cmd, result, err, "failed to update cloud account", cloudAccountTableOptions) -} diff --git a/cmd/cycloid/common/console_url.go b/cmd/cycloid/common/console_url.go deleted file mode 100644 index 474554de9..000000000 --- a/cmd/cycloid/common/console_url.go +++ /dev/null @@ -1,27 +0,0 @@ -package common - -import ( - "net/url" - "strings" -) - -// PipelineBuildConsoleURL returns a deep link to a pipeline job build in the Cycloid console. -// base must be non-empty (e.g. https://console.cycloid.io). Path segments are escaped. -func PipelineBuildConsoleURL(base, org, project, env, component, pipeline, job, buildID string) (string, bool) { - b := strings.TrimSpace(base) - if b == "" { - return "", false - } - b = strings.TrimSuffix(b, "/") - parts := []string{ - b, - "organizations", url.PathEscape(org), - "projects", url.PathEscape(project), - "environments", url.PathEscape(env), - "components", url.PathEscape(component), - "pipelines", url.PathEscape(pipeline), - "jobs", url.PathEscape(job), - "builds", url.PathEscape(buildID), - } - return strings.Join(parts, "/"), true -} diff --git a/cmd/cycloid/common/console_url_test.go b/cmd/cycloid/common/console_url_test.go deleted file mode 100644 index b8d700e8a..000000000 --- a/cmd/cycloid/common/console_url_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package common - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestPipelineBuildConsoleURL(t *testing.T) { - t.Parallel() - - u, ok := PipelineBuildConsoleURL("", "o", "p", "e", "c", "pl", "j", "42") - assert.False(t, ok) - assert.Empty(t, u) - - u, ok = PipelineBuildConsoleURL("https://console.example.com/", "my org", "p", "e", "c", "pl", "j", "99") - require.True(t, ok) - assert.Equal(t, "https://console.example.com/organizations/my%20org/projects/p/environments/e/components/c/pipelines/pl/jobs/j/builds/99", u) -} diff --git a/cmd/cycloid/common/flags.go b/cmd/cycloid/common/flags.go deleted file mode 100644 index a79af2ceb..000000000 --- a/cmd/cycloid/common/flags.go +++ /dev/null @@ -1,49 +0,0 @@ -package common - -import ( - "github.com/spf13/cobra" -) - -var ( - projectFlag, envFlag, credFlag, canFlag string - idFlag uint32 -) - -func WithFlagProject(cmd *cobra.Command) string { - flagName := "project" - cmd.PersistentFlags().StringVar(&projectFlag, flagName, "", "Project canonical name") - return flagName -} - -func WithFlagEnv(cmd *cobra.Command) string { - flagName := "env" - cmd.PersistentFlags().StringVar(&envFlag, flagName, "", "Environment") - return flagName -} - -func WithFlagCan(cmd *cobra.Command) string { - flagName := "canonical" - // TODO how make it nil or without any value in case we don't want any creds ? - cmd.Flags().StringVar(&canFlag, flagName, "", "canonical") - return flagName -} - -func WithPersistentFlagCan(cmd *cobra.Command) string { - flagName := "canonical" - // TODO how make it nil or without any value in case we don't want any creds ? - cmd.PersistentFlags().StringVar(&canFlag, flagName, "", "canonical") - return flagName -} - -func WithFlagCred(cmd *cobra.Command) string { - flagName := "cred" - // TODO how make it nil or without any value in case we don't want any creds ? - cmd.Flags().StringVar(&credFlag, flagName, "", "cred canonical") - return flagName -} - -func WithFlagID(cmd *cobra.Command) string { - flagName := "id" - cmd.Flags().Uint32Var(&idFlag, flagName, 0, "id") - return flagName -} diff --git a/cmd/cycloid/common/formsUtils.go b/cmd/cycloid/common/formsUtils.go deleted file mode 100644 index 32fd441bc..000000000 --- a/cmd/cycloid/common/formsUtils.go +++ /dev/null @@ -1,35 +0,0 @@ -package common - -import ( - "fmt" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func FormUseCaseToFormVars(stackConfig models.ServiceCatalogConfigs, useCaseName string) (models.FormVariables, error) { - useCaseData, ok := stackConfig[useCaseName] - if !ok { - return nil, fmt.Errorf("cannot find usecase named %q in stack config", useCaseName) - } - - output := make(models.FormVariables) - - for _, section := range useCaseData.Forms.Sections { - if _, ok := output[*section.Name]; !ok { - output[*section.Name] = make(map[string]map[string]any) - } - for _, group := range section.Groups { - if _, ok := output[*group.Name]; !ok { - output[*section.Name][*group.Name] = make(map[string]any) - } - - for _, widget := range group.Vars { - if widget.Default != nil { - output[*section.Name][*group.Name][*widget.Key] = widget.Default - } - } - } - } - - return output, nil -} diff --git a/cmd/cycloid/common/helpers.go b/cmd/cycloid/common/helpers.go deleted file mode 100644 index 5cabe63e4..000000000 --- a/cmd/cycloid/common/helpers.go +++ /dev/null @@ -1,262 +0,0 @@ -package common - -import ( - "encoding/json" - "fmt" - "os" - "regexp" - "strconv" - "strings" - "time" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cycloidio/cycloid-cli/config" -) - -var orgRe = regexp.MustCompile(`\(\$ organization_canonical \$\)`) -var envRe = regexp.MustCompile(`\(\$ environment \$\)`) -var projRe = regexp.MustCompile(`\(\$ project \$\)`) - -func RequiredPersistentFlag(withFlag func(cmd *cobra.Command) string, cmd *cobra.Command) { - flagName := withFlag(cmd) - cmd.MarkPersistentFlagRequired(flagName) -} -func RequiredFlag(withFlag func(cmd *cobra.Command) string, cmd *cobra.Command) { - flagName := withFlag(cmd) - cmd.MarkFlagRequired(flagName) -} - -type CycloidContext struct { - Org string - Env string - Project string -} - -func ReplaceCycloidVars(ctx CycloidContext, text []byte) []byte { - if ctx.Org != "" { - text = orgRe.ReplaceAll(text, []byte(ctx.Org)) - } - if ctx.Env != "" { - text = envRe.ReplaceAll(text, []byte(ctx.Env)) - } - if ctx.Project != "" { - text = projRe.ReplaceAll(text, []byte(ctx.Project)) - } - return text -} - -func ReplaceCycloidVarsString(ctx CycloidContext, text string) string { - if ctx.Org != "" { - text = orgRe.ReplaceAllString(text, ctx.Org) - } - if ctx.Env != "" { - text = envRe.ReplaceAllString(text, ctx.Env) - } - if ctx.Project != "" { - text = projRe.ReplaceAllString(text, ctx.Project) - } - return text -} - -type APIConfig struct { - URL string - Insecure bool - Token string -} - -type APIOptions func(acfg *APIConfig) - -func WithURL(u string) APIOptions { - return func(acfg *APIConfig) { - acfg.URL = u - } -} - -func WithInsecure(i bool) APIOptions { - return func(acfg *APIConfig) { - acfg.Insecure = i - } -} - -func WithToken(t string) APIOptions { - return func(acfg *APIConfig) { - acfg.Token = t - } -} - -type APIClient struct { - Config APIConfig -} - -func NewAPI(opts ...APIOptions) *APIClient { - acfg := APIConfig{ - URL: viper.GetString("api-url"), - Insecure: viper.GetBool("insecure"), - Token: "", - } - - for _, o := range opts { - o(&acfg) - } - - if !strings.HasPrefix(acfg.URL, "https://") && !strings.HasPrefix(acfg.URL, "http://") { - if strings.Contains(acfg.URL, "localhost") { - // This handles the weird case of localhost:3001 - // being interpreted as scheme=localhost by url.Parse - acfg.URL = "http://" + acfg.URL - } - } - - return &APIClient{ - Config: acfg, - } -} - -func (a *APIClient) GetToken(org *string) string { - var token string - token = a.Config.Token - - // we first try to get the token from the env variable - if token == "" { - for _, envVar := range []string{"CY_API_KEY", "CY_API_TOKEN", "TOKEN"} { - var ok bool - token, ok = os.LookupEnv(envVar) - - // Still display warning for future deprecation - if ok && envVar == "TOKEN" { - fmt.Fprintln(os.Stderr, "TOKEN env var is deprecated, please use CY_API_KEY instead") - } - - if ok && token != "" { - break - } - } - } - - // if the token is not set with env variable we try to fetch - // him from the config (if the user is logged) - if len(token) == 0 && org != nil { - // Check first if the config file exists - filePath, err := config.GetConfigPath() - if err != nil { - return "" - } - - _, err = os.Stat(filePath) - var pathErr os.PathError - if errors.Is(err, &pathErr) { - return "" - } - - // we fetch the running config - config, _ := config.Read() - - // we try to find a token for this `org` - if t, ok := config.Organizations[*org]; ok { - token = t.Token - } - } - - return token -} - -// GenerateCanonical will generate a canonical from the -// name passed in input -func GenerateCanonical(name string) string { - var ( - extraspaces = regexp.MustCompile(`\s+`) - spaces = regexp.MustCompile(`[^a-zA-z0-9_\-]`) - canonical string - ) - - canonical = extraspaces.ReplaceAllString(name, " ") - canonical = spaces.ReplaceAllString(canonical, "-") - - return strings.ToLower(canonical) -} - -// Update map 'm' with field 'field' to 'value' -// the field must be in dot notation -// e.g. field='one.nested.key' value='myValue' -// If the map is nil, it will be created -func UpdateMapField(field string, value string, m map[string]map[string]map[string]any) error { - keys := strings.Split(field, ".") - - if len(keys) != 3 { - return errors.New("key=val update failed, you can only update a value using `section.group.var=value` syntax") - } - - if m == nil { - m = make(map[string]map[string]map[string]any) - } - - // Try to detect JSON first - // we strip value for space and newline in begin/end of the string - trimmedValue := strings.TrimSpace(value) - if strings.HasPrefix(trimmedValue, "[") && strings.HasSuffix(trimmedValue, "]") || strings.HasPrefix(trimmedValue, "{") && strings.HasSuffix(trimmedValue, "}") { - var data any - err := json.Unmarshal([]byte(trimmedValue), &data) - if err != nil { - return errors.Wrapf(err, "invalid JSON value in key=val update with value '%s'", trimmedValue) - } - - m[keys[0]][keys[1]][keys[2]] = data - return nil - } - - // We will prioritize the use of quotes to explicitly define strings values - // This allow users to circumvent issues in case of strings that could be parsed - // as other types - if strings.HasPrefix(trimmedValue, `"`) && strings.HasSuffix(trimmedValue, `"`) || - strings.HasPrefix(trimmedValue, "'") && strings.HasSuffix(trimmedValue, "'") { - m[keys[0]][keys[1]][keys[2]] = trimmedValue[1 : len(trimmedValue)-1] - return nil - } - - // Detect standard types - // numbers, we do all as float since JSON doesn't care - // Important! We parse number firsts, since 1 and 0 are considered bools by strconv.ParseBool - float, err := strconv.ParseFloat(value, 64) - if err == nil { - m[keys[0]][keys[1]][keys[2]] = float - return nil - } - - // bools - boolean, err := strconv.ParseBool(value) - if err == nil { - m[keys[0]][keys[1]][keys[2]] = boolean - return nil - } - - // null - if strings.ToLower(value) == "null" { - m[keys[0]][keys[1]][keys[2]] = nil - return nil - } - - // if all type conversion failed, consider the value as string - m[keys[0]][keys[1]][keys[2]] = value - return nil -} - -func UnixTimestampToLocalTime(unixTime *uint64) string { - defaultTime := "date unknown" - if unixTime == nil { - return defaultTime - } - - ts := time.Unix(int64(*unixTime), 0) - return ts.Format(time.DateTime) -} - -// DetectStdinInput will return true if the current -// command effectively has some kind of stdin input -// return false otherwise -func DetectStdinInput() bool { - stats, _ := os.Stdin.Stat() - return (stats.Mode() & os.ModeCharDevice) == 0 -} diff --git a/cmd/cycloid/common/helpers_test.go b/cmd/cycloid/common/helpers_test.go deleted file mode 100644 index d0606dd61..000000000 --- a/cmd/cycloid/common/helpers_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package common - -import "testing" - -func TestUpdateMapField(t *testing.T) { - type Args struct { - field string - value string - m map[string]map[string]map[string]any - } - tests := []struct { - name string - args Args - wantErr bool - }{ - // TODO: Add test cases. - { - name: "StringDoubleQuote", - args: Args{ - field: "section.group.string", - value: `"my-string"`, - m: map[string]map[string]map[string]any{ - "section": {"group": {"string": "my-string"}}, - }, - }, - wantErr: false, - }, - { - name: "StringSimpleQuote", - args: Args{ - field: "section.group.string", - value: `'my-string'`, - m: map[string]map[string]map[string]any{ - "section": {"group": {"string": "my-string"}}, - }, - }, - wantErr: false, - }, - { - name: "StringNoQuote", - args: Args{ - field: "section.group.string", - value: `my-string`, - m: map[string]map[string]map[string]any{ - "section": {"group": {"string": "my-string"}}, - }, - }, - wantErr: false, - }, - { - name: "Int", - args: Args{ - field: "section.group.int", - value: `1`, - m: map[string]map[string]map[string]any{ - "section": {"group": {"int": 1}}, - }, - }, - wantErr: false, - }, - { - name: "IntAsString", - args: Args{ - field: "section.group.string", - value: `"1"`, - m: map[string]map[string]map[string]any{ - "section": {"group": {"string": "1"}}, - }, - }, - wantErr: false, - }, - { - name: "Array", - args: Args{ - field: "section.group.array", - value: `["hello", "world"]`, - m: map[string]map[string]map[string]any{ - "section": {"group": {"array": []string{"hello", "world"}}}, - }, - }, - wantErr: false, - }, - { - name: "ArraySingleValue", - args: Args{ - field: "section.group.array", - value: `["hi"]`, - m: map[string]map[string]map[string]any{ - "section": {"group": {"array": []string{"hi"}}}, - }, - }, - wantErr: false, - }, - { - name: "Map", - args: Args{ - field: "section.group.array", - value: `{"hello": "world"}`, - m: map[string]map[string]map[string]any{ - "section": {"group": {"array": map[string]string{"hello": "world"}}}, - }, - }, - wantErr: false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := UpdateMapField(tt.args.field, tt.args.value, tt.args.m); (err != nil) != tt.wantErr { - t.Errorf("UpdateMapField() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} diff --git a/cmd/cycloid/completion.go b/cmd/cycloid/completion.go deleted file mode 100644 index 259fe8878..000000000 --- a/cmd/cycloid/completion.go +++ /dev/null @@ -1,49 +0,0 @@ -package cycloid - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" -) - -var ( - supportedShells = []string{"bash", "fish", "zsh", "powershell"} -) - -// NewCompletionCmd returns the cobra command that outputs shell completion code -func NewCompletionCmd() *cobra.Command { - return &cobra.Command{ - Use: `completion (` + strings.Join(supportedShells, "|") + `)`, - Args: func(cmd *cobra.Command, args []string) error { - if len(args) != 1 { - return fmt.Errorf("requires 1 arg, found %d", len(args)) - } - return cobra.OnlyValidArgs(cmd, args) - }, - ValidArgs: []string{"bash", "zsh", "fish", "powershell", "pwsh"}, - Short: "Output shell completion for the given shell (bash or zsh)", - RunE: completion, - Example: `# generate completion for ZSH -cy completion zsh > _cy; cp _cy ~/.oh-my-zsh/functions; source ~/.zshrc - - # generate completion for Bash - cy completion bash > cy; sudo cp cy /etc/bash_completion.d/; source /etc/profile -`, - } -} - -func completion(cmd *cobra.Command, args []string) error { - switch args[0] { - case "bash": - return cmd.Root().GenBashCompletionV2(cmd.OutOrStdout(), true) - case "fish": - return cmd.Root().GenFishCompletion(cmd.OutOrStdout(), true) - case "zsh": - return cmd.Root().GenZshCompletion(cmd.OutOrStdout()) - case "powershell", "pwsh": - return cmd.Root().GenPowerShellCompletionWithDesc(cmd.OutOrStdout()) - default: - return fmt.Errorf("invalid shell argument %q valid options are: %v", args[0], supportedShells) - } -} diff --git a/cmd/cycloid/components/cmd.go b/cmd/cycloid/components/cmd.go deleted file mode 100644 index 7362d4e79..000000000 --- a/cmd/cycloid/components/cmd.go +++ /dev/null @@ -1,70 +0,0 @@ -package components - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCommands() *cobra.Command { - var cmd = &cobra.Command{ - Use: "components", - Args: cobra.NoArgs, - Aliases: []string{ - "component", - "comp", - }, - Short: "Manage components.", - } - - cmd.AddCommand( - NewGetComponentCommand(), - NewGetComponentsCommand(), - NewCreateComponentCommand(), - NewUpdateComponentCommand(), - NewDeleteComponentCommand(), - NewMigrateCommand(), - NewConfigCommands(), - ) - - return cmd -} - -var componentTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "Description", "StackRef", "UseCase", "Version"}, - Identifier: "Canonical", - Transform: func(obj interface{}) map[string]string { - c, ok := obj.(*models.Component) - if !ok { - return map[string]string{} - } - canonical := "" - if c.Canonical != nil { - canonical = *c.Canonical - } - name := "" - if c.Name != nil { - name = *c.Name - } - stackRef := "" - version := "" - if c.ServiceCatalog != nil { - if c.ServiceCatalog.Ref != nil { - stackRef = *c.ServiceCatalog.Ref - } - if c.ServiceCatalog.Version != nil { - version = *c.ServiceCatalog.Version - } - } - useCase := c.UseCase - return map[string]string{ - "Canonical": canonical, - "Name": name, - "Description": c.Description, - "StackRef": stackRef, - "UseCase": useCase, - "Version": version, - } - }, -} diff --git a/cmd/cycloid/components/config.go b/cmd/cycloid/components/config.go deleted file mode 100644 index 24e1529c3..000000000 --- a/cmd/cycloid/components/config.go +++ /dev/null @@ -1,20 +0,0 @@ -package components - -import "github.com/spf13/cobra" - -func NewConfigCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "config", - Args: cobra.NoArgs, - Aliases: []string{ - "cfg", - }, - Short: "Manage component config", - } - - cmd.AddCommand( - NewComponentConfigGetCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/components/config_get.go b/cmd/cycloid/components/config_get.go deleted file mode 100644 index 346790d64..000000000 --- a/cmd/cycloid/components/config_get.go +++ /dev/null @@ -1,36 +0,0 @@ -package components - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewComponentConfigGetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get", - Args: cobra.NoArgs, - Short: "Fetch the current Stackforms variables of a component in JSON format.", - RunE: getComponentConfig, - Example: "cy config get -p project -e env -c component", - } - cyargs.AddCyContext(cmd) - return cmd -} - -func getComponentConfig(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - config, _, err := m.GetComponentConfig(org, project, env, component) - return cyout.PrintWithOptions(cmd, config, err, "failed to fetch config of component '"+component+"'", printer.Options{}) -} diff --git a/cmd/cycloid/components/create.go b/cmd/cycloid/components/create.go deleted file mode 100644 index 67693a6d7..000000000 --- a/cmd/cycloid/components/create.go +++ /dev/null @@ -1,132 +0,0 @@ -package components - -import ( - "fmt" - "slices" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateComponentCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "create", - Args: cobra.NoArgs, - Short: "Create a component", - RunE: createComponent, - Example: `cy component create -p project -e env -c component -V section.group.var="value-str" -s "stack:ref" -u new-use-case`, - } - cyargs.AddCyContext(cmd) - cyargs.AddNameFlag(cmd) - cyargs.AddComponentDescriptionFlag(cmd) - cmd.MarkFlagRequired(cyargs.AddUseCaseFlag(cmd)) - cyargs.AddStackVersionFlags(cmd) - cyargs.AddCloudProviderFlag(cmd) - cmd.MarkFlagRequired(cyargs.AddComponentStackRefFlag(cmd)) - cyargs.AddStackFormsInputFlags(cmd) - cmd.Flags().Bool("update", false, "If the component exists, update it.") - return cmd -} - -func createComponent(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - if name == "" { - // if name is empty, use the canonical - name = component - } - - description, err := cyargs.GetComponentDescription(cmd) - if err != nil { - return err - } - - useCase, err := cyargs.GetUseCase(cmd) - if err != nil { - return err - } - - stackRef, err := cyargs.GetStackRef(cmd) - if err != nil { - return err - } - - cloudProvider, err := cyargs.GetCloudProvider(cmd) - if err != nil { - return err - } - - update, err := cmd.Flags().GetBool("update") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // Resolve stack version: --stack-version (new) or legacy flags. - tag, branch, hash, err := cyargs.ResolveStackVersionArg(cmd, m, org, stackRef) - if err != nil { - return errors.Wrap(err, "failed to read stack version flags") - } - - if update { - components, _, err := m.ListComponents(org, project, env) - if err != nil { - return fmt.Errorf("failed to create --update component, cannot check existing component %q: %w", component, err) - } - - componentIndex := slices.IndexFunc(components, func(c *models.Component) bool { - return *c.Canonical == component - }) - if componentIndex != -1 { - currentComponent := components[componentIndex] - - // Fetch base forms value from current component - var currentConfig = make(models.FormVariables) - if currentComponent.UseCase != "" { - currentConfig, _, err = m.GetComponentConfig(org, project, env, component) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "failed to update component '"+component+"', cannot get current config.", printer.Options{}) - } - } - - inputs, err := cyargs.GetStackformsVars(cmd, currentConfig) - if err != nil { - return err - } - - // ConfigureComponent will reconfigure the component - componentOutput, _, err := m.CreateOrUpdateComponent(org, project, env, component, *description, name, stackRef, tag, branch, hash, useCase, *cloudProvider, inputs) - return cyout.PrintWithOptions(cmd, componentOutput, err, "failed to configure component '"+component+"'", printer.Options{}) - } - } - - componentEntity, _, err := m.GetComponent(org, project, env, component) - if err == nil { - return cyout.PrintWithOptions(cmd, componentEntity, fmt.Errorf("component %q already exists, to update it, use the --update flag", component), "failed to create component", printer.Options{}) - } - - inputs, err := cyargs.GetStackformsVars(cmd, nil) - if err != nil { - return err - } - - componentOutput, _, err := m.CreateOrUpdateComponent(org, project, env, component, *description, name, stackRef, tag, branch, hash, useCase, *cloudProvider, inputs) - return cyout.PrintWithOptions(cmd, componentOutput, err, "failed to create and configure component '"+component+"'", printer.Options{}) -} diff --git a/cmd/cycloid/components/delete.go b/cmd/cycloid/components/delete.go deleted file mode 100644 index 373375078..000000000 --- a/cmd/cycloid/components/delete.go +++ /dev/null @@ -1,80 +0,0 @@ -package components - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewDeleteComponentCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "delete [canonical...]", - Args: cyargs.RequireArgsOrFlag("component"), - Short: "Delete a component", - Example: ` - # delete a component using flags - cy --org my-org component delete -p my-proj -e my-env -c my-comp - - # delete multiple components using positional args - cy --org my-org component delete -p my-proj -e my-env comp-a comp-b -`, - RunE: deleteComponent, - } - cyargs.AddProjectFlag(cmd) - cyargs.AddEnvFlag(cmd) - cyargs.AddComponentFlag(cmd) - cyargs.AddDeleteFlags(cmd) - return cmd -} - -func deleteComponent(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProject(cmd) - if err != nil { - return err - } - - env, err := cyargs.GetEnv(cmd) - if err != nil { - return err - } - - force, skipHooks, ignoreConfigFilesErr, err := cyargs.GetDeleteFlags(cmd) - if err != nil { - return err - } - - if compFlag, err := cyargs.GetComponent(cmd); err != nil { - return err - } else if compFlag != "" { - found := false - for _, a := range args { - if a == compFlag { - found = true - break - } - } - if !found { - args = append(args, compFlag) - } - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - opts := middleware.DeleteOptions{Force: force, SkipHooks: skipHooks, IgnoreConfigFilesErr: ignoreConfigFilesErr} - for _, component := range args { - _, err = m.DeleteComponent(org, project, env, component, opts) - if err != nil { - return cyout.Print(cmd, nil, err, "failed to delete component '"+component+"'") - } - } - return nil -} diff --git a/cmd/cycloid/components/get.go b/cmd/cycloid/components/get.go deleted file mode 100644 index 416a53f56..000000000 --- a/cmd/cycloid/components/get.go +++ /dev/null @@ -1,82 +0,0 @@ -package components - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewGetComponentCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get [canonical...]", - Args: cyargs.RequireArgsOrFlag("component"), - Short: "Get the state of a current component.", - Example: ` - # get a component using flags - cy --org my-org component get -p my-proj -e my-env -c my-comp - - # get multiple components using positional args - cy --org my-org component get -p my-proj -e my-env comp-a comp-b -`, - RunE: getComponent, - } - cyargs.AddProjectFlag(cmd) - cyargs.AddEnvFlag(cmd) - cyargs.AddComponentFlag(cmd) - cyout.RegisterModel(cmd, models.Component{}) - return cmd -} - -func getComponent(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProject(cmd) - if err != nil { - return err - } - - env, err := cyargs.GetEnv(cmd) - if err != nil { - return err - } - - if compFlag, err := cyargs.GetComponent(cmd); err != nil { - return err - } else if compFlag != "" { - found := false - for _, a := range args { - if a == compFlag { - found = true - break - } - } - if !found { - args = append(args, compFlag) - } - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - if len(args) == 1 { - c, _, err := m.GetComponent(org, project, env, args[0]) - return cyout.PrintWithOptions(cmd, c, err, "failed to fetch state of component '"+args[0]+"'", componentTableOptions) - } - - results := make([]*models.Component, 0, len(args)) - for _, component := range args { - c, _, err := m.GetComponent(org, project, env, component) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "failed to fetch component '"+component+"'", componentTableOptions) - } - results = append(results, c) - } - return cyout.PrintWithOptions(cmd, results, nil, "", componentTableOptions) -} diff --git a/cmd/cycloid/components/list.go b/cmd/cycloid/components/list.go deleted file mode 100644 index f4043d17c..000000000 --- a/cmd/cycloid/components/list.go +++ /dev/null @@ -1,48 +0,0 @@ -package components - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewGetComponentsCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "list -p project -e env", - Args: cobra.NoArgs, - Short: "List components in a project", - RunE: getComponents, - } - cyargs.AddProjectFlag(cmd) - cyargs.AddEnvFlag(cmd) - cyout.RegisterModel(cmd, models.Component{}) - return cmd -} - -func getComponents(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProject(cmd) - if err != nil { - return err - } - - env, err := cyargs.GetEnv(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - components, _, err := m.ListComponents(org, project, env) - errMsg := "failed to fetch list of components in '" + project + "', '" + env + "'" - return cyout.PrintWithOptions(cmd, components, err, errMsg, componentTableOptions) -} diff --git a/cmd/cycloid/components/migrate.go b/cmd/cycloid/components/migrate.go deleted file mode 100644 index 6bcf6d6d1..000000000 --- a/cmd/cycloid/components/migrate.go +++ /dev/null @@ -1,72 +0,0 @@ -package components - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewMigrateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "migrate --project old-project --env old-env --component component --new-project new-project --new-env new-env --new-canonical new-comp-canonical", - Args: cobra.NoArgs, - Short: "move a component from one project / env to another.", - RunE: migrate, - } - - cyargs.AddCyContext(cmd) - cmd.Flags().String("new-project", "", "specify a new project, if unset, will use the previous one") - cmd.Flags().String("new-env", "", "specify a new env, if unset, will use the previous one") - cmd.Flags().String("new-canonical", "", "specify a new component canonical, if unset, will use the previous one") - cmd.Flags().String("new-name", "", "specify a new component name, if unset, will use the new canonical") - return cmd -} - -func migrate(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - newProject, err := cmd.Flags().GetString("new-project") - if err != nil { - return err - } - if newProject == "" { - newProject = project - } - - newEnv, err := cmd.Flags().GetString("new-env") - if err != nil { - return err - } - if newEnv == "" { - newEnv = env - } - - newComponent, err := cmd.Flags().GetString("new-canonical") - if err != nil { - return err - } - if newComponent == "" { - newComponent = component - } - - newComponentName, err := cmd.Flags().GetString("new-name") - if err != nil { - return err - } - if newComponentName == "" { - newComponentName = newComponent - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - compResponse, _, err := m.MigrateComponent(org, project, env, component, newProject, newEnv, newComponent, newComponentName) - return cyout.PrintWithOptions(cmd, compResponse, err, "failed to migrate component", printer.Options{}) -} diff --git a/cmd/cycloid/components/update.go b/cmd/cycloid/components/update.go deleted file mode 100644 index 443c35251..000000000 --- a/cmd/cycloid/components/update.go +++ /dev/null @@ -1,133 +0,0 @@ -package components - -import ( - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUpdateComponentCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "update", - Args: cobra.NoArgs, - Short: "update an existing component", - Example: `cy component update -p project -e env -c component -V section.group.var="value-str" -u new-use-case`, - RunE: updateComponent, - } - - cyargs.AddCyContext(cmd) - cyargs.AddNameFlag(cmd) - cyargs.AddComponentDescriptionFlag(cmd) - cyargs.AddUseCaseFlag(cmd) - cyargs.AddStackVersionFlags(cmd) - cyargs.AddStackFormsInputFlags(cmd) - cyargs.AddStackRefFlag(cmd) - cyargs.AddCloudProviderFlag(cmd) - - return cmd -} - -func updateComponent(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - if name == "" { - // if name is empty, use the canonical - name = component - } - - description, err := cyargs.GetComponentDescription(cmd) - if err != nil { - return err - } - - stackRef, err := cyargs.GetStackRef(cmd) - if err != nil { - return err - } - - cloudProvider, err := cyargs.GetCloudProvider(cmd) - if err != nil { - return err - } - - useCase, err := cyargs.GetUseCase(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - currentComponent, _, err := m.GetComponent(org, project, env, component) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "failed to update component '"+component+"', cannot get current component", printer.Options{}) - } - - if stackRef == "" { - stackRef = *currentComponent.ServiceCatalog.Ref - } - - if useCase == "" && currentComponent.UseCase == "" { - return errors.New("cannot determine the use case, please fill it with -(-u)se-case flag") - } else if useCase == "" { - useCase = currentComponent.UseCase - } - - // Resolve stack version: --stack-version (new) or legacy flags; empty = preserve current. - tag, branch, hash, err := cyargs.ResolveStackVersionArg(cmd, m, org, stackRef) - if err != nil { - return errors.Wrap(err, "failed to read stack version flags") - } - - // If no version flag was specified, preserve the current component's version - // instead of defaulting to the catalog's default (which may differ). - if tag == "" && branch == "" && hash == "" { - if currentVersion := ptr.Value(currentComponent.ServiceCatalog.Version); currentVersion != "" { - versions, _, listErr := m.ListStackVersions(org, stackRef) - if listErr == nil { - for _, v := range versions { - if ptr.Value(v.Name) == currentVersion { - if ptr.Value(v.Type) == "tag" { - tag = currentVersion - } else { - branch = currentVersion - } - break - } - } - } - } - } - - var currentConfig = make(models.FormVariables) - if currentComponent.UseCase != "" { - currentConfig, _, err = m.GetComponentConfig(org, project, env, component) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "failed to update component '"+component+"', cannot get current config.", printer.Options{}) - } - } - - inputs, err := cyargs.GetStackformsVars(cmd, currentConfig) - if err != nil { - return err - } - - // CreateComponent will reconfigure the component if it already exists - updatedComponent, _, err := m.CreateOrUpdateComponent(org, project, env, component, *description, name, stackRef, tag, branch, hash, useCase, *cloudProvider, inputs) - return cyout.PrintWithOptions(cmd, updatedComponent, err, "failed to configure component '"+component+"'", printer.Options{}) -} diff --git a/cmd/cycloid/configrepositories/cmd.go b/cmd/cycloid/configrepositories/cmd.go deleted file mode 100644 index 8a2d0eb27..000000000 --- a/cmd/cycloid/configrepositories/cmd.go +++ /dev/null @@ -1,24 +0,0 @@ -package configrepositories - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - var cmd = &cobra.Command{ - Use: "config-repository", - Aliases: []string{ - "config-repo", - "config-repositories", - }, - Short: "Manage the config repositories", - } - - cmd.AddCommand(NewCreateCommand(), - NewUpdateCommand(), - NewDeleteCommand(), - NewListCommand(), - NewGetCommand()) - - return cmd -} diff --git a/cmd/cycloid/configrepositories/create.go b/cmd/cycloid/configrepositories/create.go deleted file mode 100644 index 6c2c2f9a8..000000000 --- a/cmd/cycloid/configrepositories/create.go +++ /dev/null @@ -1,111 +0,0 @@ -package configrepositories - -import ( - stderrors "errors" - "fmt" - "net/http" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "create", - Args: cobra.NoArgs, - Short: "create a config repository", - Example: ` - # create a config repository and set up as default - cy --org my-org config-repo create --branch config --cred my-cred --url "git@github.com:my/repo.git" --name default-config --default -`, - RunE: createConfigRepository, - } - - cmd.MarkFlagRequired(cyargs.AddRepoCredFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddNameFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddRepoBranchFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddRepoURLFlag(cmd)) - cyargs.AddConfigRepositoryFlag(cmd) - cyargs.AddRepoDefaultFlag(cmd) - cmd.Flags().Bool("update", false, "update the config repository if it already exists") - - return cmd -} - -func createConfigRepository(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - canonical, err := cyargs.GetConfigRepository(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - displayName, repoCanonical, err := middleware.NameOrCanonical(&name, &canonical) - if err != nil { - return err - } - - url, err := cyargs.GetRepoURL(cmd) - if err != nil { - return err - } - - branch, err := cyargs.GetRepoBranch(cmd) - if err != nil { - return err - } - - setDefault, err := cyargs.GetRepoDefault(cmd) - if err != nil { - return err - } - - cred, err := cyargs.GetRepoCred(cmd) - if err != nil { - return err - } - - update, err := cmd.Flags().GetBool("update") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - _, _, getErr := m.GetConfigRepository(org, repoCanonical) - exists := getErr == nil - if getErr != nil { - var apiErr *middleware.APIResponseError - if !stderrors.As(getErr, &apiErr) || apiErr.StatusCode != http.StatusNotFound { - return cyout.PrintWithOptions(cmd, nil, getErr, "failed to check if config repository exists", printer.Options{}) - } - } - - if exists && !update { - return cyout.PrintWithOptions(cmd, nil, - fmt.Errorf("config repository %q already exists; use --update or `cy config-repo update`", repoCanonical), - "unable to create config repository", printer.Options{}) - } - - if exists { - cr, _, err := m.UpdateConfigRepository(org, repoCanonical, cred, displayName, url, branch, setDefault) - return cyout.PrintWithOptions(cmd, cr, err, "unable to update config repository", printer.Options{}) - } - - cr, _, err := m.CreateConfigRepository(org, displayName, repoCanonical, url, branch, cred, setDefault) - return cyout.PrintWithOptions(cmd, cr, err, "unable to create config repository", printer.Options{}) -} diff --git a/cmd/cycloid/configrepositories/delete.go b/cmd/cycloid/configrepositories/delete.go deleted file mode 100644 index 54bdcfb18..000000000 --- a/cmd/cycloid/configrepositories/delete.go +++ /dev/null @@ -1,73 +0,0 @@ -package configrepositories - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewDeleteCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "delete [canonical...]", - Aliases: []string{"rm"}, - Args: cyargs.RequireArgsOrFlag("canonical"), - ValidArgsFunction: cyargs.CompleteConfigRepository, - Short: "delete a config repository", - Example: ` - # delete a config repository by canonical - cy --org my-org config-repo delete my-config-repo - - # delete multiple config repositories at once - cy --org my-org config-repo delete repo-one repo-two - - # delete using the deprecated --canonical flag - cy --org my-org config-repo delete --canonical my-config-repo -`, - RunE: deleteConfigRepository, - } - - // Keep --canonical for backward compatibility - can := cyargs.AddConfigRepoCanonicalFlag(cmd) - _ = cmd.Flags().MarkHidden(can) - - return cmd -} - -func deleteConfigRepository(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - if can, err := cyargs.GetConfigRepoCanonical(cmd); err != nil { - return err - } else if can != "" { - found := false - for _, a := range args { - if a == can { - found = true - break - } - } - if !found { - args = append(args, can) - } - } - - deleted := make([]string, 0, len(args)) - for _, can := range args { - _, err = m.DeleteConfigRepository(org, can) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to delete config repository "+can, printer.Options{}) - } - deleted = append(deleted, can) - } - return cyout.PrintWithOptions(cmd, deleted, nil, "", printer.Options{Columns: []string{"Canonical"}}) -} diff --git a/cmd/cycloid/configrepositories/get.go b/cmd/cycloid/configrepositories/get.go deleted file mode 100644 index 90dbca801..000000000 --- a/cmd/cycloid/configrepositories/get.go +++ /dev/null @@ -1,78 +0,0 @@ -package configrepositories - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewGetCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get [canonical...]", - Args: cyargs.RequireArgsOrFlag("canonical"), - ValidArgsFunction: cyargs.CompleteConfigRepository, - Short: "get a config repository", - Example: ` - # get a config repository by canonical - cy --org my-org config-repo get my-config-repo - - # get multiple config repositories at once - cy --org my-org config-repo get repo-one repo-two - - # get using the deprecated --canonical flag - cy --org my-org config-repo get --canonical my-config-repo -o yaml -`, - RunE: getConfigRepository, - } - - // Keep --canonical for backward compatibility - can := cyargs.AddConfigRepoCanonicalFlag(cmd) - _ = cmd.Flags().MarkHidden(can) - cyout.RegisterModel(cmd, models.ConfigRepository{}) - - return cmd -} - -func getConfigRepository(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - if can, err := cyargs.GetConfigRepoCanonical(cmd); err != nil { - return err - } else if can != "" { - found := false - for _, a := range args { - if a == can { - found = true - break - } - } - if !found { - args = append(args, can) - } - } - - if len(args) == 1 { - cr, _, err := m.GetConfigRepository(org, args[0]) - return cyout.PrintWithOptions(cmd, cr, err, "unable to get config repository", configRepoTableOptions) - } - - results := make([]*models.ConfigRepository, 0, len(args)) - for _, can := range args { - cr, _, err := m.GetConfigRepository(org, can) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to get config repository "+can, configRepoTableOptions) - } - results = append(results, cr) - } - return cyout.PrintWithOptions(cmd, results, nil, "", configRepoTableOptions) -} diff --git a/cmd/cycloid/configrepositories/list.go b/cmd/cycloid/configrepositories/list.go deleted file mode 100644 index 95986c8b8..000000000 --- a/cmd/cycloid/configrepositories/list.go +++ /dev/null @@ -1,45 +0,0 @@ -package configrepositories - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var configRepoTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "URL", "Branch", "Default"}, - Identifier: "Canonical", -} - -func NewListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "list the config repositories", - Example: ` - # list the config repositories in the org 'my-org' and display the result in JSON format - cy --org my-org config-repo list -o json -`, - RunE: listConfigRepositories, - } - cyout.RegisterModel(cmd, models.ConfigRepository{}) - return cmd -} - -func listConfigRepositories(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - crs, _, err := m.ListConfigRepositories(org) - return cyout.PrintWithOptions(cmd, crs, err, "unable to list config repositories", configRepoTableOptions) -} diff --git a/cmd/cycloid/configrepositories/update.go b/cmd/cycloid/configrepositories/update.go deleted file mode 100644 index f13e63e75..000000000 --- a/cmd/cycloid/configrepositories/update.go +++ /dev/null @@ -1,76 +0,0 @@ -package configrepositories - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUpdateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "update", - Args: cobra.NoArgs, - Short: "update a config repository", - Example: ` - # update a config repository - cy --org my-org config-repo update --branch my-branch --cred my-cred --url "git@github.com:my/repo.git" --name my-config-name --canonical my-config-repo -`, - RunE: updateConfigRepository, - } - - cmd.MarkFlagRequired(cyargs.AddConfigRepoCanonicalFlag(cmd)) - cyargs.AddRepoCredFlag(cmd) - cmd.MarkFlagRequired(cyargs.AddNameFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddRepoBranchFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddRepoURLFlag(cmd)) - cyargs.AddRepoDefaultFlag(cmd) - - return cmd -} - -func updateConfigRepository(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - can, err := cyargs.GetCatalogRepoCanonical(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - url, err := cyargs.GetRepoURL(cmd) - if err != nil { - return err - } - - branch, err := cyargs.GetRepoBranch(cmd) - if err != nil { - return err - } - - setDefault, err := cyargs.GetRepoDefault(cmd) - if err != nil { - return err - } - - cred, err := cyargs.GetRepoCred(cmd) - if err != nil { - return err - } - - cr, _, err := m.UpdateConfigRepository(org, can, cred, name, url, branch, setDefault) - return cyout.PrintWithOptions(cmd, cr, err, "unable to update config repository", printer.Options{}) -} diff --git a/cmd/cycloid/credentials/cmd.go b/cmd/cycloid/credentials/cmd.go deleted file mode 100644 index 8e8466e2c..000000000 --- a/cmd/cycloid/credentials/cmd.go +++ /dev/null @@ -1,28 +0,0 @@ -package credentials - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - var cmd = &cobra.Command{ - Use: "credential", - Aliases: []string{ - "creds", - "cred", - "credentials", - "c", - }, - Short: "Manage the credentials", - } - - cmd.AddCommand( - NewCreateCommand(), - NewUpdateCommand(), - NewDeleteCommand(), - NewListCommand(), - NewGetCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/credentials/common.go b/cmd/cycloid/credentials/common.go deleted file mode 100644 index 31b2c635b..000000000 --- a/cmd/cycloid/credentials/common.go +++ /dev/null @@ -1,11 +0,0 @@ -package credentials - -import ( - "regexp" -) - -func pathFromCanonical(canonical string) string { - re := regexp.MustCompile(`[^a-zA-z0-9_\-./]`) - safePath := re.ReplaceAllString(canonical, "-") - return safePath -} diff --git a/cmd/cycloid/credentials/create.go b/cmd/cycloid/credentials/create.go deleted file mode 100644 index 84344315e..000000000 --- a/cmd/cycloid/credentials/create.go +++ /dev/null @@ -1,276 +0,0 @@ -package credentials - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "create [ssh|basic_auth|custom|aws|azure|azure_storage|gcp|elasticsearch|swift]", - Short: "create a credential", - Example: `# create a credential for basic authentication - cy --org my-org credential create basic_auth --name foo --username my-username --password my-password - - # create a credential for SSH - cy --org my-org credential create ssh --name foo --ssh-key /path/to/private/key - - # create a credential for AWS - cy --org my-org credential create aws --name foo --access-key foo --secret-key bar - - # create a credential for Azure - cy --org my-org credential create azure --name foo --client-id myid --client-secret mysec --subscription-id mysub --tenant-id mytenant - - # create a credential for Azure storage - cy --org my-org credential create azure_storage --name foo --account-name myaccount --access-key mykey - - # create a credential for GCP - cy --org my-org credential create gcp --name foo --json-key /path/to/json/key - - # create a credential for Elasticsearch - cy --org my-org credential create elasticsearch --name foo --username foo --password bar --ca-cert /path/to/cert - - # create a credential for Swift - cy --org my-org credential create swift --name foo --username foo --password bar --tenant-id mytenant --auth-url url --domain-id mydomain -`, - } - cyargs.AddCredentialNamePersistentFlag(cmd) - cyargs.AddCredentialDescriptionPersistentFlag(cmd) - cmd.MarkFlagRequired(cyargs.AddCredentialCanonicalPersistentFlag(cmd)) - cyargs.AddCredentialPathPersistentFlag(cmd) - cmd.PersistentFlags().Bool(cyargs.UpdateFlag, false, "update this credential if it already exists.") - - var sshCmd = &cobra.Command{ - Use: "ssh", - Args: cobra.NoArgs, - RunE: create, - Example: ` - # create a credential for SSH - cy --org my-org credential create ssh --name foo --ssh-key /path/to/private/key -`, - } - sshCmd.MarkFlagRequired(cyargs.AddCredentialSSHKeyFlag(sshCmd)) - - var basicAuthCmd = &cobra.Command{ - Use: "basic_auth", - Args: cobra.NoArgs, - RunE: create, - Example: ` - # create a credential for basic authentication - cy --org my-org credential create basic_auth --name foo --username my-username --password my-password -`, - } - cyargs.AddCredentialUsernameFlag(basicAuthCmd) - cyargs.AddCredentialPasswordFlag(basicAuthCmd) - - var customCmd = &cobra.Command{ - Use: "custom", - Args: cobra.NoArgs, - RunE: create, - Example: ` - # create a credential for custom type - cy --org my-org credential create custom --name foo --field my-key=my-value --field my-key2=my-value2 --field-file my-key3=/file/path -`, - } - cyargs.AddCredentialFieldFlag(customCmd) - cyargs.AddCredentialFieldFileFlag(customCmd) - - var awsCmd = &cobra.Command{ - Use: "aws", - Args: cobra.NoArgs, - RunE: create, - Example: ` - # create a credential for AWS - cy --org my-org credential create aws --name foo --access-key foo --secret-key bar -`, - } - awsCmd.MarkFlagRequired(cyargs.AddCredentialAccessKeyFlag(awsCmd)) - awsCmd.MarkFlagRequired(cyargs.AddCredentialSecretKeyFlag(awsCmd)) - - var azureCmd = &cobra.Command{ - Use: "azure", - Args: cobra.NoArgs, - RunE: create, - Example: ` - # create a credential for Azure - cy --org my-org credential create azure --name foo --client-id myid --client-secret mysec --subscription-id mysub --tenant-id mytenant -`, - } - azureCmd.MarkFlagRequired(cyargs.AddCredentialClientIDFlag(azureCmd)) - azureCmd.MarkFlagRequired(cyargs.AddCredentialClientSecretFlag(azureCmd)) - azureCmd.MarkFlagRequired(cyargs.AddCredentialSubscriptionIDFlag(azureCmd)) - azureCmd.MarkFlagRequired(cyargs.AddCredentialTenantIDFlag(azureCmd)) - - var azureStorageCmd = &cobra.Command{ - Use: "azure_storage", - Args: cobra.NoArgs, - RunE: create, - Example: ` - # create a credential for Azure storage - cy --org my-org credential create azure_storage --name foo --account-name myaccount --access-key mykey -`, - } - azureStorageCmd.MarkFlagRequired(cyargs.AddCredentialAccountNameFlag(azureStorageCmd)) - azureStorageCmd.MarkFlagRequired(cyargs.AddCredentialAccessKeyFlag(azureStorageCmd)) - - var gcpCmd = &cobra.Command{ - Use: "gcp", - Args: cobra.NoArgs, - RunE: create, - Example: ` - # create a credential for GCP - cy --org my-org credential create gcp --name foo --json-key /path/to/json/key -`, - } - gcpCmd.MarkFlagRequired(cyargs.AddCredentialJSONKeyFlag(gcpCmd)) - - var swiftCmd = &cobra.Command{ - Use: "swift", - Args: cobra.NoArgs, - RunE: create, - Example: ` - # create a credential for Swift - cy --org my-org credential create swift --name foo --username foo --password bar --tenant-id mytenant --auth-url url --domain-id mydomain -`, - } - swiftCmd.MarkFlagRequired(cyargs.AddCredentialUsernameFlag(swiftCmd)) - swiftCmd.MarkFlagRequired(cyargs.AddCredentialPasswordFlag(swiftCmd)) - swiftCmd.MarkFlagRequired(cyargs.AddCredentialTenantIDFlag(swiftCmd)) - swiftCmd.MarkFlagRequired(cyargs.AddCredentialAuthURLFlag(swiftCmd)) - swiftCmd.MarkFlagRequired(cyargs.AddCredentialDomainIDFlag(swiftCmd)) - - var elasticsearchCmd = &cobra.Command{ - Use: "elasticsearch", - Args: cobra.NoArgs, - RunE: create, - Example: ` - # create a credential for Elasticsearch - cy --org my-org credential create elasticsearch --name foo --username foo --password bar --ca-cert /path/to/cert -`, - } - cyargs.AddCredentialUsernameFlag(elasticsearchCmd) - cyargs.AddCredentialPasswordFlag(elasticsearchCmd) - elasticsearchCmd.MarkFlagRequired(cyargs.AddCredentialCaCertFlag(elasticsearchCmd)) - - cmd.AddCommand( - customCmd, - basicAuthCmd, - sshCmd, - awsCmd, - azureCmd, - azureStorageCmd, - gcpCmd, - swiftCmd, - elasticsearchCmd, - ) - - return cmd -} - -func create(cmd *cobra.Command, args []string) error { - credentialType := cmd.CalledAs() - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - credential, err := cyargs.GetCredentialCanonical(cmd) - if err != nil { - return err - } - - name, _ := cyargs.GetCredentialName(cmd) - if name == "" { - name = credential - } - - credentialPath, _ := cyargs.GetCredentialPath(cmd) - credentialPath = defaultCredentialPath(credentialPath, credential, name) - - description, err := cyargs.GetCredentialDescription(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - if cyargs.GetUpdate(cmd) { - creds, _, err := m.ListCredentials(org, credentialType) - if err != nil { - return fmt.Errorf("failed to create --update credential, cannot check for existing credential (canonical=%q path=%q name=%q): %w", - credential, credentialPath, name, err) - } - - existingCredential := findCredentialForUpdate(creds, credential, credentialPath, name) - if existingCredential != nil { - // update requires the canonical in the route: infer it when the user identified - // the credential by path/name (the common create --name --update flow). - if credential == "" && existingCredential.Canonical != nil { - credential = *existingCredential.Canonical - if err := cmd.Flags().Set("canonical", credential); err != nil { - return fmt.Errorf("failed to set credential canonical before update: %w", err) - } - } - - return update(cmd, args) - } - } - - rawCred, err := BuildCredentialRaw(cmd, credentialType) - if err != nil { - return err - } - - outCredential, _, err := m.CreateCredential(org, name, credentialType, rawCred, credentialPath, credential, description) - return cyout.PrintWithOptions(cmd, outCredential, err, "unable to create credential", printer.Options{}) -} - -func defaultCredentialPath(path, canonical, name string) string { - if path != "" { - return path - } - if canonical != "" { - return pathFromCanonical(canonical) - } - if name != "" { - return pathFromCanonical(name) - } - return "" -} - -func findCredentialForUpdate(creds []*models.CredentialSimple, canonical, path, name string) *models.CredentialSimple { - if canonical != "" { - for _, credential := range creds { - if credential != nil && credential.Canonical != nil && *credential.Canonical == canonical { - return credential - } - } - } - - if path != "" { - for _, credential := range creds { - if credential != nil && credential.Path != nil && *credential.Path == path { - return credential - } - } - } - - if name != "" { - for _, credential := range creds { - if credential != nil && credential.Name != nil && *credential.Name == name { - return credential - } - } - } - - return nil -} diff --git a/cmd/cycloid/credentials/create_test.go b/cmd/cycloid/credentials/create_test.go deleted file mode 100644 index 8fa24446b..000000000 --- a/cmd/cycloid/credentials/create_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package credentials - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func TestDefaultCredentialPath(t *testing.T) { - t.Run("keep explicit path", func(t *testing.T) { - assert.Equal(t, "explicit-path", defaultCredentialPath("explicit-path", "canonical", "name")) - }) - - t.Run("fallback to canonical", func(t *testing.T) { - assert.Equal(t, "my-canonical", defaultCredentialPath("", "my-canonical", "name")) - }) - - t.Run("fallback to name when canonical missing", func(t *testing.T) { - assert.Equal(t, "my-name", defaultCredentialPath("", "", "my-name")) - }) - - t.Run("CLI-104 name-only derives path like create", func(t *testing.T) { - assert.Equal(t, "testflotmp", defaultCredentialPath("", "", "testflotmp")) - }) - - t.Run("empty when no identifier", func(t *testing.T) { - assert.Equal(t, "", defaultCredentialPath("", "", "")) - }) -} - -func TestFindCredentialForUpdate(t *testing.T) { - credentials := []*models.CredentialSimple{ - { - Canonical: ptr("cred-canonical"), - Path: ptr("cred-path"), - Name: ptr("cred-name"), - }, - { - Canonical: ptr("another-canonical"), - Path: ptr("another-path"), - Name: ptr("another-name"), - }, - } - - t.Run("match by canonical first", func(t *testing.T) { - got := findCredentialForUpdate(credentials, "cred-canonical", "another-path", "another-name") - assert.NotNil(t, got) - assert.Equal(t, "cred-canonical", *got.Canonical) - }) - - t.Run("match by path when canonical missing", func(t *testing.T) { - got := findCredentialForUpdate(credentials, "", "cred-path", "") - assert.NotNil(t, got) - assert.Equal(t, "cred-canonical", *got.Canonical) - }) - - t.Run("match by name when canonical and path missing", func(t *testing.T) { - got := findCredentialForUpdate(credentials, "", "", "cred-name") - assert.NotNil(t, got) - assert.Equal(t, "cred-canonical", *got.Canonical) - }) - - // CLI-104: `create --name X --update` leaves canonical empty; path defaults from name (e.g. testflotmp). - t.Run("match by path from name defaulting (CLI-104)", func(t *testing.T) { - issue := []*models.CredentialSimple{ - { - Canonical: ptr("testflotmp"), - Path: ptr("testflotmp"), - Name: ptr("testflotmp"), - }, - } - got := findCredentialForUpdate(issue, "", "testflotmp", "testflotmp") - assert.NotNil(t, got) - assert.Equal(t, "testflotmp", *got.Canonical) - }) - - t.Run("no match", func(t *testing.T) { - got := findCredentialForUpdate(credentials, "", "missing-path", "missing-name") - assert.Nil(t, got) - }) -} - -func ptr(value string) *string { - return &value -} diff --git a/cmd/cycloid/credentials/delete.go b/cmd/cycloid/credentials/delete.go deleted file mode 100644 index e4709e707..000000000 --- a/cmd/cycloid/credentials/delete.go +++ /dev/null @@ -1,85 +0,0 @@ -package credentials - -import ( - "fmt" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - "golang.org/x/exp/slices" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewDeleteCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "delete [canonicals...]", - Args: cobra.OnlyValidArgs, - ValidArgsFunction: cyargs.CompleteCredentialCanonical, - Short: "delete a credential", - Example: `# Delete 3 credentials: -cy --org my-org credential delete credential-canonical-1 credential-canonical-2 --canonical credential-canonical-3`, - RunE: del, - } - - cyargs.AddCredentialCanonicalFlag(cmd) - cyargs.AddCredentialPathFlag(cmd) - return cmd -} - -func del(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - credentialFlag, _ := cyargs.GetCredentialCanonical(cmd) - credentialPath, _ := cyargs.GetCredentialPath(cmd) - if credentialPath == "" && credentialFlag == "" && len(args) == 0 { - return errors.New("please fill --canonical or --path flags or pass canonicals as arguments") - } - - if credentialPath != "" && credentialFlag == "" { - credList, _, err := m.ListCredentials(org, "") - if err != nil { - return fmt.Errorf("failed to fetch cred list to match credential by path %q: %w", credentialPath, err) - } - - index := slices.IndexFunc(credList, func(c *models.CredentialSimple) bool { - if c.Path != nil { - return *c.Path == credentialPath - } else { - return false - } - }) - if index == -1 || credList[index].Canonical == nil { - return fmt.Errorf("credential with path %q not found in org %q", credentialPath, org) - } - - credentialFlag = *credList[index].Canonical - } - - credList := append(args, credentialFlag) - - for _, credential := range credList { - if credential == "" { - continue - } - - _, err := m.DeleteCredential(org, credential) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, fmt.Sprintf("unable to delete credential '%s'", credential), printer.Options{}) - } - - fmt.Fprintf(cmd.OutOrStderr(), "successfully deleted credential '%s'\n", credential) - } - - return nil -} diff --git a/cmd/cycloid/credentials/get.go b/cmd/cycloid/credentials/get.go deleted file mode 100644 index 8e8e9214a..000000000 --- a/cmd/cycloid/credentials/get.go +++ /dev/null @@ -1,114 +0,0 @@ -package credentials - -import ( - "fmt" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - "golang.org/x/exp/slices" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -// credentialGetTableOptions excludes the Raw field (sensitive) but shows Keys. -var credentialGetTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "Type", "Path", "Keys"}, - Identifier: "Canonical", -} - -func NewGetCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get [canonical...]", - Args: cobra.ArbitraryArgs, - ValidArgsFunction: cyargs.CompleteCredentialCanonical, - Short: "get a credential", - Example: ` - # get a credential by canonical - cy --org my-org credential get credential-canonical - - # get multiple credentials - cy --org my-org credential get cred-a cred-b - - # get a credential by path - cy --org my-org credential get --path /my/secret/path -`, - RunE: get, - } - - cyargs.AddCredentialCanonicalFlag(cmd) - cyargs.AddCredentialPathFlag(cmd) - cyout.RegisterModel(cmd, models.Credential{}) - return cmd -} - -func get(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - credentialFlag, _ := cyargs.GetCredentialCanonical(cmd) - credentialPath, _ := cyargs.GetCredentialPath(cmd) - - if credentialFlag != "" { - found := false - for _, a := range args { - if a == credentialFlag { - found = true - break - } - } - if !found { - args = append(args, credentialFlag) - } - } - - // Multi-arg mode - if len(args) > 1 && credentialPath == "" { - results := make([]*models.Credential, 0, len(args)) - for _, canonical := range args { - c, _, err := m.GetCredential(org, canonical) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to get credential "+canonical, credentialGetTableOptions) - } - results = append(results, c) - } - return cyout.PrintWithOptions(cmd, results, nil, "", credentialGetTableOptions) - } - - // Single credential: path > positional arg - var credential string - if credentialPath != "" { - credList, _, err := m.ListCredentials(org, "") - if err != nil { - return fmt.Errorf("failed to fetch cred list to match credential by path %q: %w", credentialPath, err) - } - - index := slices.IndexFunc(credList, func(c *models.CredentialSimple) bool { - if c.Path != nil { - return *c.Path == credentialPath - } - return false - }) - if index == -1 || credList[index].Canonical == nil { - return fmt.Errorf("credential with path %q not found in org %q", credentialPath, org) - } - - credential = *credList[index].Canonical - } else if len(args) == 1 { - credential = args[0] - } else { - return errors.New("please fill --canonical or --path flags or as argument") - } - - c, _, err := m.GetCredential(org, credential) - return cyout.PrintWithOptions(cmd, c, err, "unable to get credential from API", credentialGetTableOptions) -} diff --git a/cmd/cycloid/credentials/list.go b/cmd/cycloid/credentials/list.go deleted file mode 100644 index bc457b7b3..000000000 --- a/cmd/cycloid/credentials/list.go +++ /dev/null @@ -1,48 +0,0 @@ -package credentials - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var credentialTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "Type", "Path", "Keys"}, - Identifier: "Canonical", -} - -func NewListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "list the credentials", - Example: `cy --org my-org credentials list -o json`, - RunE: list, - } - - cyargs.AddCredentialTypeFlag(cmd) - cyout.RegisterModel(cmd, models.CredentialSimple{}) - return cmd -} - -func list(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - credT, err := cyargs.GetCredentialType(cmd) - if err != nil { - return err - } - - creds, _, err := m.ListCredentials(org, credT) - return cyout.PrintWithOptions(cmd, creds, err, "unable to list credentials", credentialTableOptions) -} diff --git a/cmd/cycloid/credentials/raw.go b/cmd/cycloid/credentials/raw.go deleted file mode 100644 index 7b13ec1f2..000000000 --- a/cmd/cycloid/credentials/raw.go +++ /dev/null @@ -1,202 +0,0 @@ -package credentials - -import ( - "fmt" - "os" - "strings" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/internal/cyargs" -) - -// AddAllRawFlags registers every flag that any credential type may consume. -// Use this when a single command needs to accept any credential type inline -// (e.g. `cy cloud-account create --new-credential aws --access-key …`). -// -// Per-type subcommands (used by `cy credential create `) should keep -// registering only the flags they need to preserve a tight UX. -func AddAllRawFlags(cmd *cobra.Command) { - cyargs.AddCredentialCanonicalFlag(cmd) - cyargs.AddCredentialPathFlag(cmd) - cyargs.AddCredentialSSHKeyFlag(cmd) - cyargs.AddCredentialUsernameFlag(cmd) - cyargs.AddCredentialPasswordFlag(cmd) - cyargs.AddCredentialFieldFlag(cmd) - cyargs.AddCredentialFieldFileFlag(cmd) - cyargs.AddCredentialAccessKeyFlag(cmd) - cyargs.AddCredentialSecretKeyFlag(cmd) - cyargs.AddCredentialClientIDFlag(cmd) - cyargs.AddCredentialClientSecretFlag(cmd) - cyargs.AddCredentialSubscriptionIDFlag(cmd) - cyargs.AddCredentialTenantIDFlag(cmd) - cyargs.AddCredentialAccountNameFlag(cmd) - cyargs.AddCredentialJSONKeyFlag(cmd) - cyargs.AddCredentialCaCertFlag(cmd) - cyargs.AddCredentialAuthURLFlag(cmd) - cyargs.AddCredentialDomainIDFlag(cmd) -} - -// BuildCredentialRaw extracts the raw credential payload from the command flags -// based on credType. Shared by `cy credential` per-type subcommands and -// `cy cloud-account` inline credential creation so both stay in sync. -func BuildCredentialRaw(cmd *cobra.Command, credType string) (*models.CredentialRaw, error) { - switch credType { - case "ssh": - sshKeyPath, err := cyargs.GetCredentialSSHKey(cmd) - if err != nil { - return nil, err - } - sshKey, err := os.ReadFile(sshKeyPath) - if err != nil { - return nil, errors.Wrap(err, "unable to read SSH key") - } - return &models.CredentialRaw{SSHKey: string(sshKey)}, nil - - case "basic_auth": - username, err := cyargs.GetCredentialUsername(cmd) - if err != nil { - return nil, err - } - password, err := cyargs.GetCredentialPassword(cmd) - if err != nil { - return nil, err - } - return &models.CredentialRaw{Username: username, Password: password}, nil - - case "custom": - fields, err := cyargs.GetCredentialField(cmd) - if err != nil { - return nil, err - } - fileFields, err := cyargs.GetCredentialFieldFile(cmd) - if err != nil { - return nil, err - } - if len(fields) == 0 && len(fileFields) == 0 { - return nil, fmt.Errorf("at least one --field or --field-file has to be specified") - } - for field, path := range fileFields { - content, err := os.ReadFile(path) - if err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("unable to read file at path %q", path)) - } - fields[field] = strings.TrimSuffix(string(content), "\n") - } - return &models.CredentialRaw{Raw: fields}, nil - - case "aws": - accessKey, err := cyargs.GetCredentialAccessKey(cmd) - if err != nil { - return nil, err - } - secretKey, err := cyargs.GetCredentialSecretKey(cmd) - if err != nil { - return nil, err - } - return &models.CredentialRaw{AccessKey: accessKey, SecretKey: secretKey}, nil - - case "azure": - clientID, err := cyargs.GetCredentialClientID(cmd) - if err != nil { - return nil, err - } - clientSecret, err := cyargs.GetCredentialClientSecret(cmd) - if err != nil { - return nil, err - } - subscriptionID, err := cyargs.GetCredentialSubscriptionID(cmd) - if err != nil { - return nil, err - } - tenantID, err := cyargs.GetCredentialTenantID(cmd) - if err != nil { - return nil, err - } - return &models.CredentialRaw{ - ClientID: clientID, - ClientSecret: clientSecret, - SubscriptionID: subscriptionID, - TenantID: tenantID, - }, nil - - case "azure_storage": - accessKey, err := cyargs.GetCredentialAccessKey(cmd) - if err != nil { - return nil, err - } - accountName, err := cyargs.GetCredentialAccountName(cmd) - if err != nil { - return nil, err - } - return &models.CredentialRaw{AccessKey: accessKey, AccountName: accountName}, nil - - case "gcp": - jsonKeyPath, err := cyargs.GetCredentialJSONKey(cmd) - if err != nil { - return nil, err - } - jsonKey, err := os.ReadFile(jsonKeyPath) - if err != nil { - return nil, errors.Wrap(err, "unable to read JSON key") - } - return &models.CredentialRaw{JSONKey: string(jsonKey)}, nil - - case "elasticsearch": - username, err := cyargs.GetCredentialUsername(cmd) - if err != nil { - return nil, err - } - password, err := cyargs.GetCredentialPassword(cmd) - if err != nil { - return nil, err - } - caCertPath, err := cyargs.GetCredentialCaCert(cmd) - if err != nil { - return nil, err - } - caCert, err := os.ReadFile(caCertPath) - if err != nil { - return nil, errors.Wrap(err, "unable to read CA cert") - } - return &models.CredentialRaw{ - Username: username, - Password: password, - CaCert: string(caCert), - }, nil - - case "swift": - username, err := cyargs.GetCredentialUsername(cmd) - if err != nil { - return nil, err - } - password, err := cyargs.GetCredentialPassword(cmd) - if err != nil { - return nil, err - } - tenantID, err := cyargs.GetCredentialTenantID(cmd) - if err != nil { - return nil, err - } - authURL, err := cyargs.GetCredentialAuthURL(cmd) - if err != nil { - return nil, err - } - domainID, err := cyargs.GetCredentialDomainID(cmd) - if err != nil { - return nil, err - } - return &models.CredentialRaw{ - Username: username, - Password: password, - TenantID: tenantID, - AuthURL: authURL, - DomainID: domainID, - }, nil - - default: - return nil, fmt.Errorf("unsupported credential type %q", credType) - } -} diff --git a/cmd/cycloid/credentials/update.go b/cmd/cycloid/credentials/update.go deleted file mode 100644 index 914905932..000000000 --- a/cmd/cycloid/credentials/update.go +++ /dev/null @@ -1,243 +0,0 @@ -package credentials - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUpdateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "update [ssh|basic_auth|custom|aws|azure|azure_storage|gcp|elasticsearch|swift]", - Args: cobra.NoArgs, - Short: "update a credential", - Example: ` - # update a credential for basic authentication - cy --org my-org credential update basic_auth --name foo --username my-username --password my-password - - # update a credential for SSH - cy --org my-org credential update ssh --name foo --ssh-key /path/to/private/key - - # update a credential for AWS - cy --org my-org credential update aws --name foo --access-key foo --secret-key bar - - # update a credential for Azure - cy --org my-org credential update azure --name foo --client-id myid --client-secret mysec --subscription-id mysub --tenant-id mytenant - - # update a credential for Azure storage - cy --org my-org credential update azure_storage --name foo --account-name myaccount --access-key mykey - - # update a credential for GCP - cy --org my-org credential update gcp --name foo --json-key /path/to/json/key - - # update a credential for Elasticsearch - cy --org my-org credential update elasticsearch --name foo --username foo --password bar --ca-cert /path/to/cert - - # update a credential for Swift - cy --org my-org credential update swift --name foo --username foo --password bar --tenant-id mytenant --auth-url url --domain-id mydomain -`, - } - - cyargs.AddCredentialNamePersistentFlag(cmd) - cyargs.AddCredentialDescriptionPersistentFlag(cmd) - cyargs.AddCredentialCanonicalPersistentFlag(cmd) - cyargs.AddCredentialPathPersistentFlag(cmd) - cmd.PersistentFlags().Bool(cyargs.UpdateFlag, false, "update this credential if it already exists.") - if err := cmd.PersistentFlags().MarkHidden(cyargs.UpdateFlag); err != nil { - panic(fmt.Sprintf("We should be able to mark this flag hidden: %s", err.Error())) - } - - // SSH - var sshCmd = &cobra.Command{ - Use: "ssh", - Args: cobra.NoArgs, - RunE: update, - Example: ` - # update a credential for SSH - cy --org my-org credential update ssh --name foo --ssh-key /path/to/private/key -`, - } - sshCmd.MarkFlagRequired(cyargs.AddCredentialSSHKeyFlag(sshCmd)) - - // Basic auth - var basicAuthCmd = &cobra.Command{ - Use: "basic_auth", - Args: cobra.NoArgs, - RunE: update, - Example: ` - # update a credential for basic authentication - cy --org my-org credential update basic_auth --name foo --username my-username --password my-password -`, - } - cyargs.AddCredentialUsernameFlag(basicAuthCmd) - cyargs.AddCredentialPasswordFlag(basicAuthCmd) - - // Custom - var customCmd = &cobra.Command{ - Use: "custom", - Args: cobra.NoArgs, - RunE: update, - Example: ` - # update a credential for custom type - cy --org my-org credential update custom --name foo --field my-key=my-value --field my-key2=my-value2 --field-file my-key3=/file/path -`, - } - - cyargs.AddCredentialFieldFlag(customCmd) - cyargs.AddCredentialFieldFileFlag(customCmd) - - // AWS - var awsCmd = &cobra.Command{ - Use: "aws", - Args: cobra.NoArgs, - RunE: update, - Example: ` - # update a credential for AWS - cy --org my-org credential update aws --name foo --access-key foo --secret-key bar -`, - } - awsCmd.MarkFlagRequired(cyargs.AddCredentialAccessKeyFlag(awsCmd)) - awsCmd.MarkFlagRequired(cyargs.AddCredentialSecretKeyFlag(awsCmd)) - - // Azure - var azureCmd = &cobra.Command{ - Use: "azure", - Args: cobra.NoArgs, - RunE: update, - Example: ` - # update a credential for Azure - cy --org my-org credential update azure --name foo --client-id myid --client-secret mysec --subscription-id mysub --tenant-id mytenant -`, - } - azureCmd.MarkFlagRequired(cyargs.AddCredentialClientIDFlag(azureCmd)) - azureCmd.MarkFlagRequired(cyargs.AddCredentialClientSecretFlag(azureCmd)) - azureCmd.MarkFlagRequired(cyargs.AddCredentialSubscriptionIDFlag(azureCmd)) - azureCmd.MarkFlagRequired(cyargs.AddCredentialTenantIDFlag(azureCmd)) - - // Azure Storage - var azureStorageCmd = &cobra.Command{ - Use: "azure_storage", - Args: cobra.NoArgs, - RunE: update, - Example: ` - # update a credential for Azure storage - cy --org my-org credential update azure_storage --name foo --account-name myaccount --access-key mykey -`, - } - azureStorageCmd.MarkFlagRequired(cyargs.AddCredentialAccountNameFlag(azureStorageCmd)) - azureStorageCmd.MarkFlagRequired(cyargs.AddCredentialAccessKeyFlag(azureStorageCmd)) - - // GCP - var gcpCmd = &cobra.Command{ - Use: "gcp", - Args: cobra.NoArgs, - RunE: update, - Example: ` - # update a credential for GCP - cy --org my-org credential update gcp --name foo --json-key /path/to/json/key -`, - } - gcpCmd.MarkFlagRequired(cyargs.AddCredentialJSONKeyFlag(gcpCmd)) - - // Swift - var swiftCmd = &cobra.Command{ - Use: "swift", - Args: cobra.NoArgs, - RunE: update, - Example: ` - # update a credential for Swift - cy --org my-org credential update swift --name foo --username foo --password bar --tenant-id mytenant --auth-url url --domain-id mydomain -`, - } - swiftCmd.MarkFlagRequired(cyargs.AddCredentialUsernameFlag(swiftCmd)) - swiftCmd.MarkFlagRequired(cyargs.AddCredentialPasswordFlag(swiftCmd)) - swiftCmd.MarkFlagRequired(cyargs.AddCredentialTenantIDFlag(swiftCmd)) - swiftCmd.MarkFlagRequired(cyargs.AddCredentialAuthURLFlag(swiftCmd)) - swiftCmd.MarkFlagRequired(cyargs.AddCredentialDomainIDFlag(swiftCmd)) - - // Elasticsearch - var elasticsearchCmd = &cobra.Command{ - Use: "elasticsearch", - Args: cobra.NoArgs, - RunE: update, - Example: ` - # update a credential for Elasticsearch - cy --org my-org credential update elasticsearch --name foo --username foo --password bar --ca-cert /path/to/cert -`, - } - - cyargs.AddCredentialUsernameFlag(elasticsearchCmd) - cyargs.AddCredentialPasswordFlag(elasticsearchCmd) - elasticsearchCmd.MarkFlagRequired(cyargs.AddCredentialCaCertFlag(elasticsearchCmd)) - - // Command - cmd.AddCommand( - customCmd, - basicAuthCmd, - sshCmd, - awsCmd, - azureCmd, - azureStorageCmd, - gcpCmd, - swiftCmd, - elasticsearchCmd, - ) - - return cmd -} - -// /organizations/{organization_canonical}/credentials/{credential_id} -// put: updateCredential -// Update an existing Credential, based on the type you will have to pass different parameters within the body: -// * ssh: ssh_key -// * aws: access_key, secret_key -// * gcp: json_key -// * azure: client_id, client_secret, subscription_id, tenant_id -// * azure_storage: account_name, access_key -// * basic_auth: username, password -// * elasticsearch: username, password, ca_cert -// * swift: auth_url, username, password, domain_id, tenant_id -func update(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - credT := cmd.CalledAs() - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - credential, err := cyargs.GetCredentialCanonical(cmd) - if err != nil { - return err - } - - name, _ := cyargs.GetCredentialName(cmd) - if name == "" { - name = credential - } - - credentialPath, _ := cyargs.GetCredentialPath(cmd) - if credentialPath == "" { - credentialPath = pathFromCanonical(credential) - } - - description, err := cyargs.GetCredentialDescription(cmd) - if err != nil { - return err - } - - rawCred, err := BuildCredentialRaw(cmd, credT) - if err != nil { - return err - } - - outCred, _, err := m.UpdateCredential(org, name, credT, rawCred, credentialPath, credential, description) - return cyout.PrintWithOptions(cmd, outCred, err, "unable to update credential", printer.Options{}) -} diff --git a/cmd/cycloid/environments/cmd.go b/cmd/cycloid/environments/cmd.go deleted file mode 100644 index 89997b71b..000000000 --- a/cmd/cycloid/environments/cmd.go +++ /dev/null @@ -1,29 +0,0 @@ -package environments - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - var cmd = &cobra.Command{ - Use: "environment", - Aliases: []string{ - "e", - "env", - "environments", - }, - Short: "Manage organization environments.", - } - - cmd.AddCommand( - NewDeleteCommand(), - NewCreateCommand(), - NewListCommand(), - NewGetCommand(), - NewUpdateCommand(), - NewLinkCommand(), - NewUnlinkCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/environments/create.go b/cmd/cycloid/environments/create.go deleted file mode 100644 index 1a3d0a323..000000000 --- a/cmd/cycloid/environments/create.go +++ /dev/null @@ -1,52 +0,0 @@ -package environments - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "create", - Args: cobra.NoArgs, - Short: "create an environment", - Example: `cy --org my-org environment create --env my-environment --name "My Environment"`, - RunE: create, - } - - cyargs.AddEnvironmentTypeFlag(cmd) - cyargs.AddDescriptionFlag(cmd) - cyargs.AddEnvironmentOwnerFlag(cmd) - cyargs.AddCloudAccountCanonicalsFlag(cmd) - cyargs.AddEnvironmentVariablesFlag(cmd) - cyargs.AddEnvironmentVariablesFileFlag(cmd) - _ = cmd.Flags().MarkDeprecated(cyargs.AddColorFlag(cmd), "color now lives on environment-type and will be ignored") - cyargs.AddUpdateFlag(cmd, "if set, will update the environment if it exists.") - cyargs.AddNameFlag(cmd) - cyargs.AddEnvFlag(cmd) - cmd.MarkFlagsOneRequired("name", "env") - return cmd -} - -func create(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - env, err := cyargs.GetEnvOrEmpty(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, err := createOrUpdateEnvironment(cmd, m, org, env, cyargs.GetUpdate(cmd)) - return cyout.PrintWithOptions(cmd, result, err, "failed to create environment", printer.Options{}) -} diff --git a/cmd/cycloid/environments/delete.go b/cmd/cycloid/environments/delete.go deleted file mode 100644 index ff3620b94..000000000 --- a/cmd/cycloid/environments/delete.go +++ /dev/null @@ -1,72 +0,0 @@ -package environments - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewDeleteCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "delete [canonical...]", - Args: cyargs.RequireArgsOrFlag("env"), - Aliases: []string{"del", "rm"}, - Short: "delete an environment", - Example: ` - # delete an environment using the --env flag - cy --org my-org environment delete --env my-env - - # delete multiple environments using positional args - cy --org my-org environment delete env-a env-b -`, - RunE: deleteEnvironment, - } - - cyargs.AddEnvFlag(cmd) - cyargs.AddProjectFlag(cmd) - return cmd -} - -func deleteEnvironment(cmd *cobra.Command, args []string) error { - if cyargs.IsSet(cmd, "project") { - return fmt.Errorf(`--project is no longer accepted on environment delete. -Did you mean cy environment unlink --project %s --env ? -Use cy environment delete --env to destroy the org-level environment.`, cmd.Flag("project").Value.String()) - } - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - if envFlag, err := cyargs.GetEnv(cmd); err != nil { - return err - } else if envFlag != "" { - found := false - for _, a := range args { - if a == envFlag { - found = true - break - } - } - if !found { - args = append(args, envFlag) - } - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - for _, env := range args { - _, err = m.DeleteOrgEnv(org, env) - if err != nil { - return cyout.Print(cmd, nil, err, "unable to delete environment "+env) - } - } - return nil -} diff --git a/cmd/cycloid/environments/get.go b/cmd/cycloid/environments/get.go deleted file mode 100644 index 9069d309d..000000000 --- a/cmd/cycloid/environments/get.go +++ /dev/null @@ -1,90 +0,0 @@ -package environments - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewGetCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get [canonical...]", - Args: cyargs.RequireArgsOrFlag("env"), - Short: "get an environment", - Example: ` - # get an environment using the --env flag - cy --org my-org environment get --env my-env -o yaml - - # get multiple environments using positional args - cy --org my-org environment get env-a env-b -`, - RunE: get, - } - - cyargs.AddEnvFlag(cmd) - cyout.RegisterModel(cmd, models.Environment{}) - return cmd -} - -func get(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - if envFlag, err := cyargs.GetEnv(cmd); err != nil { - return err - } else if envFlag != "" { - found := false - for _, a := range args { - if a == envFlag { - found = true - break - } - } - if !found { - args = append(args, envFlag) - } - } - - if len(args) == 1 { - e, _, err := m.GetOrgEnv(org, args[0]) - return cyout.PrintWithOptions(cmd, e, err, "unable to get environment", environmentTableOptions) - } - - results := make([]*models.Environment, 0, len(args)) - for _, env := range args { - e, _, err := m.GetOrgEnv(org, env) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to get environment "+env, environmentTableOptions) - } - results = append(results, e) - } - return cyout.PrintWithOptions(cmd, results, nil, "", environmentTableOptions) -} - -func projectEnvToEnvironment(env *models.ProjectEnvironment) *models.Environment { - if env == nil { - return nil - } - return &models.Environment{ - Canonical: env.Canonical, - CloudAccounts: env.CloudAccounts, - Components: env.Components, - CreatedAt: env.CreatedAt, - Description: env.Description, - EnvironmentType: env.EnvironmentType, - ID: env.ID, - Name: env.Name, - Owner: env.Owner, - UpdatedAt: env.UpdatedAt, - VersionStatus: env.VersionStatus, - } -} diff --git a/cmd/cycloid/environments/link.go b/cmd/cycloid/environments/link.go deleted file mode 100644 index 73011ddc3..000000000 --- a/cmd/cycloid/environments/link.go +++ /dev/null @@ -1,101 +0,0 @@ -package environments - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewLinkCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "link", - Args: cobra.NoArgs, - Short: "link an environment to a project", - Example: `cy --org my-org environment link --project my-proj --env my-env`, - RunE: link, - } - - cyargs.AddProjectFlag(cmd) - cyargs.AddEnvFlag(cmd) - _ = cmd.MarkFlagRequired("project") - _ = cmd.MarkFlagRequired("env") - return cmd -} - -func link(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProject(cmd) - if err != nil { - return err - } - - env, err := cyargs.GetEnv(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - _, err = m.LinkEnvToProject(org, project, env) - if err != nil { - return cyout.Print(cmd, nil, err, "failed to link environment to project") - } - return nil -} - -func NewUnlinkCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "unlink", - Args: cobra.NoArgs, - Short: "unlink an environment from a project", - Example: `cy --org my-org environment unlink --project my-proj --env my-env`, - RunE: unlink, - } - - cyargs.AddProjectFlag(cmd) - cyargs.AddEnvFlag(cmd) - _ = cmd.MarkFlagRequired("project") - _ = cmd.MarkFlagRequired("env") - cyargs.AddDeleteFlags(cmd) - return cmd -} - -func unlink(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProject(cmd) - if err != nil { - return err - } - - env, err := cyargs.GetEnv(cmd) - if err != nil { - return err - } - - force, skipHooks, ignoreConfigFilesErr, err := cyargs.GetDeleteFlags(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - opts := middleware.DeleteOptions{Force: force, SkipHooks: skipHooks, IgnoreConfigFilesErr: ignoreConfigFilesErr} - _, err = m.UnlinkEnvFromProject(org, project, env, opts) - if err != nil { - return cyout.Print(cmd, nil, err, "failed to unlink environment from project") - } - return nil -} diff --git a/cmd/cycloid/environments/list.go b/cmd/cycloid/environments/list.go deleted file mode 100644 index 1403db278..000000000 --- a/cmd/cycloid/environments/list.go +++ /dev/null @@ -1,61 +0,0 @@ -package environments - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var environmentTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name"}, - Identifier: "Canonical", -} - -func NewListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "list environments", - Example: `cy --org my-org environments list -o json`, - RunE: list, - } - - cyargs.AddProjectFlag(cmd) - cyout.RegisterModel(cmd, models.Environment{}) - return cmd -} - -func list(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProjectOrEmpty(cmd) - if err != nil { - return err - } - - if project != "" { - projectEnvs, _, err := m.ListProjectEnvs(org, project) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to list project environments", environmentTableOptions) - } - environments := make([]*models.Environment, 0, len(projectEnvs)) - for _, env := range projectEnvs { - environments = append(environments, projectEnvToEnvironment(env)) - } - return cyout.PrintWithOptions(cmd, environments, nil, "", environmentTableOptions) - } - - environments, _, err := m.ListOrgEnvs(org) - return cyout.PrintWithOptions(cmd, environments, err, "unable to list environments", environmentTableOptions) -} diff --git a/cmd/cycloid/environments/update.go b/cmd/cycloid/environments/update.go deleted file mode 100644 index 8d520a957..000000000 --- a/cmd/cycloid/environments/update.go +++ /dev/null @@ -1,51 +0,0 @@ -package environments - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUpdateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "update", - Args: cobra.NoArgs, - Short: "update an environment", - Example: `cy --org my-org environment update --env my-environment --name "New Name"`, - RunE: update, - } - - cyargs.AddEnvFlag(cmd) - _ = cmd.MarkFlagRequired("env") - cyargs.AddNameFlag(cmd) - cyargs.AddEnvironmentTypeFlag(cmd) - cyargs.AddDescriptionFlag(cmd) - cyargs.AddEnvironmentOwnerFlag(cmd) - cyargs.AddCloudAccountCanonicalsFlag(cmd) - cyargs.AddEnvironmentVariablesFlag(cmd) - cyargs.AddEnvironmentVariablesFileFlag(cmd) - _ = cmd.Flags().MarkDeprecated(cyargs.AddColorFlag(cmd), "color now lives on environment-type and will be ignored") - return cmd -} - -func update(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - env, err := cyargs.GetEnv(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, err := createOrUpdateEnvironment(cmd, m, org, env, true) - return cyout.PrintWithOptions(cmd, result, err, "failed to update environment", printer.Options{}) -} diff --git a/cmd/cycloid/environments/utils.go b/cmd/cycloid/environments/utils.go deleted file mode 100644 index 2742ccd1a..000000000 --- a/cmd/cycloid/environments/utils.go +++ /dev/null @@ -1,212 +0,0 @@ -package environments - -import ( - stderrors "errors" - "fmt" - "net/http" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -func envTypeFromCurrent(current *models.Environment) string { - if current != nil && current.EnvironmentType != nil && current.EnvironmentType.Canonical != nil { - return *current.EnvironmentType.Canonical - } - return "" -} - -func ownerFromCurrent(current *models.Environment) string { - if current != nil && current.Owner != nil && current.Owner.Username != nil { - return *current.Owner.Username - } - return "" -} - -func cloudAccountsFromCurrent(current *models.Environment) []string { - if current == nil { - return nil - } - out := make([]string, 0, len(current.CloudAccounts)) - for _, account := range current.CloudAccounts { - if account != nil && account.Canonical != nil { - out = append(out, *account.Canonical) - } - } - return out -} - -func variablesFromCurrent(current *models.Environment) []*models.EnvironmentVariableItem { - if current == nil { - return nil - } - return current.Variables -} - -func buildNewEnvironment(cmd *cobra.Command, name, canonical string, current *models.Environment) (*models.NewEnvironment, error) { - body := &models.NewEnvironment{ - Canonical: canonical, - Name: ptr.Ptr(name), - } - - if cyargs.IsSet(cmd, "type") { - value, err := cyargs.GetEnvironmentType(cmd) - if err != nil { - return nil, err - } - body.Type = ptr.Ptr(value) - } else if current != nil { - if t := envTypeFromCurrent(current); t != "" { - body.Type = ptr.Ptr(t) - } - } - - if cyargs.IsSet(cmd, "description") { - description, err := cyargs.GetDescription(cmd) - if err != nil { - return nil, err - } - body.Description = description - } else if current != nil { - body.Description = current.Description - } - - if cyargs.IsSet(cmd, "owner") { - owner, err := cyargs.GetEnvironmentOwner(cmd) - if err != nil { - return nil, err - } - body.Owner = owner - } else if current != nil { - body.Owner = ownerFromCurrent(current) - } - - if cyargs.IsSet(cmd, "cloud-account") { - accounts, err := cyargs.GetCloudAccountCanonicals(cmd) - if err != nil { - return nil, err - } - body.CloudAccountCanonicals = accounts - } else if current != nil { - body.CloudAccountCanonicals = cloudAccountsFromCurrent(current) - } - - if cyargs.IsSet(cmd, "variable") || cyargs.IsSet(cmd, "variables-file") { - variables, err := cyargs.GetEnvironmentVariables(cmd) - if err != nil { - return nil, err - } - body.Variables = variables - } else if current != nil { - body.Variables = variablesFromCurrent(current) - } - - return body, nil -} - -func buildUpdateEnvironment(cmd *cobra.Command, current *models.Environment) (*models.UpdateEnvironment, error) { - name := current.Name - if cyargs.IsSet(cmd, "name") { - value, err := cyargs.GetName(cmd) - if err != nil { - return nil, err - } - if value != "" { - name = value - } - } - - body := &models.UpdateEnvironment{ - Name: ptr.Ptr(name), - } - - if cyargs.IsSet(cmd, "type") { - value, err := cyargs.GetEnvironmentType(cmd) - if err != nil { - return nil, err - } - body.Type = ptr.Ptr(value) - } else if t := envTypeFromCurrent(current); t != "" { - body.Type = ptr.Ptr(t) - } - - if cyargs.IsSet(cmd, "description") { - description, err := cyargs.GetDescription(cmd) - if err != nil { - return nil, err - } - body.Description = description - } else { - body.Description = current.Description - } - - if cyargs.IsSet(cmd, "owner") { - owner, err := cyargs.GetEnvironmentOwner(cmd) - if err != nil { - return nil, err - } - body.Owner = owner - } else { - body.Owner = ownerFromCurrent(current) - } - - if cyargs.IsSet(cmd, "cloud-account") { - accounts, err := cyargs.GetCloudAccountCanonicals(cmd) - if err != nil { - return nil, err - } - body.CloudAccountCanonicals = accounts - } else { - body.CloudAccountCanonicals = cloudAccountsFromCurrent(current) - } - - if cyargs.IsSet(cmd, "variable") || cyargs.IsSet(cmd, "variables-file") { - variables, err := cyargs.GetEnvironmentVariables(cmd) - if err != nil { - return nil, err - } - body.Variables = variables - } - - return body, nil -} - -func createOrUpdateEnvironment(cmd *cobra.Command, m middleware.Middleware, org, canonical string, allowUpdate bool) (*models.Environment, error) { - name, err := cyargs.GetName(cmd) - if err != nil { - return nil, err - } - name, canonical, err = middleware.NameOrCanonical(&name, &canonical) - if err != nil { - return nil, err - } - - current, _, err := m.GetOrgEnv(org, canonical) - if err == nil { - if !allowUpdate { - return nil, fmt.Errorf("environment %q already exists (use --update to upsert)", canonical) - } - updateBody, err := buildUpdateEnvironment(cmd, current) - if err != nil { - return nil, err - } - updated, _, err := m.UpdateOrgEnv(org, canonical, updateBody) - return updated, err - } - - var apiErr *middleware.APIResponseError - if !stderrors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound { - return nil, err - } - - createBody, err := buildNewEnvironment(cmd, name, canonical, nil) - if err != nil { - return nil, err - } - created, _, err := m.CreateOrgEnv(org, createBody) - return created, err -} diff --git a/cmd/cycloid/environmenttypes/cmd.go b/cmd/cycloid/environmenttypes/cmd.go deleted file mode 100644 index 7f12fd880..000000000 --- a/cmd/cycloid/environmenttypes/cmd.go +++ /dev/null @@ -1,29 +0,0 @@ -package environmenttypes - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "environment-type", - Aliases: []string{"environment-types", "env-type", "env-types"}, - Short: "Manage environment types", - } - - cmd.AddCommand( - NewCreateCommand(), - NewUpdateCommand(), - NewGetCommand(), - NewDeleteCommand(), - NewListCommand(), - ) - return cmd -} - -var environmentTypeTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "Color"}, - Identifier: "Canonical", -} diff --git a/cmd/cycloid/environmenttypes/cmd_test.go b/cmd/cycloid/environmenttypes/cmd_test.go deleted file mode 100644 index 43a809d57..000000000 --- a/cmd/cycloid/environmenttypes/cmd_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package environmenttypes - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestEnvironmentTypesCommandTree(t *testing.T) { - t.Parallel() - root := NewCommands() - assert.Equal(t, "environment-type", root.Name()) - - names := make(map[string]int) - for _, c := range root.Commands() { - names[c.Name()]++ - } - - require.Equal(t, 1, names["list"]) - require.Equal(t, 1, names["get"]) - require.Equal(t, 1, names["create"]) - require.Equal(t, 1, names["update"]) - require.Equal(t, 1, names["delete"]) -} - -func TestEnvironmentTypeCreateFlags(t *testing.T) { - t.Parallel() - cmd := NewCreateCommand() - - require.NotNil(t, cmd.Flags().Lookup("color"), "color flag must be registered") - require.NotNil(t, cmd.Flags().Lookup("environment-type-name"), "environment-type-name flag must be registered") - require.NotNil(t, cmd.Flags().Lookup("environment-type"), "environment-type (canonical) flag must be registered") -} - -func TestEnvironmentTypeCreateHasUpdateFlag(t *testing.T) { - t.Parallel() - cmd := NewCreateCommand() - f := cmd.Flags().Lookup("update") - require.NotNil(t, f, "create must carry --update for upsert") - assert.Equal(t, "bool", f.Value.Type()) -} - -func TestEnvironmentTypeUpdateNoUpdateFlag(t *testing.T) { - t.Parallel() - cmd := NewUpdateCommand() - // update subcommand is always an update; no upsert --update flag - assert.Nil(t, cmd.Flags().Lookup("update")) -} - -func TestAppendUniqueArg(t *testing.T) { - t.Parallel() - - t.Run("appends new value", func(t *testing.T) { - result := appendUniqueArg([]string{"a", "b"}, "c") - assert.Equal(t, []string{"a", "b", "c"}, result) - }) - - t.Run("deduplicates existing value", func(t *testing.T) { - result := appendUniqueArg([]string{"a", "b"}, "b") - assert.Equal(t, []string{"a", "b"}, result) - }) - - t.Run("works on empty slice", func(t *testing.T) { - result := appendUniqueArg(nil, "x") - assert.Equal(t, []string{"x"}, result) - }) -} diff --git a/cmd/cycloid/environmenttypes/create.go b/cmd/cycloid/environmenttypes/create.go deleted file mode 100644 index 17eda129b..000000000 --- a/cmd/cycloid/environmenttypes/create.go +++ /dev/null @@ -1,144 +0,0 @@ -package environmenttypes - -import ( - stderrors "errors" - "net/http" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "create", - Short: "Create an environment type", - Example: `cy --org my-org environment-type create --environment-type qa --environment-type-name QA --color staging`, - RunE: create, - Args: cobra.NoArgs, - } - - cmd.MarkFlagsOneRequired( - cyargs.AddEnvironmentTypeNameFlag(cmd), - cyargs.AddEnvironmentTypeCanonicalFlag(cmd), - ) - _ = cmd.MarkFlagRequired(cyargs.AddColorFlag(cmd)) - cyargs.AddUpdateFlag(cmd, "update the environment type if it already exists") - return cmd -} - -func create(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetEnvironmentTypeName(cmd) - if err != nil { - return err - } - - canonical, err := cyargs.GetEnvironmentTypeCanonical(cmd) - if err != nil { - return err - } - name, canonical, err = middleware.NameOrCanonical(&name, &canonical) - if err != nil { - return err - } - - color, err := cyargs.GetColor(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - if cyargs.GetUpdate(cmd) { - _, _, getErr := m.GetEnvironmentType(org, canonical) - if getErr == nil { - return updateEnvironmentType(cmd, args) - } - var apiErr *middleware.APIResponseError - if !stderrors.As(getErr, &apiErr) || apiErr.StatusCode != http.StatusNotFound { - return cyout.PrintWithOptions(cmd, nil, getErr, "failed to check existing environment type", printer.Options{}) - } - } - - body := &models.NewEnvironmentType{ - Canonical: canonical, - Name: ptr.Ptr(name), - Color: ptr.Ptr(color), - } - result, _, err := m.CreateEnvironmentType(org, body) - return cyout.PrintWithOptions(cmd, result, err, "failed to create environment type", environmentTypeTableOptions) -} - -func NewUpdateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "update", - Short: "Update an environment type", - RunE: updateEnvironmentType, - Args: cobra.NoArgs, - } - - cyargs.AddEnvironmentTypeCanonicalFlag(cmd) - _ = cmd.MarkFlagRequired("environment-type") - cyargs.AddEnvironmentTypeNameFlag(cmd) - cyargs.AddColorFlag(cmd) - return cmd -} - -func updateEnvironmentType(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - canonical, err := cyargs.GetEnvironmentTypeCanonical(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - current, _, err := m.GetEnvironmentType(org, canonical) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "environment type not found", environmentTypeTableOptions) - } - - name := ptr.Value(current.Name) - if cyargs.IsSet(cmd, "environment-type-name") { - value, err := cyargs.GetEnvironmentTypeName(cmd) - if err != nil { - return err - } - if value != "" { - name = value - } - } - - color := ptr.Value(current.Color) - if cyargs.IsSet(cmd, "color") { - value, err := cyargs.GetColor(cmd) - if err != nil { - return err - } - color = value - } - - body := &models.UpdateEnvironmentType{ - Name: ptr.Ptr(name), - Color: ptr.Ptr(color), - } - result, _, err := m.UpdateEnvironmentType(org, canonical, body) - return cyout.PrintWithOptions(cmd, result, err, "failed to update environment type", environmentTypeTableOptions) -} diff --git a/cmd/cycloid/environmenttypes/list.go b/cmd/cycloid/environmenttypes/list.go deleted file mode 100644 index 269741295..000000000 --- a/cmd/cycloid/environmenttypes/list.go +++ /dev/null @@ -1,128 +0,0 @@ -package environmenttypes - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewListCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "list", - Short: "List environment types", - RunE: list, - Args: cobra.NoArgs, - } - - cyout.RegisterModel(cmd, models.EnvironmentType{}) - return cmd -} - -func list(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - types, _, err := m.ListEnvironmentTypes(org) - return cyout.PrintWithOptions(cmd, types, err, "failed to list environment types", environmentTypeTableOptions) -} - -func NewGetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get [environment_type_canonical...]", - Short: "Get environment type details", - RunE: get, - Args: cyargs.RequireArgsOrFlag("environment-type"), - ValidArgsFunction: cyargs.CompleteEnvironmentTypeCanonical, - } - - cyargs.AddEnvironmentTypeCanonicalFlag(cmd) - cyout.RegisterModel(cmd, models.EnvironmentType{}) - return cmd -} - -func get(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - if flag, err := cyargs.GetEnvironmentTypeCanonical(cmd); err != nil { - return err - } else if flag != "" { - args = appendUniqueArg(args, flag) - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - if len(args) == 1 { - envType, _, err := m.GetEnvironmentType(org, args[0]) - return cyout.PrintWithOptions(cmd, envType, err, "failed to get environment type", environmentTypeTableOptions) - } - - results := make([]*models.EnvironmentType, 0, len(args)) - for _, canonical := range args { - envType, _, err := m.GetEnvironmentType(org, canonical) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, fmt.Sprintf("failed to get environment type %q", canonical), environmentTypeTableOptions) - } - results = append(results, envType) - } - return cyout.PrintWithOptions(cmd, results, nil, "", environmentTypeTableOptions) -} - -func NewDeleteCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "delete [environment_type_canonical...]", - Short: "Delete environment types", - RunE: deleteEnvironmentType, - Args: cyargs.RequireArgsOrFlag("environment-type"), - ValidArgsFunction: cyargs.CompleteEnvironmentTypeCanonical, - } - - cyargs.AddEnvironmentTypeCanonicalFlag(cmd) - return cmd -} - -func deleteEnvironmentType(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - if flag, err := cyargs.GetEnvironmentTypeCanonical(cmd); err != nil { - return err - } else if flag != "" { - args = appendUniqueArg(args, flag) - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - for _, canonical := range args { - if _, err := m.DeleteEnvironmentType(org, canonical); err != nil { - return cyout.Print(cmd, nil, err, "failed to delete environment type "+canonical) - } - } - return nil -} - -func appendUniqueArg(args []string, value string) []string { - for _, existing := range args { - if existing == value { - return args - } - } - return append(args, value) -} diff --git a/cmd/cycloid/events/cmd.go b/cmd/cycloid/events/cmd.go deleted file mode 100644 index ecb942539..000000000 --- a/cmd/cycloid/events/cmd.go +++ /dev/null @@ -1,22 +0,0 @@ -package events - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - var cmd = &cobra.Command{ - Use: "event", - Aliases: []string{ - "events", - }, - Short: "Manage the events", - } - - cmd.AddCommand( - NewSendCommand(), - NewListCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/events/list.go b/cmd/cycloid/events/list.go deleted file mode 100644 index 512a260ef..000000000 --- a/cmd/cycloid/events/list.go +++ /dev/null @@ -1,69 +0,0 @@ -package events - -import ( - "time" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Aliases: []string{"ls"}, - Short: "list events", - Example: `# Get events since last week -cy --org my-org event list --begin 0 --end "$(date --date "last week" +"%s")" --severity info,warn,err,crit --type Cycloid,AWS,Monitoring,Custom -`, - RunE: list, - } - - now := time.Now().Unix() - yesterday := time.Now().AddDate(0, 0, -1).Unix() - cmd.Flags().Uint64P("begin", "b", uint64(yesterday), "the starting date to get events from, using a unix timestamp, default to yesterday") - cmd.Flags().Uint64P("end", "e", uint64(now), "the starting date to get events from, using a unix timestamp, default to now") - - cmd.Flags().StringSliceP("severity", "s", []string{"info", "err", "warn", "crit"}, "filter events by severity, you can set more than one, default '-s info,err,warn,crit'") - cmd.Flags().StringSliceP("type", "t", []string{"Cycloid", "Custom", "AWS", "Monitoring"}, "filter events by type, you can set more than one, default '-t Cycloid,Custom,AWS,Monitoring'") - return cmd -} - -func list(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - var err error - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - begin, err := cmd.Flags().GetUint64("begin") - if err != nil { - return err - } - - end, err := cmd.Flags().GetUint64("end") - if err != nil { - return err - } - - eventSeverity, err := cmd.Flags().GetStringSlice("severity") - if err != nil { - return err - } - eventType, err := cmd.Flags().GetStringSlice("type") - if err != nil { - return err - } - - events, _, err := m.ListEvents(org, eventType, eventSeverity, begin*1000, end*1000) - return cyout.PrintWithOptions(cmd, events, err, "failed to list events", printer.Options{}) -} diff --git a/cmd/cycloid/events/send.go b/cmd/cycloid/events/send.go deleted file mode 100644 index 06760cb52..000000000 --- a/cmd/cycloid/events/send.go +++ /dev/null @@ -1,108 +0,0 @@ -package events - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var ( - colorFlag string - iconFlag string - messageFlag string - messageFileFlag string - severityFlag string - titleFlag string - typeFlag string - tagsFlag map[string]string -) - -func NewSendCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "create", - Args: cobra.NoArgs, - Short: "create an event", - Example: ` - # create a custom event - cy --org my-org event create --tag env=staging --title success --message "successful deployment" -`, - RunE: send, - } - - cmd.Flags().StringToStringVar(&tagsFlag, "tag", nil, "tags of the event (key=value)") - cmd.MarkFlagRequired("tag") - cmd.Flags().StringVar(&titleFlag, "title", "", "title of the event") - cmd.MarkFlagRequired("title") - - cmd.Flags().StringVar(&colorFlag, "color", "", "color of the event") - cmd.Flags().StringVar(&messageFlag, "message", "", "message of the event") - cmd.Flags().StringVar(&messageFileFlag, "message-file", "", "path to the file holding the message") - cmd.Flags().StringVar(&iconFlag, "icon", "", "icon of the event") - cmd.Flags().StringVar(&severityFlag, "severity", "info", "severity of the event") - cmd.Flags().StringVar(&typeFlag, "type", "Custom", "type of the event") - - return cmd -} - -func send(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - var err error - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - color, err := cmd.Flags().GetString("color") - if err != nil { - return err - } - severity, err := cmd.Flags().GetString("severity") - if err != nil { - return err - } - eType, err := cmd.Flags().GetString("type") - if err != nil { - return err - } - title, err := cmd.Flags().GetString("title") - if err != nil { - return err - } - message, err := cmd.Flags().GetString("message") - if err != nil { - return err - } - messageFile, err := cmd.Flags().GetString("message-file") - if err != nil { - return err - } - tags, err := cmd.Flags().GetStringToString("tag") - if err != nil { - return err - } - - var msg string - if messageFile != "" { - rawMsg, err := os.ReadFile(messageFile) - if err != nil { - return fmt.Errorf("unable to read message file: %w", err) - } - msg = string(rawMsg) - } else if message != "" { - msg = message - } else { - return fmt.Errorf("required flag(s) \"message\" or \"message-file\" not set") - } - - _, err = m.SendEvent(org, eType, title, msg, severity, tags, color) - return cyout.PrintWithOptions(cmd, nil, err, "unable to send event", printer.Options{}) -} diff --git a/cmd/cycloid/externalbackends/cmd.go b/cmd/cycloid/externalbackends/cmd.go deleted file mode 100644 index db5a03ad5..000000000 --- a/cmd/cycloid/externalbackends/cmd.go +++ /dev/null @@ -1,23 +0,0 @@ -package externalbackends - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - var cmd = &cobra.Command{ - Use: "external-backend", - Aliases: []string{ - "external-backends", - "eb", - }, - Short: "manage external backends", - } - - cmd.AddCommand(NewGetCommand(), - NewDeleteCommand(), - NewListCommand(), - NewCreateCommand()) - - return cmd -} diff --git a/cmd/cycloid/externalbackends/common.go b/cmd/cycloid/externalbackends/common.go deleted file mode 100644 index e935de62d..000000000 --- a/cmd/cycloid/externalbackends/common.go +++ /dev/null @@ -1,71 +0,0 @@ -package externalbackends - -import "github.com/spf13/cobra" - -var ( - regionAwsFlag string - regionFlag string - awsBucketName string - awsBucketPath string - awsS3BucketEndpoint string - urls []string - prefilters map[string]string - skipVerifySSL bool - awsS3ForcePathStyle bool - def bool -) - -func WithFlagAwsRegion(cmd *cobra.Command) string { - flagName := "region" - cmd.Flags().StringVar(®ionAwsFlag, flagName, "eu-west-1", "region") - return flagName -} - -func WithFlagRegion(cmd *cobra.Command) string { - flagName := "region" - cmd.Flags().StringVar(®ionFlag, flagName, "", "region") - return flagName -} - -func WithFlagBucketName(cmd *cobra.Command) string { - flagName := "bucket-name" - cmd.Flags().StringVar(&awsBucketName, flagName, "", "bucket name") - return flagName -} -func WithFlagBucketPath(cmd *cobra.Command) string { - flagName := "bucket-path" - cmd.Flags().StringVar(&awsBucketPath, flagName, "", "bucket path") - return flagName -} - -func WithFlagS3BucketEndpoint(cmd *cobra.Command) string { - flagName := "endpoint" - cmd.Flags().StringVar(&awsS3BucketEndpoint, flagName, "", "Aws S3 endpoint") - return flagName -} -func WithFlagS3ForcePathStyle(cmd *cobra.Command) string { - flagName := "s3-force-path-style" - cmd.Flags().BoolVar(&awsS3ForcePathStyle, flagName, true, "") - return flagName -} -func WithFlagSkipVerifySSL(cmd *cobra.Command) string { - flagName := "skip-verify-ssl" - cmd.Flags().BoolVar(&skipVerifySSL, flagName, false, "") - return flagName -} -func WithFlagDefault(cmd *cobra.Command) string { - flagName := "default" - cmd.Flags().BoolVar(&def, flagName, false, "") - return flagName -} - -func WithFlagURL(cmd *cobra.Command) string { - flagName := "url" - cmd.Flags().StringSliceVar(&urls, flagName, nil, "urls") - return flagName -} -func WithFlagPrefilter(cmd *cobra.Command) string { - flagName := "prefilter" - cmd.Flags().StringToStringVar(&prefilters, flagName, nil, "key=value") - return flagName -} diff --git a/cmd/cycloid/externalbackends/create.go b/cmd/cycloid/externalbackends/create.go deleted file mode 100644 index 1b50b526d..000000000 --- a/cmd/cycloid/externalbackends/create.go +++ /dev/null @@ -1,143 +0,0 @@ -package externalbackends - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" -) - -const noDefault = false - -var hostMapping, messageMapping, timestampMapping, esIndex string - -func NewCreateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "create [log|infraview]", - Args: cobra.NoArgs, - Short: "create an external-backend", - Example: ` - # create AWS external backend for logs - cy --org my-org eb create logs AWSCloudWatchLogs --project foo --org bar --region eu-west-1 - - # create Elasticsearch external backend for logs - cy --org my-org eb create logs ElasticsearchLogs source-name --project foo --org bar --env foo --cred my-credential --url http://elasticsearch.local.tld --prefilter foo=bar -`, - } - - infraViewCmd := newInfraViewCommand() - logsCmd := newLogsCommand() - eventsCmd := newEventsCommand() - - cmd.AddCommand(logsCmd, eventsCmd, infraViewCmd) - return cmd -} - -func newInfraViewCommand() *cobra.Command { - - var infraViewCmd = &cobra.Command{ - Use: "infraview [backend]", - // RunE: create, - } - common.RequiredPersistentFlag(common.WithFlagProject, infraViewCmd) - common.RequiredPersistentFlag(common.WithFlagEnv, infraViewCmd) - - // AWSRemoteTFState - var aWSRemoteTFState = &cobra.Command{ - Use: "AWSRemoteTFState", - Args: cobra.NoArgs, - RunE: createInfraView, - } - WithFlagAwsRegion(aWSRemoteTFState) - common.RequiredFlag(common.WithFlagCred, aWSRemoteTFState) - WithFlagBucketName(aWSRemoteTFState) - WithFlagBucketPath(aWSRemoteTFState) - WithFlagS3BucketEndpoint(aWSRemoteTFState) - WithFlagS3ForcePathStyle(aWSRemoteTFState) - WithFlagSkipVerifySSL(aWSRemoteTFState) - WithFlagDefault(aWSRemoteTFState) - - var gCPRemoteTFState = &cobra.Command{ - Use: "GCPRemoteTFState", - Args: cobra.NoArgs, - RunE: createInfraView, - } - common.RequiredFlag(common.WithFlagCred, gCPRemoteTFState) - WithFlagBucketName(gCPRemoteTFState) - WithFlagBucketPath(gCPRemoteTFState) - WithFlagDefault(gCPRemoteTFState) - - var swiftRemoteTFState = &cobra.Command{ - Use: "SwiftRemoteTFState", - Args: cobra.NoArgs, - RunE: createInfraView, - } - common.RequiredFlag(common.WithFlagCred, swiftRemoteTFState) - WithFlagBucketName(swiftRemoteTFState) - WithFlagBucketPath(swiftRemoteTFState) - common.RequiredFlag(WithFlagRegion, swiftRemoteTFState) - WithFlagSkipVerifySSL(swiftRemoteTFState) - WithFlagDefault(swiftRemoteTFState) - - infraViewCmd.AddCommand( - aWSRemoteTFState, - gCPRemoteTFState, - swiftRemoteTFState, - ) - return infraViewCmd -} - -func newEventsCommand() *cobra.Command { - var eventCmd = &cobra.Command{ - Use: "events [backend]", - Hidden: true, - } - - // Aws CW logs - var eventsAWSCloudWatchLogsCmd = &cobra.Command{ - Use: "AWSCloudWatchLogs", - Args: cobra.NoArgs, - RunE: createEvents, - } - WithFlagAwsRegion(eventsAWSCloudWatchLogsCmd) - common.RequiredFlag(common.WithFlagCred, eventsAWSCloudWatchLogsCmd) - - eventCmd.AddCommand(eventsAWSCloudWatchLogsCmd) - return eventCmd -} - -func newLogsCommand() *cobra.Command { - var logsCmd = &cobra.Command{ - Use: "logs [backend]", - } - - // Aws CW logs - var logsAWSCloudWatchLogsCmd = &cobra.Command{ - Use: "AWSCloudWatchLogs", - RunE: createLogs, - } - WithFlagAwsRegion(logsAWSCloudWatchLogsCmd) - common.RequiredPersistentFlag(common.WithFlagProject, logsAWSCloudWatchLogsCmd) - common.RequiredFlag(common.WithFlagCred, logsAWSCloudWatchLogsCmd) - - // Elasticsearch - var logsElasticsearchLogsCmd = &cobra.Command{ - Use: "ElasticsearchLogs [SourceName]", - Args: cobra.ExactArgs(1), - RunE: createLogs, - } - common.RequiredPersistentFlag(common.WithFlagProject, logsElasticsearchLogsCmd) - common.RequiredPersistentFlag(common.WithFlagEnv, logsElasticsearchLogsCmd) - common.RequiredFlag(WithFlagURL, logsElasticsearchLogsCmd) - common.RequiredFlag(WithFlagPrefilter, logsElasticsearchLogsCmd) - common.WithFlagCred(logsElasticsearchLogsCmd) - logsElasticsearchLogsCmd.Flags().StringVar(&esIndex, "index", "default", "") - logsElasticsearchLogsCmd.Flags().StringVar(&hostMapping, "host-mapping", "hostname", "") - logsElasticsearchLogsCmd.Flags().StringVar(&messageMapping, "message-mapping", "message", "") - logsElasticsearchLogsCmd.Flags().StringVar(×tampMapping, "timestamp-mapping", "timestamp", "") - - // Note if one exist it should trigger an update (to append the new source to sources if the source does not exist yet) - // Will require list sources maybe ? - - logsCmd.AddCommand(logsAWSCloudWatchLogsCmd, logsElasticsearchLogsCmd) - return logsCmd -} diff --git a/cmd/cycloid/externalbackends/create_events.go b/cmd/cycloid/externalbackends/create_events.go deleted file mode 100644 index cb9371923..000000000 --- a/cmd/cycloid/externalbackends/create_events.go +++ /dev/null @@ -1,56 +0,0 @@ -package externalbackends - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func createEvents(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - var ( - err error - cred string - purpose = "events" - ebC models.ExternalBackendConfiguration - engine = cmd.CalledAs() - ) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - // AWS CW logs - if engine == "AWSCloudWatchLogs" { - region, err := cmd.Flags().GetString("region") - if err != nil { - return err - } - cred, err = cmd.Flags().GetString("cred") - if err != nil { - return err - } - - ebC = &models.AWSCloudWatchLogs{ - Region: ®ion, - } - } else { - return fmt.Errorf("unexpected backend name") - } - - // Set project and env to empty cause events are not linked to a project - project := "" - env := "" - resp, _, err := m.CreateExternalBackends(org, project, env, purpose, cred, noDefault, ebC) - return cyout.PrintWithOptions(cmd, resp, err, "unable to create external backend", printer.Options{}) -} diff --git a/cmd/cycloid/externalbackends/create_infra_view.go b/cmd/cycloid/externalbackends/create_infra_view.go deleted file mode 100644 index 66b528fb6..000000000 --- a/cmd/cycloid/externalbackends/create_infra_view.go +++ /dev/null @@ -1,126 +0,0 @@ -package externalbackends - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func createInfraView(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - var ( - purpose = "remote_tfstate" - err error - project, env string - ebC models.ExternalBackendConfiguration - engine = cmd.CalledAs() - defaultEB bool - ) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - project, err = cmd.Flags().GetString("project") - if err != nil { - return err - } - env, err = cmd.Flags().GetString("env") - if err != nil { - return err - } - defaultEB, err = cmd.Flags().GetBool("default") - if err != nil { - return err - } - - //Common - cred, err := cmd.Flags().GetString("cred") - if err != nil { - return err - } - - bucketName, err := cmd.Flags().GetString("bucket-name") - if err != nil { - return err - } - if bucketName == "" { - bucketName = fmt.Sprintf("%s-terraform-remote-state", org) - } - - bucketpath, err := cmd.Flags().GetString("bucket-path") - if err != nil { - return err - } - if bucketpath == "" { - bucketpath = fmt.Sprintf("%s/%s/%s-%s.tfstate", project, env, project, env) - } - skipSSL, err := cmd.Flags().GetBool("skip-verify-ssl") - if err != nil { - return err - } - region, err := cmd.Flags().GetString("region") - if err != nil { - return err - } - - switch engine { - case "AWSRemoteTFState": - endpoint, err := cmd.Flags().GetString("endpoint") - if err != nil { - return err - } - - forcePathStyle, err := cmd.Flags().GetBool("s3-force-path-style") - if err != nil { - return err - } - - if endpoint != "" { - ebC = &models.AWSRemoteTFState{ - Region: ®ion, - Bucket: &bucketName, - Key: bucketpath, - Endpoint: endpoint, - S3ForcePathStyle: forcePathStyle, - SkipVerifySsl: skipSSL, - } - } else { - ebC = &models.AWSRemoteTFState{ - Region: ®ion, - Bucket: &bucketName, - Key: bucketpath, - } - } - - case "SwiftRemoteTFState": - - ebC = &models.SwiftRemoteTFState{ - Container: &bucketName, - Object: bucketpath, - SkipVerifySsl: skipSSL, - Region: ®ion, - } - - case "GCPRemoteTFState": - - ebC = &models.GCPRemoteTFState{ - Bucket: &bucketName, - Object: bucketpath, - } - default: - return fmt.Errorf("unexpected backend name") - } - - resp, _, err := m.CreateExternalBackends(org, project, env, purpose, cred, defaultEB, ebC) - return cyout.PrintWithOptions(cmd, resp, err, "unable to create external backend", printer.Options{}) -} diff --git a/cmd/cycloid/externalbackends/create_logs.go b/cmd/cycloid/externalbackends/create_logs.go deleted file mode 100644 index d99a45201..000000000 --- a/cmd/cycloid/externalbackends/create_logs.go +++ /dev/null @@ -1,127 +0,0 @@ -package externalbackends - -import ( - "fmt" - - "github.com/go-openapi/strfmt" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func createLogs(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - var ( - ebC models.ExternalBackendConfiguration - engine = cmd.CalledAs() - cred string - purpose = "logs" - ) - - project, err := cmd.Flags().GetString("project") - if err != nil { - return err - } - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - cred, err = cmd.Flags().GetString("cred") - if err != nil { - return err - } - - switch engine { - case "AWSCloudWatchLogs": - region, err := cmd.Flags().GetString("region") - if err != nil { - return err - } - - ebC = &models.AWSCloudWatchLogs{ - Region: ®ion, - } - - case "ElasticsearchLogs": - prefilters, err := cmd.Flags().GetStringToString("prefilter") - if err != nil { - return err - } - urls, err := cmd.Flags().GetStringSlice("url") - if err != nil { - return err - } - env, err := cmd.Flags().GetString("env") - if err != nil { - return err - } - // TODO Note: are those useful as I also can directly access to the local defined var for the flag - hostMapping, err := cmd.Flags().GetString("host-mapping") - if err != nil { - return err - } - messageMapping, err := cmd.Flags().GetString("message-mapping") - if err != nil { - return err - } - timestampMapping, err := cmd.Flags().GetString("timestamp-mapping") - if err != nil { - return err - } - esIndex, err := cmd.Flags().GetString("index") - if err != nil { - return err - } - - // In this case we know there is exactly one arg - var sourceName = args[0] - - esM := models.ElasticsearchLogsSourcesAnonMapping{ - Host: &hostMapping, - Message: &messageMapping, - Timestamp: ×tampMapping, - } - err = esM.Validate(strfmt.Default) - if err != nil { - return err - } - - esS := models.ElasticsearchLogsSourcesAnon{ - Index: esIndex, - Mapping: &esM, - Prefilters: prefilters, - } - err = esS.Validate(strfmt.Default) - if err != nil { - return err - } - - sources := map[string]map[string]models.ElasticsearchLogsSourcesAnon{ - env: map[string]models.ElasticsearchLogsSourcesAnon{ - sourceName: esS, - }, - } - - version := "7" - ebC = &models.ElasticsearchLogs{ - Version: &version, - Urls: urls, - Sources: sources, - } - - default: - return fmt.Errorf("unexpected backend name") - } - - // Set env to empty cause is not used to create log eb - envP := "" - resp, _, err := m.CreateExternalBackends(org, project, envP, purpose, cred, noDefault, ebC) - return cyout.PrintWithOptions(cmd, resp, err, "unable to create external backend", printer.Options{}) -} diff --git a/cmd/cycloid/externalbackends/delete.go b/cmd/cycloid/externalbackends/delete.go deleted file mode 100644 index 88825be0e..000000000 --- a/cmd/cycloid/externalbackends/delete.go +++ /dev/null @@ -1,44 +0,0 @@ -package externalbackends - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewDeleteCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "delete", - Args: cobra.NoArgs, - Short: "delete an external backend configuration", - Example: ` - # delete an existing external backend with ID 123 - cy --org my-org eb delete --id 123 -`, - RunE: del, - } - common.RequiredFlag(common.WithFlagID, cmd) - - return cmd -} - -func del(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - id, err := cmd.Flags().GetUint32("id") - if err != nil { - return err - } - - _, err = m.DeleteExternalBackend(org, id) - return cyout.PrintWithOptions(cmd, nil, err, "unable to delete external backend", printer.Options{}) -} diff --git a/cmd/cycloid/externalbackends/get.go b/cmd/cycloid/externalbackends/get.go deleted file mode 100644 index 0020b340d..000000000 --- a/cmd/cycloid/externalbackends/get.go +++ /dev/null @@ -1,27 +0,0 @@ -package externalbackends - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func NewGetCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get", - Args: cobra.NoArgs, - Hidden: true, - Short: "not implemented yet", - Long: `not implemented yet`, - RunE: func(cmd *cobra.Command, args []string) error { - fmt.Println("not implemented yet") - return nil - }, - } - - return cmd -} - -// /organizations/{organization_canonical}/external_backends/{external_backend_id} -// get: getExternalBackend -// Get the external backend diff --git a/cmd/cycloid/externalbackends/list.go b/cmd/cycloid/externalbackends/list.go deleted file mode 100644 index 1cd6e9ae2..000000000 --- a/cmd/cycloid/externalbackends/list.go +++ /dev/null @@ -1,49 +0,0 @@ -package externalbackends - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var ( - example = ` - # List all the external backends within my-org organization in JSON output format - cy --org my-org external-backends list --output=json - - # List all the external backends within my-org organization in YAML output format - cy --org my-org external-backends list --output=yaml -` - short = "Get the list of organization external backends" - long = short -) - -func NewListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Example: example, - Short: short, - Long: long, - RunE: list, - } - - return cmd -} - -func list(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - ebs, _, err := m.ListExternalBackends(org) - return cyout.PrintWithOptions(cmd, ebs, err, "unable to list external backends", printer.Options{}) -} diff --git a/cmd/cycloid/externalbackends/update.go b/cmd/cycloid/externalbackends/update.go deleted file mode 100644 index c678fea9c..000000000 --- a/cmd/cycloid/externalbackends/update.go +++ /dev/null @@ -1,29 +0,0 @@ -package externalbackends - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func NewUpdateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "update", - Args: cobra.NoArgs, - Hidden: true, - Short: "not implemented yet", - Long: `not implemented yet`, - RunE: func(cmd *cobra.Command, args []string) error { - fmt.Println("not implemented yet") - return nil - }, - } - - return cmd -} - -// Update will not be available on logs, only create/delete as it's too complexe - -// /organizations/{organization_canonical}/external_backends/{external_backend_id} -// put: updateExternalBackend -// Update an External Backend diff --git a/cmd/cycloid/get.go b/cmd/cycloid/get.go deleted file mode 100644 index 4d0d3d3eb..000000000 --- a/cmd/cycloid/get.go +++ /dev/null @@ -1,11 +0,0 @@ -package cycloid - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/uri" -) - -func NewGetCommand() *cobra.Command { - return uri.NewGetCommand() -} diff --git a/cmd/cycloid/internal/version.go b/cmd/cycloid/internal/version.go deleted file mode 100644 index 4945f6c81..000000000 --- a/cmd/cycloid/internal/version.go +++ /dev/null @@ -1,43 +0,0 @@ -package internal - -import ( - "fmt" - "io" - "os" - - "github.com/spf13/viper" -) - -func Error(out io.Writer, msg string) { - switch viper.GetString("verbosity") { - case "info", "debug", "warning": - // This is still dirty, we should detect if the current - // terminal is able to support colors - // But that would be for another PR. - fmt.Fprintf(out, "\033[1;31merror:\033[0m %s", msg) - default: - } -} - -func Warning(out io.Writer, msg string) { - switch viper.GetString("verbosity") { - case "info", "debug", "warning": - // This is still dirty, we should detect if the current - // terminal is able to support colors - // But that would be for another PR. - fmt.Fprintf(out, "\033[1;35mwarning:\033[0m %s", msg) - default: - } -} - -func Debug(msg ...any) { - switch viper.GetString("verbosity") { - case "debug": - // This is still dirty, we should detect if the current - // terminal is able to support colors - // But that would be for another PR. - fmt.Fprintf(os.Stderr, "\033[1;34mdebug:\033[0m ") - fmt.Fprintln(os.Stderr, msg...) - default: - } -} diff --git a/cmd/cycloid/kpis/cmd.go b/cmd/cycloid/kpis/cmd.go deleted file mode 100644 index c2452ae3a..000000000 --- a/cmd/cycloid/kpis/cmd.go +++ /dev/null @@ -1,20 +0,0 @@ -package kpis - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - var cmd = &cobra.Command{ - Use: "kpi", - Aliases: []string{ - "kpis", - }, - Short: "Manage the kpis", - } - - cmd.AddCommand(NewCreateCommand(), - NewDeleteCommand(), - NewListCommand()) - return cmd -} diff --git a/cmd/cycloid/kpis/common.go b/cmd/cycloid/kpis/common.go deleted file mode 100644 index de08102b3..000000000 --- a/cmd/cycloid/kpis/common.go +++ /dev/null @@ -1,43 +0,0 @@ -package kpis - -import ( - "github.com/spf13/cobra" -) - -var ( - nameFlag string - typeFlag string - widgetFlag string - jobFlag string - configFlag string -) - -func WithFlagName(cmd *cobra.Command) string { - flagName := "name" - cmd.Flags().StringVar(&nameFlag, flagName, "", "") - return flagName -} - -func WithFlagConfig(cmd *cobra.Command) string { - flagName := "config" - cmd.Flags().StringVar(&configFlag, flagName, "", "") - return flagName -} - -func WithFlagType(cmd *cobra.Command) string { - flagName := "type" - cmd.Flags().StringVar(&typeFlag, flagName, "", "") - return flagName -} - -func WithFlagWidget(cmd *cobra.Command) string { - flagName := "widget" - cmd.Flags().StringVar(&widgetFlag, flagName, "", "") - return flagName -} - -func WithFlagJob(cmd *cobra.Command) string { - flagName := "job" - cmd.Flags().StringVar(&jobFlag, flagName, "", "") - return flagName -} diff --git a/cmd/cycloid/kpis/create.go b/cmd/cycloid/kpis/create.go deleted file mode 100644 index 09ddda18a..000000000 --- a/cmd/cycloid/kpis/create.go +++ /dev/null @@ -1,87 +0,0 @@ -package kpis - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" -) - -func NewCreateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "create", - Args: cobra.NoArgs, - Short: "create a kpi", - Example: ` - # create a build_history kpi - cy --org my-org kpi create \ - --name "Build history" \ - --type build_history \ - --widget history \ - --project foo \ - --env environment-name \ - --job hello -`, - RunE: func(cmd *cobra.Command, args []string) error { panic("Not implemented") }, //create, - } - common.RequiredFlag(WithFlagName, cmd) - common.RequiredFlag(WithFlagType, cmd) - common.RequiredFlag(WithFlagWidget, cmd) - - common.WithFlagProject(cmd) - common.WithFlagEnv(cmd) - WithFlagJob(cmd) - WithFlagConfig(cmd) - - return cmd -} - -// func create(cmd *cobra.Command, args []string) error { -// api := common.NewAPI() -// m := middleware.NewMiddleware(api) -// -// org, err := cy_args.GetOrg(cmd) -// if err != nil { -// return err -// } -// name, err := cmd.Flags().GetString("name") -// if err != nil { -// return err -// } -// env, err := cmd.Flags().GetString("env") -// if err != nil { -// return err -// } -// project, err := cmd.Flags().GetString("project") -// if err != nil { -// return err -// } -// job, err := cmd.Flags().GetString("job") -// if err != nil { -// return err -// } -// widget, err := cmd.Flags().GetString("widget") -// if err != nil { -// return err -// } -// kpiType, err := cmd.Flags().GetString("type") -// if err != nil { -// return err -// } -// config, err := cmd.Flags().GetString("config") -// if err != nil { -// return err -// } -// output, err := cmd.Flags().GetString("output") -// if err != nil { -// return errors.Wrap(err, "unable to get output flag") -// } -// -// // fetch the printer from the factory -// p, err := factory.GetPrinter(output) -// if err != nil { -// return errors.Wrap(err, "unable to get printer") -// } -// -// kpi, err := m.CreateKpi(name, kpiType, widget, org, project, job, env, config) -// return printer.SmartPrint(p, kpi, err, "Unable to create the KPI", printer.Options{}, cmd.OutOrStdout()) -// } diff --git a/cmd/cycloid/kpis/delete.go b/cmd/cycloid/kpis/delete.go deleted file mode 100644 index 36e9fbcd3..000000000 --- a/cmd/cycloid/kpis/delete.go +++ /dev/null @@ -1,53 +0,0 @@ -package kpis - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" -) - -func NewDeleteCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "delete", - Args: cobra.NoArgs, - Short: "delete a kpi", - Example: ` - # delete a kpi - cy --org my-org kpi delete \ - --canonical kpi -`, - // RunE: delete, - RunE: func(cmd *cobra.Command, args []string) error { panic("Not implemented") }, //create, - } - - common.RequiredFlag(common.WithFlagCan, cmd) - - return cmd -} - -// func delete(cmd *cobra.Command, args []string) error { -// api := common.NewAPI() -// m := middleware.NewMiddleware(api) -// -// org, err := cy_args.GetOrg(cmd) -// if err != nil { -// return err -// } -// can, err := cmd.Flags().GetString("canonical") -// if err != nil { -// return err -// } -// output, err := cmd.Flags().GetString("output") -// if err != nil { -// return errors.Wrap(err, "unable to get output flag") -// } -// -// // fetch the printer from the factory -// p, err := factory.GetPrinter(output) -// if err != nil { -// return errors.Wrap(err, "unable to get printer") -// } -// -// err = m.DeleteKpi(org, can) -// return printer.SmartPrint(p, nil, err, "unable to delete kpi", printer.Options{}, cmd.OutOrStdout()) -// } diff --git a/cmd/cycloid/kpis/list.go b/cmd/cycloid/kpis/list.go deleted file mode 100644 index de5920114..000000000 --- a/cmd/cycloid/kpis/list.go +++ /dev/null @@ -1,58 +0,0 @@ -package kpis - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" -) - -func NewListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "list kpis", - Example: ` - # list kpis - cy --org my-org kpi list -`, - // RunE: list, - RunE: func(cmd *cobra.Command, args []string) error { panic("Not implemented") }, //create, - } - - common.WithFlagProject(cmd) - common.WithFlagEnv(cmd) - - return cmd -} - -// func list(cmd *cobra.Command, args []string) error { -// api := common.NewAPI() -// m := middleware.NewMiddleware(api) -// -// org, err := cy_args.GetOrg(cmd) -// if err != nil { -// return err -// } -// project, err := cmd.Flags().GetString("project") -// if err != nil { -// return err -// } -// env, err := cmd.Flags().GetString("env") -// if err != nil { -// return err -// } -// -// output, err := cmd.Flags().GetString("output") -// if err != nil { -// return errors.Wrap(err, "unable to get output flag") -// } -// -// // fetch the printer from the factory -// p, err := factory.GetPrinter(output) -// if err != nil { -// return errors.Wrap(err, "unable to get printer") -// } -// -// kpis, err := m.ListKpi(org, project, env) -// return printer.SmartPrint(p, kpis, err, "unable to list kpis", printer.Options{}, cmd.OutOrStdout()) -// } diff --git a/cmd/cycloid/login/list.go b/cmd/cycloid/login/list.go deleted file mode 100644 index 7f9270a3b..000000000 --- a/cmd/cycloid/login/list.go +++ /dev/null @@ -1,52 +0,0 @@ -package login - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/config" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -// NewListCommand returns the cobra command holding -// the list login subcommand -func NewListCommand() *cobra.Command { - return &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "list the current logged organizations", - Example: ` - # list the organizations where the user is logged in - cy login list -`, - RunE: listLogins, - } -} - -func listLogins(cmd *cobra.Command, args []string) error { - // fetch any existing config - // we skip the error in case it's the first usage and the config - // file does not exist - conf, _ := config.Read() - - // we need to peform this hack because the printer is waiting for - // a struct or a slice of structs. Not a map, since the header of the table - // is the name of the field, we need to pass to the printer a slice of anonymous - // struct - var orgs []*struct { - Name string - Token string - } - for name, o := range conf.Organizations { - orgs = append(orgs, &struct { - Name string - Token string - }{ - Name: name, - // Special formatting to display only the 7 last chars of a token - Token: o.Token[len(o.Token)-7:], - }) - } - - return cyout.PrintWithOptions(cmd, orgs, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/login/login.go b/cmd/cycloid/login/login.go deleted file mode 100644 index 6f82b2ad3..000000000 --- a/cmd/cycloid/login/login.go +++ /dev/null @@ -1,73 +0,0 @@ -package login - -import ( - "github.com/pkg/errors" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/internal" - "github.com/cycloidio/cycloid-cli/config" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -// NewCommands returns the cobra command holding -// the login command / subcommands -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "login", - Args: cobra.NoArgs, - Short: "Login against the Cycloid console", - Example: `# Login in an org using api-key -export CY_API_KEY=xxxx -cy login --org my-org`, - RunE: login, - } - - cmd.Flags().String("api-key", "", "[deprecated] set the API key, use CY_API_KEY env var instead.") - viper.BindPFlag("api-key", cmd.Flags().Lookup("api-key")) - - cmd.AddCommand( - NewListCommand(), - ) - - return cmd -} - -func login(cmd *cobra.Command, args []string) error { - conf, _ := config.Read() - // If err != nil, the file does not exist, we create it anyway - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return errors.Wrap(err, "unable to get org flag") - } - - // Get api key via env var or cli flag - apiKey := viper.GetString("api-key") - if apiKey == "" { - return cyout.PrintWithOptions(cmd, nil, nil, "CY_API_KEY is not set or invalid", printer.Options{}) - } - - // Warn user about deprecation - if cmd.Flags().Lookup("api-key").Changed { - internal.Warning(cmd.ErrOrStderr(), "--api-key is deprecated, use CY_API_KEY env var instead") - } - - // Check for a nil map. - // This can be the case if the config file is empty - if conf.Organizations == nil { - conf.Organizations = make(map[string]config.Organization) - } - - conf.Organizations[org] = config.Organization{ - Token: apiKey, - } - - if err := config.Write(conf); err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to write config file", printer.Options{}) - } - - return nil -} diff --git a/cmd/cycloid/members/cmd.go b/cmd/cycloid/members/cmd.go deleted file mode 100644 index adb9940d4..000000000 --- a/cmd/cycloid/members/cmd.go +++ /dev/null @@ -1,34 +0,0 @@ -package members - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - var ( - example = ` - # Manage members of my-org organization - cy --org my-org members [invite|list|get|update|delete] - ` - short = "Manage members from the organization" - long = short - ) - - var cmd = &cobra.Command{ - Use: "members", - Aliases: []string{"member"}, - Example: example, - Short: short, - Long: long, - } - - cmd.AddCommand(NewUpdateCommand(), - NewDeleteCommand(), - NewListCommand(), - NewGetCommand(), - NewInviteCommand(), - NewListInvitesCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/members/delete.go b/cmd/cycloid/members/delete.go deleted file mode 100644 index 74bfe04eb..000000000 --- a/cmd/cycloid/members/delete.go +++ /dev/null @@ -1,71 +0,0 @@ -package members - -import ( - "fmt" - "strconv" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewDeleteCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "delete [id...]", - Aliases: []string{"rm"}, - Args: cyargs.RequireArgsOrFlag("id"), - Short: "Remove a user from the organization", - Example: ` - # Remove a member from my-org organization using the --id flag - cy --org my-org members delete --id 50 - - # Remove multiple members using positional args - cy --org my-org members delete 50 51 52 -`, - RunE: deleteMember, - } - - cyargs.AddMemberIDFlag(cmd) - - return cmd -} - -func deleteMember(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - if flagID, _ := cyargs.GetMemberID(cmd); flagID != 0 { - idStr := strconv.FormatUint(uint64(flagID), 10) - found := false - for _, a := range args { - if a == idStr { - found = true - break - } - } - if !found { - args = append(args, idStr) - } - } - - for _, arg := range args { - id64, parseErr := strconv.ParseUint(arg, 10, 32) - if parseErr != nil { - return fmt.Errorf("invalid member ID %q: %w", arg, parseErr) - } - id := uint32(id64) - _, err = m.DeleteMember(org, id) - if err != nil { - return cyout.Print(cmd, nil, err, fmt.Sprintf("unable to remove member %d", id)) - } - } - return nil -} diff --git a/cmd/cycloid/members/get.go b/cmd/cycloid/members/get.go deleted file mode 100644 index f3eae6b81..000000000 --- a/cmd/cycloid/members/get.go +++ /dev/null @@ -1,82 +0,0 @@ -package members - -import ( - "fmt" - "strconv" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewGetCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get [id...]", - Args: cyargs.RequireArgsOrFlag("id"), - Short: "Get the organization member", - Example: ` - # Get a member within my-org organization using the --id flag - cy --org my-org members get --id 50 - - # Get multiple members using positional args - cy --org my-org members get 50 51 52 -`, - RunE: getMember, - } - - cyargs.AddMemberIDFlag(cmd) - cyout.RegisterModel(cmd, models.MemberOrg{}) - - return cmd -} - -func getMember(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - if flagID, _ := cyargs.GetMemberID(cmd); flagID != 0 { - idStr := strconv.FormatUint(uint64(flagID), 10) - found := false - for _, a := range args { - if a == idStr { - found = true - break - } - } - if !found { - args = append(args, idStr) - } - } - - if len(args) == 1 { - id64, parseErr := strconv.ParseUint(args[0], 10, 32) - if parseErr != nil { - return fmt.Errorf("invalid member ID %q: %w", args[0], parseErr) - } - mb, _, err := m.GetMember(org, uint32(id64)) - return cyout.PrintWithOptions(cmd, mb, err, "unable to get member", memberTableOptions) - } - - results := make([]*models.MemberOrg, 0, len(args)) - for _, arg := range args { - id64, parseErr := strconv.ParseUint(arg, 10, 32) - if parseErr != nil { - return fmt.Errorf("invalid member ID %q: %w", arg, parseErr) - } - mb, _, err := m.GetMember(org, uint32(id64)) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, fmt.Sprintf("unable to get member %s", arg), memberTableOptions) - } - results = append(results, mb) - } - return cyout.PrintWithOptions(cmd, results, nil, "", memberTableOptions) -} diff --git a/cmd/cycloid/members/invite.go b/cmd/cycloid/members/invite.go deleted file mode 100644 index e2ac93815..000000000 --- a/cmd/cycloid/members/invite.go +++ /dev/null @@ -1,52 +0,0 @@ -package members - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewInviteCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "invite", - Args: cobra.NoArgs, - Short: "Invite a user to the organization", - Example: ` - # Invite a member within my-org organization - cy --org my-org members invite --role organization-member --email user@email.com -`, - RunE: inviteMember, - } - - cmd.MarkFlagRequired(cyargs.AddMemberEmailFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddMemberRoleFlag(cmd)) - - return cmd -} - -func inviteMember(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - email, err := cyargs.GetMemberEmail(cmd) - if err != nil { - return err - } - - role, err := cyargs.GetMemberRole(cmd) - if err != nil { - return err - } - - mb, _, err := m.InviteMember(org, email, role) - return cyout.PrintWithOptions(cmd, mb, err, "unable to invite member", printer.Options{}) -} diff --git a/cmd/cycloid/members/list-invites.go b/cmd/cycloid/members/list-invites.go deleted file mode 100644 index 61b1bd884..000000000 --- a/cmd/cycloid/members/list-invites.go +++ /dev/null @@ -1,46 +0,0 @@ -package members - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListInvitesCommand() *cobra.Command { - var ( - example = ` - # List all invites within my-org organization - cy --org my-org members list-invites - ` - short = "Get the list of organization members invites" - long = short - ) - - var cmd = &cobra.Command{ - Use: "list-invites", - Args: cobra.NoArgs, - Example: example, - Short: short, - Long: long, - RunE: listInvites, - } - - return cmd -} - -func listInvites(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - mbs, _, err := m.ListInvites(org) - return cyout.PrintWithOptions(cmd, mbs, err, "unable to list invites", printer.Options{}) -} diff --git a/cmd/cycloid/members/list.go b/cmd/cycloid/members/list.go deleted file mode 100644 index c6ec1399b..000000000 --- a/cmd/cycloid/members/list.go +++ /dev/null @@ -1,52 +0,0 @@ -package members - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var memberTableOptions = printer.Options{ - Columns: []string{"Username", "Email", "GivenName", "FamilyName"}, - Identifier: "Username", -} - -func NewListCommand() *cobra.Command { - var ( - example = ` - # List all the members within my-org organization - cy --org my-org members list - ` - short = "Get the list of organization members" - long = short - ) - - var cmd = &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Example: example, - Short: short, - Long: long, - RunE: listMembers, - } - cyout.RegisterModel(cmd, models.User{}) - return cmd -} - -func listMembers(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - mbs, _, err := m.ListMembers(org) - return cyout.PrintWithOptions(cmd, mbs, err, "unable to list members", memberTableOptions) -} diff --git a/cmd/cycloid/members/update.go b/cmd/cycloid/members/update.go deleted file mode 100644 index 428369c87..000000000 --- a/cmd/cycloid/members/update.go +++ /dev/null @@ -1,52 +0,0 @@ -package members - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUpdateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "update", - Args: cobra.NoArgs, - Short: "Update a member", - Example: ` - # Update a member within my-org organization - cy --org my-org members update --id 50 --role my-role -`, - RunE: updateMember, - } - - cmd.MarkFlagRequired(cyargs.AddMemberIDFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddMemberRoleFlag(cmd)) - - return cmd -} - -func updateMember(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - id, err := cyargs.GetMemberID(cmd) - if err != nil { - return err - } - - role, err := cyargs.GetMemberRole(cmd) - if err != nil { - return err - } - - mb, _, err := m.UpdateMember(org, id, role) - return cyout.PrintWithOptions(cmd, mb, err, "unable to update member", printer.Options{}) -} diff --git a/cmd/cycloid/middleware/catalog_repositories.go b/cmd/cycloid/middleware/catalog_repositories.go deleted file mode 100644 index 266649927..000000000 --- a/cmd/cycloid/middleware/catalog_repositories.go +++ /dev/null @@ -1,150 +0,0 @@ -package middleware - -import ( - "net/http" - "net/url" - - "github.com/pkg/errors" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// ListCatalogRepositories lists catalog repositories for an organization. -// -// NOTE: the backend handler for this route does not call lhs.ParseQuery, so -// LHS filters are accepted by the middleware but silently ignored server-side. -func (m *middleware) ListCatalogRepositories(org string, filters ...LHSFilter) ([]*models.ServiceCatalogSource, *http.Response, error) { - var result []*models.ServiceCatalogSource - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "service_catalog_sources"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetCatalogRepository(org, catalogRepo string) (*models.ServiceCatalogSource, *http.Response, error) { - var result *models.ServiceCatalogSource - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "service_catalog_sources", catalogRepo}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeleteCatalogRepository(org, catalogRepo string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "service_catalog_sources", catalogRepo}, - }, nil) - return resp, err -} - -func (m *middleware) CreateCatalogRepository(org, name, url, branch, cred, visibility, teamCanonical string) (*models.ServiceCatalogSource, *http.Response, error) { - var body *models.NewServiceCatalogSource - - if len(cred) != 0 { - body = &models.NewServiceCatalogSource{ - Branch: &branch, - CredentialCanonical: cred, - Name: &name, - URL: &url, - } - } else { - body = &models.NewServiceCatalogSource{ - Branch: &branch, - Name: &name, - URL: &url, - } - } - - switch visibility { - case "shared", "local", "hidden": - body.Visibility = visibility - case "": - break - default: - return nil, nil, errors.New("invalid visibility parameter for CreateCatalogRepository, accepted values are 'local', 'shared' or 'hidden'") - } - - if teamCanonical != "" { - body.TeamCanonical = teamCanonical - } - - var result *models.ServiceCatalogSource - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "service_catalog_sources"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UpdateCatalogRepository(org, catalogRepo string, name, url, branch, cred string, visibility *string) (*models.ServiceCatalogSource, *http.Response, error) { - body := &models.UpdateServiceCatalogSource{ - Branch: branch, - CredentialCanonical: cred, - Name: &name, - URL: &url, - } - - var result *models.ServiceCatalogSource - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "service_catalog_sources", catalogRepo}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) RefreshCatalogRepository(org, catalogRepo string) (*models.ServiceCatalogChanges, *http.Response, error) { - var result *models.ServiceCatalogChanges - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "service_catalog_sources", catalogRepo, "refresh"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// RefreshCatalogRepositoryVersions triggers an immediate re-index of all branches and tags -// for the given catalog repository. The backend clones the git repository, fetches all refs, -// and updates the service_catalog_source_versions table synchronously before returning. -// -// This resolves the eventual-consistency race where a freshly created catalog repository has no -// version rows yet (the background cron that populates them runs every ~10 minutes by default). -func (m *middleware) RefreshCatalogRepositoryVersions(org, catalogRepo string) ([]*StackVersion, *http.Response, error) { - var result []*StackVersion - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "service_catalog_sources", catalogRepo, "versions", "refresh"}, - Query: url.Values{ - "sync_presence": []string{"true"}, - }, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/catalog_repositories_test.go b/cmd/cycloid/middleware/catalog_repositories_test.go deleted file mode 100644 index 02381dec7..000000000 --- a/cmd/cycloid/middleware/catalog_repositories_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestListCatalogRepositories(t *testing.T) { - m := config.Middleware - - repos, _, err := m.ListCatalogRepositories(config.Org) - require.NoError(t, err) - assert.NotEmpty(t, repos) -} - -func TestGetCatalogRepository(t *testing.T) { - m := config.Middleware - - repo, _, err := m.GetCatalogRepository(config.Org, *config.CatalogRepo.Canonical) - require.NoError(t, err) - assert.Equal(t, *config.CatalogRepo.Canonical, *repo.Canonical) -} - -func TestRefreshCatalogRepository(t *testing.T) { - m := config.Middleware - - changes, _, err := m.RefreshCatalogRepository(config.Org, *config.CatalogRepo.Canonical) - require.NoError(t, err) - assert.NotNil(t, changes) -} diff --git a/cmd/cycloid/middleware/component_pipelines.go b/cmd/cycloid/middleware/component_pipelines.go deleted file mode 100644 index daf473829..000000000 --- a/cmd/cycloid/middleware/component_pipelines.go +++ /dev/null @@ -1,141 +0,0 @@ -package middleware - -import ( - "net/http" - "net/url" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func componentsPipelineName(project, env string) string { - return project + "-" + env -} - -func (m *middleware) PausePipeline(org, project, env, component, pipelineName string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipelineName, "pause"}, - }, nil) - return resp, err -} - -func (m *middleware) UnpausePipeline(org, project, env, component, pipelineName string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipelineName, "unpause"}, - }, nil) - return resp, err -} - -func (m *middleware) DiffPipeline(org, project, env, component, pipelineName, yamlPipeline, yamlVariables string, checkCredentials bool) (*models.PipelineDiffs, *http.Response, error) { - body := &models.UpdatePipeline{ - PassedConfig: yamlPipeline, - YamlVars: yamlVariables, - CheckCredentials: checkCredentials, - } - - var result *models.PipelineDiffs - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipelineName, "diff"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) CreatePipeline(org, project, env, pipeline, component, yamlPipeline, yamlVariables string, checkCredentials bool) (*models.Pipeline, *http.Response, error) { - pipelineName := componentsPipelineName(project, env) - - body := &models.NewPipeline{ - PipelineName: &pipelineName, - PassedConfig: yamlPipeline, - YamlVars: yamlVariables, - CheckCredentials: checkCredentials, - } - - var result *models.Pipeline - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) RenamePipeline(org, project, env, component, pipeline, newName string) (*http.Response, error) { - // renamePipeline uses a query param for the new name - query := url.Values{"pipeline_name": []string{newName}} - - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "rename"}, - Query: query, - }, nil) - return resp, err -} - -func (m *middleware) SyncedPipeline(org, project, env, component, pipeline string) (*models.PipelineStatus, *http.Response, error) { - var result *models.PipelineStatus - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "synced"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetPipeline(org, project, env, component, pipeline string) (*models.Pipeline, *http.Response, error) { - var result *models.Pipeline - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UpdatePipeline(org, project, env, component, pipelineName, yamlPipeline, yamlVariables string, checkCredentials bool) (*models.Pipeline, *http.Response, error) { - body := &models.UpdatePipeline{ - PassedConfig: yamlPipeline, - YamlVars: yamlVariables, - CheckCredentials: checkCredentials, - } - - var result *models.Pipeline - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipelineName}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeletePipeline(org, project, env, component, pipeline string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline}, - }, nil) - return resp, err -} diff --git a/cmd/cycloid/middleware/component_pipelines_jobs.go b/cmd/cycloid/middleware/component_pipelines_jobs.go deleted file mode 100644 index 7406ca5c4..000000000 --- a/cmd/cycloid/middleware/component_pipelines_jobs.go +++ /dev/null @@ -1,64 +0,0 @@ -package middleware - -import ( - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) GetJobs(org, project, env, component, pipeline string) ([]*models.Job, *http.Response, error) { - var result []*models.Job - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetJob(org, project, env, component, pipeline, job string) (*models.Job, *http.Response, error) { - var result *models.Job - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs", job}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) PauseJob(org, project, env, component, pipeline, job string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs", job, "pause"}, - }, nil) - return resp, err -} - -func (m *middleware) UnPauseJob(org, project, env, component, pipeline, job string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs", job, "unpause"}, - }, nil) - return resp, err -} - -func (m *middleware) ClearTaskCache(org, project, env, component, pipeline, job, step string) (*models.ClearTaskCache, *http.Response, error) { - var result *models.ClearTaskCache - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs", job, "tasks", step, "cache"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/component_pipelines_jobs_builds.go b/cmd/cycloid/middleware/component_pipelines_jobs_builds.go deleted file mode 100644 index 2fec5bf42..000000000 --- a/cmd/cycloid/middleware/component_pipelines_jobs_builds.go +++ /dev/null @@ -1,179 +0,0 @@ -package middleware - -import ( - "bytes" - "context" - "fmt" - "io" - "net/http" - "net/url" - "path" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) GetBuilds(org, project, env, component, pipeline, job string) ([]*models.Build, *http.Response, error) { - var result []*models.Build - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs", job, "builds"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetBuild(org, project, env, component, pipeline, job, buildID string) (*models.Build, *http.Response, error) { - var result *models.Build - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs", job, "builds", buildID}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) CreateBuild(org, project, env, component, pipeline, job string) (*models.Build, *http.Response, error) { - var result *models.Build - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs", job, "builds"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) RerunBuild(org, project, env, component, pipeline, job, buildID string) (*models.Build, *http.Response, error) { - var result *models.Build - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs", job, "builds", buildID}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) AbortBuild(org, project, env, component, pipeline, job, buildID string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs", job, "builds", buildID, "abort"}, - }, nil) - return resp, err -} - -// GetBuildEvents returns the build events as a raw string (text/event-stream). -func (m *middleware) GetBuildEvents(org, project, env, component, pipeline, buildID string) (*string, *http.Response, error) { - body, resp, err := m.OpenBuildEventsStream(context.Background(), org, project, env, component, pipeline, buildID, "") - if err != nil { - return nil, resp, err - } - defer body.Close() - - content, err := io.ReadAll(body) - if err != nil { - return nil, resp, fmt.Errorf("failed to read response body: %w", err) - } - - s := string(content) - return &s, resp, nil -} - -// OpenBuildEventsStream opens a text/event-stream reader for build logs. -func (m *middleware) OpenBuildEventsStream( - ctx context.Context, - org, project, env, component, pipeline, buildID, lastEventID string, -) (io.ReadCloser, *http.Response, error) { - baseURL, err := url.Parse(m.api.Config.URL) - if err != nil { - return nil, nil, fmt.Errorf("failed to parse base url: %w", err) - } - - baseURL.Path = path.Join( - baseURL.Path, - "organizations", org, - "projects", project, - "environments", env, - "components", component, - "pipelines", pipeline, - "builds", buildID, - "events", - ) - - req, err := http.NewRequestWithContext(ctx, "GET", baseURL.String(), nil) - if err != nil { - return nil, nil, fmt.Errorf("failed to create request: %w", err) - } - - req.Header.Set("Accept", "text/event-stream") - req.Header.Set("Authorization", "Bearer "+m.api.GetToken(&org)) - if lastEventID != "" { - req.Header.Set("Last-Event-ID", lastEventID) - } - - resp, err := m.GenericClient.Do(req) - if err != nil { - return nil, nil, fmt.Errorf("HTTP request failed: %w", err) - } - - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - body, readErr := io.ReadAll(resp.Body) - resp.Body.Close() - if readErr != nil { - return nil, resp, fmt.Errorf("failed to read error response body: %w", readErr) - } - return nil, resp, newAPIResponseError(resp, bytes.TrimSpace(body), nil, "GET") - } - - return resp.Body, resp, nil -} - -func (m *middleware) GetBuildPlan(org, project, env, component, pipeline, job, buildID string) (*models.PublicPlan, *http.Response, error) { - var result *models.PublicPlan - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs", job, "builds", buildID, "plan"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetBuildPreparation(org, project, env, component, pipeline, job, buildID string) (*models.Preparation, *http.Response, error) { - var result *models.Preparation - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs", job, "builds", buildID, "preparation"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetBuildResources(org, project, env, component, pipeline, job, buildID string) (*models.BuildInputsOutputs, *http.Response, error) { - var result *models.BuildInputsOutputs - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "pipelines", pipeline, "jobs", job, "builds", buildID, "resources"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/component_pipelines_jobs_builds_test.go b/cmd/cycloid/middleware/component_pipelines_jobs_builds_test.go deleted file mode 100644 index d5f93dceb..000000000 --- a/cmd/cycloid/middleware/component_pipelines_jobs_builds_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package middleware_test - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGetBuilds(t *testing.T) { - m := config.Middleware - - pipelineName := fmt.Sprintf("%s-%s-%s", *config.Project.Canonical, *config.Environment.Canonical, *config.Component.Canonical) - - jobs, _, err := m.GetJobs(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *config.Component.Canonical, pipelineName) - require.NoError(t, err) - require.NotEmpty(t, jobs, "expected at least one job in the default component pipeline") - - builds, _, err := m.GetBuilds(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *config.Component.Canonical, pipelineName, *jobs[0].Name) - require.NoError(t, err) - assert.NotNil(t, builds) -} diff --git a/cmd/cycloid/middleware/component_pipelines_jobs_test.go b/cmd/cycloid/middleware/component_pipelines_jobs_test.go deleted file mode 100644 index d7d24ac2d..000000000 --- a/cmd/cycloid/middleware/component_pipelines_jobs_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package middleware_test - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGetJobs(t *testing.T) { - m := config.Middleware - - pipelineName := fmt.Sprintf("%s-%s-%s", *config.Project.Canonical, *config.Environment.Canonical, *config.Component.Canonical) - - jobs, _, err := m.GetJobs(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *config.Component.Canonical, pipelineName) - require.NoError(t, err) - assert.NotNil(t, jobs) -} diff --git a/cmd/cycloid/middleware/component_pipelines_test.go b/cmd/cycloid/middleware/component_pipelines_test.go deleted file mode 100644 index 232c19b66..000000000 --- a/cmd/cycloid/middleware/component_pipelines_test.go +++ /dev/null @@ -1,144 +0,0 @@ -package middleware_test - -import ( - "fmt" - "strconv" - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -func TestComponentPipeline(t *testing.T) { - m := config.Middleware - - component, err := config.NewTestComponent( - *config.Project.Canonical, *config.Environment.Canonical, t.Name(), config.Org+":"+pipelineTestStackCanonical, pipelineTestStackUseCase, "", "", *config.CatalogRepoVersionStacks.CommitHash, pipelineTestDefaultVars, - ) - if err != nil { - t.Errorf("failed to setup base component for test %q: %v", t.Name(), err) - } - - t.Run("GetPipeline", func(t *testing.T) { - pipelineName := fmt.Sprintf("%s-%s-%s", *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical) - got, _, err := m.GetPipeline(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical, pipelineName) - if err != nil { - t.Errorf("middleware.GetComponentPipelines() error = %v", err) - return - } - - got.Component.Project.Owner = component.Project.Owner - require.Equal(t, *got.Component, *component) - }) - - t.Run("PausePipeline", func(t *testing.T) { - pipelineName := fmt.Sprintf("%s-%s-%s", *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical) - _, err := m.PausePipeline(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical, pipelineName) - if err != nil { - t.Errorf("%s error = %v", t.Name(), err) - return - } - }) - - t.Run("UnpausePipeline", func(t *testing.T) { - pipelineName := fmt.Sprintf("%s-%s-%s", *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical) - _, err := m.UnpausePipeline(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical, pipelineName) - if err != nil { - t.Errorf("%s error = %v", t.Name(), err) - return - } - }) - - t.Run("SynchedPipelineOk", func(t *testing.T) { - pipelineName := fmt.Sprintf("%s-%s-%s", *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical) - got, _, err := m.SyncedPipeline(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical, pipelineName) - if err != nil { - t.Errorf("%s error = %v", t.Name(), err) - return - } - - if *got.Synced != "synced" { - t.Errorf("pipeline must be in sync: %v", *got) - } - }) - - t.Run("UpdatePipelineAndGetJobs", func(t *testing.T) { - newPipeline := `--- -jobs: -- name: job-hello-world - build_logs_to_retain: 1 - plan: - - task: hello-world - config: - platform: linux - image_resource: - type: registry-image - source: {repository: busybox, tag: latest} - run: - path: /bin/sh - args: - - -ec - - | - echo ${MESSAGE} - params: - MESSAGE: ((message)) -` - pipelineName := fmt.Sprintf("%s-%s-%s", *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical) - updatedPipeline, _, err := m.UpdatePipeline(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical, pipelineName, newPipeline, "---\nmessage: hello", false) - if err != nil { - t.Errorf("%s error = %v", t.Name(), err) - return - } - - pipelineJobs, _, err := m.GetJobs(config.Org, *updatedPipeline.Project.Canonical, *updatedPipeline.Environment.Canonical, *updatedPipeline.Component.Canonical, *updatedPipeline.Name) - if err != nil { - t.Logf("failed to get jobs in pipeline '%s' in test '%s': %s", *updatedPipeline.Name, t.Name(), err) - return - } - - if len(pipelineJobs) != 1 { - t.Errorf("invalid number of jobs, must be only one, got: %d", len(pipelineJobs)) - return - } - - if *pipelineJobs[0].Name != "job-hello-world" { - t.Errorf("job name should be 'job-hello-world' as in the updated pipeline, got: %s", *pipelineJobs[0].Name) - return - } - - t.Run("TestBuilds", func(t *testing.T) { - build, _, err := m.CreateBuild(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical, *updatedPipeline.Name, *pipelineJobs[0].Name) - if err != nil { - t.Errorf("failed to trigger build in job '%s': %s", *pipelineJobs[0].Name, err) - return - } - - buildIDStr := strconv.Itoa(int(*build.ID)) - getBuild, _, err := m.GetBuild(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical, *updatedPipeline.Name, *pipelineJobs[0].Name, buildIDStr) - if err != nil { - t.Errorf("failed to get build in job '%s': %s", *pipelineJobs[0].Name, err) - return - } - - if *build.ID != *getBuild.ID { - t.Errorf("build are not matching:\ngot: %v\nexpected:\n%v", *getBuild, *build) - return - } - - time.Sleep(1 * time.Second) - - _, err = m.AbortBuild(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical, *updatedPipeline.Name, *pipelineJobs[0].Name, buildIDStr) - if err != nil { - t.Errorf("failed to abort build '%s': %s", buildIDStr, err) - } - - // // Add a bit of time, concourse seems to not like it - // time.Sleep(3 * time.Second) - // - // _, err = m.RerunBuild(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *component.Canonical, *updatedPipeline.Name, *pipelineJobs[0].Name, buildIDStr) - // if err != nil { - // t.Errorf("failed to re-run build '%s': %s", buildIDStr, err) - // } - }) - }) -} diff --git a/cmd/cycloid/middleware/config_repositories.go b/cmd/cycloid/middleware/config_repositories.go deleted file mode 100644 index df0782e7d..000000000 --- a/cmd/cycloid/middleware/config_repositories.go +++ /dev/null @@ -1,99 +0,0 @@ -package middleware - -import ( - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// ListConfigRepositories lists config repositories for an organization. -// -// NOTE: the backend handler for this route does not call lhs.ParseQuery, so -// LHS filters are accepted by the middleware but silently ignored server-side. -func (m *middleware) ListConfigRepositories(org string, filters ...LHSFilter) ([]*models.ConfigRepository, *http.Response, error) { - var result []*models.ConfigRepository - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "config_repositories"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetConfigRepository(org, configRepo string) (*models.ConfigRepository, *http.Response, error) { - var result *models.ConfigRepository - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "config_repositories", configRepo}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeleteConfigRepository(org, configRepo string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "config_repositories", configRepo}, - }, nil) - return resp, err -} - -func (m *middleware) CreateConfigRepository(org, name, canonical, url, branch, cred string, setDefault bool) (*models.ConfigRepository, *http.Response, error) { - if name == "" { - name = canonical - } - - body := &models.NewConfigRepository{ - Branch: &branch, - Canonical: canonical, - Default: &setDefault, - Name: &name, - URL: &url, - } - - if cred != "" { - body.CredentialCanonical = &cred - } - - var result *models.ConfigRepository - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "config_repositories"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UpdateConfigRepository(org, configRepo, cred, name, url, branch string, setDefault bool) (*models.ConfigRepository, *http.Response, error) { - body := &models.UpdateConfigRepository{ - Branch: &branch, - CredentialCanonical: &cred, - Default: &setDefault, - Name: &name, - URL: &url, - } - - var result *models.ConfigRepository - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "config_repositories", configRepo}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/config_repositories_test.go b/cmd/cycloid/middleware/config_repositories_test.go deleted file mode 100644 index 0d993b55c..000000000 --- a/cmd/cycloid/middleware/config_repositories_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestListConfigRepositories(t *testing.T) { - m := config.Middleware - - repos, _, err := m.ListConfigRepositories(config.Org) - require.NoError(t, err) - assert.NotEmpty(t, repos) -} - -func TestGetConfigRepository(t *testing.T) { - m := config.Middleware - - repo, _, err := m.GetConfigRepository(config.Org, *config.ConfigRepo.Canonical) - require.NoError(t, err) - assert.Equal(t, *config.ConfigRepo.Canonical, *repo.Canonical) -} diff --git a/cmd/cycloid/middleware/cost_estimation.go b/cmd/cycloid/middleware/cost_estimation.go deleted file mode 100644 index b197e642e..000000000 --- a/cmd/cycloid/middleware/cost_estimation.go +++ /dev/null @@ -1,28 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// CostEstimation will consume the backend API endpoint for cost estimation -func (m *middleware) CostEstimation(org string, plan []byte) (*models.CostEstimationResult, *http.Response, error) { - tfplan := string(plan) - body := &models.TerraformPlanInput{ - Tfplan: &tfplan, - } - - var result *models.CostEstimationResult - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "cost_estimation", "tfplan"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("unable to estimate cost infrastructure: %w", err) - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/credentials.go b/cmd/cycloid/middleware/credentials.go deleted file mode 100644 index 5e4c099c4..000000000 --- a/cmd/cycloid/middleware/credentials.go +++ /dev/null @@ -1,117 +0,0 @@ -package middleware - -import ( - "net/http" - "net/url" - "regexp" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) CreateCredential(org, name, credentialType string, rawCred *models.CredentialRaw, path, canonical, description string) (*models.Credential, *http.Response, error) { - if path == "" { - re := regexp.MustCompile(`[^a-zA-z0-9_\-./]`) - path = re.ReplaceAllString(name, "-") - } - - body := &models.NewCredential{ - Description: description, - Name: &name, - Path: &path, - Raw: rawCred, - Type: &credentialType, - Canonical: canonical, - } - - var result *models.Credential - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "credentials"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UpdateCredential(org, name, credentialType string, rawCred *models.CredentialRaw, path, canonical, description string) (*models.Credential, *http.Response, error) { - if path == "" { - re := regexp.MustCompile(`[^a-zA-z0-9_\-./]`) - path = re.ReplaceAllString(name, "-") - } - - body := &models.UpdateCredential{ - Description: description, - Name: &name, - Path: &path, - Raw: rawCred, - Type: &credentialType, - Canonical: &canonical, - } - - var result *models.Credential - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "credentials", canonical}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetCredential(org, credential string) (*models.Credential, *http.Response, error) { - var result *models.Credential - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "credentials", credential}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeleteCredential(org, credential string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "credentials", credential}, - }, nil) - return resp, err -} - -// ListCredentials lists credentials for an organization. -// -// NOTE: the backend handler for this route does not call lhs.ParseQuery, so -// LHS filters are accepted by the middleware but silently ignored server-side. -func (m *middleware) ListCredentials(org, credentialType string, filters ...LHSFilter) ([]*models.CredentialSimple, *http.Response, error) { - // Explicit pagination matches swagger defaults (page_size 1000) so callers such as - // `credential create --update` do not miss an existing credential on backends that - // use a smaller default page size. - query := url.Values{ - "page_index": []string{"1"}, - "page_size": []string{"1000"}, - } - if credentialType != "" { - query.Set("credential_type", credentialType) - } - - var result []*models.CredentialSimple - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "credentials"}, - Query: query, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/credentials_test.go b/cmd/cycloid/middleware/credentials_test.go deleted file mode 100644 index 15014d48b..000000000 --- a/cmd/cycloid/middleware/credentials_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -func TestCredentialsCRUD(t *testing.T) { - m := config.Middleware - - canonical := testcfg.RandomCanonical("test-cred") - name := "Test Credential" - raw := &models.CredentialRaw{ - Password: "test-password", - Username: "test-user", - } - - created, _, err := m.CreateCredential(config.Org, name, "basic_auth", raw, "", canonical, "test credential") - require.NoError(t, err, "CreateCredential should succeed") - require.NotNil(t, created) - - defer func() { - _, err := m.DeleteCredential(config.Org, *created.Canonical) - require.NoError(t, err, "DeleteCredential should succeed") - }() - - got, _, err := m.GetCredential(config.Org, *created.Canonical) - require.NoError(t, err, "GetCredential should succeed") - assert.Equal(t, *created.Canonical, *got.Canonical) - - list, _, err := m.ListCredentials(config.Org, "") - require.NoError(t, err, "ListCredentials should succeed") - assert.NotEmpty(t, list) - - updated, _, err := m.UpdateCredential(config.Org, name, "basic_auth", raw, "", canonical, "updated description") - require.NoError(t, err, "UpdateCredential should succeed") - assert.Equal(t, "updated description", updated.Description) -} diff --git a/cmd/cycloid/middleware/cycloid.go b/cmd/cycloid/middleware/cycloid.go deleted file mode 100644 index 982d16a24..000000000 --- a/cmd/cycloid/middleware/cycloid.go +++ /dev/null @@ -1,35 +0,0 @@ -package middleware - -import ( - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// GetAppVersion returns the version of the running Cycloid server -func (m *middleware) GetAppVersion() (*models.AppVersion, *http.Response, error) { - var result *models.AppVersion - resp, err := m.GenericRequest(Request{ - Method: "GET", - NoAuth: true, - Route: []string{"version"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// GetStatus returns the status of the various Cycloid services -func (m *middleware) GetStatus() (*models.GeneralStatus, *http.Response, error) { - var result *models.GeneralStatus - resp, err := m.GenericRequest(Request{ - Method: "GET", - NoAuth: true, - Route: []string{"status"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/cycloid_test.go b/cmd/cycloid/middleware/cycloid_test.go deleted file mode 100644 index 26b24008b..000000000 --- a/cmd/cycloid/middleware/cycloid_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGetAppVersion(t *testing.T) { - m := config.Middleware - - version, _, err := m.GetAppVersion() - require.NoError(t, err) - assert.NotNil(t, version) -} - -func TestGetStatus(t *testing.T) { - m := config.Middleware - - status, _, err := m.GetStatus() - require.NoError(t, err) - assert.NotNil(t, status) -} diff --git a/cmd/cycloid/middleware/debug.go b/cmd/cycloid/middleware/debug.go deleted file mode 100644 index d3480a3a6..000000000 --- a/cmd/cycloid/middleware/debug.go +++ /dev/null @@ -1,80 +0,0 @@ -package middleware - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" - "os" - "strings" - "time" -) - -// requestLogger formats and writes HTTP debug logs to stderr. -// Update the Log* methods here to change the output format for all requests. -type requestLogger struct{} - -// logRequest logs an outgoing HTTP request to stderr. -func (l *requestLogger) logRequest(req *http.Request, body []byte) { - var sb strings.Builder - fmt.Fprintf(&sb, "\n[DEBUG] → %s %s\n", req.Method, req.URL.String()) - sb.WriteString("Request Headers:\n") - for k, vs := range req.Header { - v := strings.Join(vs, ", ") - if strings.EqualFold(k, "Authorization") { - v = redactAuth(v) - } - fmt.Fprintf(&sb, " %s: %s\n", k, v) - } - if len(body) > 0 { - sb.WriteString("Request Body:\n") - sb.WriteString(prettyJSON(sanitizeBody(body))) - sb.WriteString("\n") - } - fmt.Fprint(os.Stderr, sb.String()) -} - -// logResponse logs an incoming HTTP response to stderr. -func (l *requestLogger) logResponse(resp *http.Response, body []byte, elapsed time.Duration) { - var sb strings.Builder - fmt.Fprintf(&sb, "[DEBUG] ← %s (%dms)\n", resp.Status, elapsed.Milliseconds()) - sb.WriteString("Response Headers:\n") - for k, vs := range resp.Header { - fmt.Fprintf(&sb, " %s: %s\n", k, strings.Join(vs, ", ")) - } - if len(body) > 0 { - sb.WriteString("Response Body:\n") - sb.WriteString(prettyJSON(sanitizeBody(body))) - sb.WriteString("\n") - } - fmt.Fprint(os.Stderr, sb.String()) -} - -// httpDebugLogger is the package-level logger used by GenericRequest. -var httpDebugLogger = &requestLogger{} - -// redactAuth masks all but the last 5 characters of a Bearer token so the -// caller can verify which key is in use without exposing the full secret. -func redactAuth(value string) string { - const prefix = "Bearer " - if strings.HasPrefix(value, prefix) { - token := value[len(prefix):] - if len(token) > 5 { - return prefix + "***" + token[len(token)-5:] - } - return prefix + "***" - } - if len(value) > 5 { - return "***" + value[len(value)-5:] - } - return "***" -} - -// prettyJSON returns an indented JSON string, or the raw bytes if indenting fails. -func prettyJSON(data []byte) string { - var buf bytes.Buffer - if err := json.Indent(&buf, data, "", " "); err != nil { - return string(data) - } - return buf.String() -} diff --git a/cmd/cycloid/middleware/environment_pipelines.go b/cmd/cycloid/middleware/environment_pipelines.go deleted file mode 100644 index 7b1046676..000000000 --- a/cmd/cycloid/middleware/environment_pipelines.go +++ /dev/null @@ -1,21 +0,0 @@ -package middleware - -import ( - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// GetEnvPipelines list all pipeline of a designated env. -func (m *middleware) GetEnvPipelines(org, project, env string) ([]*models.Pipeline, *http.Response, error) { - var result []*models.Pipeline - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "pipelines"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/environment_pipelines_test.go b/cmd/cycloid/middleware/environment_pipelines_test.go deleted file mode 100644 index f6f633d76..000000000 --- a/cmd/cycloid/middleware/environment_pipelines_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGetEnvPipelines(t *testing.T) { - m := config.Middleware - - pipelines, _, err := m.GetEnvPipelines(config.Org, *config.Project.Canonical, *config.Environment.Canonical) - require.NoError(t, err) - assert.NotNil(t, pipelines) -} diff --git a/cmd/cycloid/middleware/errors.go b/cmd/cycloid/middleware/errors.go deleted file mode 100644 index 26388aa5a..000000000 --- a/cmd/cycloid/middleware/errors.go +++ /dev/null @@ -1,63 +0,0 @@ -package middleware - -import ( - "fmt" - "regexp" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -type ErrorPayloader interface { - Error() string - GetPayload() *models.ErrorPayload -} - -type APIError struct { - HTTPMethod string - URL string - HTTPCode string - APIAction string - - Payload *models.ErrorPayload -} - -var reAPIError = regexp.MustCompile(`\[(?P\w+)\s(?P.*)\]\[(?P\d{3})\]\s(?P\w+)\s`) - -// NewAPIError will try to convert the err to a more standard one if possible, -// if the err does not implement ErrorPayloader and not match the reApiError -// then nothing will be done and the same err will be returned -func NewAPIError(err error) error { - ep, ok := err.(ErrorPayloader) - // If it's not implementing the interface then we just return - // the old error - if !ok { - return err - } - - match := reAPIError.FindStringSubmatch(ep.Error()) - if match == nil { - // If even being the ErrorPayload we cannot match the string - // we just still return the old err - return err - } - - apierr := APIError{ - HTTPMethod: match[1], - URL: match[2], - HTTPCode: match[3], - APIAction: match[4], - - Payload: ep.GetPayload(), - } - - return &apierr -} - -func (a *APIError) Error() string { - var msg string - - if a.Payload != nil && len(a.Payload.Errors) != 0 && a.Payload.Errors[0].Message != nil { - msg = *a.Payload.Errors[0].Message - } - return fmt.Sprintf("A %s error was returned on %q call with message: %s", a.HTTPCode, a.APIAction, msg) -} diff --git a/cmd/cycloid/middleware/errors_test.go b/cmd/cycloid/middleware/errors_test.go deleted file mode 100644 index dfe69336d..000000000 --- a/cmd/cycloid/middleware/errors_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package middleware_test - -import ( - "net/http" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func ptrStr(s string) *string { return &s } - -func TestAPIResponseError(t *testing.T) { - t.Run("ErrorWithPayload", func(t *testing.T) { - err := &middleware.APIResponseError{ - StatusCode: 422, - Status: "422 Unprocessable Entity", - Payload: &models.ErrorPayload{ - Errors: []*models.ErrorDetailsItem{ - { - Code: ptrStr("code"), - Details: []string{"some", "details"}, - Message: ptrStr("the error that actually returned the BE"), - }, - }, - }, - } - - assert.Equal(t, 422, err.StatusCode) - assert.Equal(t, "API error 422: the error that actually returned the BE", err.Error()) - }) - - t.Run("ErrorWithoutPayload", func(t *testing.T) { - err := &middleware.APIResponseError{ - StatusCode: 500, - Status: "500 Internal Server Error", - } - assert.Equal(t, "API error 500: 500 Internal Server Error", err.Error()) - }) - - t.Run("ErrorWithoutPayloadFallbackToRawBodyAndPath", func(t *testing.T) { - err := &middleware.APIResponseError{ - StatusCode: 422, - Status: "422 Unprocessable Entity", - Path: "/organizations/org/projects/project/environments/env/components", - Body: []byte("stack branch simple-terraform not found"), - } - assert.Equal( - t, - `API error 422 on "/organizations/org/projects/project/environments/env/components": stack branch simple-terraform not found`, - err.Error(), - ) - }) - - t.Run("GetPayload", func(t *testing.T) { - payload := &models.ErrorPayload{} - err := &middleware.APIResponseError{ - StatusCode: http.StatusConflict, - Payload: payload, - } - assert.Equal(t, payload, err.GetPayload()) - }) - - t.Run("ErrorWithoutPayloadFallbackToRawBodyWithoutPath", func(t *testing.T) { - err := &middleware.APIResponseError{ - StatusCode: 422, - Status: "422 Unprocessable Entity", - Body: []byte("stack branch simple-terraform not found"), - } - assert.Equal( - t, - "API error 422: stack branch simple-terraform not found", - err.Error(), - ) - }) -} diff --git a/cmd/cycloid/middleware/event.go b/cmd/cycloid/middleware/event.go deleted file mode 100644 index d36932790..000000000 --- a/cmd/cycloid/middleware/event.go +++ /dev/null @@ -1,65 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) SendEvent(org, eventType, title, message, severity string, tags map[string]string, color string) (*http.Response, error) { - var ts []*models.Tag - - for k, v := range tags { - _k := k - _v := v - tag := &models.Tag{ - Key: &_k, - Value: &_v, - } - ts = append(ts, tag) - } - - body := &models.NewEvent{ - Tags: ts, - Type: &eventType, - Title: &title, - Color: color, - Severity: &severity, - Message: &message, - } - - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "events"}, - Body: body, - }, nil) - return resp, err -} - -func (m *middleware) ListEvents(org string, eventType, eventSeverity []string, begin, end uint64) ([]*models.Event, *http.Response, error) { - query := url.Values{} - query.Set("begin", strconv.FormatUint(begin, 10)) - query.Set("end", strconv.FormatUint(end, 10)) - for _, s := range eventSeverity { - query.Add("severity", s) - } - for _, t := range eventType { - query.Add("type", t) - } - - var result []*models.Event - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "events"}, - Query: query, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to list events: %w", err) - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/event_test.go b/cmd/cycloid/middleware/event_test.go deleted file mode 100644 index 8e1b15007..000000000 --- a/cmd/cycloid/middleware/event_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestSendEvent(t *testing.T) { - m := config.Middleware - - _, err := m.SendEvent(config.Org, "Cycloid", "test event", "middleware test", "info", map[string]string{"env": "test"}, "blue") - require.NoError(t, err) -} - -func TestListEvents(t *testing.T) { - m := config.Middleware - - events, _, err := m.ListEvents(config.Org, nil, nil, 0, 0) - require.NoError(t, err) - assert.NotNil(t, events) -} diff --git a/cmd/cycloid/middleware/external_backends.go b/cmd/cycloid/middleware/external_backends.go deleted file mode 100644 index 61a6d1965..000000000 --- a/cmd/cycloid/middleware/external_backends.go +++ /dev/null @@ -1,122 +0,0 @@ -package middleware - -import ( - "errors" - "fmt" - "net/http" - "strconv" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) GetRemoteTFExternalBackend(org string) (*models.ExternalBackend, error) { - data, _, err := m.ListExternalBackends(org) - if err != nil { - return nil, err - } - if len(data) == 0 { - return nil, errors.New("couldn't find the remote terraform backend") - } - return data[0], nil -} - -func (m *middleware) GetExternalBackend(org string, externalBackend uint32) (*models.ExternalBackend, *http.Response, error) { - var result *models.ExternalBackend - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "external_backends", strconv.FormatUint(uint64(externalBackend), 10)}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) ListExternalBackends(org string) ([]*models.ExternalBackend, *http.Response, error) { - var result []*models.ExternalBackend - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "external_backends"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeleteExternalBackend(org string, externalBackend uint32) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "external_backends", strconv.FormatUint(uint64(externalBackend), 10)}, - }, nil) - return resp, err -} - -func (m *middleware) CreateExternalBackends(org, project, env, purpose, credential string, isDefault bool, ebConfig models.ExternalBackendConfiguration) (*models.ExternalBackend, *http.Response, error) { - var body *models.NewExternalBackend - - if len(credential) != 0 { - body = &models.NewExternalBackend{ - ProjectCanonical: project, - Purpose: &purpose, - EnvironmentCanonical: env, - CredentialCanonical: credential, - Default: isDefault, - } - } else { - body = &models.NewExternalBackend{ - ProjectCanonical: project, - EnvironmentCanonical: env, - Purpose: &purpose, - Default: isDefault, - } - } - - body.SetConfiguration(ebConfig) - - var result *models.ExternalBackend - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "external_backends"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to create external backend: %w", err) - } - return result, resp, nil -} - -func (m *middleware) UpdateExternalBackend(org string, externalBackendID uint32, purpose, credential string, isDefault bool, ebConfig models.ExternalBackendConfiguration) (*models.ExternalBackend, *http.Response, error) { - var body *models.UpdateExternalBackend - - if len(credential) != 0 { - body = &models.UpdateExternalBackend{ - Purpose: &purpose, - CredentialCanonical: credential, - Default: isDefault, - } - } else { - body = &models.UpdateExternalBackend{ - Purpose: &purpose, - Default: isDefault, - } - } - - body.SetConfiguration(ebConfig) - - var result *models.ExternalBackend - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "external_backends", strconv.FormatUint(uint64(externalBackendID), 10)}, - Body: body, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to update external backend: %w", err) - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/external_backends_test.go b/cmd/cycloid/middleware/external_backends_test.go deleted file mode 100644 index 14b3d0303..000000000 --- a/cmd/cycloid/middleware/external_backends_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestListExternalBackends(t *testing.T) { - m := config.Middleware - - backends, _, err := m.ListExternalBackends(config.Org) - require.NoError(t, err) - assert.NotNil(t, backends) -} diff --git a/cmd/cycloid/middleware/generic_client.go b/cmd/cycloid/middleware/generic_client.go deleted file mode 100644 index e00f50b68..000000000 --- a/cmd/cycloid/middleware/generic_client.go +++ /dev/null @@ -1,245 +0,0 @@ -package middleware - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - "time" - - "github.com/spf13/viper" -) - -// genericRequestRaw sends an HTTP request and returns the raw response body on success. -func (m *middleware) genericRequestRaw(req Request) (*http.Response, []byte, error) { - baseURL, err := url.Parse(m.api.Config.URL) - if err != nil { - return nil, nil, fmt.Errorf("failed to parse base url from %q, this means that CY_API_URL is probably invalid: %w", m.api.Config.URL, err) - } - - routeParts := make([]string, 0, len(req.Route)+1) - routeParts = append(routeParts, baseURL.Path) - routeParts = append(routeParts, req.Route...) - baseURL.Path = path.Join(routeParts...) - - var rawQueryParts []string - if req.Query != nil { - qv, err := encodeQuery(req.Query) - if err != nil { - return nil, nil, fmt.Errorf("failed to encode query params: %w", err) - } - if encoded := qv.Encode(); encoded != "" { - rawQueryParts = append(rawQueryParts, encoded) - } - } - if len(req.LHSFilters) > 0 { - rawQueryParts = append(rawQueryParts, buildLHSFilterQuery(req.LHSFilters)) - } - if len(rawQueryParts) > 0 { - baseURL.RawQuery = strings.Join(rawQueryParts, "&") - } - - var bodyBytes []byte - if req.Body != nil { - bodyBytes, err = json.Marshal(req.Body) - if err != nil { - return nil, nil, fmt.Errorf("failed to serialize body to JSON for HTTP request: %w", err) - } - } - - httpReq, err := http.NewRequest(req.Method, baseURL.String(), bytes.NewReader(bodyBytes)) - if err != nil { - return nil, nil, fmt.Errorf("failed to create request with method %q and url %q: %w", req.Method, baseURL.String(), err) - } - - for k, v := range req.Headers { - httpReq.Header.Add(k, v) - } - httpReq.Header.Set("Content-Type", "application/json") - if req.Accept != nil { - httpReq.Header.Set("Accept", *req.Accept) - } - if !req.NoAuth { - httpReq.Header.Set("Authorization", "Bearer "+m.api.GetToken(req.Organization)) - } - - debug := viper.GetString("verbosity") == "debug" - if debug { - httpDebugLogger.logRequest(httpReq, bodyBytes) - } - - start := time.Now() - resp, err := m.GenericClient.Do(httpReq) - if err != nil { - return nil, nil, fmt.Errorf("HTTP request failed: %w", err) - } - elapsed := time.Since(start) - defer resp.Body.Close() - - respBody, err := io.ReadAll(resp.Body) - if err != nil { - return nil, nil, fmt.Errorf("failed to read body from HTTP response: %w", err) - } - - if debug { - httpDebugLogger.logResponse(resp, respBody, elapsed) - } - - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return resp, respBody, newAPIResponseError(resp, respBody, sanitizeBody(bodyBytes), req.Method) - } - - return resp, respBody, nil -} - -// GenericRequest sends an HTTP request to the Cycloid API. -// It adds default authentication headers and handles JSON marshaling/unmarshaling. -// On non-2xx responses, it returns an *APIResponseError. -// On 2xx responses, it unwraps the {"data": } envelope into the response pointer. -// Pass nil as response to discard the response body. -func (m *middleware) GenericRequest(req Request, response any) (*http.Response, error) { - baseURL, err := url.Parse(m.api.Config.URL) - if err != nil { - return nil, fmt.Errorf("failed to parse base url from %q, this means that CY_API_URL is probably invalid: %w", m.api.Config.URL, err) - } - - // Build URL from route segments - routeParts := make([]string, 0, len(req.Route)+1) - routeParts = append(routeParts, baseURL.Path) - routeParts = append(routeParts, req.Route...) - baseURL.Path = path.Join(routeParts...) - - // Encode query parameters; LHS filters use raw encoding to preserve literal brackets. - var rawQueryParts []string - if req.Query != nil { - qv, err := encodeQuery(req.Query) - if err != nil { - return nil, fmt.Errorf("failed to encode query params: %w", err) - } - if encoded := qv.Encode(); encoded != "" { - rawQueryParts = append(rawQueryParts, encoded) - } - } - if len(req.LHSFilters) > 0 { - rawQueryParts = append(rawQueryParts, buildLHSFilterQuery(req.LHSFilters)) - } - if len(rawQueryParts) > 0 { - baseURL.RawQuery = strings.Join(rawQueryParts, "&") - } - - // Marshal body - var bodyBytes []byte - if req.Body != nil { - bodyBytes, err = json.Marshal(req.Body) - if err != nil { - return nil, fmt.Errorf("failed to serialize body to JSON for HTTP request: %w", err) - } - } - - httpReq, err := http.NewRequest(req.Method, baseURL.String(), bytes.NewReader(bodyBytes)) - if err != nil { - return nil, fmt.Errorf("failed to create request with method %q and url %q: %w", req.Method, baseURL.String(), err) - } - - // Set headers - for k, v := range req.Headers { - httpReq.Header.Add(k, v) - } - - httpReq.Header.Set("Content-Type", "application/json") - - // Set Accept header - if req.Accept != nil { - httpReq.Header.Set("Accept", *req.Accept) - } - - // Set auth header - if !req.NoAuth { - httpReq.Header.Set("Authorization", "Bearer "+m.api.GetToken(req.Organization)) - } - - debug := viper.GetString("verbosity") == "debug" - if debug { - httpDebugLogger.logRequest(httpReq, bodyBytes) - } - - start := time.Now() - resp, err := m.GenericClient.Do(httpReq) - if err != nil { - return nil, fmt.Errorf("HTTP request failed: %w", err) - } - elapsed := time.Since(start) - defer resp.Body.Close() - - respBody, err := io.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("failed to read body from HTTP response: %w", err) - } - - if debug { - httpDebugLogger.logResponse(resp, respBody, elapsed) - } - - // Handle non-2xx responses - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return resp, newAPIResponseError(resp, respBody, sanitizeBody(bodyBytes), req.Method) - } - - // Unwrap {"data": ...} envelope - if response != nil && len(respBody) > 0 { - var envelope struct { - Data json.RawMessage `json:"data"` - } - if err := json.Unmarshal(respBody, &envelope); err != nil { - // Try direct unmarshal if envelope fails - if err2 := json.Unmarshal(respBody, response); err2 != nil { - return resp, &responseJSONError{ - statusCode: resp.StatusCode, - body: respBody, - cause: fmt.Errorf("%w (envelope error: %v)", err2, err), - } - } - return resp, nil - } - - if envelope.Data != nil { - if err := json.Unmarshal(envelope.Data, response); err != nil { - return resp, &responseJSONError{ - statusCode: resp.StatusCode, - body: respBody, - cause: err, - } - } - } - } - - return resp, nil -} - -// responseJSONError is returned when the API responded 2xx but the body could -// not be decoded into the expected JSON shape. -type responseJSONError struct { - statusCode int - body []byte - cause error -} - -func (e *responseJSONError) Error() string { - return fmt.Sprintf("failed to decode JSON response (HTTP %d): %v", e.statusCode, e.cause) -} - -func (e *responseJSONError) Unwrap() error { - return e.cause -} - -func (e *responseJSONError) HTTPStatusCode() int { - return e.statusCode -} - -func (e *responseJSONError) HTTPResponseBody() []byte { - return e.body -} diff --git a/cmd/cycloid/middleware/generic_client_test.go b/cmd/cycloid/middleware/generic_client_test.go deleted file mode 100644 index a95867dbe..000000000 --- a/cmd/cycloid/middleware/generic_client_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package middleware_test - -import ( - "net/http" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func TestGenericRequest_ListProjects(t *testing.T) { - m := config.Middleware - - var projects []*models.Project - httpResp, err := m.GenericRequest(middleware.Request{ - Method: http.MethodGet, - Organization: &config.Org, - Route: []string{"organizations", config.Org, "projects"}, - }, &projects) - - require.NoError(t, err) - require.NotNil(t, httpResp) - assert.Equal(t, http.StatusOK, httpResp.StatusCode) - assert.NotNil(t, projects) -} - -func TestGenericRequest_NotFound(t *testing.T) { - m := config.Middleware - - var out any - httpResp, err := m.GenericRequest(middleware.Request{ - Method: http.MethodGet, - Organization: &config.Org, - Route: []string{"organizations", config.Org, "projects", "this-project-does-not-exist-xyz"}, - }, &out) - - require.Error(t, err) - require.NotNil(t, httpResp) - assert.Equal(t, http.StatusNotFound, httpResp.StatusCode) - - var apiErr *middleware.APIResponseError - require.ErrorAs(t, err, &apiErr) - assert.Equal(t, http.StatusNotFound, apiErr.StatusCode) - assert.NotEmpty(t, apiErr.Error()) -} - -func TestGenericRequest_NoAuth(t *testing.T) { - m := config.Middleware - - var out any - httpResp, err := m.GenericRequest(middleware.Request{ - Method: http.MethodGet, - Route: []string{"organizations", config.Org, "projects"}, - NoAuth: true, - }, &out) - - require.Error(t, err) - require.NotNil(t, httpResp) - assert.Equal(t, http.StatusForbidden, httpResp.StatusCode) -} diff --git a/cmd/cycloid/middleware/http_client.go b/cmd/cycloid/middleware/http_client.go deleted file mode 100644 index 757b99287..000000000 --- a/cmd/cycloid/middleware/http_client.go +++ /dev/null @@ -1,156 +0,0 @@ -package middleware - -import ( - "encoding/json" - "fmt" - "net/http" - "strings" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// StackVersion is the local representation of a stack catalog version. -// The model was removed from the generated swagger client. -type StackVersion struct { - CommitHash *string `json:"commit_hash"` - ID *uint32 `json:"id"` - IsLatest *bool `json:"is_latest"` - Name *string `json:"name"` - Status *string `json:"status"` - Type *string `json:"type"` - Usage *int64 `json:"usage"` -} - -// InventoryOutput is the local representation of a terraform state output. -// The model is not yet generated in the swagger client. -type InventoryOutput struct { - ID uint32 `json:"id"` - Key string `json:"key"` - Value interface{} `json:"value,omitempty"` - Type interface{} `json:"type,omitempty"` - Description string `json:"description,omitempty"` - Sensitive bool `json:"sensitive,omitempty"` - Pinned bool `json:"pinned,omitempty"` -} - -// StackUseCase is the local representation of a stack use case. -// The model was removed from the generated swagger client. -type StackUseCase struct { - CloudProvider string `json:"cloud_provider,omitempty"` - Description string `json:"description,omitempty"` - Name *string `json:"name"` - UseCase *string `json:"use_case"` -} - -// DeleteOptions carries the caller-facing flags for delete operations. -// Force is sugar for enabling both SkipHooks and IgnoreConfigFilesErr. -// Resolve expands Force before building the API query. -type DeleteOptions struct { - Force bool - SkipHooks bool - IgnoreConfigFilesErr bool -} - -// deleteQuery is the wire representation sent as URL query params. -type deleteQuery struct { - SkipHooks bool `url:"skip_hooks"` - IgnoreConfigFilesErr bool `url:"ignore_config_files_err"` -} - -// Resolve returns the effective deleteQuery, merging Force into both fields. -func (o DeleteOptions) Resolve() deleteQuery { - return deleteQuery{ - SkipHooks: o.SkipHooks || o.Force, - IgnoreConfigFilesErr: o.IgnoreConfigFilesErr || o.Force, - } -} - -// Request represents an HTTP request to the Cycloid API. -type Request struct { - Method string - Organization *string // used for auth token lookup - NoAuth bool // disables auth header - Route []string // joined onto base URL: ["organizations", org, "projects"] - Query any // url.Values or struct with `url` tags - LHSFilters []LHSFilter // LHS bracket filters: encoded as attribute[condition]=value with literal brackets - Headers map[string]string - Accept *string // overrides default Accept header - Body any // JSON-marshaled when non-nil -} - -// APIResponseError is returned when the API returns a non-2xx response. -type APIResponseError struct { - StatusCode int - Status string - Body []byte - Payload *models.ErrorPayload - Path string - Method string // HTTP method of the failed request - ReqBody []byte // sanitized request body (sensitive fields redacted) -} - -func (e *APIResponseError) Error() string { - if e.Payload != nil && len(e.Payload.Errors) > 0 && e.Payload.Errors[0].Message != nil { - return fmt.Sprintf("API error %d: %s", e.StatusCode, *e.Payload.Errors[0].Message) - } - - body := strings.TrimSpace(string(e.Body)) - if body != "" { - if e.Path != "" { - return fmt.Sprintf("API error %d on %q: %s", e.StatusCode, e.Path, body) - } - return fmt.Sprintf("API error %d: %s", e.StatusCode, body) - } - - return fmt.Sprintf("API error %d: %s", e.StatusCode, e.Status) -} - -// GetPayload implements ErrorPayloader for backwards compatibility. -func (e *APIResponseError) GetPayload() *models.ErrorPayload { - return e.Payload -} - -// HTTPStatusCode implements printer.ErrHTTPResponse. -func (e *APIResponseError) HTTPStatusCode() int { - return e.StatusCode -} - -// HTTPResponseBody implements printer.ErrHTTPResponse. -func (e *APIResponseError) HTTPResponseBody() []byte { - return e.Body -} - -// HTTPRequestPath implements printer.RequestPather. -func (e *APIResponseError) HTTPRequestPath() string { - return e.Path -} - -// HTTPRequestMethod returns the HTTP method of the failed request. -func (e *APIResponseError) HTTPRequestMethod() string { - return e.Method -} - -// HTTPRequestBody returns the sanitized request body (sensitive fields redacted). -func (e *APIResponseError) HTTPRequestBody() []byte { - return e.ReqBody -} - -func newAPIResponseError(resp *http.Response, body, reqBody []byte, method string) *APIResponseError { - apiErr := &APIResponseError{ - StatusCode: resp.StatusCode, - Status: resp.Status, - Body: body, - Method: method, - ReqBody: reqBody, - } - if resp.Request != nil && resp.Request.URL != nil { - apiErr.Path = resp.Request.URL.RequestURI() - } - - var payload models.ErrorPayload - if err := json.Unmarshal(body, &payload); err == nil && len(payload.Errors) > 0 { - apiErr.Payload = &payload - } - - return apiErr -} diff --git a/cmd/cycloid/middleware/http_client_test.go b/cmd/cycloid/middleware/http_client_test.go deleted file mode 100644 index c2d3cea2c..000000000 --- a/cmd/cycloid/middleware/http_client_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package middleware - -import ( - "net/http" - "net/url" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestNewAPIResponseError_PathFallback(t *testing.T) { - u, err := url.Parse("https://http-api.cycloid.io/organizations/org/projects/project?foo=bar") - assert.NoError(t, err) - - resp := &http.Response{ - StatusCode: http.StatusBadRequest, - Status: "400 Bad Request", - Request: &http.Request{ - URL: u, - }, - } - - apiErr := newAPIResponseError(resp, []byte("raw backend error"), nil, "GET") - assert.Equal(t, http.StatusBadRequest, apiErr.StatusCode) - assert.Equal(t, "/organizations/org/projects/project?foo=bar", apiErr.Path) - assert.Equal(t, "API error 400 on \"/organizations/org/projects/project?foo=bar\": raw backend error", apiErr.Error()) -} diff --git a/cmd/cycloid/middleware/init_first_org.go b/cmd/cycloid/middleware/init_first_org.go deleted file mode 100644 index d4dfb493a..000000000 --- a/cmd/cycloid/middleware/init_first_org.go +++ /dev/null @@ -1,135 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - "strings" - - "github.com/pkg/errors" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -// InitFirstOrg will create the first user, org and inject the licence to the -// current console. -// If apiKeyCanonical != nil, will also create an api key admin and add it to a -// credential. -func (m *middleware) InitFirstOrg(org, userName, fullName, email, password, licence string, apiKeyCanonical *string) (*FirstOrgData, *http.Response, error) { - originalToken := m.api.Config.Token - defer func() { m.api.Config.Token = originalToken }() - - _, err := m.UserSignup(userName, email, password, fullName) - var signupErr *APIResponseError - if errors.As(err, &signupErr) { - if signupErr.StatusCode != 409 && err != nil { - return nil, nil, fmt.Errorf("failed to signup first user: %w", err) - } - } - - login, _, err := m.UserLogin(&org, &email, password) - if err != nil { - return nil, nil, fmt.Errorf("failed to login with admin user: %w", err) - } - m.api.Config.Token = *login.Token - - _, _, err = m.CreateOrganization(org) - var orgErr *APIResponseError - if errors.As(err, &orgErr) { - if orgErr.StatusCode != 409 && err != nil { - return nil, nil, fmt.Errorf("failed to create first org: %w", err) - } - } - - refresh, _, err := m.RefreshToken(&org, nil, *login.Token) - if err != nil { - return nil, nil, fmt.Errorf("failed to refresh token: %w", err) - } - m.api.Config.Token = *refresh.Token - - _, err = m.ActivateLicence(org, licence) - if err != nil { - return nil, nil, fmt.Errorf("failed to activate Licence: %w", err) - } - - output := &FirstOrgData{ - Org: org, - Username: userName, - FullName: fullName, - Email: email, - Password: password, - Token: *refresh.Token, - } - - if apiKeyCanonical == nil { - return output, nil, nil - } - - refresh, _, err = m.RefreshToken(&org, nil, *refresh.Token) - if err != nil { - return nil, nil, fmt.Errorf("failed to refresh token: %w", err) - } - m.api.Config.Token = *refresh.Token - - // to make API key creation idempotent, let's recreate it everytime this runs - cred, _, err := m.GetCredential(org, *apiKeyCanonical) - var credErr *APIResponseError - if errors.As(err, &credErr) && credErr.StatusCode != 404 { - return output, nil, fmt.Errorf("api error: %w", err) - } - - currentAPIKey, _, err := m.GetAPIKey(org, *apiKeyCanonical) - var apiErr *APIResponseError - if errors.As(err, &apiErr) && apiErr.StatusCode != 404 { - return output, nil, fmt.Errorf("failed to fetch current apiKey %q: %w", *apiKeyCanonical, err) - } - - var credAPIKey string - if cred != nil { - credAPIKey, _ = cred.Raw.Raw.(map[string]any)["key"].(string) - } - - if cred == nil || !strings.HasSuffix(credAPIKey, *currentAPIKey.LastSeven) { - if currentAPIKey != nil { - _, err := m.DeleteAPIKey(org, *apiKeyCanonical) - if err != nil { - return output, nil, fmt.Errorf("failed to remove previous key %q: %w", *apiKeyCanonical, err) - } - } - - APIKey, _, err := m.CreateAPIKey( - org, *apiKeyCanonical, "Initial api key admin", fullName, apiKeyCanonical, - []*models.NewRule{ - {Action: ptr.Ptr("organization:**"), Effect: ptr.Ptr("allow"), Resources: []string{}}, - }, - ) - if err != nil { - return output, nil, fmt.Errorf("failed to create api-key %q: %w", *apiKeyCanonical, err) - } - - output.APIKey = &APIKey.Token - - var credAPIErr *APIResponseError - _, _, err = m.CreateCredential(org, *apiKeyCanonical, "custom", - &models.CredentialRaw{Raw: map[string]string{"key": APIKey.Token}}, - "", *apiKeyCanonical, "First Admin API Key.", - ) - if errors.As(err, &credAPIErr) && credAPIErr.StatusCode == 409 { - _, _, err = m.UpdateCredential(org, *apiKeyCanonical, "custom", - &models.CredentialRaw{Raw: map[string]string{"key": APIKey.Token}}, - "", *apiKeyCanonical, "First Admin API Key.", - ) - } - if err != nil { - // Cleanup in case of failure - defer m.DeleteAPIKey(org, *apiKeyCanonical) - defer m.DeleteCredential(org, *apiKeyCanonical) - return output, nil, fmt.Errorf("failed to persist api key to credential %q: %w", *apiKeyCanonical, err) - } - } else { - output.APIKey = &credAPIKey - } - - output.CredentialCanonical = apiKeyCanonical - return output, nil, nil -} diff --git a/cmd/cycloid/middleware/init_first_org_test.go b/cmd/cycloid/middleware/init_first_org_test.go deleted file mode 100644 index 53ac9e810..000000000 --- a/cmd/cycloid/middleware/init_first_org_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package middleware_test - -import ( - "os" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestInitFirstOrgIdempotent(t *testing.T) { - m := config.Middleware - - licenceKey, ok := os.LookupEnv("API_LICENCE_KEY") - require.True(t, ok, "API_LICENCE_KEY must be set for bootstrap tests") - - apiKeyCanonical := "admin-init-first-org-test" - result, _, err := m.InitFirstOrg( - config.Org, - "administrator", - "administrator", - "admin@cycloid.io", - "cycloidadmin", - licenceKey, - &apiKeyCanonical, - ) - require.NoError(t, err) - require.NotNil(t, result) - assert.Equal(t, config.Org, result.Org) - assert.NotEmpty(t, result.Token) - require.NotNil(t, result.APIKey) - assert.NotEmpty(t, *result.APIKey) - - resultAgain, _, err := m.InitFirstOrg( - config.Org, - "administrator", - "administrator", - "admin@cycloid.io", - "cycloidadmin", - licenceKey, - &apiKeyCanonical, - ) - require.NoError(t, err) - require.NotNil(t, resultAgain) - assert.Equal(t, config.Org, resultAgain.Org) - assert.NotEmpty(t, resultAgain.Token) -} diff --git a/cmd/cycloid/middleware/inventory.go b/cmd/cycloid/middleware/inventory.go deleted file mode 100644 index 66e39ee2d..000000000 --- a/cmd/cycloid/middleware/inventory.go +++ /dev/null @@ -1,84 +0,0 @@ -package middleware - -import ( - "net/http" - "strconv" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// ListInventoryResources lists inventory resources for an organization. -// -// Supported LHS filter attributes: -// - resources_provider, resources_type, resources_name (display_name), resources_module, -// resources_mode, resources_label — resource-level fields -// - project_canonical, environment_canonical, component_canonical — via linked TF state -// - service_catalog_canonical, service_catalog_ref — via linked component -// - organization_canonical — organization scope -// -// Any unknown attribute key is treated as a JSON path filter against sr.attributes -// and sr.custom_attributes (e.g. "tags.env[eq]=prod"). -func (m *middleware) ListInventoryResources(org string, filters ...LHSFilter) ([]*models.InventoryResource, *http.Response, error) { - var result []*models.InventoryResource - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "inventory"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// ListInventoryOutputs lists terraform state outputs for an organization. -// -// Supported LHS filter attributes: -// - output_key — output key name -// - output_type — output type filter -// - output_is_pinned — boolean, "true" or "false" -// - project_canonical, environment_canonical, component_canonical — via linked TF state -// - service_catalog_canonical — via linked component -// - organization_canonical — organization scope -// -// Any unknown attribute key is treated as a JSON path filter against ou.value -// (e.g. "instance_ip[eq]=1.2.3.4"). -func (m *middleware) ListInventoryOutputs(org string, filters ...LHSFilter) ([]*InventoryOutput, *http.Response, error) { - var result []*InventoryOutput - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "inventory", "outputs"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// CreateInventoryResource creates an inventory resource for an organization. -func (m *middleware) CreateInventoryResource(org string, body *models.NewInventoryResource) (*models.InventoryResource, *http.Response, error) { - var result *models.InventoryResource - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "inventory", "resources"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// DeleteInventoryResource deletes an inventory resource by ID. -func (m *middleware) DeleteInventoryResource(org string, id uint32) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "inventory", "resources", strconv.FormatUint(uint64(id), 10)}, - }, nil) - return resp, err -} diff --git a/cmd/cycloid/middleware/lhs_filter.go b/cmd/cycloid/middleware/lhs_filter.go deleted file mode 100644 index e5240d6aa..000000000 --- a/cmd/cycloid/middleware/lhs_filter.go +++ /dev/null @@ -1,46 +0,0 @@ -package middleware - -import ( - "fmt" - "strings" -) - -// LHSFilter represents a single LHS bracket filter: attribute[condition]=value. -// Encoded as a raw query parameter with literal brackets so the API receives -// exactly attribute[condition]=value (not attribute%5Bcondition%5D=value). -type LHSFilter struct { - Attribute string - Condition string - Value string -} - -// buildLHSFilterQuery builds a raw query string for LHS bracket filter params. -// Brackets are kept literal in keys; values use lhsEscapeValue to preserve -// regex metacharacters while encoding structurally significant chars. -func buildLHSFilterQuery(filters []LHSFilter) string { - parts := make([]string, 0, len(filters)) - for _, f := range filters { - key := f.Attribute + "[" + f.Condition + "]" - parts = append(parts, key+"="+lhsEscapeValue(f.Value)) - } - return strings.Join(parts, "&") -} - -// lhsEscapeValue percent-encodes only characters that are structurally -// significant in query strings (&, =, #, space, control chars), preserving -// regex metacharacters such as ?, *, +, [, ], (, ), {, }, |, ^, $, \. -func lhsEscapeValue(s string) string { - var buf strings.Builder - for i := 0; i < len(s); i++ { - c := s[i] - switch { - case c == '&' || c == '=' || c == '#' || c == ' ': - fmt.Fprintf(&buf, "%%%02X", c) - case c < 0x20 || c >= 0x7F: - fmt.Fprintf(&buf, "%%%02X", c) - default: - buf.WriteByte(c) - } - } - return buf.String() -} diff --git a/cmd/cycloid/middleware/lhs_filter_discovery_test.go b/cmd/cycloid/middleware/lhs_filter_discovery_test.go deleted file mode 100644 index d4baafe33..000000000 --- a/cmd/cycloid/middleware/lhs_filter_discovery_test.go +++ /dev/null @@ -1,301 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/testcfg" -) - -// TestLHSFilterDiscovery verifies which attributes the backend accepts as LHS -// filters on each List route that supports them. Field names follow the -// backend's filtersMappings convention: _. -// -// Routes confirmed to NOT support LHS filters (backend handler does not call -// lhs.ParseQuery): ListTeamMembers, ListRoles, ListCredentials, -// ListCatalogRepositories, ListConfigRepositories, ListStackVersions, -// ListStackUseCases. -// -// A subtest failure means the attribute is not supported for that route. -// Results inform the godoc on each List* middleware method. -func TestLHSFilterDiscovery(t *testing.T) { - m := config.Middleware - org := config.Org - - t.Run("Projects", func(t *testing.T) { - projA := testcfg.RandomCanonical("lhs-disc-a") - projB := testcfg.RandomCanonical("lhs-disc-b") - nameA := "LHS Discovery Alpha " + projA - nameB := "LHS Discovery Beta " + projB - configRepo := *config.ConfigRepo.Canonical - - _, _, err := m.CreateProject(org, nameA, projA, "desc a", configRepo, "", "", "default", "world") - require.NoError(t, err, "setup: create projA") - defer func() { _, _ = m.DeleteProject(org, projA, middleware.DeleteOptions{}) }() - - _, _, err = m.CreateProject(org, nameB, projB, "desc b", configRepo, "", "", "default", "world") - require.NoError(t, err, "setup: create projB") - defer func() { _, _ = m.DeleteProject(org, projB, middleware.DeleteOptions{}) }() - - t.Run("project_canonical[eq]", func(t *testing.T) { - results, _, err := m.ListProjects(org, middleware.LHSFilter{Attribute: "project_canonical", Condition: "eq", Value: projA}) - require.NoError(t, err) - require.NotEmpty(t, results) - for _, p := range results { - assert.Equal(t, projA, *p.Canonical) - } - }) - - t.Run("project_name[eq]", func(t *testing.T) { - results, _, err := m.ListProjects(org, middleware.LHSFilter{Attribute: "project_name", Condition: "eq", Value: nameA}) - require.NoError(t, err) - require.NotEmpty(t, results) - for _, p := range results { - assert.Equal(t, nameA, *p.Name) - } - }) - - t.Run("project_name[rlike]", func(t *testing.T) { - results, _, err := m.ListProjects(org, middleware.LHSFilter{Attribute: "project_name", Condition: "rlike", Value: "LHS Discovery .*"}) - require.NoError(t, err) - var found int - for _, p := range results { - if *p.Canonical == projA || *p.Canonical == projB { - found++ - } - } - assert.Equal(t, 2, found, "rlike must match both lhs-disc projects") - }) - }) - - t.Run("Stacks", func(t *testing.T) { - // Stack creation requires complex catalog-repo setup — rely on the - // test stack seeded by testcfg. - testCanonical := "stack-e2e-stackforms" - testRef := org + ":" + testCanonical - - all, _, err := m.ListStacks(org) - require.NoError(t, err) - require.NotEmpty(t, all, "test stacks must exist") - - t.Run("service_catalog_ref[eq]", func(t *testing.T) { - results, _, err := m.ListStacks(org, middleware.LHSFilter{Attribute: "service_catalog_ref", Condition: "eq", Value: testRef}) - require.NoError(t, err) - require.NotEmpty(t, results) - for _, s := range results { - assert.Equal(t, testRef, *s.Ref) - } - assert.Less(t, len(results), len(all), "filtered must be smaller than full list") - }) - - t.Run("service_catalog_visibility[eq]", func(t *testing.T) { - // valid values: local, shared, hidden (handled with custom logic in backend) - results, _, err := m.ListStacks(org, middleware.LHSFilter{Attribute: "service_catalog_visibility", Condition: "eq", Value: "local"}) - require.NoError(t, err) - for _, s := range results { - assert.Equal(t, "local", *s.Visibility) - } - }) - - t.Run("service_catalog_blueprint[eq]", func(t *testing.T) { - results, _, err := m.ListStacks(org, middleware.LHSFilter{Attribute: "service_catalog_blueprint", Condition: "eq", Value: "false"}) - require.NoError(t, err) - assert.NotNil(t, results) - }) - }) - - t.Run("Components", func(t *testing.T) { - knownCanonical := *config.Component.Canonical - proj := *config.Project.Canonical - env := *config.Environment.Canonical - - all, _, err := m.ListComponents(org, proj, env) - require.NoError(t, err) - require.NotEmpty(t, all, "test component must exist") - - t.Run("component_canonical[eq]", func(t *testing.T) { - results, _, err := m.ListComponents(org, proj, env, middleware.LHSFilter{Attribute: "component_canonical", Condition: "eq", Value: knownCanonical}) - require.NoError(t, err) - require.NotEmpty(t, results) - for _, c := range results { - assert.Equal(t, knownCanonical, *c.Canonical) - } - }) - - t.Run("service_catalog_ref[eq]", func(t *testing.T) { - stackRef := org + ":stack-e2e-stackforms" - results, _, err := m.ListComponents(org, proj, env, middleware.LHSFilter{Attribute: "service_catalog_ref", Condition: "eq", Value: stackRef}) - require.NoError(t, err) - assert.NotNil(t, results) - }) - - t.Run("environment_canonical[eq]", func(t *testing.T) { - results, _, err := m.ListComponents(org, proj, env, middleware.LHSFilter{Attribute: "environment_canonical", Condition: "eq", Value: env}) - require.NoError(t, err) - assert.NotEmpty(t, results) - }) - }) - - t.Run("Members", func(t *testing.T) { - // List all members to get a known canonical for filtering - all, _, err := m.ListMembers(org) - require.NoError(t, err) - require.NotEmpty(t, all, "org must have at least one member") - knownCanonical := all[0].Username - - t.Run("user_canonical[eq]", func(t *testing.T) { - results, _, err := m.ListMembers(org, middleware.LHSFilter{Attribute: "user_canonical", Condition: "eq", Value: knownCanonical}) - require.NoError(t, err) - require.NotEmpty(t, results) - for _, member := range results { - assert.Equal(t, knownCanonical, member.Username) - } - }) - - t.Run("invitation_state[eq]", func(t *testing.T) { - // accepted is the normal state for active members - results, _, err := m.ListMembers(org, middleware.LHSFilter{Attribute: "invitation_state", Condition: "eq", Value: "accepted"}) - require.NoError(t, err) - assert.NotNil(t, results) - }) - }) - - t.Run("Teams", func(t *testing.T) { - // List all teams; test env may or may not have teams, so we just verify - // the filter is accepted without error. If teams exist, verify filtering. - all, _, err := m.ListTeams(org, nil, nil, nil, nil) - require.NoError(t, err) - - t.Run("team_canonical[eq]", func(t *testing.T) { - if len(all) == 0 { - t.Skip("no teams in test org") - } - knownCanonical := *all[0].Canonical - results, _, err2 := m.ListTeams(org, nil, nil, nil, nil, middleware.LHSFilter{Attribute: "team_canonical", Condition: "eq", Value: knownCanonical}) - require.NoError(t, err2) - for _, team := range results { - assert.Equal(t, knownCanonical, *team.Canonical) - } - }) - - t.Run("team_name[rlike]", func(t *testing.T) { - if len(all) == 0 { - t.Skip("no teams in test org") - } - _, _, err2 := m.ListTeams(org, nil, nil, nil, nil, middleware.LHSFilter{Attribute: "team_name", Condition: "rlike", Value: ".*"}) - require.NoError(t, err2) - }) - }) - - t.Run("InventoryResources", func(t *testing.T) { - label := "lhs-disc-label" - provider := "custom_resources" - resType := "custom_instance" - nameA := testcfg.RandomCanonical("lhs-res-a") - nameB := testcfg.RandomCanonical("lhs-res-b") - - resA, _, err := m.CreateInventoryResource(org, &models.NewInventoryResource{ - Label: &label, - Name: &nameA, - Provider: &provider, - Type: &resType, - }) - require.NoError(t, err, "setup: create inventory resource A") - defer func() { _, _ = m.DeleteInventoryResource(org, resA.ID) }() - - resB, _, err := m.CreateInventoryResource(org, &models.NewInventoryResource{ - Label: &label, - Name: &nameB, - Provider: &provider, - Type: &resType, - }) - require.NoError(t, err, "setup: create inventory resource B") - defer func() { _, _ = m.DeleteInventoryResource(org, resB.ID) }() - - t.Run("resources_provider[eq]", func(t *testing.T) { - results, _, err := m.ListInventoryResources(org, middleware.LHSFilter{Attribute: "resources_provider", Condition: "eq", Value: provider}) - require.NoError(t, err) - for _, r := range results { - assert.Equal(t, provider, *r.Provider) - } - }) - - t.Run("resources_type[eq]", func(t *testing.T) { - results, _, err := m.ListInventoryResources(org, middleware.LHSFilter{Attribute: "resources_type", Condition: "eq", Value: resType}) - require.NoError(t, err) - for _, r := range results { - assert.Equal(t, resType, *r.Type) - } - }) - - t.Run("resources_label[eq]", func(t *testing.T) { - results, _, err := m.ListInventoryResources(org, middleware.LHSFilter{Attribute: "resources_label", Condition: "eq", Value: label}) - require.NoError(t, err) - require.GreaterOrEqual(t, len(results), 2) - for _, r := range results { - assert.Equal(t, label, r.Label) - } - }) - - t.Run("resources_name[rlike]", func(t *testing.T) { - results, _, err := m.ListInventoryResources(org, middleware.LHSFilter{Attribute: "resources_name", Condition: "rlike", Value: "lhs-res-.*"}) - require.NoError(t, err) - var found int - for _, r := range results { - if *r.Name == nameA || *r.Name == nameB { - found++ - } - } - assert.Equal(t, 2, found, "rlike must match both lhs-disc inventory resources") - }) - }) - - t.Run("InventoryOutputs", func(t *testing.T) { - // Outputs come from TF states — cannot be created directly. We verify - // the filter attributes are accepted by the route without error. - t.Run("output_key[eq] accepted", func(t *testing.T) { - _, _, err := m.ListInventoryOutputs(org, middleware.LHSFilter{Attribute: "output_key", Condition: "eq", Value: "nonexistent"}) - require.NoError(t, err) - }) - - t.Run("output_is_pinned[eq] accepted", func(t *testing.T) { - _, _, err := m.ListInventoryOutputs(org, middleware.LHSFilter{Attribute: "output_is_pinned", Condition: "eq", Value: "false"}) - require.NoError(t, err) - }) - - t.Run("output_type[eq] accepted", func(t *testing.T) { - _, _, err := m.ListInventoryOutputs(org, middleware.LHSFilter{Attribute: "output_type", Condition: "eq", Value: "string"}) - require.NoError(t, err) - }) - - t.Run("project_canonical[eq] accepted", func(t *testing.T) { - _, _, err := m.ListInventoryOutputs(org, middleware.LHSFilter{Attribute: "project_canonical", Condition: "eq", Value: "nonexistent"}) - require.NoError(t, err) - }) - }) - - t.Run("APIKeys", func(t *testing.T) { - all, _, err := m.ListAPIKeys(org) - require.NoError(t, err) - - t.Run("organization_canonical[eq]", func(t *testing.T) { - // organization_canonical is always org in this context - results, _, err2 := m.ListAPIKeys(org, middleware.LHSFilter{Attribute: "organization_canonical", Condition: "eq", Value: org}) - require.NoError(t, err2) - assert.Equal(t, len(all), len(results), "filtering by org canonical should return same count") - }) - - t.Run("user_canonical[eq]", func(t *testing.T) { - if len(all) == 0 { - t.Skip("no API keys in test org") - } - // Verify filter is accepted; nonexistent user returns empty not error - _, _, err2 := m.ListAPIKeys(org, middleware.LHSFilter{Attribute: "user_canonical", Condition: "eq", Value: "nonexistent"}) - require.NoError(t, err2) - }) - }) -} diff --git a/cmd/cycloid/middleware/middleware.go b/cmd/cycloid/middleware/middleware.go deleted file mode 100644 index 8696f2b95..000000000 --- a/cmd/cycloid/middleware/middleware.go +++ /dev/null @@ -1,300 +0,0 @@ -package middleware - -import ( - "context" - "crypto/tls" - "io" - "net/http" - "time" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" -) - -type Middleware interface { - UserLogin(org, email *string, password string) (*models.UserSession, *http.Response, error) - UserLoginToOrg(org, email, password string) (*models.UserSession, *http.Response, error) - UserSignup(username, email, password, fullName string) (*http.Response, error) - RefreshToken(org, childOrg *string, token string) (*models.UserSession, *http.Response, error) - - GetLicence(org string) (*models.Licence, *http.Response, error) - ActivateLicence(org, licence string) (*http.Response, error) - - // cycloid - GetAppVersion() (*models.AppVersion, *http.Response, error) - GetStatus() (*models.GeneralStatus, *http.Response, error) - - // catalog_repositories - CreateCatalogRepository(org, name, url, branch, cred, visibility, teamCanonical string) (*models.ServiceCatalogSource, *http.Response, error) - ListCatalogRepositories(org string, filters ...LHSFilter) ([]*models.ServiceCatalogSource, *http.Response, error) - GetCatalogRepository(org, catalogRepo string) (*models.ServiceCatalogSource, *http.Response, error) - DeleteCatalogRepository(org, catalogRepo string) (*http.Response, error) - UpdateCatalogRepository(org, catalogRepo string, name, url, branch, cred string, visibility *string) (*models.ServiceCatalogSource, *http.Response, error) - RefreshCatalogRepository(org, catalogRepo string) (*models.ServiceCatalogChanges, *http.Response, error) - RefreshCatalogRepositoryVersions(org, catalogRepo string) ([]*StackVersion, *http.Response, error) - - CreateConfigRepository(org, name, canonical, url, branch, cred string, setDefault bool) (*models.ConfigRepository, *http.Response, error) - DeleteConfigRepository(org, configRepo string) (*http.Response, error) - GetConfigRepository(org, configRepo string) (*models.ConfigRepository, *http.Response, error) - ListConfigRepositories(org string, filters ...LHSFilter) ([]*models.ConfigRepository, *http.Response, error) - UpdateConfigRepository(org, configRepo, cred, name, url, branch string, setDefault bool) (*models.ConfigRepository, *http.Response, error) - - // stacks (service_catalogs) - GetStack(org, ref string) (*models.ServiceCatalog, *http.Response, error) - UpdateStack(org, ref, teamCanonical string, visibility *string) (*models.ServiceCatalog, *http.Response, error) - ListStacks(org string, filters ...LHSFilter) ([]*models.ServiceCatalog, *http.Response, error) - ListStackUseCases(org, ref, versionTag, versionBranch, versionCommitHash string, filters ...LHSFilter) ([]*StackUseCase, *http.Response, error) - ListStackVersions(org, ref string, filters ...LHSFilter) ([]*StackVersion, *http.Response, error) - ResolveStackVersion(org, ref, stackVersion string) (uint32, string, error) - ListBlueprints(org string, filters ...LHSFilter) ([]*models.ServiceCatalog, *http.Response, error) - CreateStackFromBlueprint(org, blueprintRef, name, stack, catalogRepository, useCase string) (*models.ServiceCatalog, *http.Response, error) - - // organization_credentials - CreateCredential(org, name, credentialType string, rawCred *models.CredentialRaw, path, canonical, description string) (*models.Credential, *http.Response, error) - UpdateCredential(org, name, credentialType string, rawCred *models.CredentialRaw, path, canonical, description string) (*models.Credential, *http.Response, error) - DeleteCredential(org, credential string) (*http.Response, error) - GetCredential(org, credential string) (*models.Credential, *http.Response, error) - ListCredentials(org, credentialType string, filters ...LHSFilter) ([]*models.CredentialSimple, *http.Response, error) - - // events - SendEvent(org, eventType, title, message, severity string, tags map[string]string, color string) (*http.Response, error) - ListEvents(org string, eventType, eventSeverity []string, begin, end uint64) ([]*models.Event, *http.Response, error) - - // external_backends - DeleteExternalBackend(org string, externalBackend uint32) (*http.Response, error) - CreateExternalBackends(org, project, env, purpose, credential string, isDefault bool, externalBackendConfig models.ExternalBackendConfiguration) (*models.ExternalBackend, *http.Response, error) - ListExternalBackends(org string) ([]*models.ExternalBackend, *http.Response, error) - GetExternalBackend(org string, externalBackend uint32) (*models.ExternalBackend, *http.Response, error) - GetRemoteTFExternalBackend(org string) (*models.ExternalBackend, error) - UpdateExternalBackend(org string, externalBackendID uint32, purpose, credential string, isDefault bool, externalBackendConfig models.ExternalBackendConfiguration) (*models.ExternalBackend, *http.Response, error) - - // organization_member - DeleteMember(org string, id uint32) (*http.Response, error) - GetMember(org string, id uint32) (*models.MemberOrg, *http.Response, error) - InviteMember(org, email, role string) (*models.MemberOrg, *http.Response, error) - ListMembers(org string, filters ...LHSFilter) ([]*models.MemberOrg, *http.Response, error) - ListInvites(org string) ([]*models.MemberOrg, *http.Response, error) - UpdateMember(org string, id uint32, role string) (*models.MemberOrg, *http.Response, error) - - // organization_teams - ListTeams(org string, teamNameFilter *string, createdAtFilter *uint64, memberIDFilter *uint32, orderBy *TeamOrderByParam, filters ...LHSFilter) ([]*models.Team, *http.Response, error) - GetTeam(org, team string) (*models.Team, *http.Response, error) - CreateTeam(org string, name, team, owner *string, roles []string) (*models.Team, *http.Response, error) - UpdateTeam(org string, name, team, owner *string, roles []string) (*models.Team, *http.Response, error) - DeleteTeam(org, team string) (*http.Response, error) - - // organization_team_members - ListTeamMembers(org string, team string, filters ...LHSFilter) ([]*models.MemberTeam, *http.Response, error) - GetTeamMember(org string, team string, memberID uint32) (*models.MemberTeam, *http.Response, error) - AssignMemberToTeam(org, team string, username, email *string) (*models.MemberTeam, *http.Response, error) - UnAssignMemberFromTeam(org, team string, memberID uint32) (*http.Response, error) - - // organization_oidc — OIDC group->team mappings + per-org reconciliation settings - ListOIDCGroupMappings(org string, filters ...LHSFilter) ([]*OIDCGroupMapping, *http.Response, error) - CreateOIDCGroupMapping(org, groupName, teamCanonical string) (*OIDCGroupMapping, *http.Response, error) - DeleteOIDCGroupMapping(org string, id uint32) (*http.Response, error) - GetOIDCOrganizationSettings(org string) (*OIDCOrganizationSettings, *http.Response, error) - UpdateOIDCOrganizationSettings(org string, settings UpdateOIDCOrganizationSettings) (*OIDCOrganizationSettings, *http.Response, error) - GetOIDCIntegration(org string) (*OIDCIntegration, *http.Response, error) - UpdateOIDCIntegration(org string, config map[string]interface{}) (*OIDCIntegration, *http.Response, error) - - // organizations - CreateOrganization(name string) (*models.Organization, *http.Response, error) - UpdateOrganization(org, name string) (*models.Organization, *http.Response, error) - DeleteOrganization(org string) (*http.Response, error) - GetOrganization(org string) (*models.Organization, *http.Response, error) - ListOrganizations() ([]*models.Organization, *http.Response, error) - ListOrganizationWorkers(org string) ([]*models.Worker, *http.Response, error) - ListOrganizationChildrens(org string) ([]*models.Organization, *http.Response, error) - CreateOrganizationChild(org, childOrg string, childOrgName *string) (*models.Organization, *http.Response, error) - CreateOrUpdateSubscription(org string, plan SubscriptionPlan, expiresAt time.Time, membersCount uint64, overwrite bool) (*models.Subscription, *http.Response, error) - - // Organization Forms - InterpolateFormsConfig(org, env, project, component, serviceCatalogRef, useCase string, inputs models.FormVariables) (*models.ServiceCatalogConfig, *http.Response, error) - ValidateForm(org string, rawForms []byte) (*models.FormsValidationResult, *http.Response, error) - - // Organization pipelines - GetOrgPipelines(org string, concoursePipeline, project, env *string, statuses []string) ([]*models.Pipeline, *http.Response, error) - - // Project Pipelines - GetProjectPipelines(org, project string) ([]*models.Pipeline, *http.Response, error) - - // Environments pipelines - GetEnvPipelines(org, project, env string) ([]*models.Pipeline, *http.Response, error) - - // Component pipelines - PausePipeline(org, project, env, component, pipelineName string) (*http.Response, error) - UnpausePipeline(org, project, env, component, pipelineName string) (*http.Response, error) - DiffPipeline(org, project, env, component, pipelineName, yamlPipeline, yamlVariables string, checkCredentials bool) (*models.PipelineDiffs, *http.Response, error) - CreatePipeline(org, project, env, pipeline, component, yamlPipeline, yamlVariables string, checkCredentials bool) (*models.Pipeline, *http.Response, error) - RenamePipeline(org, project, env, component, pipeline, newName string) (*http.Response, error) - SyncedPipeline(org, project, env, component, pipeline string) (*models.PipelineStatus, *http.Response, error) - GetPipeline(org, project, env, component, pipeline string) (*models.Pipeline, *http.Response, error) - UpdatePipeline(org, project, env, component, pipelineName, yamlPipeline, yamlVariables string, checkCredentials bool) (*models.Pipeline, *http.Response, error) - DeletePipeline(org, project, env, component, pipeline string) (*http.Response, error) - - // Component pipelines jobs - GetJobs(org, project, env, component, pipeline string) ([]*models.Job, *http.Response, error) - GetJob(org, project, env, component, pipeline, job string) (*models.Job, *http.Response, error) - PauseJob(org, project, env, component, pipeline, job string) (*http.Response, error) - UnPauseJob(org, project, env, component, pipeline, job string) (*http.Response, error) - ClearTaskCache(org, project, env, component, pipeline, job, step string) (*models.ClearTaskCache, *http.Response, error) - - // Component pipelines jobs build - GetBuilds(org, project, env, component, pipeline, job string) ([]*models.Build, *http.Response, error) - CreateBuild(org, project, env, component, pipeline, job string) (*models.Build, *http.Response, error) - GetBuild(org, project, env, component, pipeline, job, buildID string) (*models.Build, *http.Response, error) - RerunBuild(org, project, env, component, pipeline, job, buildID string) (*models.Build, *http.Response, error) - AbortBuild(org, project, env, component, pipeline, job, buildID string) (*http.Response, error) - GetBuildEvents(org, project, env, component, pipeline, buildID string) (*string, *http.Response, error) - OpenBuildEventsStream(ctx context.Context, org, project, env, component, pipeline, buildID, lastEventID string) (io.ReadCloser, *http.Response, error) - GetBuildPlan(org, project, env, component, pipeline, job, buildID string) (*models.PublicPlan, *http.Response, error) - GetBuildPreparation(org, project, env, component, pipeline, job, buildID string) (*models.Preparation, *http.Response, error) - GetBuildResources(org, project, env, component, pipeline, job, buildID string) (*models.BuildInputsOutputs, *http.Response, error) - - // Project - CreateProject(org, projectName, project, description, configRepository, owner, team, color, icon string) (*models.Project, *http.Response, error) - UpdateProject(org, projectName, project, description, configRepository, owner, team, color, icon, cloudProvider string) (*models.Project, *http.Response, error) - DeleteProject(org, project string, opts DeleteOptions) (*http.Response, error) - GetProject(org string, project string) (*models.Project, *http.Response, error) - ListProjects(org string, filters ...LHSFilter) ([]*models.Project, *http.Response, error) - ListProjectEnvs(org, project string, filters ...LHSFilter) ([]*models.ProjectEnvironment, *http.Response, error) - - // Env (org-scoped) - ListOrgEnvs(org string, filters ...LHSFilter) ([]*models.Environment, *http.Response, error) - GetOrgEnv(org, env string) (*models.Environment, *http.Response, error) - CreateOrgEnv(org string, body *models.NewEnvironment) (*models.Environment, *http.Response, error) - UpdateOrgEnv(org, env string, body *models.UpdateEnvironment) (*models.Environment, *http.Response, error) - DeleteOrgEnv(org, env string) (*http.Response, error) - LinkEnvToProject(org, project, env string) (*http.Response, error) - UnlinkEnvFromProject(org, project, env string, opts DeleteOptions) (*http.Response, error) - - // Cloud accounts - ListCloudAccounts(org string) ([]*models.CloudAccountDetail, *http.Response, error) - GetCloudAccount(org, canonical string) (*models.CloudAccountDetail, *http.Response, error) - CreateCloudAccount(org string, body *models.NewCloudAccount) (*models.CloudAccount, *http.Response, error) - CreateCloudAccountWithCredentials(org string, body *models.NewCloudAccountWithCredentials) (*models.CloudAccount, *http.Response, error) - UpdateCloudAccount(org, canonical string, body *models.UpdateCloudAccount) (*models.CloudAccount, *http.Response, error) - DeleteCloudAccount(org, canonical string) (*http.Response, error) - - // Environment types - ListEnvironmentTypes(org string) ([]*models.EnvironmentType, *http.Response, error) - GetEnvironmentType(org, canonical string) (*models.EnvironmentType, *http.Response, error) - CreateEnvironmentType(org string, body *models.NewEnvironmentType) (*models.EnvironmentType, *http.Response, error) - UpdateEnvironmentType(org, canonical string, body *models.UpdateEnvironmentType) (*models.EnvironmentType, *http.Response, error) - DeleteEnvironmentType(org, canonical string) (*http.Response, error) - - // Component - CreateOrUpdateComponent(org, project, env, component, description, name, stackRef, versionTag, versionBranch, versionCommitHash, useCase, cloudProvider string, vars models.FormVariables) (*models.Component, *http.Response, error) - ListComponents(org, project, env string, filters ...LHSFilter) ([]*models.Component, *http.Response, error) - GetComponent(org, project, env, component string) (*models.Component, *http.Response, error) - MigrateComponent(org, project, env, component, targetProject, targetEnv, newCanonical, newName string) (*models.Component, *http.Response, error) - DeleteComponent(org, project, env, component string, opts DeleteOptions) (*http.Response, error) - GetComponentConfig(org, project, env, component string) (models.FormVariables, *http.Response, error) - GetComponentStackConfig(org, project, env, component, useCase, versionTag, versionBranch, versionCommitHash string) (models.ServiceCatalogConfigs, *http.Response, error) - - DeleteRole(org, role string) (*http.Response, error) - GetRole(org, role string) (*models.Role, *http.Response, error) - ListRoles(org string, filters ...LHSFilter) ([]*models.Role, *http.Response, error) - CreateRole(org string, name, canonical, description *string, rules []*models.NewRule) (*models.NewRole, *http.Response, error) - UpdateRole(org, roleCanonical string, name, canonical, description *string, rules []*models.NewRule) (*models.Role, *http.Response, error) - - // inventory - ListInventoryResources(org string, filters ...LHSFilter) ([]*models.InventoryResource, *http.Response, error) - ListInventoryOutputs(org string, filters ...LHSFilter) ([]*InventoryOutput, *http.Response, error) - CreateInventoryResource(org string, body *models.NewInventoryResource) (*models.InventoryResource, *http.Response, error) - DeleteInventoryResource(org string, id uint32) (*http.Response, error) - - // ApiKeys - ListAPIKeys(org string, filters ...LHSFilter) ([]*models.APIKey, *http.Response, error) - GetAPIKey(org, canonical string) (*models.APIKey, *http.Response, error) - CreateAPIKey(org, canonical, description, owner string, name *string, rules []*models.NewRule) (*models.APIKey, *http.Response, error) - DeleteAPIKey(org, canonical string) (*http.Response, error) - - // organization_plugin_managers - ListPluginManagers(org string) ([]*models.PluginManager, *http.Response, error) - GetPluginManager(org string, id uint32) (*models.PluginManager, *http.Response, error) - CreatePluginManager(org, name, url string, autoRegister bool) (*models.PluginManager, *http.Response, error) - UpdatePluginManager(org string, id uint32, inviteStatus string) (*models.PluginManager, *http.Response, error) - DeletePluginManager(org string, id uint32) (*http.Response, error) - - // organization_plugins (installs) - ListPlugins(org string) ([]*models.Plugin, *http.Response, error) - GetPlugin(org string, id uint32) (*models.PluginInstall, *http.Response, error) - UpdatePlugin(org string, id, versionID uint32, config map[string]string) (*models.PluginInstall, *http.Response, error) - DeletePlugin(org string, id uint32) (*http.Response, error) - ListPluginLogs(org string, id uint32) (*models.PluginLogs, *http.Response, error) - - // organization_plugin_registries - ListPluginRegistries(org string) ([]*models.PluginRegistry, *http.Response, error) - GetPluginRegistry(org string, id uint32) (*models.PluginRegistry, *http.Response, error) - CreatePluginRegistry(org, name, url string) (*models.PluginRegistry, *http.Response, error) - UpdatePluginRegistry(org string, id uint32, name string) (*models.PluginRegistry, *http.Response, error) - DeletePluginRegistry(org string, id uint32) (*http.Response, error) - - // organization_plugin_registries — plugins - ListRegistryPlugins(org string, registryID uint32) ([]*models.Plugin, *http.Response, error) - GetRegistryPlugin(org string, registryID, pluginID uint32) (*models.Plugin, *http.Response, error) - CreateRegistryPlugin(org string, registryID uint32, name string) (*models.Plugin, *http.Response, error) - UpdateRegistryPlugin(org string, registryID, pluginID uint32, name string) (*models.Plugin, *http.Response, error) - DeleteRegistryPlugin(org string, registryID, pluginID uint32) (*http.Response, error) - - // organization_plugin_registries — versions - ListPluginVersions(org string, registryID, pluginID uint32) ([]*models.PluginVersion, *http.Response, error) - GetPluginVersion(org string, registryID, pluginID, versionID uint32) (*models.PluginVersion, *http.Response, error) - CreatePluginVersion(org string, registryID, pluginID uint32, url string) (*models.PluginVersion, *http.Response, error) - DeletePluginVersion(org string, registryID, pluginID, versionID uint32) (*http.Response, error) - InstallPluginVersion(org string, registryID, pluginID, versionID uint32, configuration map[string]string) (*http.Response, error) - RetryPluginVersion(org string, registryID, pluginID, versionID uint32) (*http.Response, error) - ListPluginVersionLogs(org string, registryID, pluginID, versionID uint32) ([]*models.PluginVersionLog, *http.Response, error) - - // component plugins - ListComponentPlugins(org, project, env, component string) ([]*models.Plugin, *http.Response, error) - SetComponentPluginRelation(org, project, env, component string, pluginInstallID uint32, enabled bool) (*models.PluginRelation, *http.Response, error) - - // org plugin widgets - ListPluginWidgets(org, placement string) ([]*models.PluginWidget, *http.Response, error) - QueryPluginWidget(org string, widgetID uint32) (*models.PluginWidgetData, *http.Response, error) - - // component plugin widgets - ListComponentPluginWidgets(org, project, env, component string) ([]*models.PluginWidget, *http.Response, error) - QueryComponentPluginWidget(org, project, env, component string, widgetID uint32) (*models.PluginWidgetData, *http.Response, error) - - // CostEstimation will consume the backend API endpoint for cost estimation - CostEstimation(org string, plan []byte) (*models.CostEstimationResult, *http.Response, error) - - // Extra actions out of the api - InitFirstOrg(org, userName, fullName, email, password, licence string, apiKeyCanonical *string) (*FirstOrgData, *http.Response, error) - - // Generic request for un-implemented routes - GenericRequest(req Request, response any) (*http.Response, error) -} - -type FirstOrgData struct { - Org string - Username string - FullName string - Email string - Password string - Token string - APIKey *string - CredentialCanonical *string -} - -type middleware struct { - api *common.APIClient - GenericClient http.Client -} - -func NewMiddleware(api *common.APIClient) Middleware { - client := http.DefaultClient - client.Transport = &http.Transport{ - TLSClientConfig: &tls.Config{ - InsecureSkipVerify: api.Config.Insecure, - }, - } - return &middleware{ - api: api, - GenericClient: *client, - } -} diff --git a/cmd/cycloid/middleware/middleware_test.go b/cmd/cycloid/middleware/middleware_test.go deleted file mode 100644 index c7c62a898..000000000 --- a/cmd/cycloid/middleware/middleware_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package middleware_test - -import ( - "context" - "fmt" - "log" - "os" - "testing" - - "github.com/spf13/viper" - - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -var config *testcfg.Config - -// Put any preparation code here so that defer() can work -func runMain(ctx context.Context, main *testing.M) (int, error) { - _ = ctx - // Initialize global vars - var err error - config, err = testcfg.NewConfig("middleware") - defer config.Cleanup() - if err != nil { - return 1, fmt.Errorf("config setup failed for package middleware: %w", err) - } - - os.Setenv("CY_API_URL", config.APIUrl) - os.Setenv("CY_API_KEY", config.APIKey) - os.Setenv("CY_ORG", config.Org) - if v := os.Getenv("CY_TEST_VERBOSITY"); v != "" { - viper.Set("verbosity", v) - } - return main.Run(), nil -} - -func TestMain(main *testing.M) { - ctx := context.Background() - code, err := runMain(ctx, main) - if err != nil { - log.Fatal(err) - } - - os.Exit(code) -} diff --git a/cmd/cycloid/middleware/offline/catalog_repository_refresh_versions_test.go b/cmd/cycloid/middleware/offline/catalog_repository_refresh_versions_test.go deleted file mode 100644 index bfe6329b9..000000000 --- a/cmd/cycloid/middleware/offline/catalog_repository_refresh_versions_test.go +++ /dev/null @@ -1,200 +0,0 @@ -package offline_test - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "sync/atomic" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -// catalogRepoResponse returns a minimal valid service_catalog_source JSON response. -func catalogRepoResponse(canonical string) string { - return fmt.Sprintf(`{"data":{"canonical":%q,"name":%q,"url":"git@github.com:my/repo.git","branch":"main"}}`, canonical, canonical) -} - -// versionsRefreshResponse returns a minimal versions/refresh JSON response. -func versionsRefreshResponse() string { - return `{"data":[{"id":1,"commit_hash":"abc1234","name":"main","type":"branch"},{"id":2,"commit_hash":"def5678","name":"feat/my-branch","type":"branch"}]}` -} - -// TestRefreshCatalogRepositoryVersions_CalledOnceWithFlag verifies that RefreshCatalogRepositoryVersions -// hits the versions/refresh endpoint exactly once when invoked. -func TestRefreshCatalogRepositoryVersions_CalledOnceWithFlag(t *testing.T) { - var refreshCalls int32 - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - switch { - case r.Method == http.MethodGet && r.URL.Path == "/organizations/org/service_catalog_sources/my-catalog/versions/refresh": - atomic.AddInt32(&refreshCalls, 1) - assert.Equal(t, "true", r.URL.Query().Get("sync_presence"), "sync_presence query param must be true") - fmt.Fprint(w, versionsRefreshResponse()) - default: - http.NotFound(w, r) - } - })) - defer srv.Close() - - m := middleware.NewMiddleware(common.NewAPI(common.WithURL(srv.URL), common.WithToken("token"))) - - versions, _, err := m.RefreshCatalogRepositoryVersions("org", "my-catalog") - require.NoError(t, err) - assert.Equal(t, int32(1), atomic.LoadInt32(&refreshCalls), "versions/refresh called exactly once") - assert.Len(t, versions, 2) -} - -// TestCreateCatalogRepository_RefreshCalledWhenFlagSet simulates the full create + refresh flow: -// POST creates the repo, then GET versions/refresh is called, confirming --refresh triggers exactly -// one refresh call and zero calls without the flag. -func TestCreateCatalogRepository_RefreshCalledWhenFlagSet(t *testing.T) { - var createCalls int32 - var refreshCalls int32 - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - switch { - case r.Method == http.MethodPost && r.URL.Path == "/organizations/org/service_catalog_sources": - atomic.AddInt32(&createCalls, 1) - // Verify body has required fields - var body map[string]any - require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) - assert.NotEmpty(t, body["name"]) - fmt.Fprint(w, catalogRepoResponse("my-catalog")) - case r.Method == http.MethodGet && r.URL.Path == "/organizations/org/service_catalog_sources/my-catalog/versions/refresh": - atomic.AddInt32(&refreshCalls, 1) - assert.Equal(t, "true", r.URL.Query().Get("sync_presence"), "sync_presence query param must be true") - fmt.Fprint(w, versionsRefreshResponse()) - default: - http.NotFound(w, r) - } - })) - defer srv.Close() - - m := middleware.NewMiddleware(common.NewAPI(common.WithURL(srv.URL), common.WithToken("token"))) - - // Simulate create (the command does this then calls RefreshCatalogRepositoryVersions when --refresh is set) - cr, _, err := m.CreateCatalogRepository("org", "my-catalog", "git@github.com:my/repo.git", "main", "", "", "") - require.NoError(t, err) - require.NotNil(t, cr) - assert.Equal(t, int32(1), atomic.LoadInt32(&createCalls)) - assert.Equal(t, int32(0), atomic.LoadInt32(&refreshCalls), "no refresh yet — flag not set") - - // Now simulate --refresh: the command calls RefreshCatalogRepositoryVersions after create - _, _, err = m.RefreshCatalogRepositoryVersions("org", "my-catalog") - require.NoError(t, err) - assert.Equal(t, int32(1), atomic.LoadInt32(&refreshCalls), "refresh called exactly once with flag") -} - -// TestUpdateCatalogRepository_RefreshCalledWhenFlagSet mirrors the create test for update. -func TestUpdateCatalogRepository_RefreshCalledWhenFlagSet(t *testing.T) { - var updateCalls int32 - var refreshCalls int32 - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - switch { - case r.Method == http.MethodPut && r.URL.Path == "/organizations/org/service_catalog_sources/my-catalog": - atomic.AddInt32(&updateCalls, 1) - fmt.Fprint(w, catalogRepoResponse("my-catalog")) - case r.Method == http.MethodGet && r.URL.Path == "/organizations/org/service_catalog_sources/my-catalog/versions/refresh": - atomic.AddInt32(&refreshCalls, 1) - assert.Equal(t, "true", r.URL.Query().Get("sync_presence"), "sync_presence query param must be true") - fmt.Fprint(w, versionsRefreshResponse()) - default: - http.NotFound(w, r) - } - })) - defer srv.Close() - - m := middleware.NewMiddleware(common.NewAPI(common.WithURL(srv.URL), common.WithToken("token"))) - - // Simulate update without --refresh - cr, _, err := m.UpdateCatalogRepository("org", "my-catalog", "my-catalog", "git@github.com:my/repo.git", "main", "", nil) - require.NoError(t, err) - require.NotNil(t, cr) - assert.Equal(t, int32(1), atomic.LoadInt32(&updateCalls)) - assert.Equal(t, int32(0), atomic.LoadInt32(&refreshCalls), "no refresh — flag not set") - - // Now simulate --refresh: the command calls RefreshCatalogRepositoryVersions after update - _, _, err = m.RefreshCatalogRepositoryVersions("org", "my-catalog") - require.NoError(t, err) - assert.Equal(t, int32(1), atomic.LoadInt32(&refreshCalls), "refresh called exactly once with flag") -} - -// TestCreateCatalogRepository_NoRefreshWithoutFlag verifies that when --refresh is not set, -// the versions/refresh endpoint is NOT called (zero calls). -func TestCreateCatalogRepository_NoRefreshWithoutFlag(t *testing.T) { - var refreshCalls int32 - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - switch { - case r.Method == http.MethodPost && r.URL.Path == "/organizations/org/service_catalog_sources": - fmt.Fprint(w, catalogRepoResponse("my-catalog")) - case r.Method == http.MethodGet && r.URL.Path == "/organizations/org/service_catalog_sources/my-catalog/versions/refresh": - atomic.AddInt32(&refreshCalls, 1) - t.Error("RefreshCatalogRepositoryVersions must not be called when --refresh flag is absent") - default: - http.NotFound(w, r) - } - })) - defer srv.Close() - - m := middleware.NewMiddleware(common.NewAPI(common.WithURL(srv.URL), common.WithToken("token"))) - - // Create without --refresh: only the POST happens, no refresh - cr, _, err := m.CreateCatalogRepository("org", "my-catalog", "git@github.com:my/repo.git", "main", "", "", "") - require.NoError(t, err) - require.NotNil(t, cr) - assert.Equal(t, int32(0), atomic.LoadInt32(&refreshCalls), "zero refresh calls without --refresh flag") -} - -// TestUpdateCatalogRepository_NoRefreshWithoutFlag mirrors the create test for update. -func TestUpdateCatalogRepository_NoRefreshWithoutFlag(t *testing.T) { - var refreshCalls int32 - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - switch { - case r.Method == http.MethodPut && r.URL.Path == "/organizations/org/service_catalog_sources/my-catalog": - fmt.Fprint(w, catalogRepoResponse("my-catalog")) - case r.Method == http.MethodGet && r.URL.Path == "/organizations/org/service_catalog_sources/my-catalog/versions/refresh": - atomic.AddInt32(&refreshCalls, 1) - t.Error("RefreshCatalogRepositoryVersions must not be called when --refresh flag is absent") - default: - http.NotFound(w, r) - } - })) - defer srv.Close() - - m := middleware.NewMiddleware(common.NewAPI(common.WithURL(srv.URL), common.WithToken("token"))) - - // Update without --refresh: only the PUT happens, no refresh - cr, _, err := m.UpdateCatalogRepository("org", "my-catalog", "my-catalog", "git@github.com:my/repo.git", "main", "", nil) - require.NoError(t, err) - require.NotNil(t, cr) - assert.Equal(t, int32(0), atomic.LoadInt32(&refreshCalls), "zero refresh calls without --refresh flag") -} - -// TestRefreshCatalogRepositoryVersions_PropagatesError verifies that a non-2xx response -// from the versions/refresh endpoint is propagated as an error to the caller. -func TestRefreshCatalogRepositoryVersions_PropagatesError(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Error(w, `{"errors":[{"code":"ServerError","message":"backend error"}]}`, http.StatusInternalServerError) - })) - defer srv.Close() - - m := middleware.NewMiddleware(common.NewAPI(common.WithURL(srv.URL), common.WithToken("token"))) - - versions, _, err := m.RefreshCatalogRepositoryVersions("org", "my-catalog") - require.Error(t, err) - assert.Nil(t, versions) -} diff --git a/cmd/cycloid/middleware/offline/generic_client_decode_test.go b/cmd/cycloid/middleware/offline/generic_client_decode_test.go deleted file mode 100644 index 26b0c569f..000000000 --- a/cmd/cycloid/middleware/offline/generic_client_decode_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package offline_test - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/printer" -) - -func TestGenericRequest_200InvalidJSON(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`not-valid-json`)) - })) - defer srv.Close() - - api := common.NewAPI(common.WithURL(srv.URL), common.WithToken("test-token")) - m := middleware.NewMiddleware(api) - - var out map[string]any - httpResp, err := m.GenericRequest(middleware.Request{ - Method: http.MethodGet, - Route: []string{"test"}, - }, &out) - - require.Error(t, err) - require.NotNil(t, httpResp) - assert.Equal(t, http.StatusOK, httpResp.StatusCode) - - var httpErr printer.ErrHTTPResponse - require.ErrorAs(t, err, &httpErr) - assert.Equal(t, http.StatusOK, httpErr.HTTPStatusCode()) - assert.Contains(t, string(httpErr.HTTPResponseBody()), "not-valid-json") -} - -func TestGenericRequest_200EnvelopeDataTypeMismatch(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"data":true}`)) - })) - defer srv.Close() - - api := common.NewAPI(common.WithURL(srv.URL), common.WithToken("test-token")) - m := middleware.NewMiddleware(api) - - var out map[string]any - httpResp, err := m.GenericRequest(middleware.Request{ - Method: http.MethodGet, - Route: []string{"test"}, - }, &out) - - require.Error(t, err) - require.NotNil(t, httpResp) - assert.Equal(t, http.StatusOK, httpResp.StatusCode) - - var httpErr printer.ErrHTTPResponse - require.ErrorAs(t, err, &httpErr) - assert.Equal(t, `{"data":true}`, string(httpErr.HTTPResponseBody())) -} diff --git a/cmd/cycloid/middleware/offline/lhs_filter_test.go b/cmd/cycloid/middleware/offline/lhs_filter_test.go deleted file mode 100644 index dc090b95c..000000000 --- a/cmd/cycloid/middleware/offline/lhs_filter_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package offline_test - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -// captureRawQuery runs a GenericRequest with the given LHSFilters against a local -// test server and returns the raw query string the server received. -func captureRawQuery(t *testing.T, filters []middleware.LHSFilter) string { - t.Helper() - var captured string - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - captured = r.URL.RawQuery - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"data":[]}`)) - })) - defer srv.Close() - - api := common.NewAPI(common.WithURL(srv.URL), common.WithToken("test-token")) - m := middleware.NewMiddleware(api) - - var out []any - _, err := m.GenericRequest(middleware.Request{ - Method: http.MethodGet, - Route: []string{"test"}, - LHSFilters: filters, - }, &out) - require.NoError(t, err) - return captured -} - -func TestLHSFilterBracketsNotEncoded(t *testing.T) { - raw := captureRawQuery(t, []middleware.LHSFilter{ - {Attribute: "name", Condition: "eq", Value: "my-project"}, - }) - assert.Equal(t, "name[eq]=my-project", raw, "brackets must be literal, not percent-encoded") -} - -func TestLHSFilterMultipleFilters(t *testing.T) { - raw := captureRawQuery(t, []middleware.LHSFilter{ - {Attribute: "name", Condition: "eq", Value: "my-project"}, - {Attribute: "canonical", Condition: "rlike", Value: "proj.*"}, - }) - assert.Equal(t, "name[eq]=my-project&canonical[rlike]=proj.*", raw) -} - -func TestLHSFilterRegexMetacharsPreserved(t *testing.T) { - tests := []struct { - name string - value string - wantValue string - }{ - {"dot wildcard", "dg.growy", "dg.growy"}, - {"question mark", "dg.?growy", "dg.?growy"}, - {"star wildcard", "dg.*growy", "dg.*growy"}, - {"plus quantifier", "dg.+growy", "dg.+growy"}, - {"brackets", "[A-Z]+", "[A-Z]+"}, - {"pipe alternation", "foo|bar", "foo|bar"}, - {"caret anchor", "^foo", "^foo"}, - {"dollar anchor", "foo$", "foo$"}, - {"backslash escape", `foo\.bar`, `foo\.bar`}, - {"parens groups", "(foo|bar)", "(foo|bar)"}, - {"curly braces", "a{2,4}", "a{2,4}"}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - raw := captureRawQuery(t, []middleware.LHSFilter{ - {Attribute: "name", Condition: "rlike", Value: tt.value}, - }) - assert.Equal(t, "name[rlike]="+tt.wantValue, raw) - }) - } -} - -func TestLHSFilterStructuralCharsEncoded(t *testing.T) { - tests := []struct { - name string - value string - wantValue string - }{ - {"ampersand", "foo&bar", "foo%26bar"}, - {"equals", "foo=bar", "foo%3Dbar"}, - {"hash", "foo#bar", "foo%23bar"}, - {"space", "foo bar", "foo%20bar"}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - raw := captureRawQuery(t, []middleware.LHSFilter{ - {Attribute: "name", Condition: "eq", Value: tt.value}, - }) - assert.Equal(t, "name[eq]="+tt.wantValue, raw) - }) - } -} - -func TestLHSFilterCombinedWithRegularQuery(t *testing.T) { - var captured string - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - captured = r.URL.RawQuery - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"data":[]}`)) - })) - defer srv.Close() - - api := common.NewAPI(common.WithURL(srv.URL), common.WithToken("test-token")) - m := middleware.NewMiddleware(api) - - type queryParams struct { - PageSize int `url:"page_size"` - } - - var out []any - _, err := m.GenericRequest(middleware.Request{ - Method: http.MethodGet, - Route: []string{"test"}, - Query: queryParams{PageSize: 100}, - LHSFilters: []middleware.LHSFilter{ - {Attribute: "name", Condition: "eq", Value: "my-project"}, - }, - }, &out) - require.NoError(t, err) - - assert.Contains(t, captured, "page_size=100") - assert.Contains(t, captured, "name[eq]=my-project") -} - -func TestLHSFilterEmpty(t *testing.T) { - raw := captureRawQuery(t, nil) - assert.Equal(t, "", raw, "no filters should produce no query string") -} diff --git a/cmd/cycloid/middleware/organization.go b/cmd/cycloid/middleware/organization.go deleted file mode 100644 index 41976e5f0..000000000 --- a/cmd/cycloid/middleware/organization.go +++ /dev/null @@ -1,129 +0,0 @@ -package middleware - -import ( - "net/http" - "net/url" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) CreateOrganization(name string) (*models.Organization, *http.Response, error) { - body := &models.NewOrganization{ - Name: &name, - } - - var result *models.Organization - resp, err := m.GenericRequest(Request{ - Method: "POST", - Route: []string{"organizations"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UpdateOrganization(can, name string) (*models.Organization, *http.Response, error) { - body := &models.UpdateOrganization{ - Name: &name, - } - - var result *models.Organization - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &can, - Route: []string{"organizations", can}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetOrganization(org string) (*models.Organization, *http.Response, error) { - var result *models.Organization - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) ListOrganizationWorkers(org string) ([]*models.Worker, *http.Response, error) { - var result []*models.Worker - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "workers"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) ListOrganizations() ([]*models.Organization, *http.Response, error) { - var result []*models.Organization - resp, err := m.GenericRequest(Request{ - Method: "GET", - Route: []string{"organizations"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) ListOrganizationChildrens(org string) ([]*models.Organization, *http.Response, error) { - query := url.Values{"order_by": []string{"organization_canonical:asc"}} - - var result []*models.Organization - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "children"}, - Query: query, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) CreateOrganizationChild(org, childOrg string, childOrgName *string) (*models.Organization, *http.Response, error) { - if childOrgName == nil { - childOrgName = &childOrg - } - - body := &models.NewOrganization{ - Name: childOrgName, - Canonical: childOrg, - } - - var result *models.Organization - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "children"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeleteOrganization(org string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org}, - }, nil) - return resp, err -} diff --git a/cmd/cycloid/middleware/organization_api_key.go b/cmd/cycloid/middleware/organization_api_key.go deleted file mode 100644 index c196d7c55..000000000 --- a/cmd/cycloid/middleware/organization_api_key.go +++ /dev/null @@ -1,78 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// ListAPIKeys lists API keys for an organization. -// -// Supported LHS filter attributes: organization_canonical, user_canonical. -func (m *middleware) ListAPIKeys(org string, filters ...LHSFilter) ([]*models.APIKey, *http.Response, error) { - var result []*models.APIKey - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "api_keys"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("unable to list API keys: %w", err) - } - return result, resp, nil -} - -// GetAPIKey will request API to get a specified generated API key by its canonical -func (m *middleware) GetAPIKey(org, canonical string) (*models.APIKey, *http.Response, error) { - var result *models.APIKey - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "api_keys", canonical}, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("unable to get API key: %w", err) - } - return result, resp, nil -} - -// CreateAPIKey will request API to create an API key -func (m *middleware) CreateAPIKey(org, canonical, description, owner string, name *string, rules []*models.NewRule) (*models.APIKey, *http.Response, error) { - body := models.NewAPIKey{ - Canonical: canonical, - Name: name, - Description: description, - Rules: rules, - } - - if owner != "" { - body.Owner = owner - } - - var result *models.APIKey - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "api_keys"}, - Body: &body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// DeleteAPIKey will request API to delete a specified generated API key -func (m *middleware) DeleteAPIKey(org, canonical string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "api_keys", canonical}, - }, nil) - if err != nil { - return resp, fmt.Errorf("unable to delete API key: %w", err) - } - return resp, nil -} diff --git a/cmd/cycloid/middleware/organization_api_key_test.go b/cmd/cycloid/middleware/organization_api_key_test.go deleted file mode 100644 index f7fee0750..000000000 --- a/cmd/cycloid/middleware/organization_api_key_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -func TestAPIKeyCRUD(t *testing.T) { - m := config.Middleware - - canonical := testcfg.RandomCanonical("test-apikey") - name := ptr.Ptr("Test API Key") - - rule := &models.NewRule{Action: ptr.Ptr("*"), Effect: ptr.Ptr(models.NewRuleEffectAllow)} - created, _, err := m.CreateAPIKey(config.Org, canonical, "test api key", "administrator", name, []*models.NewRule{rule}) - require.NoError(t, err, "CreateAPIKey should succeed") - require.NotNil(t, created) - - defer func() { - _, err := m.DeleteAPIKey(config.Org, canonical) - require.NoError(t, err, "DeleteAPIKey should succeed") - }() - - got, _, err := m.GetAPIKey(config.Org, canonical) - require.NoError(t, err, "GetAPIKey should succeed") - assert.Equal(t, canonical, *got.Canonical) - - list, _, err := m.ListAPIKeys(config.Org) - require.NoError(t, err, "ListAPIKeys should succeed") - assert.NotEmpty(t, list) -} diff --git a/cmd/cycloid/middleware/organization_cloud_accounts.go b/cmd/cycloid/middleware/organization_cloud_accounts.go deleted file mode 100644 index c37cc07d9..000000000 --- a/cmd/cycloid/middleware/organization_cloud_accounts.go +++ /dev/null @@ -1,82 +0,0 @@ -package middleware - -import ( - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) ListCloudAccounts(org string) ([]*models.CloudAccountDetail, *http.Response, error) { - result, resp, err := paginatedList[*models.CloudAccountDetail](m, Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "cloud_accounts"}, - }, defaultPageSize) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetCloudAccount(org, canonical string) (*models.CloudAccountDetail, *http.Response, error) { - var result *models.CloudAccountDetail - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "cloud_accounts", canonical}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) CreateCloudAccount(org string, body *models.NewCloudAccount) (*models.CloudAccount, *http.Response, error) { - var result *models.CloudAccount - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "cloud_accounts"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) CreateCloudAccountWithCredentials(org string, body *models.NewCloudAccountWithCredentials) (*models.CloudAccount, *http.Response, error) { - var result *models.CloudAccount - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "cloud_accounts", "with_credentials"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UpdateCloudAccount(org, canonical string, body *models.UpdateCloudAccount) (*models.CloudAccount, *http.Response, error) { - var result *models.CloudAccount - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "cloud_accounts", canonical}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeleteCloudAccount(org, canonical string) (*http.Response, error) { - return m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "cloud_accounts", canonical}, - }, nil) -} diff --git a/cmd/cycloid/middleware/organization_cloud_accounts_test.go b/cmd/cycloid/middleware/organization_cloud_accounts_test.go deleted file mode 100644 index 3e75f0ee2..000000000 --- a/cmd/cycloid/middleware/organization_cloud_accounts_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -func TestCloudAccountCRUD(t *testing.T) { - m := config.Middleware - - // Pre-create a credential — cloud accounts require one at create time. - credCanonical := testcfg.RandomCanonical("test-ca-cred") - cred, _, err := m.CreateCredential(config.Org, credCanonical, "aws", - &models.CredentialRaw{AccessKey: "AKIAIOSFODNN7EXAMPLE", SecretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"}, - "", credCanonical, "", - ) - require.NoError(t, err, "CreateCredential should succeed") - require.NotNil(t, cred) - defer func() { - // The backend cascades credential deletion when a cloud account is deleted, - // so a 404 here is expected when the cloud account cleanup ran first. - _, _ = m.DeleteCredential(config.Org, *cred.Canonical) - }() - - // Create - canonical := testcfg.RandomCanonical("test-ca") - createBody := &models.NewCloudAccount{ - Canonical: canonical, - Name: ptr.Ptr(canonical), - CloudProvider: ptr.Ptr("aws"), - CredentialCanonical: ptr.Ptr(*cred.Canonical), - } - created, _, err := m.CreateCloudAccount(config.Org, createBody) - require.NoError(t, err, "CreateCloudAccount should succeed") - require.NotNil(t, created) - assert.Equal(t, canonical, *created.Canonical) - - defer func() { - _, err := m.DeleteCloudAccount(config.Org, *created.Canonical) - require.NoError(t, err, "DeleteCloudAccount cleanup should succeed") - }() - - // Get - got, _, err := m.GetCloudAccount(config.Org, *created.Canonical) - require.NoError(t, err, "GetCloudAccount should succeed") - assert.Equal(t, *created.Canonical, *got.Canonical) - assert.Equal(t, "aws", *got.CloudProvider) - - // List — created account must appear - list, _, err := m.ListCloudAccounts(config.Org) - require.NoError(t, err, "ListCloudAccounts should succeed") - assert.NotEmpty(t, list) - found := false - for _, ca := range list { - if ca.Canonical != nil && *ca.Canonical == *created.Canonical { - found = true - break - } - } - assert.True(t, found, "created cloud account must appear in list") - - // Update — rename only; credential stays the same - updatedName := canonical + "-updated" - updateBody := &models.UpdateCloudAccount{ - Name: ptr.Ptr(updatedName), - CredentialCanonical: cred.Canonical, - } - updated, _, err := m.UpdateCloudAccount(config.Org, *created.Canonical, updateBody) - require.NoError(t, err, "UpdateCloudAccount should succeed") - assert.Equal(t, updatedName, *updated.Name) -} - -func TestGetCloudAccount_NotFound(t *testing.T) { - m := config.Middleware - - _, resp, err := m.GetCloudAccount(config.Org, "nonexistent-cloud-account-xyz") - assert.Error(t, err, "GetCloudAccount should return an error for an unknown canonical") - require.NotNil(t, resp) - assert.Equal(t, 404, resp.StatusCode) -} diff --git a/cmd/cycloid/middleware/organization_components.go b/cmd/cycloid/middleware/organization_components.go deleted file mode 100644 index 9a1410aa7..000000000 --- a/cmd/cycloid/middleware/organization_components.go +++ /dev/null @@ -1,176 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -func (m *middleware) GetComponentConfig(org, project, env, component string) (models.FormVariables, *http.Response, error) { - var result models.FormVariables - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "config"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetComponent(org, project, env, component string) (*models.Component, *http.Response, error) { - var result *models.Component - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// ListComponents lists components for a project environment. -// -// Supported LHS filter attributes: component_canonical, service_catalog_ref, -// service_catalog_source_canonical, environment_canonical, project_canonical, -// component_version_type, component_version_status, component_version_name. -func (m *middleware) ListComponents(org, project, env string, filters ...LHSFilter) ([]*models.Component, *http.Response, error) { - var result []*models.Component - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// newComponentBody is a local body struct used for component upsert. -// It includes service_catalog_source_version_id which the backend still requires -// but which was removed from the generated models.NewComponent. -type newComponentBody struct { - Canonical string `json:"canonical,omitempty"` - CloudProviderCanonical string `json:"cloud_provider_canonical,omitempty"` - Description string `json:"description,omitempty"` - Name *string `json:"name"` - ServiceCatalogRef *string `json:"service_catalog_ref"` - ServiceCatalogSourceVersionID *uint32 `json:"service_catalog_source_version_id,omitempty"` - ServiceCatalogSourceVersionCommitHash *string `json:"service_catalog_source_version_commit_hash,omitempty"` - UseCase *string `json:"use_case,omitempty"` - Vars models.FormVariables `json:"vars,omitempty"` -} - -// CreateOrUpdateComponent creates or updates a component with the provided configuration, -// including syncing the Concourse pipeline. Uses PUT on the collection endpoint. -func (m *middleware) CreateOrUpdateComponent(org, project, env, component, description, name, stackRef, versionTag, versionBranch, versionCommitHash, useCase, cloudProvider string, vars models.FormVariables) (*models.Component, *http.Response, error) { - versionID, commitHash, err := m.resolveStackVersion(org, stackRef, versionTag, versionBranch, versionCommitHash) - if err != nil { - return nil, nil, err - } - var useCasePtr *string - if useCase != "" { - useCasePtr = ptr.Ptr(useCase) - } - body := &newComponentBody{ - Canonical: component, - CloudProviderCanonical: cloudProvider, - Description: description, - Name: ptr.Ptr(name), - ServiceCatalogRef: ptr.Ptr(stackRef), - ServiceCatalogSourceVersionID: ptr.Ptr(versionID), - ServiceCatalogSourceVersionCommitHash: ptr.Ptr(commitHash), - UseCase: useCasePtr, - Vars: vars, - } - - var result *models.Component - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to create or update component: %w", err) - } - return result, resp, nil -} - -func (m *middleware) MigrateComponent(org, project, env, component, targetProject, targetEnv, newCanonical, newName string) (*models.Component, *http.Response, error) { - body := models.MigrateComponent{ - DestinationProjectCanonical: targetProject, - DestinationEnvironmentCanonical: targetEnv, - DestinationComponentCanonical: newCanonical, - DestinationComponentName: newName, - } - - var result *models.Component - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "migrate"}, - Body: &body, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to migrate component: %w", err) - } - return result, resp, nil -} - -func (m *middleware) DeleteComponent(org, project, env, component string, opts DeleteOptions) (*http.Response, error) { - req := Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component}, - } - if q := opts.Resolve(); q.SkipHooks || q.IgnoreConfigFilesErr { - req.Query = q - } - return m.GenericRequest(req, nil) -} - -func (m *middleware) GetComponentStackConfig(org, project, env, component, useCase, versionTag, versionBranch, versionCommitHash string) (models.ServiceCatalogConfigs, *http.Response, error) { - // Need to get component to determine stack ref - comp, _, err := m.GetComponent(org, project, env, component) - if err != nil { - return nil, nil, err - } - - stackRef := *comp.ServiceCatalog.Ref - - // Resolve version parameters to ID and commit hash - versionID, commitHash, err := m.resolveStackVersion(org, stackRef, versionTag, versionBranch, versionCommitHash) - if err != nil { - return nil, nil, err - } - - query := url.Values{ - "service_catalog_source_version_id": []string{strconv.FormatUint(uint64(versionID), 10)}, - "service_catalog_source_version_commit_hash": []string{commitHash}, - } - if useCase != "" { - query.Set("use_case", useCase) - } - - var result models.ServiceCatalogConfigs - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "stack_config"}, - Query: query, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/organization_components_test.go b/cmd/cycloid/middleware/organization_components_test.go deleted file mode 100644 index 91a74efa6..000000000 --- a/cmd/cycloid/middleware/organization_components_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package middleware_test - -import ( - "errors" - "log" - "strconv" - "testing" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func TestComponentCRUD(t *testing.T) { - m := config.Middleware - for index := range 2 { // Made only two to speed up tests - var ( - componentName = "Test Component " + strconv.Itoa(index) - component = "test-component-" + strconv.Itoa(index) - componentDescription = "My cool component" - stackRef = config.Org + ":stack-e2e-stackforms" - useCase = "default" - newVar = models.FormVariables{ - "can two sections have same name with different caps ?": { - "can two groups have same name with different caps ?": { - "group1": "EDITED", - }, - }, - } - formVars = &models.FormVariables{ - "can two sections have same name with different caps ?": { - "can two groups have same name with different caps ?": { - "group1": "osef", - }, - }, - "CAN TWO SECTIONS HAVE SAME NAME WITH DIFFERENT CAPS ?": { - "CAN TWO GROUPS HAVE SAME NAME WITH DIFFERENT CAPS ?": { - "group2": "osef", - }, - }, - "section spaces AND CAPS": { - "group spaces AND CAPS": { - "no_spaces_no_caps": "osef", - }, - }, - "section with spaces": { - "group with spaces": { - "no_spaces": "osef", - }, - }, - "types": { - "tests": { - "array": []any{ - "hello", - "world", - false, - index, - 1.1, - }, - "bool": true, - "float": 0.1, - "integer": 1, - "map": map[string]any{ - "array": []any{ - "hello", - "world", - }, - "bool": false, - "float": 0.1, - "integer": 1, - "nested": map[string]string{ - "map": "hello", - }, - "string": "string", - }, - "string": "stringValue1", - }, - }, - } - ) - - var createdComponent *models.Component - var err, errList error - for range 3 { // retries due to concurenccy bug in backend - createdComponent, _, err = m.GetComponent(config.Org, *config.Project.Canonical, *config.Environment.Canonical, component) - if err == nil { - errList = nil - break - } - - createdComponent, _, err = m.CreateOrUpdateComponent(config.Org, *config.Project.Canonical, *config.Environment.Canonical, component, componentDescription, componentName, stackRef, "", "", "", useCase, "", *formVars) - if err != nil { - errList = errors.Join(errList, err) - continue - } - - errList = nil - break - } - - if errList != nil { - t.Errorf("Failed to create component '%s':\n%v", component, err) - } - - defer func() { - _, err := m.DeleteComponent(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *createdComponent.Canonical, middleware.DeleteOptions{}) - if err != nil { - log.Fatalf("Failed to delete component '%s': %v", *createdComponent.Canonical, err) - return - } - }() - - var ( - newDescription = "New desc" - newComponentName = "New name" + strconv.Itoa(index) - ) - errList, err = nil, nil - for range 3 { - _, _, err = m.CreateOrUpdateComponent(config.Org, *config.Project.Canonical, *config.Environment.Canonical, *createdComponent.Canonical, newDescription, newComponentName, stackRef, "", "", *config.CatalogRepoVersionStacks.CommitHash, useCase, "", newVar) - if err != nil { - errList = errors.Join(errList, err) - continue - } - - errList = nil - break - } - if errList != nil { - t.Errorf("Failed to update component '%s':\n%v", *createdComponent.Canonical, err) - } - - // TODO: Fix after issue: https://linear.app/cycloid/issue/BE-801/invalid-response-for-updatecomponent - // assert.NotNil(t, updatedComponent, "response should not be nil.") - // assert.NotNil(t, updatedComponent.Name, "Name should not be nil.") - // assert.Equal(t, newComponentName, *updatedComponent.Name) - // assert.Equal(t, newDescription, *updatedComponent.Canonical) - } - - _, _, err := m.ListComponents(config.Org, *config.Project.Canonical, *config.Environment.Canonical) - if err != nil { - t.Errorf("Failed to list components in project '%s':\n%v", *config.Project.Canonical, err) - } -} diff --git a/cmd/cycloid/middleware/organization_environment_types.go b/cmd/cycloid/middleware/organization_environment_types.go deleted file mode 100644 index f1810b418..000000000 --- a/cmd/cycloid/middleware/organization_environment_types.go +++ /dev/null @@ -1,73 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) ListEnvironmentTypes(org string) ([]*models.EnvironmentType, *http.Response, error) { - result, resp, err := paginatedList[*models.EnvironmentType](m, Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "environment_types"}, - }, defaultPageSize) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetEnvironmentType(org, canonical string) (*models.EnvironmentType, *http.Response, error) { - types, resp, err := m.ListEnvironmentTypes(org) - if err != nil { - return nil, resp, err - } - for _, envType := range types { - if envType.Canonical != nil && *envType.Canonical == canonical { - return envType, resp, nil - } - } - return nil, resp, &APIResponseError{ - StatusCode: http.StatusNotFound, - Status: "404 Not Found", - Body: []byte(fmt.Sprintf("environment type %q not found", canonical)), - } -} - -func (m *middleware) CreateEnvironmentType(org string, body *models.NewEnvironmentType) (*models.EnvironmentType, *http.Response, error) { - var result *models.EnvironmentType - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "environment_types"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UpdateEnvironmentType(org, canonical string, body *models.UpdateEnvironmentType) (*models.EnvironmentType, *http.Response, error) { - var result *models.EnvironmentType - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "environment_types", canonical}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeleteEnvironmentType(org, canonical string) (*http.Response, error) { - return m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "environment_types", canonical}, - }, nil) -} diff --git a/cmd/cycloid/middleware/organization_environment_types_test.go b/cmd/cycloid/middleware/organization_environment_types_test.go deleted file mode 100644 index 96407e868..000000000 --- a/cmd/cycloid/middleware/organization_environment_types_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -func TestEnvironmentTypeCRUD(t *testing.T) { - m := config.Middleware - - canonical := testcfg.RandomCanonical("test-env-type") - name := "Test Env Type" - color := "#3498db" - - createBody := &models.NewEnvironmentType{ - Canonical: canonical, - Name: ptr.Ptr(name), - Color: ptr.Ptr(color), - } - created, _, err := m.CreateEnvironmentType(config.Org, createBody) - require.NoError(t, err, "CreateEnvironmentType should succeed") - require.NotNil(t, created) - assert.Equal(t, canonical, *created.Canonical) - assert.Equal(t, name, *created.Name) - - defer func() { - _, err := m.DeleteEnvironmentType(config.Org, *created.Canonical) - require.NoError(t, err, "DeleteEnvironmentType cleanup should succeed") - }() - - // Get — must round-trip through list since GET-by-canonical is list-based - got, _, err := m.GetEnvironmentType(config.Org, *created.Canonical) - require.NoError(t, err, "GetEnvironmentType should succeed") - assert.Equal(t, *created.Canonical, *got.Canonical) - assert.Equal(t, color, *got.Color) - - // List — created type must appear - list, _, err := m.ListEnvironmentTypes(config.Org) - require.NoError(t, err, "ListEnvironmentTypes should succeed") - assert.NotEmpty(t, list) - found := false - for _, et := range list { - if et.Canonical != nil && *et.Canonical == *created.Canonical { - found = true - break - } - } - assert.True(t, found, "created environment type must appear in list") - - // Update - updatedName := name + " Updated" - updateBody := &models.UpdateEnvironmentType{ - Name: ptr.Ptr(updatedName), - Color: ptr.Ptr(color), - } - updated, _, err := m.UpdateEnvironmentType(config.Org, *created.Canonical, updateBody) - require.NoError(t, err, "UpdateEnvironmentType should succeed") - assert.Equal(t, updatedName, *updated.Name) -} - -func TestGetEnvironmentType_NotFound(t *testing.T) { - m := config.Middleware - - _, _, err := m.GetEnvironmentType(config.Org, "nonexistent-env-type-xyz") - assert.Error(t, err, "GetEnvironmentType should return an error for an unknown canonical") - assert.Contains(t, err.Error(), "nonexistent-env-type-xyz") -} diff --git a/cmd/cycloid/middleware/organization_environments.go b/cmd/cycloid/middleware/organization_environments.go deleted file mode 100644 index 4b35f970c..000000000 --- a/cmd/cycloid/middleware/organization_environments.go +++ /dev/null @@ -1,104 +0,0 @@ -package middleware - -import ( - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) ListOrgEnvs(org string, filters ...LHSFilter) ([]*models.Environment, *http.Response, error) { - result, resp, err := paginatedList[*models.Environment](m, Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "environments"}, - LHSFilters: filters, - }, defaultPageSize) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetOrgEnv(org, env string) (*models.Environment, *http.Response, error) { - var result *models.Environment - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "environments", env}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) CreateOrgEnv(org string, body *models.NewEnvironment) (*models.Environment, *http.Response, error) { - var result *models.Environment - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "environments"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UpdateOrgEnv(org, env string, body *models.UpdateEnvironment) (*models.Environment, *http.Response, error) { - var result *models.Environment - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "environments", env}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeleteOrgEnv(org, env string) (*http.Response, error) { - return m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "environments", env}, - }, nil) -} - -func (m *middleware) LinkEnvToProject(org, project, env string) (*http.Response, error) { - envs, _, err := m.ListProjectEnvs(org, project) - if err != nil { - return nil, err - } - for _, linked := range envs { - if linked.Canonical != nil && *linked.Canonical == env { - return nil, nil - } - } - - type linkEnvBody struct { - EnvironmentCanonical string `json:"environment_canonical"` - } - - return m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments"}, - Body: &linkEnvBody{EnvironmentCanonical: env}, - }, nil) -} - -func (m *middleware) UnlinkEnvFromProject(org, project, env string, opts DeleteOptions) (*http.Response, error) { - req := Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env}, - } - if q := opts.Resolve(); q.SkipHooks || q.IgnoreConfigFilesErr { - req.Query = q - } - return m.GenericRequest(req, nil) -} diff --git a/cmd/cycloid/middleware/organization_forms.go b/cmd/cycloid/middleware/organization_forms.go deleted file mode 100644 index c7df5fc74..000000000 --- a/cmd/cycloid/middleware/organization_forms.go +++ /dev/null @@ -1,72 +0,0 @@ -package middleware - -import ( - "errors" - "net/http" - - "gopkg.in/yaml.v3" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) ValidateForm(org string, rawForms []byte) (*models.FormsValidationResult, *http.Response, error) { - var formsfile any - - err := yaml.Unmarshal(rawForms, &formsfile) - if err != nil { - ve := &models.FormsValidationResult{ - Errors: []string{err.Error()}, - Forms: nil, - } - return ve, nil, nil - } - - body := &models.FormsValidation{ - FormFile: formsfile, - } - - var result *models.FormsValidationResult - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "forms", "validate"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// interpolateFormsConfigBody mirrors the fields needed for the forms config interpolation -type interpolateFormsConfigBody struct { - ServiceCatalogRef *string `json:"service_catalog_ref"` - ComponentCanonical *string `json:"component_canonical"` - UseCase *string `json:"use_case"` - Vars models.FormVariables `json:"vars"` -} - -func (m *middleware) InterpolateFormsConfig(org, project, env, component, serviceCatalogRef, useCase string, inputs models.FormVariables) (*models.ServiceCatalogConfig, *http.Response, error) { - if inputs == nil { - return nil, nil, errors.New("form inputs for interpolateFormsConfig must not be nil") - } - - body := interpolateFormsConfigBody{ - ServiceCatalogRef: &serviceCatalogRef, - ComponentCanonical: &component, - UseCase: &useCase, - Vars: inputs, - } - - var result *models.ServiceCatalogConfig - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "forms", "config"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/organization_forms_test.go b/cmd/cycloid/middleware/organization_forms_test.go deleted file mode 100644 index 0ac9e6a0b..000000000 --- a/cmd/cycloid/middleware/organization_forms_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func TestValidateFormYamlAnchors(t *testing.T) { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - var org = "cycloid-sandbox" - var rawForms = []byte( - `--- - shared: - - &some_anchor - key: hello - name: hello - type: string - widget: simple_text - - sections: - - name: "section" - groups: - - name: "group" - technologies: [pipeline] - vars: - - *some_anchor - `, - ) - - _, _, err := m.ValidateForm(org, rawForms) - if err != nil { - t.Errorf("Using yaml anchor should not error:\nerr: '%s'\nyaml files: '%v'", err, rawForms) - } -} diff --git a/cmd/cycloid/middleware/organization_licence.go b/cmd/cycloid/middleware/organization_licence.go deleted file mode 100644 index 5a78b3f0b..000000000 --- a/cmd/cycloid/middleware/organization_licence.go +++ /dev/null @@ -1,31 +0,0 @@ -package middleware - -import ( - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) GetLicence(org string) (*models.Licence, *http.Response, error) { - var result *models.Licence - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "licence"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) ActivateLicence(org, licence string) (*http.Response, error) { - body := map[string]string{"key": licence} - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "licence"}, - Body: body, - }, nil) - return resp, err -} diff --git a/cmd/cycloid/middleware/organization_licence_test.go b/cmd/cycloid/middleware/organization_licence_test.go deleted file mode 100644 index b6b488f5e..000000000 --- a/cmd/cycloid/middleware/organization_licence_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package middleware_test - -import ( - "os" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGetLicence(t *testing.T) { - m := config.Middleware - - licence, _, err := m.GetLicence(config.Org) - require.NoError(t, err) - require.NotNil(t, licence) - require.NotNil(t, licence.Key) - assert.NotEmpty(t, *licence.Key) -} - -func TestActivateLicenceOverwrite(t *testing.T) { - m := config.Middleware - - licenceKey, ok := os.LookupEnv("API_LICENCE_KEY") - require.True(t, ok, "API_LICENCE_KEY must be set for licence tests") - - _, err := m.ActivateLicence(config.Org, licenceKey) - require.NoError(t, err) - - got, _, err := m.GetLicence(config.Org) - require.NoError(t, err) - require.NotNil(t, got.Key) - assert.Equal(t, licenceKey, *got.Key) - - _, err = m.ActivateLicence(config.Org, licenceKey) - require.NoError(t, err) - - gotAgain, _, err := m.GetLicence(config.Org) - require.NoError(t, err) - require.NotNil(t, gotAgain.Key) - assert.Equal(t, licenceKey, *gotAgain.Key) -} diff --git a/cmd/cycloid/middleware/organization_members.go b/cmd/cycloid/middleware/organization_members.go deleted file mode 100644 index 8a8e98940..000000000 --- a/cmd/cycloid/middleware/organization_members.go +++ /dev/null @@ -1,106 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/go-openapi/strfmt" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// ListMembers lists organization members. -// -// Supported LHS filter attributes: user_canonical, user_full_name, -// invitation_state, invitation_created_at, role_name. -func (m *middleware) ListMembers(org string, filters ...LHSFilter) ([]*models.MemberOrg, *http.Response, error) { - var result []*models.MemberOrg - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "members"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) ListInvites(org string) ([]*models.MemberOrg, *http.Response, error) { - query := url.Values{"invitation_state": []string{"pending"}} - - var result []*models.MemberOrg - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "members"}, - Query: query, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetMember(org string, id uint32) (*models.MemberOrg, *http.Response, error) { - var result *models.MemberOrg - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "members", strconv.FormatUint(uint64(id), 10)}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeleteMember(org string, id uint32) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "members", strconv.FormatUint(uint64(id), 10)}, - }, nil) - return resp, err -} - -func (m *middleware) UpdateMember(org string, id uint32, role string) (*models.MemberOrg, *http.Response, error) { - body := &models.MemberAssignation{ - RoleCanonical: &role, - } - - var result *models.MemberOrg - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "members", strconv.FormatUint(uint64(id), 10)}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) InviteMember(org, email, role string) (*models.MemberOrg, *http.Response, error) { - fmtEmail := strfmt.Email(email) - body := &models.NewMemberInvitation{ - Email: &fmtEmail, - RoleCanonical: &role, - } - - var result *models.MemberOrg - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "members"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to invite member: %w", err) - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/organization_members_test.go b/cmd/cycloid/middleware/organization_members_test.go deleted file mode 100644 index 63da8fc5d..000000000 --- a/cmd/cycloid/middleware/organization_members_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestListMembers(t *testing.T) { - m := config.Middleware - - members, _, err := m.ListMembers(config.Org) - require.NoError(t, err) - assert.NotEmpty(t, members) -} - -func TestListInvites(t *testing.T) { - m := config.Middleware - - invites, _, err := m.ListInvites(config.Org) - require.NoError(t, err) - assert.NotNil(t, invites) -} - -func TestGetMember(t *testing.T) { - m := config.Middleware - - members, _, err := m.ListMembers(config.Org) - require.NoError(t, err) - require.NotEmpty(t, members) - - got, _, - err := m.GetMember(config.Org, *members[0].ID) - require.NoError(t, err) - assert.Equal(t, *members[0].ID, *got.ID) -} diff --git a/cmd/cycloid/middleware/organization_oidc.go b/cmd/cycloid/middleware/organization_oidc.go deleted file mode 100644 index b203f35b6..000000000 --- a/cmd/cycloid/middleware/organization_oidc.go +++ /dev/null @@ -1,209 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - "strconv" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// OIDCGroupMapping maps an OIDC provider group-claim value to a Cycloid team. -// One mapping is a single (group_name, team) pair; a group that grants access -// to several teams is represented as several mappings. -// -// These types live in the middleware package (not client/models) because the -// OIDC group-mapping endpoints are not part of the published swagger spec yet. -// Reuse models.Role for the team's roles since that model is already generated. -type OIDCGroupMapping struct { - ID uint32 `json:"id"` - GroupName string `json:"group_name"` - Team *OIDCGroupMappingTeam `json:"team"` - CreatedAt uint64 `json:"created_at,omitempty"` - UpdatedAt uint64 `json:"updated_at,omitempty"` -} - -// OIDCGroupMappingTeam is the team an OIDC group maps to, as returned by the API. -type OIDCGroupMappingTeam struct { - ID uint32 `json:"id"` - Canonical string `json:"canonical"` - Name string `json:"name"` - Roles []*models.Role `json:"roles"` -} - -// NewOIDCGroupMapping is the request body to create an OIDC group mapping. -type NewOIDCGroupMapping struct { - GroupName *string `json:"group_name"` - TeamCanonical *string `json:"team_canonical"` -} - -// OIDCOrganizationSettings holds the per-organization OIDC reconciliation -// settings returned by the API. -type OIDCOrganizationSettings struct { - // DefaultRoleCanonical is the org role granted to OIDC-provisioned members. - // Empty when no default role is configured. - DefaultRoleCanonical string `json:"default_role_canonical,omitempty"` - // OIDCManaged, when true, makes OIDC the source of truth for membership and - // disables local member/team/invite mutations on the org. - OIDCManaged bool `json:"oidc_managed"` - // OIDCNoMatchPolicy is the action for a member whose OIDC groups map to no - // team: "keep_membership" (default) or "eject". - OIDCNoMatchPolicy string `json:"oidc_no_match_policy"` -} - -// UpdateOIDCOrganizationSettings is the request body to upsert the per-org OIDC -// settings. oidc_no_match_policy="eject" requires oidc_managed=true (the API -// rejects the combination with HTTP 422). default_role_canonical is always sent -// (an empty string clears a previously-set default role). -type UpdateOIDCOrganizationSettings struct { - OIDCManaged bool `json:"oidc_managed"` - OIDCNoMatchPolicy string `json:"oidc_no_match_policy"` - DefaultRoleCanonical string `json:"default_role_canonical"` -} - -// ListOIDCGroupMappings returns the OIDC group->team mappings configured on the -// organization. -func (m *middleware) ListOIDCGroupMappings(org string, filters ...LHSFilter) ([]*OIDCGroupMapping, *http.Response, error) { - var result []*OIDCGroupMapping - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "oidc-group-mappings"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to list OIDC group mappings: %w", err) - } - return result, resp, nil -} - -// CreateOIDCGroupMapping creates a mapping from an OIDC group-claim value to a -// team. A group that should grant several teams needs one call per team. -func (m *middleware) CreateOIDCGroupMapping(org, groupName, teamCanonical string) (*OIDCGroupMapping, *http.Response, error) { - body := &NewOIDCGroupMapping{ - GroupName: &groupName, - TeamCanonical: &teamCanonical, - } - - var result *OIDCGroupMapping - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "oidc-group-mappings"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to create OIDC group mapping: %w", err) - } - return result, resp, nil -} - -// DeleteOIDCGroupMapping removes an OIDC group mapping by its ID. -func (m *middleware) DeleteOIDCGroupMapping(org string, id uint32) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "oidc-group-mappings", strconv.FormatUint(uint64(id), 10)}, - }, nil) - if err != nil { - return resp, fmt.Errorf("failed to delete OIDC group mapping: %w", err) - } - return resp, nil -} - -// GetOIDCOrganizationSettings returns the per-org OIDC reconciliation settings. -func (m *middleware) GetOIDCOrganizationSettings(org string) (*OIDCOrganizationSettings, *http.Response, error) { - var result *OIDCOrganizationSettings - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "oidc-organization-settings"}, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to get OIDC organization settings: %w", err) - } - return result, resp, nil -} - -// UpdateOIDCOrganizationSettings upserts the per-org OIDC reconciliation -// settings. -func (m *middleware) UpdateOIDCOrganizationSettings(org string, settings UpdateOIDCOrganizationSettings) (*OIDCOrganizationSettings, *http.Response, error) { - var result *OIDCOrganizationSettings - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "oidc-organization-settings"}, - Body: &settings, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to update OIDC organization settings: %w", err) - } - return result, resp, nil -} - -// OIDCIntegration is the AuthenticationOIDC SSO integration config as returned by -// the API. Secrets are never returned: oidc_client_secret / oidc_ca_cert are -// replaced by the read-only HasSecret / HasCaCertificate presence booleans. These -// types live in the middleware package because several fields (oidc_discovery_url, -// oidc_allow_insecure_discovery, oidc_groups_claim_name, oidc_session_ttl_seconds) -// are not in the published swagger / generated models.AuthenticationOIDC yet. -type OIDCIntegration struct { - Type string `json:"type,omitempty"` - Enabled bool `json:"enabled"` - OidcDisplayName string `json:"oidc_display_name,omitempty"` - OidcClientID string `json:"oidc_client_id,omitempty"` - OidcIssuer string `json:"oidc_issuer,omitempty"` - OidcIcon string `json:"oidc_icon,omitempty"` - OidcClientSecretJwt bool `json:"oidc_client_secret_jwt,omitempty"` - OidcUseCaCert bool `json:"oidc_use_ca_cert,omitempty"` - OidcSkipTLSVerify bool `json:"oidc_skip_tls_verify,omitempty"` - OidcDiscoveryURL *string `json:"oidc_discovery_url,omitempty"` - OidcAllowInsecureDiscovery *bool `json:"oidc_allow_insecure_discovery,omitempty"` - OidcAdoptManualMembers *bool `json:"oidc_adopt_manual_members,omitempty"` - OidcGroupsClaimName string `json:"oidc_groups_claim_name,omitempty"` - OidcSessionTTLSeconds *int64 `json:"oidc_session_ttl_seconds,omitempty"` - // Read-only presence flags — the API never returns the secret/cert values. - HasSecret *bool `json:"has_secret,omitempty"` - HasCaCertificate *bool `json:"has_ca_certificate,omitempty"` -} - -// authenticationEnvelope wraps an OIDCIntegration in the API's {"config": {...}} -// Authentication envelope used by the /authentications/{type} routes. -type authenticationEnvelope struct { - Config *OIDCIntegration `json:"config"` -} - -// GetOIDCIntegration returns the org's AuthenticationOIDC SSO integration config. -// The secret and CA cert are never included (HasSecret / HasCaCertificate report -// presence only). -func (m *middleware) GetOIDCIntegration(org string) (*OIDCIntegration, *http.Response, error) { - var result authenticationEnvelope - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "authentications", "AuthenticationOIDC"}, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to get OIDC integration: %w", err) - } - return result.Config, resp, nil -} - -// UpdateOIDCIntegration creates-or-updates the org's AuthenticationOIDC config. -// config carries the fields to apply; always include "type" ("AuthenticationOIDC") -// and "enabled". The backend MERGES: any key absent from config keeps its stored -// value, and an absent/empty oidc_client_secret or oidc_ca_cert preserves the -// stored secret. Pass only the keys you intend to change. -func (m *middleware) UpdateOIDCIntegration(org string, config map[string]interface{}) (*OIDCIntegration, *http.Response, error) { - var result authenticationEnvelope - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "authentications", "AuthenticationOIDC"}, - Body: map[string]interface{}{"config": config}, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to update OIDC integration: %w", err) - } - return result.Config, resp, nil -} diff --git a/cmd/cycloid/middleware/organization_pipelines.go b/cmd/cycloid/middleware/organization_pipelines.go deleted file mode 100644 index 4a8e9f649..000000000 --- a/cmd/cycloid/middleware/organization_pipelines.go +++ /dev/null @@ -1,37 +0,0 @@ -package middleware - -import ( - "net/http" - "net/url" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// GetOrgPipelines list all pipeline of a designated org. -func (m *middleware) GetOrgPipelines(org string, concoursePipeline, project, env *string, statuses []string) ([]*models.Pipeline, *http.Response, error) { - query := url.Values{} - if concoursePipeline != nil { - query.Set("concourse_pipeline_name", *concoursePipeline) - } - if project != nil { - query.Set("project_canonical", *project) - } - if env != nil { - query.Set("environment_canonical", *env) - } - for _, s := range statuses { - query.Add("statuses", s) - } - - var result []*models.Pipeline - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "pipelines"}, - Query: query, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/organization_pipelines_test.go b/cmd/cycloid/middleware/organization_pipelines_test.go deleted file mode 100644 index 5eae453ac..000000000 --- a/cmd/cycloid/middleware/organization_pipelines_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package middleware_test - -import ( - "fmt" - "slices" - "testing" - - "github.com/sanity-io/litter" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -var ( - pipelineTestStackCanonical = "stack-test-pipeline" - pipelineTestStackUseCase = "default" - pipelineTestDefaultVars = models.FormVariables{"section": {"group": {"var": "hello"}}} -) - -func TestGetOrgPipelines(t *testing.T) { - m := config.Middleware - - pipelineName := fmt.Sprintf("%s-%s-%s", *config.Project.Canonical, *config.Environment.Canonical, *config.Component.Canonical) - got, _, err := m.GetOrgPipelines(config.Org, &pipelineName, config.Project.Canonical, config.Environment.Canonical, []string{}) - if err != nil { - t.Errorf("middleware.GetOrgPipelines() error = %v", err) - return - } - - index := slices.IndexFunc(got, func(p *models.Pipeline) bool { - return *p.Component.Canonical == *config.Component.Canonical - }) - - if index == -1 { - t.Errorf("failed to find created component in the list: %v\nexpected component: %v", litter.Sdump(got), litter.Sdump(config.Component)) - } -} diff --git a/cmd/cycloid/middleware/organization_project_environment_test.go b/cmd/cycloid/middleware/organization_project_environment_test.go deleted file mode 100644 index febd05fad..000000000 --- a/cmd/cycloid/middleware/organization_project_environment_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package middleware_test - -import ( - "log" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -func TestEnvCrud(t *testing.T) { - m := config.Middleware - - var ( - projectName = "Test CRUD ENV" - project = testcfg.RandomCanonical("test-crud-env") - description = "Testing env" - configRepository = *config.ConfigRepo.Canonical - owner = "" - team = "" - color = "blue" - icon = "planet" - ) - - defer func() { - _, err := m.DeleteProject(config.Org, project, middleware.DeleteOptions{}) - if err != nil { - log.Fatalf("Failed to decommission project '%s' from CRUD tests: %v", project, err) - } - }() - - createdProject, _, err := m.CreateProject(config.Org, projectName, project, description, configRepository, owner, team, color, icon) - if err != nil { - t.Fatalf("Failed to create pre-requisite project: %v", err) - } - - var ( - env = testcfg.RandomCanonical("test-crud") - envName = "TestCRUD" - ) - - createBody := &models.NewEnvironment{ - Canonical: env, - Name: ptr.Ptr(envName), - Type: ptr.Ptr("production"), - } - createdEnv, _, err := m.CreateOrgEnv(config.Org, createBody) - if err != nil { - t.Fatalf("Failed to create env %q: %v", env, err) - } - - defer func() { - if createdEnv == nil { - return - } - // Org-level envs cannot be deleted while still linked to a project - // (backend returns 409). Unlink first so cleanup is best-effort even - // when the test panics mid-flight. - if _, err := m.UnlinkEnvFromProject(config.Org, *createdProject.Canonical, *createdEnv.Canonical, middleware.DeleteOptions{}); err != nil { - log.Printf("Warning: failed to unlink env %q from project %q during cleanup: %v", env, *createdProject.Canonical, err) - } - if _, err := m.DeleteOrgEnv(config.Org, *createdEnv.Canonical); err != nil { - log.Fatalf("Failed to delete org env %q: %v", env, err) - } - }() - - _, err = m.LinkEnvToProject(config.Org, *createdProject.Canonical, env) - if err != nil { - t.Fatalf("Failed to link env %q to project: %v", env, err) - } - - newEnvName := "New" - updateBody := &models.UpdateEnvironment{ - Name: ptr.Ptr(newEnvName), - Type: ptr.Ptr("production"), - } - updatedEnv, _, err := m.UpdateOrgEnv(config.Org, *createdEnv.Canonical, updateBody) - if err != nil { - t.Fatalf("Failed to update env %q: %v", env, err) - } - - assert.Equal(t, newEnvName, updatedEnv.Name) -} diff --git a/cmd/cycloid/middleware/organization_projects.go b/cmd/cycloid/middleware/organization_projects.go deleted file mode 100644 index b93115a7a..000000000 --- a/cmd/cycloid/middleware/organization_projects.go +++ /dev/null @@ -1,121 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// ListProjects lists projects for an organization. -// -// Supported LHS filter attributes: project_canonical, project_name, -// project_description, project_created_at, project_config_repository_canonical, -// environment_canonical, user_canonical. -func (m *middleware) ListProjects(org string, filters ...LHSFilter) ([]*models.Project, *http.Response, error) { - var result []*models.Project - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// ListProjectEnvs lists environments linked to a project. -// -// Supported LHS filter attributes: environment_canonical, environment_created_at. -func (m *middleware) ListProjectEnvs(org, project string, filters ...LHSFilter) ([]*models.ProjectEnvironment, *http.Response, error) { - result, resp, err := paginatedList[*models.ProjectEnvironment](m, Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments"}, - LHSFilters: filters, - }, defaultPageSize) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetProject(org, project string) (*models.Project, *http.Response, error) { - var result *models.Project - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) CreateProject(org, projectName, project, description, configRepository, owner, team, color, icon string) (*models.Project, *http.Response, error) { - projectName, project, err := NameOrCanonical(&projectName, &project) - if err != nil { - return nil, nil, err - } - - body := &models.NewProject{ - Name: &projectName, - Description: description, - Canonical: project, - ConfigRepositoryCanonical: &configRepository, - Owner: owner, - Icon: icon, - Color: color, - } - - var result *models.Project - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "projects"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to create project: %w", err) - } - return result, resp, nil -} - -func (m *middleware) UpdateProject(org, projectName, project, description, configRepository, owner, team, color, icon, cloudProvider string) (*models.Project, *http.Response, error) { - body := &models.UpdateProject{ - Name: &projectName, - Description: description, - ConfigRepositoryCanonical: configRepository, - Owner: owner, - Icon: icon, - Color: color, - CloudProvider: cloudProvider, - } - - var result *models.Project - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "projects", project}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeleteProject(org, project string, opts DeleteOptions) (*http.Response, error) { - req := Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "projects", project}, - } - if q := opts.Resolve(); q.SkipHooks || q.IgnoreConfigFilesErr { - req.Query = q - } - return m.GenericRequest(req, nil) -} diff --git a/cmd/cycloid/middleware/organization_projects_test.go b/cmd/cycloid/middleware/organization_projects_test.go deleted file mode 100644 index 2dab496c7..000000000 --- a/cmd/cycloid/middleware/organization_projects_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -func TestProjectCrud(t *testing.T) { - m := config.Middleware - - var ( - projectName = "Test CRUD Projects" - project = testcfg.RandomCanonical("test-crud-project") - description = "My cool project description !\nWith a nexline" - owner = "" - team = "" - color = "default" - icon = "world" - ) - - createProjet, _, err := m.CreateProject(config.Org, projectName, project, description, *config.ConfigRepo.Canonical, owner, team, color, icon) - if err != nil { - t.Errorf("Failed to create project '%s': %v", project, err) - } - - _, _, err = m.GetProject(config.Org, *createProjet.Canonical) - if err != nil { - t.Errorf("Did not found create project '%s' with get request: %v", *createProjet.Canonical, err) - } - - defer func() { - _, err := m.DeleteProject(config.Org, project, middleware.DeleteOptions{}) - if err != nil { - t.Errorf("Failed to delete project '%s': %v", project, err) - } - }() - - var ( - newIcon = "world" - newName = "My cool new name" - newDescription = "Updated description" - newColor = "red" - ) - - updatedProject, _, err := m.UpdateProject( - config.Org, newName, project, newDescription, *config.ConfigRepo.Canonical, - owner, team, newColor, newIcon, "aws", - ) - if err != nil { - t.Errorf("Failed to update project '%s': %v", project, err) - } - - assert.Equal(t, newName, *updatedProject.Name) - assert.Equal(t, newDescription, updatedProject.Description) - assert.Equal(t, newIcon, *updatedProject.Icon) - assert.Equal(t, newColor, *updatedProject.Color) -} diff --git a/cmd/cycloid/middleware/organization_roles.go b/cmd/cycloid/middleware/organization_roles.go deleted file mode 100644 index abc681f8e..000000000 --- a/cmd/cycloid/middleware/organization_roles.go +++ /dev/null @@ -1,106 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -// ListRoles lists roles for an organization. -// -// NOTE: the backend handler for this route does not call lhs.ParseQuery, so -// LHS filters are accepted by the middleware but silently ignored server-side. -func (m *middleware) ListRoles(org string, filters ...LHSFilter) ([]*models.Role, *http.Response, error) { - var result []*models.Role - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "roles"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetRole(org, role string) (*models.Role, *http.Response, error) { - var result *models.Role - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "roles", role}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeleteRole(org, role string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "roles", role}, - }, nil) - return resp, err -} - -// CreateRole requires org, name or canonical and rules -func (m *middleware) CreateRole(org string, name, canonical, description *string, rules []*models.NewRule) (*models.NewRole, *http.Response, error) { - n, c, err := NameOrCanonical(name, canonical) - if err != nil { - return nil, nil, err - } - - body := &models.NewRole{ - Name: &n, - Canonical: c, - Description: ptr.Value(description), - Rules: rules, - } - - var result *models.NewRole - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "roles"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// UpdateRole updates an existing role (PUT). roleCanonical must match the resolved canonical from name/--role. -func (m *middleware) UpdateRole(org, roleCanonical string, name, canonical, description *string, rules []*models.NewRule) (*models.Role, *http.Response, error) { - n, c, err := NameOrCanonical(name, canonical) - if err != nil { - return nil, nil, err - } - if c != roleCanonical { - return nil, nil, fmt.Errorf("role canonical %q must match update target %q", c, roleCanonical) - } - - body := &models.NewRole{ - Name: &n, - Canonical: c, - Description: ptr.Value(description), - Rules: rules, - } - - var result *models.Role - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "roles", roleCanonical}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/organization_roles_test.go b/cmd/cycloid/middleware/organization_roles_test.go deleted file mode 100644 index f190c4ef1..000000000 --- a/cmd/cycloid/middleware/organization_roles_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -func TestRolesCRUD(t *testing.T) { - m := config.Middleware - - canonical := testcfg.RandomCanonical("test-role") - - rule := &models.NewRule{Action: ptr.Ptr("*"), Effect: ptr.Ptr(models.NewRuleEffectAllow)} - created, _, err := m.CreateRole(config.Org, ptr.Ptr("Test Role"), ptr.Ptr(canonical), ptr.Ptr("test role description"), []*models.NewRule{rule}) - require.NoError(t, err, "CreateRole should succeed") - require.NotNil(t, created) - - defer func() { - _, err := m.DeleteRole(config.Org, canonical) - require.NoError(t, err, "DeleteRole should succeed") - }() - - got, _, err := m.GetRole(config.Org, canonical) - require.NoError(t, err, "GetRole should succeed") - assert.Equal(t, canonical, *got.Canonical) - - updated, _, err := m.UpdateRole(config.Org, canonical, ptr.Ptr("Updated Role Name"), ptr.Ptr(canonical), ptr.Ptr("updated description"), []*models.NewRule{rule}) - require.NoError(t, err, "UpdateRole should succeed") - require.NotNil(t, updated) - assert.Equal(t, "Updated Role Name", *updated.Name) - assert.Equal(t, "updated description", *updated.Description) - - got, _, err = m.GetRole(config.Org, canonical) - require.NoError(t, err) - assert.Equal(t, "Updated Role Name", *got.Name) - - list, _, err := m.ListRoles(config.Org) - require.NoError(t, err, "ListRoles should succeed") - assert.NotEmpty(t, list) -} diff --git a/cmd/cycloid/middleware/organization_subscriptions.go b/cmd/cycloid/middleware/organization_subscriptions.go deleted file mode 100644 index 9dca5ac8c..000000000 --- a/cmd/cycloid/middleware/organization_subscriptions.go +++ /dev/null @@ -1,51 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - "time" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -type SubscriptionPlan = string - -const ( - FreeTrial = "free_trial" - PlatformTeam = "platform_teams" -) - -var ( - AvailableSubscriptionPlans = []string{ - FreeTrial, - PlatformTeam, - } -) - -type SubscriptionRequest struct { - ExpiresAt string `json:"expires_at"` - MembersCount uint64 `json:"members_count"` - Overwrite bool `json:"overwrite"` - PlanCanonical string `json:"plan_canonical"` -} - -func (m *middleware) CreateOrUpdateSubscription(org string, plan SubscriptionPlan, expiresAt time.Time, membersCount uint64, overwrite bool) (*models.Subscription, *http.Response, error) { - body := SubscriptionRequest{ - ExpiresAt: expiresAt.Format(time.RFC3339), - MembersCount: membersCount, - Overwrite: overwrite, - PlanCanonical: plan, - } - - var result *models.Subscription - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "subscriptions"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to update subscription: %w", err) - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/organization_team_members.go b/cmd/cycloid/middleware/organization_team_members.go deleted file mode 100644 index 6fd229a1e..000000000 --- a/cmd/cycloid/middleware/organization_team_members.go +++ /dev/null @@ -1,76 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - "strconv" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// ListTeamMembers lists members of a team. -// -// NOTE: the backend handler for this route does not call lhs.ParseQuery, so -// LHS filters are accepted by the middleware but silently ignored server-side. -func (m *middleware) ListTeamMembers(org string, team string, filters ...LHSFilter) ([]*models.MemberTeam, *http.Response, error) { - var result []*models.MemberTeam - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "teams", team, "members"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetTeamMember(org string, team string, memberID uint32) (*models.MemberTeam, *http.Response, error) { - var result *models.MemberTeam - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "teams", team, "members", strconv.FormatUint(uint64(memberID), 10)}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// AssignMemberToTeam will assign a organization member to a team using either username or email -// one of them is required -func (m *middleware) AssignMemberToTeam(org, team string, username, email *string) (*models.MemberTeam, *http.Response, error) { - if username == nil && email == nil { - return nil, nil, fmt.Errorf("missing email or username for AssignMemberToTeam") - } - - body := map[string]string{} - if username != nil { - body["username"] = *username - } else { - body["email"] = *email - } - - var result *models.MemberTeam - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "teams", team, "members"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UnAssignMemberFromTeam(org, team string, memberID uint32) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "teams", team, "members", strconv.FormatUint(uint64(memberID), 10)}, - }, nil) - return resp, err -} diff --git a/cmd/cycloid/middleware/organization_team_members_test.go b/cmd/cycloid/middleware/organization_team_members_test.go deleted file mode 100644 index 17c156950..000000000 --- a/cmd/cycloid/middleware/organization_team_members_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -func TestTeamMembersCRUD(t *testing.T) { - m := config.Middleware - - canonical := testcfg.RandomCanonical("test-team-members") - - _, _, err := m.CreateTeam(config.Org, ptr.Ptr("Test Team Members"), ptr.Ptr(canonical), nil, []string{}) - require.NoError(t, err, "CreateTeam should succeed") - - defer func() { - _, err := m.DeleteTeam(config.Org, canonical) - require.NoError(t, err, "DeleteTeam cleanup should succeed") - }() - - members, _, err := m.ListTeamMembers(config.Org, canonical) - require.NoError(t, err, "ListTeamMembers should succeed on empty team") - assert.NotNil(t, members) - - assigned, _, err := m.AssignMemberToTeam(config.Org, canonical, ptr.Ptr("administrator"), nil) - require.NoError(t, err, "AssignMemberToTeam should succeed") - require.NotNil(t, assigned) - - got, _, err := m.GetTeamMember(config.Org, canonical, *assigned.ID) - require.NoError(t, err, "GetTeamMember should succeed") - assert.Equal(t, *assigned.ID, *got.ID) - - _, err = m.UnAssignMemberFromTeam(config.Org, canonical, *assigned.ID) - require.NoError(t, err, "UnAssignMemberFromTeam should succeed") -} diff --git a/cmd/cycloid/middleware/organization_teams.go b/cmd/cycloid/middleware/organization_teams.go deleted file mode 100644 index 63aad7165..000000000 --- a/cmd/cycloid/middleware/organization_teams.go +++ /dev/null @@ -1,129 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -type TeamOrderByParam string - -var ( - Ascending TeamOrderByParam = "asc" - Descending TeamOrderByParam = "desc" -) - -// ListTeams lists teams for an organization. -// -// Supported LHS filter attributes: team_canonical, team_name, team_description, team_created_at. -func (m *middleware) ListTeams(org string, teamNameFilter *string, createdAtFilter *uint64, memberIDFilter *uint32, orderBy *TeamOrderByParam, filters ...LHSFilter) ([]*models.Team, *http.Response, error) { - query := url.Values{} - if teamNameFilter != nil { - query.Set("team_name", *teamNameFilter) - } - if createdAtFilter != nil { - query.Set("team_created_at", strconv.FormatUint(*createdAtFilter, 10)) - } - if memberIDFilter != nil { - query.Set("member_id", strconv.FormatUint(uint64(*memberIDFilter), 10)) - } - if orderBy != nil { - query.Set("order_by", string(*orderBy)) - } - - var result []*models.Team - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "teams"}, - Query: query, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetTeam(org, team string) (*models.Team, *http.Response, error) { - var result *models.Team - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "teams", team}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) CreateTeam(org string, name, team, owner *string, roles []string) (*models.Team, *http.Response, error) { - teamName, canonical, err := NameOrCanonical(name, team) - if err != nil { - return nil, nil, err - } - - body := &models.NewTeam{ - Name: &teamName, - Canonical: canonical, - RolesCanonical: roles, - } - - if owner != nil { - body.Owner = *owner - } - - var result *models.Team - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "teams"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to create team: %w", err) - } - return result, resp, nil -} - -func (m *middleware) UpdateTeam(org string, name, team, owner *string, roles []string) (*models.Team, *http.Response, error) { - teamName, canonical, err := NameOrCanonical(name, team) - if err != nil { - return nil, nil, err - } - - body := &models.UpdateTeam{ - Name: &teamName, - Canonical: &canonical, - RolesCanonical: roles, - } - - if owner != nil { - body.Owner = *owner - } - - var result *models.Team - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "teams", canonical}, - Body: body, - }, &result) - if err != nil { - return nil, resp, fmt.Errorf("failed to update team: %w", err) - } - return result, resp, nil -} - -func (m *middleware) DeleteTeam(org, team string) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "teams", team}, - }, nil) - return resp, err -} diff --git a/cmd/cycloid/middleware/organization_teams_test.go b/cmd/cycloid/middleware/organization_teams_test.go deleted file mode 100644 index 11e20928c..000000000 --- a/cmd/cycloid/middleware/organization_teams_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -func TestTeamsCRUD(t *testing.T) { - m := config.Middleware - - canonical := testcfg.RandomCanonical("test-team") - - created, _, err := m.CreateTeam(config.Org, ptr.Ptr("Test Team"), ptr.Ptr(canonical), nil, []string{}) - require.NoError(t, err, "CreateTeam should succeed") - require.NotNil(t, created) - - defer func() { - _, err := m.DeleteTeam(config.Org, canonical) - require.NoError(t, err, "DeleteTeam should succeed") - }() - - got, _, err := m.GetTeam(config.Org, canonical) - require.NoError(t, err, "GetTeam should succeed") - assert.Equal(t, canonical, *got.Canonical) - - list, _, err := m.ListTeams(config.Org, nil, nil, nil, nil) - require.NoError(t, err, "ListTeams should succeed") - assert.NotEmpty(t, list) - - newName := ptr.Ptr("Updated Team Name") - updated, _, err := m.UpdateTeam(config.Org, newName, ptr.Ptr(canonical), nil, []string{}) - require.NoError(t, err, "UpdateTeam should succeed") - assert.Equal(t, *newName, *updated.Name) - -} diff --git a/cmd/cycloid/middleware/organization_test.go b/cmd/cycloid/middleware/organization_test.go deleted file mode 100644 index 777044c22..000000000 --- a/cmd/cycloid/middleware/organization_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package middleware_test - -import ( - "log" - "testing" -) - -// We need to ensure the Child org CRUD works before kicking off tests. -func TestChildOrgCrud(t *testing.T) { - // config, err := testcfg.NewConfig() - // defer config.Cleanup() - // if err != nil { - // t.Errorf("Config setup failed: %v", err) - // } - m := config.Middleware - - var childOrg = "test-create-child-org" - defer func() { - _, err := m.DeleteOrganization(childOrg) - if err != nil { - log.Fatalf("Failed to delete org '%s': %v", childOrg, err) - return - } - }() - - _, _, err := m.CreateOrganizationChild(config.Org, childOrg, nil) - if err != nil { - t.Errorf("Failed to create org '%s': %v", childOrg, err) - return - } - - var newName = "test-update-child-org" - newOrg, _, err := m.UpdateOrganization(childOrg, newName) - if err != nil { - t.Errorf("Failed to update org '%s': %v", childOrg, err) - } - - if *newOrg.Name != newName { - t.Errorf("Update org failed.\nExpected: %s | Got: %s", newName, *newOrg.Name) - } - - _, _, err = m.GetOrganization(childOrg) - if err != nil { - t.Errorf("Org '%s' is not created: %v", childOrg, err) - return - } -} diff --git a/cmd/cycloid/middleware/pagination.go b/cmd/cycloid/middleware/pagination.go deleted file mode 100644 index ed65b065f..000000000 --- a/cmd/cycloid/middleware/pagination.go +++ /dev/null @@ -1,72 +0,0 @@ -package middleware - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -const defaultPageSize = 100 -const maxPages = 1_000 - -type paginatedListResponse[T any] struct { - Data []T `json:"data"` - Pagination *models.Pagination `json:"pagination"` -} - -// paginatedList fetches all pages for a paginated list endpoint. -func paginatedList[T any](m *middleware, req Request, pageSize int) ([]T, *http.Response, error) { - if pageSize <= 0 { - pageSize = defaultPageSize - } - - var ( - all []T - lastResp *http.Response - ) - - for page := 1; page <= maxPages; page++ { - query := url.Values{} - if req.Query != nil { - encoded, err := encodeQuery(req.Query) - if err != nil { - return nil, lastResp, err - } - query = encoded - } - query.Set("page_index", strconv.Itoa(page)) - query.Set("page_size", strconv.Itoa(pageSize)) - - pageReq := req - pageReq.Query = query - - resp, body, err := m.genericRequestRaw(pageReq) - lastResp = resp - if err != nil { - return nil, resp, err - } - - var pageResult paginatedListResponse[T] - if err := json.Unmarshal(body, &pageResult); err != nil { - return nil, resp, fmt.Errorf("failed to decode paginated JSON response: %w", err) - } - - all = append(all, pageResult.Data...) - - if len(pageResult.Data) == 0 { - break - } - if pageResult.Pagination == nil || pageResult.Pagination.Total == nil { - break - } - if uint64(len(all)) >= *pageResult.Pagination.Total { - break - } - } - - return all, lastResp, nil -} diff --git a/cmd/cycloid/middleware/plugins.go b/cmd/cycloid/middleware/plugins.go deleted file mode 100644 index eb99171a8..000000000 --- a/cmd/cycloid/middleware/plugins.go +++ /dev/null @@ -1,492 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - - "github.com/go-openapi/strfmt" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func registryPluginsRoute(org string, registryID uint32, extra ...string) []string { - base := []string{"organizations", org, "plugin_registries", fmt.Sprint(registryID), "plugins"} - return append(base, extra...) -} - -// --- Plugin Managers --- - -func (m *middleware) ListPluginManagers(org string) ([]*models.PluginManager, *http.Response, error) { - var result []*models.PluginManager - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "plugin_managers"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetPluginManager(org string, id uint32) (*models.PluginManager, *http.Response, error) { - var result *models.PluginManager - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "plugin_managers", fmt.Sprint(id)}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) CreatePluginManager(org, name, url string, autoRegister bool) (*models.PluginManager, *http.Response, error) { - u := strfmt.URI(url) - body := &models.NewPluginManager{ - AutoRegister: autoRegister, - Name: &name, - URL: &u, - } - var result *models.PluginManager - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "plugin_managers"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UpdatePluginManager(org string, id uint32, inviteStatus string) (*models.PluginManager, *http.Response, error) { - body := &models.UpdatePluginManager{ - InviteStatus: &inviteStatus, - } - var result *models.PluginManager - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "plugin_managers", fmt.Sprint(id)}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeletePluginManager(org string, id uint32) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "plugin_managers", fmt.Sprint(id)}, - }, nil) - return resp, err -} - -// --- Plugin Installs --- - -func (m *middleware) ListPlugins(org string) ([]*models.Plugin, *http.Response, error) { - var result []*models.Plugin - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "plugins"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetPlugin(org string, id uint32) (*models.PluginInstall, *http.Response, error) { - var result *models.PluginInstall - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "plugins", fmt.Sprint(id)}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UpdatePlugin(org string, id, versionID uint32, config map[string]string) (*models.PluginInstall, *http.Response, error) { - body := &models.UpdatePluginInstall{ - Configuration: config, - PluginVersionID: &versionID, - } - var result *models.PluginInstall - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "plugins", fmt.Sprint(id)}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeletePlugin(org string, id uint32) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "plugins", fmt.Sprint(id)}, - }, nil) - return resp, err -} - -func (m *middleware) ListPluginLogs(org string, id uint32) (*models.PluginLogs, *http.Response, error) { - var result *models.PluginLogs - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "plugins", fmt.Sprint(id), "logs"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// --- Plugin Registries --- - -func (m *middleware) ListPluginRegistries(org string) ([]*models.PluginRegistry, *http.Response, error) { - var result []*models.PluginRegistry - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "plugin_registries"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// GetPluginRegistry retrieves a single plugin registry by ID. -// The API has no GET-by-ID endpoint for registries, so this lists all and filters. -func (m *middleware) GetPluginRegistry(org string, id uint32) (*models.PluginRegistry, *http.Response, error) { - regs, resp, err := m.ListPluginRegistries(org) - if err != nil { - return nil, resp, err - } - for _, r := range regs { - if r.ID != nil && *r.ID == id { - return r, resp, nil - } - } - return nil, resp, fmt.Errorf("plugin registry %d not found", id) -} - -func (m *middleware) CreatePluginRegistry(org, name, url string) (*models.PluginRegistry, *http.Response, error) { - u := strfmt.URI(url) - body := &models.NewPluginRegistry{ - Name: &name, - URL: &u, - } - var result *models.PluginRegistry - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "plugin_registries"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UpdatePluginRegistry(org string, id uint32, name string) (*models.PluginRegistry, *http.Response, error) { - body := &models.UpdatePluginRegistry{Name: &name} - var result *models.PluginRegistry - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "plugin_registries", fmt.Sprint(id)}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeletePluginRegistry(org string, id uint32) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: []string{"organizations", org, "plugin_registries", fmt.Sprint(id)}, - }, nil) - return resp, err -} - -// --- Registry Plugins --- - -// ListRegistryPlugins lists plugins belonging to a specific registry. -// The API has no GET /plugin_registries/{id}/plugins endpoint (only POST for create), -// so we list all plugins and filter by registry ID. -func (m *middleware) ListRegistryPlugins(org string, registryID uint32) ([]*models.Plugin, *http.Response, error) { - all, resp, err := m.ListPlugins(org) - if err != nil { - return nil, resp, err - } - var result []*models.Plugin - for _, p := range all { - if p.Registry != nil && p.Registry.ID != nil && *p.Registry.ID == registryID { - result = append(result, p) - } - } - return result, resp, nil -} - -func (m *middleware) GetRegistryPlugin(org string, registryID, pluginID uint32) (*models.Plugin, *http.Response, error) { - var result *models.Plugin - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: registryPluginsRoute(org, registryID, fmt.Sprint(pluginID)), - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) CreateRegistryPlugin(org string, registryID uint32, name string) (*models.Plugin, *http.Response, error) { - body := &models.NewPlugin{Name: &name} - var result *models.Plugin - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: registryPluginsRoute(org, registryID), - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UpdateRegistryPlugin(org string, registryID, pluginID uint32, name string) (*models.Plugin, *http.Response, error) { - body := &models.UpdatePlugin{Name: &name} - var result *models.Plugin - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: registryPluginsRoute(org, registryID, fmt.Sprint(pluginID)), - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeleteRegistryPlugin(org string, registryID, pluginID uint32) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: registryPluginsRoute(org, registryID, fmt.Sprint(pluginID)), - }, nil) - return resp, err -} - -// --- Registry Plugin Versions --- - -func versionsRoute(org string, registryID, pluginID uint32, extra ...string) []string { - base := registryPluginsRoute(org, registryID, fmt.Sprint(pluginID), "versions") - return append(base, extra...) -} - -func (m *middleware) ListPluginVersions(org string, registryID, pluginID uint32) ([]*models.PluginVersion, *http.Response, error) { - var result []*models.PluginVersion - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: versionsRoute(org, registryID, pluginID), - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) GetPluginVersion(org string, registryID, pluginID, versionID uint32) (*models.PluginVersion, *http.Response, error) { - var result *models.PluginVersion - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: versionsRoute(org, registryID, pluginID, fmt.Sprint(versionID)), - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) CreatePluginVersion(org string, registryID, pluginID uint32, url string) (*models.PluginVersion, *http.Response, error) { - // Use a plain struct instead of models.NewPluginVersion to avoid strfmt.URI - // coercion, which rejects Docker image references (scheme-less URIs). - body := struct { - URL string `json:"url"` - }{URL: url} - var result *models.PluginVersion - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: versionsRoute(org, registryID, pluginID), - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) DeletePluginVersion(org string, registryID, pluginID, versionID uint32) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "DELETE", - Organization: &org, - Route: versionsRoute(org, registryID, pluginID, fmt.Sprint(versionID)), - }, nil) - return resp, err -} - -func (m *middleware) InstallPluginVersion(org string, registryID, pluginID, versionID uint32, configuration map[string]string) (*http.Response, error) { - if configuration == nil { - configuration = map[string]string{} - } - body := &models.NewPluginInstall{Configuration: configuration} - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: versionsRoute(org, registryID, pluginID, fmt.Sprint(versionID), "install"), - Body: body, - }, nil) - return resp, err -} - -func (m *middleware) RetryPluginVersion(org string, registryID, pluginID, versionID uint32) (*http.Response, error) { - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: versionsRoute(org, registryID, pluginID, fmt.Sprint(versionID), "retry"), - }, nil) - return resp, err -} - -func (m *middleware) ListPluginVersionLogs(org string, registryID, pluginID, versionID uint32) ([]*models.PluginVersionLog, *http.Response, error) { - var result []*models.PluginVersionLog - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: versionsRoute(org, registryID, pluginID, fmt.Sprint(versionID), "logs"), - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// --- Component Plugins --- - -func (m *middleware) ListComponentPlugins(org, project, env, component string) ([]*models.Plugin, *http.Response, error) { - var result []*models.Plugin - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "plugins"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) SetComponentPluginRelation(org, project, env, component string, pluginInstallID uint32, enabled bool) (*models.PluginRelation, *http.Response, error) { - body := &models.PluginRelation{ - Enabled: &enabled, - Relations: map[string]any{}, - } - var result *models.PluginRelation - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "plugins", fmt.Sprint(pluginInstallID), "relation"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// --- Plugin Widgets (org) --- - -type listPluginWidgetsQuery struct { - Placement string `url:"placement"` -} - -func (m *middleware) ListPluginWidgets(org, placement string) ([]*models.PluginWidget, *http.Response, error) { - var result []*models.PluginWidget - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "plugin_widgets"}, - Query: listPluginWidgetsQuery{Placement: placement}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) QueryPluginWidget(org string, widgetID uint32) (*models.PluginWidgetData, *http.Response, error) { - var result *models.PluginWidgetData - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "plugin_widgets", fmt.Sprint(widgetID), "query"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// --- Plugin Widgets (component) --- - -func (m *middleware) ListComponentPluginWidgets(org, project, env, component string) ([]*models.PluginWidget, *http.Response, error) { - var result []*models.PluginWidget - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "plugin_widgets"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) QueryComponentPluginWidget(org, project, env, component string, widgetID uint32) (*models.PluginWidgetData, *http.Response, error) { - var result *models.PluginWidgetData - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "environments", env, "components", component, "plugin_widgets", fmt.Sprint(widgetID), "query"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/plugins_test.go b/cmd/cycloid/middleware/plugins_test.go deleted file mode 100644 index 5fc443611..000000000 --- a/cmd/cycloid/middleware/plugins_test.go +++ /dev/null @@ -1,317 +0,0 @@ -package middleware_test - -import ( - "fmt" - "math/rand" - "net/http" - "os" - "os/exec" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -// pluginsMiddlewareEnabled reports whether the plugin middleware tests should run. -func pluginsMiddlewareEnabled() bool { - return os.Getenv("CY_TEST_E2E_PLUGINS") == "1" -} - -// uniquePluginImage generates a unique semver-tagged plugin image URL for use with -// CreatePluginVersion. The plugin-registry enforces a global unique constraint on -// version URLs, so each version creation requires a different docker image tag. -func uniquePluginImage(t *testing.T) string { - t.Helper() - tag := fmt.Sprintf("1.0.%d", rand.Intn(999999)) - local := fmt.Sprintf("localhost:5000/plugin-hello-world:%s", tag) - api := fmt.Sprintf("docker-registry:5000/plugin-hello-world:%s", tag) - - run := func(name string, args ...string) { - t.Helper() - cmd := exec.Command(name, args...) - if err := cmd.Run(); err != nil { - t.Fatalf("uniquePluginImage: %q %v failed: %v", name, args, err) - } - } - run("docker", "tag", "cycloid/plugin-hello-world:latest", local) - run("docker", "push", local) - return api -} - -func TestPluginManagersCRUD(t *testing.T) { - if !pluginsMiddlewareEnabled() { - t.Skip("set CY_TEST_E2E_PLUGINS=1 to run plugin middleware tests") - } - - m := config.Middleware - org := config.Org - - t.Run("List", func(t *testing.T) { - managers, resp, err := m.ListPluginManagers(org) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.NotNil(t, managers) - }) - - t.Run("AcceptTestPluginManager", func(t *testing.T) { - mgr, err := config.AcceptPluginManager(t) - require.NoError(t, err) - require.NotNil(t, mgr) - // API returns "invite_accepted" once accepted (not "accepted"). - assert.Contains(t, []string{"accepted", "invite_accepted"}, *mgr.InviteStatus) - }) -} - -func TestPluginRegistryCRUD(t *testing.T) { - if !pluginsMiddlewareEnabled() { - t.Skip("set CY_TEST_E2E_PLUGINS=1 to run plugin middleware tests") - } - - m := config.Middleware - org := config.Org - name := testcfg.RandomCanonical("mw-registry") - regURL := "http://plugin-registry:4000" - - reg, _, err := m.CreatePluginRegistry(org, name, regURL) - require.NoError(t, err) - require.NotNil(t, reg) - assert.Equal(t, name, *reg.Name) - - defer func() { - if _, delErr := m.DeletePluginRegistry(org, *reg.ID); delErr != nil { - t.Logf("cleanup: delete registry %d: %v", *reg.ID, delErr) - } - }() - - t.Run("Get", func(t *testing.T) { - got, resp, err := m.GetPluginRegistry(org, *reg.ID) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.Equal(t, name, *got.Name) - }) - - t.Run("List", func(t *testing.T) { - regs, resp, err := m.ListPluginRegistries(org) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - var found bool - for _, r := range regs { - if *r.ID == *reg.ID { - found = true - break - } - } - assert.True(t, found, "created registry not found in list") - }) - - t.Run("Update", func(t *testing.T) { - newName := name + "-upd" - updated, resp, err := m.UpdatePluginRegistry(org, *reg.ID, newName) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.Equal(t, newName, *updated.Name) - }) -} - -func TestRegistryPluginCRUD(t *testing.T) { - if !pluginsMiddlewareEnabled() { - t.Skip("set CY_TEST_E2E_PLUGINS=1 to run plugin middleware tests") - } - - m := config.Middleware - org := config.Org - - reg, err := config.NewTestPluginRegistry(t, testcfg.RandomCanonical("mw-reg-pl"), "http://plugin-registry:4000") - require.NoError(t, err) - - pluginName := testcfg.RandomCanonical("mw-plugin") - plugin, _, err := m.CreateRegistryPlugin(org, *reg.ID, pluginName) - require.NoError(t, err) - require.NotNil(t, plugin) - - defer func() { - if _, delErr := m.DeleteRegistryPlugin(org, *reg.ID, *plugin.ID); delErr != nil { - t.Logf("cleanup: delete plugin %d: %v", *plugin.ID, delErr) - } - }() - - t.Run("Get", func(t *testing.T) { - got, resp, err := m.GetRegistryPlugin(org, *reg.ID, *plugin.ID) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.Equal(t, pluginName, *got.Name) - }) - - t.Run("List", func(t *testing.T) { - plugins, resp, err := m.ListRegistryPlugins(org, *reg.ID) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - var found bool - for _, p := range plugins { - if *p.ID == *plugin.ID { - found = true - break - } - } - assert.True(t, found, "created plugin not found in list") - }) - - t.Run("Update", func(t *testing.T) { - newName := pluginName + "-upd" - updated, resp, err := m.UpdateRegistryPlugin(org, *reg.ID, *plugin.ID, newName) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.Equal(t, newName, *updated.Name) - }) -} - -func TestPluginVersionCRUD(t *testing.T) { - if !pluginsMiddlewareEnabled() { - t.Skip("set CY_TEST_E2E_PLUGINS=1 to run plugin middleware tests") - } - - m := config.Middleware - org := config.Org - - reg, err := config.NewTestPluginRegistry(t, testcfg.RandomCanonical("mw-reg-ver"), "http://plugin-registry:4000") - require.NoError(t, err) - - plugin, err := config.NewTestPluginInRegistry(t, *reg.ID, testcfg.RandomCanonical("mw-plver")) - require.NoError(t, err) - - ver, _, err := m.CreatePluginVersion(org, *reg.ID, *plugin.ID, uniquePluginImage(t)) - require.NoError(t, err) - require.NotNil(t, ver) - - defer func() { - if _, delErr := m.DeletePluginVersion(org, *reg.ID, *plugin.ID, *ver.ID); delErr != nil { - t.Logf("cleanup: delete version %d: %v", *ver.ID, delErr) - } - }() - - t.Run("Get", func(t *testing.T) { - got, resp, err := m.GetPluginVersion(org, *reg.ID, *plugin.ID, *ver.ID) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.Equal(t, *ver.ID, *got.ID) - }) - - t.Run("List", func(t *testing.T) { - versions, resp, err := m.ListPluginVersions(org, *reg.ID, *plugin.ID) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.NotEmpty(t, versions) - }) - - t.Run("ListLogs", func(t *testing.T) { - logs, resp, err := m.ListPluginVersionLogs(org, *reg.ID, *plugin.ID, *ver.ID) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.NotNil(t, logs) - }) -} - -func TestPluginInstallAndGet(t *testing.T) { - if !pluginsMiddlewareEnabled() { - t.Skip("set CY_TEST_E2E_PLUGINS=1 to run plugin middleware tests") - } - - m := config.Middleware - org := config.Org - - _, err := config.AcceptPluginManager(t) - require.NoError(t, err) - - reg, err := config.NewTestPluginRegistry(t, testcfg.RandomCanonical("mw-reg-ins"), "http://plugin-registry:4000") - require.NoError(t, err) - - plugin, err := config.NewTestPluginInRegistry(t, *reg.ID, testcfg.RandomCanonical("mw-plinst")) - require.NoError(t, err) - - ver, err := config.NewTestPluginVersion(t, *reg.ID, *plugin.ID, uniquePluginImage(t)) - require.NoError(t, err) - - // Install returns 200 with PluginInstall body (swagger: "200 The Plugin Install data"). - resp, err := m.InstallPluginVersion(org, *reg.ID, *plugin.ID, *ver.ID, nil) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - - // Resolve install ID from list — allow a moment for the record to appear. - var installID uint32 - for i := 0; i < 10; i++ { - plugins, _, _ := m.ListPlugins(org) - for _, p := range plugins { - if p.Name != nil && *p.Name == *plugin.Name && p.Install != nil { - installID = *p.Install.ID - } - } - if installID != 0 { - break - } - time.Sleep(2 * time.Second) - } - require.NotZero(t, installID, "install record not found in ListPlugins") - - t.Cleanup(func() { - if _, delErr := m.DeletePlugin(org, installID); delErr != nil { - t.Logf("cleanup: delete plugin install %d: %v", installID, delErr) - } - }) - - t.Run("GetInstall", func(t *testing.T) { - install, resp, err := m.GetPlugin(org, installID) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - require.NotNil(t, install) - // The plugin-manager deploys asynchronously; status may be pending/running. - assert.NotNil(t, install.ID) - }) - - t.Run("ListInstalls", func(t *testing.T) { - plugins, resp, err := m.ListPlugins(org) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - var found bool - for _, p := range plugins { - if p.Install != nil && *p.Install.ID == installID { - found = true - break - } - } - assert.True(t, found, "install %d not found in ListPlugins", installID) - }) - - t.Run("RetryIdempotent", func(t *testing.T) { - // Second install should return 409 Conflict; retry endpoint returns 204. - retryResp, err := m.InstallPluginVersion(org, *reg.ID, *plugin.ID, *ver.ID, nil) - if err == nil { - // First install on a freshly reset DB — no conflict yet. - assert.Contains(t, []int{http.StatusOK, http.StatusAccepted}, retryResp.StatusCode) - return - } - if retryResp != nil && retryResp.StatusCode == http.StatusConflict { - retryResp2, retryErr := m.RetryPluginVersion(org, *reg.ID, *plugin.ID, *ver.ID) - require.NoError(t, retryErr) - assert.Equal(t, http.StatusNoContent, retryResp2.StatusCode) - return - } - t.Fatalf("unexpected error on second install: %v", err) - }) - - t.Run("Logs", func(t *testing.T) { - logs, resp, err := m.ListPluginLogs(org, installID) - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.NotNil(t, logs) - }) - - t.Run("ListWidgets", func(t *testing.T) { - widgets, resp, err := m.ListPluginWidgets(org, "sideMenuPage") - require.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.NotNil(t, widgets) - }) -} diff --git a/cmd/cycloid/middleware/project_kpi.go b/cmd/cycloid/middleware/project_kpi.go deleted file mode 100644 index d059e0983..000000000 --- a/cmd/cycloid/middleware/project_kpi.go +++ /dev/null @@ -1,98 +0,0 @@ -package middleware - -// import ( -// "encoding/json" -// -// strfmt "github.com/go-openapi/strfmt" -// -// "github.com/cycloidio/cycloid-cli/client/client/organization_kpis" -// "github.com/cycloidio/cycloid-cli/client/models" -// "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" -// ) -// -// func (m *middleware) CreateKpi(name, kpiType, widget, org, project, job, env, config string) (*models.KPI, error) { -// var body *models.NewKPI -// var err error -// -// params := organization_kpis.NewCreateKpiParams() -// params.SetOrganizationCanonical(org) -// pipeline := "" -// if project != "" { -// params.WithProjectCanonical(&project) -// } -// if env != "" { -// params.WithEnvironmentCanonical(&env) -// } -// -// if project != "" && env != "" { -// pipeline = common.GetPipelineName(project, env) -// } -// -// var uConfig interface{} -// if config != "" { -// err = json.Unmarshal([]byte(config), &uConfig) -// if err != nil { -// return nil, err -// } -// } -// -// body = &models.NewKPI{ -// EnvironmentCanonical: env, -// Config: uConfig, -// JobName: job, -// Name: &name, -// PipelineName: pipeline, -// ProjectCanonical: project, -// Type: &kpiType, -// Widget: &widget, -// } -// -// err = body.Validate(strfmt.Default) -// if err != nil { -// return nil, err -// } -// -// params.SetBody(body) -// resp, err := m.api.OrganizationKpis.CreateKpi(params, m.api.Credentials(&org)) -// if err != nil { -// return nil, NewAPIError(err) -// } -// -// p := resp.GetPayload() -// -// d := p.Data -// return d, nil -// } -// -// func (m *middleware) ListKpi(org, project, env string) ([]*models.KPI, error) { -// params := organization_kpis.NewGetKpisParams() -// params.SetOrganizationCanonical(org) -// if project != "" { -// params.WithProjectCanonical(&project) -// } -// if env != "" { -// params.WithEnvironmentCanonical(&env) -// } -// -// resp, err := m.api.OrganizationKpis.GetKpis(params, m.api.Credentials(&org)) -// if err != nil { -// return nil, NewAPIError(err) -// } -// -// p := resp.GetPayload() -// -// d := p.Data -// return d, nil -// } -// -// func (m *middleware) DeleteKpi(org, kpi string) error { -// params := organization_kpis.NewDeleteKpiParams() -// params.SetOrganizationCanonical(org) -// params.SetKpiCanonical(kpi) -// -// _, err := m.api.OrganizationKpis.DeleteKpi(params, m.api.Credentials(&org)) -// if err != nil { -// return NewAPIError(err) -// } -// return nil -// } diff --git a/cmd/cycloid/middleware/project_pipelines.go b/cmd/cycloid/middleware/project_pipelines.go deleted file mode 100644 index 57c4bf83b..000000000 --- a/cmd/cycloid/middleware/project_pipelines.go +++ /dev/null @@ -1,21 +0,0 @@ -package middleware - -import ( - "net/http" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// GetProjectPipelines lists all pipelines of a designated project. -func (m *middleware) GetProjectPipelines(org, project string) ([]*models.Pipeline, *http.Response, error) { - var result []*models.Pipeline - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project, "pipelines"}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/project_pipelines_test.go b/cmd/cycloid/middleware/project_pipelines_test.go deleted file mode 100644 index f6b9a667b..000000000 --- a/cmd/cycloid/middleware/project_pipelines_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package middleware_test - -import ( - "slices" - "testing" - - "github.com/sanity-io/litter" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func TestGetProjectPipelines(t *testing.T) { - m := config.Middleware - - got, _, err := m.GetProjectPipelines(config.Org, *config.Project.Canonical) - if err != nil { - t.Errorf("middleware.GetProjectPipelines() error = %v", err) - return - } - - index := slices.IndexFunc(got, func(p *models.Pipeline) bool { - return *p.Component.Canonical == *config.Component.Canonical - }) - - if index == -1 { - t.Errorf("failed to find created component in the list: %v\nexpected component: %v", litter.Sdump(got), litter.Sdump(config.Component)) - } -} diff --git a/cmd/cycloid/middleware/query_encode.go b/cmd/cycloid/middleware/query_encode.go deleted file mode 100644 index 56c7f613f..000000000 --- a/cmd/cycloid/middleware/query_encode.go +++ /dev/null @@ -1,98 +0,0 @@ -package middleware - -import ( - "fmt" - "net/url" - "reflect" - "strconv" - "strings" -) - -// encodeQuery encodes query parameters from either a url.Values or a struct -// with `url` tags into a url.Values. -func encodeQuery(query any) (url.Values, error) { - if query == nil { - return nil, nil - } - - if v, ok := query.(url.Values); ok { - return v, nil - } - - result := url.Values{} - rv := reflect.ValueOf(query) - if rv.Kind() == reflect.Ptr { - if rv.IsNil() { - return nil, nil - } - rv = rv.Elem() - } - - if rv.Kind() != reflect.Struct { - return nil, fmt.Errorf("encodeQuery: unsupported query type %T, must be url.Values or struct with url tags", query) - } - - rt := rv.Type() - for i := 0; i < rt.NumField(); i++ { - field := rt.Field(i) - value := rv.Field(i) - - tag := field.Tag.Get("url") - if tag == "" || tag == "-" { - continue - } - - name := strings.Split(tag, ",")[0] - if name == "" { - continue - } - - if !encodeValue(result, name, value) { - continue - } - } - - return result, nil -} - -func encodeValue(result url.Values, name string, value reflect.Value) bool { - if value.Kind() == reflect.Ptr { - if value.IsNil() { - return false - } - value = value.Elem() - } - - switch value.Kind() { - case reflect.String: - s := value.String() - if s != "" { - result.Set(name, s) - } - case reflect.Bool: - result.Set(name, strconv.FormatBool(value.Bool())) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - result.Set(name, strconv.FormatInt(value.Int(), 10)) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - result.Set(name, strconv.FormatUint(value.Uint(), 10)) - case reflect.Float32, reflect.Float64: - result.Set(name, strconv.FormatFloat(value.Float(), 'f', -1, 64)) - case reflect.Slice: - for j := 0; j < value.Len(); j++ { - elem := value.Index(j) - if elem.Kind() == reflect.Ptr { - if elem.IsNil() { - continue - } - elem = elem.Elem() - } - if elem.Kind() == reflect.String { - result.Add(name, elem.String()) - } - } - default: - return false - } - - return true -} diff --git a/cmd/cycloid/middleware/sanitize.go b/cmd/cycloid/middleware/sanitize.go deleted file mode 100644 index 93f9de67e..000000000 --- a/cmd/cycloid/middleware/sanitize.go +++ /dev/null @@ -1,87 +0,0 @@ -package middleware - -import ( - "encoding/json" - "strings" -) - -// sensitiveKeys is the set of JSON field names (lowercased) whose values are -// always redacted when displaying request bodies in error output. -// These cover credentials, tokens, and secrets across all Cycloid API models. -var sensitiveKeys = map[string]bool{ - "ssh_key": true, - "password": true, - "secret_key": true, - "access_key": true, - "client_secret": true, - "oidc_client_secret": true, // OIDC integration client secret - "json_key": true, - "token": true, - "ca_cert": true, - "oidc_ca_cert": true, // OIDC integration CA certificate (PEM) - "raw": true, // CredentialRaw.Raw — custom catch-all - "current": true, // password_update.current -} - -// sensitiveKeySuffixes redacts any field whose (lowercased) name ends with one -// of these, so prefixed provider variants (oidc_client_secret, saml_client_secret, -// ...) are redacted by default rather than leaking into debug/error output. -var sensitiveKeySuffixes = []string{"_secret", "_ca_cert"} - -// isSensitiveKey reports whether a JSON field name's value must be redacted. -func isSensitiveKey(k string) bool { - lk := strings.ToLower(k) - if sensitiveKeys[lk] { - return true - } - for _, suf := range sensitiveKeySuffixes { - if strings.HasSuffix(lk, suf) { - return true - } - } - return false -} - -// sanitizeBody returns a compact JSON copy of body with sensitive field values -// replaced by "[REDACTED]". Returns nil if body is nil or empty. Returns body -// unchanged if it is not valid JSON (non-JSON bodies are typically not secrets). -func sanitizeBody(body []byte) []byte { - if len(body) == 0 { - return nil - } - var v interface{} - if err := json.Unmarshal(body, &v); err != nil { - return body - } - sanitized := sanitizeValue(v) - out, err := json.Marshal(sanitized) - if err != nil { - return body - } - return out -} - -func sanitizeValue(v interface{}) interface{} { - switch val := v.(type) { - case map[string]interface{}: - out := make(map[string]interface{}, len(val)) - for k, child := range val { - // isSensitiveKey is the single redaction gate (exact-match map + - // suffix net). Do not reintroduce a direct sensitiveKeys lookup here. - if isSensitiveKey(k) { - out[k] = "[REDACTED]" - } else { - out[k] = sanitizeValue(child) - } - } - return out - case []interface{}: - out := make([]interface{}, len(val)) - for i, child := range val { - out[i] = sanitizeValue(child) - } - return out - default: - return v - } -} diff --git a/cmd/cycloid/middleware/sanitize_test.go b/cmd/cycloid/middleware/sanitize_test.go deleted file mode 100644 index beca12356..000000000 --- a/cmd/cycloid/middleware/sanitize_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package middleware - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestSanitizeBody(t *testing.T) { - t.Run("NilInput", func(t *testing.T) { - assert.Nil(t, sanitizeBody(nil)) - }) - - t.Run("EmptyInput", func(t *testing.T) { - assert.Nil(t, sanitizeBody([]byte{})) - }) - - t.Run("InvalidJSON", func(t *testing.T) { - input := []byte("not json") - assert.Equal(t, input, sanitizeBody(input)) - }) - - t.Run("RedactsKnownKeys", func(t *testing.T) { - input := []byte(`{"name":"my-cred","password":"secret123","type":"ssh"}`) - out := sanitizeBody(input) - require.NotNil(t, out) - - var m map[string]interface{} - require.NoError(t, json.Unmarshal(out, &m)) - assert.Equal(t, "my-cred", m["name"]) - assert.Equal(t, "[REDACTED]", m["password"]) - assert.Equal(t, "ssh", m["type"]) - }) - - t.Run("RedactsSSHKey", func(t *testing.T) { - input := []byte(`{"ssh_key":"-----BEGIN RSA PRIVATE KEY-----"}`) - out := sanitizeBody(input) - var m map[string]interface{} - require.NoError(t, json.Unmarshal(out, &m)) - assert.Equal(t, "[REDACTED]", m["ssh_key"]) - }) - - t.Run("RawKeyIsRedacted", func(t *testing.T) { - // "raw" is a sensitive catch-all field in CredentialRaw - input := []byte(`{"name":"cred","raw":{"ssh_key":"secret","type":"ssh"}}`) - out := sanitizeBody(input) - var m map[string]interface{} - require.NoError(t, json.Unmarshal(out, &m)) - assert.Equal(t, "[REDACTED]", m["raw"], "raw key itself should be redacted") - }) - - t.Run("NestedSensitiveField", func(t *testing.T) { - input := []byte(`{"credential":{"password":"x","name":"foo"}}`) - out := sanitizeBody(input) - var m map[string]interface{} - require.NoError(t, json.Unmarshal(out, &m)) - nested := m["credential"].(map[string]interface{}) - assert.Equal(t, "[REDACTED]", nested["password"]) - assert.Equal(t, "foo", nested["name"]) - }) - - t.Run("ArrayElements", func(t *testing.T) { - input := []byte(`[{"token":"abc"},{"token":"def","name":"foo"}]`) - out := sanitizeBody(input) - var arr []map[string]interface{} - require.NoError(t, json.Unmarshal(out, &arr)) - assert.Equal(t, "[REDACTED]", arr[0]["token"]) - assert.Equal(t, "[REDACTED]", arr[1]["token"]) - assert.Equal(t, "foo", arr[1]["name"]) - }) - - t.Run("CaseInsensitiveKey", func(t *testing.T) { - input := []byte(`{"Password":"xxx","SECRET_KEY":"yyy"}`) - out := sanitizeBody(input) - var m map[string]interface{} - require.NoError(t, json.Unmarshal(out, &m)) - assert.Equal(t, "[REDACTED]", m["Password"]) - assert.Equal(t, "[REDACTED]", m["SECRET_KEY"]) - }) - - t.Run("NoSensitiveKeys", func(t *testing.T) { - input := []byte(`{"name":"foo","canonical":"bar"}`) - out := sanitizeBody(input) - var m map[string]interface{} - require.NoError(t, json.Unmarshal(out, &m)) - assert.Equal(t, "foo", m["name"]) - assert.Equal(t, "bar", m["canonical"]) - }) - - t.Run("RedactsOIDCSecrets", func(t *testing.T) { - // `oidc integration set` sends oidc_client_secret / oidc_ca_cert in - // the request body; these must never reach DEBUG or error output. Non-secret - // OIDC fields must stay visible so debugging stays useful. - input := []byte(`{"config":{"type":"AuthenticationOIDC","enabled":true,"oidc_issuer":"https://idp.example.com","oidc_client_id":"public-id","oidc_client_secret":"s3cr3t","oidc_ca_cert":"-----BEGIN CERTIFICATE-----"}}`) - out := sanitizeBody(input) - var m map[string]interface{} - require.NoError(t, json.Unmarshal(out, &m)) - cfg := m["config"].(map[string]interface{}) - assert.Equal(t, "[REDACTED]", cfg["oidc_client_secret"], "oidc_client_secret must be redacted") - assert.Equal(t, "[REDACTED]", cfg["oidc_ca_cert"], "oidc_ca_cert must be redacted") - assert.Equal(t, "https://idp.example.com", cfg["oidc_issuer"], "non-secret oidc_issuer must stay visible") - assert.Equal(t, "public-id", cfg["oidc_client_id"], "non-secret oidc_client_id must stay visible") - }) - - t.Run("RedactsSecretSuffixKeys", func(t *testing.T) { - // Defense-in-depth: any *_secret / *_ca_cert field is redacted by suffix, - // so a new provider's secret field does not leak by default. - input := []byte(`{"saml_client_secret":"x","some_secret":"y","azure_ca_cert":"z","name":"ok"}`) - out := sanitizeBody(input) - var m map[string]interface{} - require.NoError(t, json.Unmarshal(out, &m)) - assert.Equal(t, "[REDACTED]", m["saml_client_secret"]) - assert.Equal(t, "[REDACTED]", m["some_secret"]) - assert.Equal(t, "[REDACTED]", m["azure_ca_cert"]) - assert.Equal(t, "ok", m["name"]) - }) -} diff --git a/cmd/cycloid/middleware/stacks.go b/cmd/cycloid/middleware/stacks.go deleted file mode 100644 index d2f751d42..000000000 --- a/cmd/cycloid/middleware/stacks.go +++ /dev/null @@ -1,271 +0,0 @@ -package middleware - -import ( - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/pkg/errors" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -func (m *middleware) GetStack(org, ref string) (*models.ServiceCatalog, *http.Response, error) { - var result *models.ServiceCatalog - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "service_catalogs", ref}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// ListStacks lists service catalog stacks for an organization. -// -// Supported LHS filter attributes: service_catalog_ref, service_catalog_visibility -// (values: local, shared, hidden), service_catalog_author, service_catalog_blueprint, -// service_catalog_form_enabled, service_catalog_source_canonical, user_canonical. -func (m *middleware) ListStacks(org string, filters ...LHSFilter) ([]*models.ServiceCatalog, *http.Response, error) { - var result []*models.ServiceCatalog - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "service_catalogs"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// resolveStackVersion resolves versionTag/versionBranch/versionCommitHash to version ID and commit hash. -// Priority: tag > branch > commitHash (whichever is provided first) -// If all parameters are empty, uses the default catalog version (latest tag or branch HEAD). -func (m *middleware) resolveStackVersion(org, stackRef, versionTag, versionBranch, versionCommitHash string) (versionID uint32, commitHash string, err error) { - // If all are empty, use default version - if versionTag == "" && versionBranch == "" && versionCommitHash == "" { - defaultVersion, err := m.getDefaultCatalogVersion(org, stackRef) - if err != nil { - return 0, "", fmt.Errorf("failed to get default stack version: %w", err) - } - - if defaultVersion == nil || defaultVersion.ID == nil || defaultVersion.CommitHash == nil { - return 0, "", errors.New("no stack catalog version found") - } - - return *defaultVersion.ID, *defaultVersion.CommitHash, nil - } - - // List all versions for the stack - versions, _, err := m.ListStackVersions(org, stackRef) - if err != nil { - return 0, "", fmt.Errorf("failed to list stack versions: %w", err) - } - - // Priority 1: tag - if versionTag != "" { - for _, version := range versions { - if ptr.Value(version.Type) == "tag" && - ptr.Value(version.Name) == versionTag { - return *version.ID, *version.CommitHash, nil - } - } - return 0, "", fmt.Errorf("stack version tag %q not found", versionTag) - } - - // Priority 2: branch - if versionBranch != "" { - for _, version := range versions { - if ptr.Value(version.Type) == "branch" && - ptr.Value(version.Name) == versionBranch { - return *version.ID, *version.CommitHash, nil - } - } - return 0, "", fmt.Errorf("stack version branch %q not found", versionBranch) - } - - // Priority 3: commit hash - for _, version := range versions { - if ptr.Value(version.CommitHash) == versionCommitHash { - return *version.ID, *version.CommitHash, nil - } - } - return 0, "", fmt.Errorf("stack version commit hash %q not found", versionCommitHash) -} - -// ListStackUseCases lists use cases for a stack version. -// -// NOTE: the backend handler for this route does not call lhs.ParseQuery, so -// LHS filters are accepted by the middleware but silently ignored server-side. -func (m *middleware) ListStackUseCases(org, ref, versionTag, versionBranch, versionCommitHash string, filters ...LHSFilter) ([]*StackUseCase, *http.Response, error) { - // Resolve version parameters to ID - versionID, _, err := m.resolveStackVersion(org, ref, versionTag, versionBranch, versionCommitHash) - if err != nil { - return nil, nil, err - } - - query := url.Values{ - "service_catalog_source_version_id": []string{strconv.FormatUint(uint64(versionID), 10)}, - } - - var result []*StackUseCase - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "service_catalogs", ref, "use_cases"}, - Query: query, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// ListStackVersions lists versions for a stack. -// -// NOTE: the backend handler for this route does not call lhs.ParseQuery, so -// LHS filters are accepted by the middleware but silently ignored server-side. -func (m *middleware) ListStackVersions(org, ref string, filters ...LHSFilter) ([]*StackVersion, *http.Response, error) { - var result []*StackVersion - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "service_catalogs", ref, "versions"}, - LHSFilters: filters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// ResolveStackVersion is the public API for resolving a stack version string to (versionID, commitHash). -// The stackVersion parameter is treated as a tag name; if empty, the default version is used. -func (m *middleware) ResolveStackVersion(org, ref, stackVersion string) (uint32, string, error) { - return m.resolveStackVersion(org, ref, stackVersion, "", "") -} - -// getDefaultCatalogVersion returns the default catalog version for a stack based on priority: -// 1. If a version with is_latest=true and type="tag" exists, use that -// 2. Otherwise, use the latest commit of the branch of the catalog repository of the stack -func (m *middleware) getDefaultCatalogVersion(org, ref string) (*StackVersion, error) { - stack, _, err := m.GetStack(org, ref) - if err != nil { - return nil, err - } - - var catalogRepoBranch string - if stack.ServiceCatalogSourceCanonical != "" { - catalogRepo, _, err := m.GetCatalogRepository(org, stack.ServiceCatalogSourceCanonical) - if err != nil { - return nil, err - } - catalogRepoBranch = catalogRepo.Branch - } - - versions, _, err := m.ListStackVersions(org, ref) - if err != nil { - return nil, err - } - - var branchVersion *StackVersion - // Default to default catalog branch - for _, version := range versions { - if ptr.Value(version.Type) == "branch" && - ptr.Value(version.Name) == catalogRepoBranch { - branchVersion = version - } - } - - if branchVersion != nil { - return branchVersion, nil - } - - return nil, fmt.Errorf("failed to find the default version") -} - -// ListBlueprints lists stacks flagged as blueprints (service_catalog_blueprint=true). -// Additional caller-supplied filters are merged in. -// -// Supported LHS filter attributes: same as ListStacks (service_catalog_ref, -// service_catalog_visibility, service_catalog_author, service_catalog_source_canonical, -// user_canonical). service_catalog_blueprint is always set to true internally. -func (m *middleware) ListBlueprints(org string, filters ...LHSFilter) ([]*models.ServiceCatalog, *http.Response, error) { - lhsFilters := append( - []LHSFilter{{Attribute: "service_catalog_blueprint", Condition: "eq", Value: "true"}}, - filters..., - ) - - var result []*models.ServiceCatalog - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "service_catalogs"}, - LHSFilters: lhsFilters, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) CreateStackFromBlueprint(org, blueprintRef, name, stack, catalogRepository, useCase string) (*models.ServiceCatalog, *http.Response, error) { - body := &models.NewServiceCatalogFromTemplate{ - Name: &name, - Canonical: &stack, - ServiceCatalogSourceCanonical: &catalogRepository, - UseCase: &useCase, - } - - var result *models.ServiceCatalog - resp, err := m.GenericRequest(Request{ - Method: "POST", - Organization: &org, - Route: []string{"organizations", org, "service_catalogs", blueprintRef, "template"}, - Body: body, - }, &result) - if err != nil { - return nil, resp, errors.Wrap(err, "failed to create stack from blueprint") - } - return result, resp, nil -} - -func (m *middleware) UpdateStack( - org, ref, teamCanonical string, - visibility *string, -) (*models.ServiceCatalog, *http.Response, error) { - body := &models.UpdateServiceCatalog{ - TeamCanonical: teamCanonical, - Visibility: visibility, - } - - var result *models.ServiceCatalog - resp, err := m.GenericRequest(Request{ - Method: "PUT", - Organization: &org, - Route: []string{"organizations", org, "service_catalogs", ref}, - Body: body, - }, &result) - if err != nil { - return nil, resp, err - } - - // TODO: This is a local fix for https://github.com/cycloidio/youdeploy-http-api/issues/5020 - // Remove this condition when backend will be fixed - // If the team attribute is nil, this means that the backend did not found the maitainer canonical - if teamCanonical != "" && result.Team == nil { - return result, resp, errors.Errorf( - "maintainer with canonical '%s' may not exists, maintainer on stack ref '%s' has been removed, please check you team canonical argument and ensure that the team exists.", - teamCanonical, ref, - ) - } - - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/stacks_test.go b/cmd/cycloid/middleware/stacks_test.go deleted file mode 100644 index e61233409..000000000 --- a/cmd/cycloid/middleware/stacks_test.go +++ /dev/null @@ -1,227 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -const ( - testStackCanonical = "stack-e2e-stackforms" - testStackRef = "cycloid:stack-e2e-stackforms" - testStackUseCase = "default" -) - -func TestStacksGetStack(t *testing.T) { - m := config.Middleware - t.Run("GetStackOk", func(t *testing.T) { - stack, _, err := m.GetStack(config.Org, testStackRef) - require.NoError(t, err) - require.NotNil(t, stack) - assert.Equal(t, testStackCanonical, *stack.Canonical) - assert.NotNil(t, stack.Ref) - assert.Equal(t, testStackRef, *stack.Ref) - }) - t.Run("GetStackNotFound", func(t *testing.T) { - _, _, err := m.GetStack(config.Org, "org:nonexistent-stack") - require.Error(t, err) - assert.Contains(t, err.Error(), "404") - }) -} -func TestStacksListStacks(t *testing.T) { - m := config.Middleware - t.Run("ListStacksOk", func(t *testing.T) { - stacks, _, err := m.ListStacks(config.Org) - require.NoError(t, err) - require.NotNil(t, stacks) - assert.NotEmpty(t, stacks, "should have at least one stack") - // Verify the test stack is in the list - found := false - for _, stack := range stacks { - if stack.Canonical != nil && *stack.Canonical == testStackCanonical { - found = true - assert.Equal(t, testStackRef, *stack.Ref) - break - } - } - assert.True(t, found, "test stack should be in the list") - }) -} -func TestStacksListStackVersions(t *testing.T) { - m := config.Middleware - t.Run("ListStackVersionsOk", func(t *testing.T) { - versions, _, err := m.ListStackVersions(config.Org, testStackRef) - require.NoError(t, err) - require.NotNil(t, versions) - assert.NotEmpty(t, versions, "should have at least one version") - // Verify all versions have required fields - for _, version := range versions { - assert.NotNil(t, version.ID, "version should have an ID") - assert.NotNil(t, version.CommitHash, "version should have a commit hash") - assert.NotNil(t, version.Type, "version should have a type") - assert.NotNil(t, version.Name, "version should have a name") - } - }) - t.Run("ListStackVersionsNotFound", func(t *testing.T) { - _, _, err := m.ListStackVersions(config.Org, "org:nonexistent-stack") - require.Error(t, err) - }) -} -func TestStacksListStackUseCases(t *testing.T) { - m := config.Middleware - t.Run("ListStackUseCasesWithDefaultVersion", func(t *testing.T) { - // When all version params are empty, should use default version - useCases, _, err := m.ListStackUseCases(config.Org, testStackRef, "", "", "") - require.NoError(t, err) - require.NotNil(t, useCases) - assert.NotEmpty(t, useCases, "should have at least one use case") - found := false - for _, uc := range useCases { - if uc.UseCase != nil && *uc.UseCase == testStackUseCase { - found = true - assert.NotNil(t, uc.Name, "use case should have a name") - break - } - } - assert.True(t, found, "default use case should be in the list") - }) - t.Run("ListStackUseCasesWithCommitHash", func(t *testing.T) { - // First, get a valid commit hash. We'll use commit hash from the stacks - // branch version to ensure we're getting use cases - versions, _, err := m.ListStackVersions(config.Org, testStackRef) - require.NoError(t, err) - require.NotEmpty(t, versions) - var commitHash string - for _, version := range versions { - if version.Type != nil && *version.Type == "branch" && version.Name != nil && *version.Name == "stacks" { - commitHash = *version.CommitHash - break - } - } - // Use the commit hash to list use cases - useCases, _, err := m.ListStackUseCases(config.Org, testStackRef, "", "", commitHash) - require.NoError(t, err) - require.NotNil(t, useCases) - assert.NotEmpty(t, useCases, "should have at least one use case") - }) - t.Run("ListStackUseCasesWithTag", func(t *testing.T) { - versions, _, err := m.ListStackVersions(config.Org, testStackRef) - require.NoError(t, err) - require.NotEmpty(t, versions) - - useCases, _, err := m.ListStackUseCases(config.Org, testStackRef, "stack-e2e-stackforms/v1", "", "") - require.NoError(t, err) - require.NotNil(t, useCases) - assert.NotEmpty(t, useCases, "should have at least one use case") - }) - t.Run("ListStackUseCasesWithStacksBranch", func(t *testing.T) { - // Use the branch to list use cases - useCases, _, err := m.ListStackUseCases(config.Org, testStackRef, "", "stacks", "") - require.NoError(t, err) - require.NotNil(t, useCases) - assert.NotEmpty(t, useCases, "should have at least one use case") - }) - t.Run("ListStackUseCasesTagNotFound", func(t *testing.T) { - _, _, err := m.ListStackUseCases(config.Org, testStackRef, "v999.999.999", "", "") - require.Error(t, err) - assert.Contains(t, err.Error(), "not found") - }) - t.Run("ListStackUseCasesBranchNotFound", func(t *testing.T) { - _, _, err := m.ListStackUseCases(config.Org, testStackRef, "", "nonexistent-branch-xyz", "") - require.Error(t, err) - assert.Contains(t, err.Error(), "not found") - }) - t.Run("ListStackUseCasesCommitHashNotFound", func(t *testing.T) { - _, _, err := m.ListStackUseCases(config.Org, testStackRef, "", "", "0000000000000000000000000000000000000000") - require.Error(t, err) - assert.Contains(t, err.Error(), "not found") - }) - t.Run("ListStackUseCasesStackNotFound", func(t *testing.T) { - _, _, err := m.ListStackUseCases(config.Org, "org:nonexistent-stack", "", "", "") - require.Error(t, err) - }) -} -func TestStacksUpdateStack(t *testing.T) { - m := config.Middleware - t.Run("UpdateStackVisibility", func(t *testing.T) { - stack, _, err := m.GetStack(config.Org, testStackRef) - require.NoError(t, err) - originalVisibility := stack.Visibility - teamCanonical := "" - if stack.Team != nil && stack.Team.Canonical != nil { - teamCanonical = *stack.Team.Canonical - } - // Toggle visibility - newVisibility := "local" - if originalVisibility != nil && *originalVisibility == "local" { - newVisibility = "shared" - } - updatedStack, _, err := m.UpdateStack(config.Org, testStackRef, teamCanonical, ptr.Ptr(newVisibility)) - require.NoError(t, err) - require.NotNil(t, updatedStack) - assert.Equal(t, newVisibility, *updatedStack.Visibility) - - _, _, err = m.UpdateStack(config.Org, testStackRef, teamCanonical, originalVisibility) - require.NoError(t, err) - }) - t.Run("UpdateStackNotFound", func(t *testing.T) { - _, _, err := m.UpdateStack(config.Org, "org:nonexistent-stack", "", ptr.Ptr("private")) - require.Error(t, err) - }) -} - -func TestResolveStackVersionIntegration(t *testing.T) { - // These tests verify that resolveStackVersion works correctly through the public method ListStackUseCases - - m := config.Middleware - t.Run("ResolveDefaultVersionThroughListStackUseCases", func(t *testing.T) { - // When no version is specified, should use default version - useCases1, _, err1 := m.ListStackUseCases(config.Org, testStackRef, "", "", "") - require.NoError(t, err1) - require.NotEmpty(t, useCases1) - // Should return the same use cases each time with default version - useCases2, _, err2 := m.ListStackUseCases(config.Org, testStackRef, "", "", "") - require.NoError(t, err2) - require.NotEmpty(t, useCases2) - assert.Equal(t, len(useCases1), len(useCases2), "default version should be consistent") - }) - t.Run("ResolveCommitHashThroughListStackUseCases", func(t *testing.T) { - versions, _, err := m.ListStackVersions(config.Org, testStackRef) - require.NoError(t, err) - require.NotEmpty(t, versions) - commitHash := *versions[0].CommitHash - useCases, _, err := m.ListStackUseCases(config.Org, testStackRef, "", "", commitHash) - require.NoError(t, err) - require.NotEmpty(t, useCases) - }) - t.Run("PriorityTagOverBranchOverCommitHash", func(t *testing.T) { - versions, _, err := m.ListStackVersions(config.Org, testStackRef) - require.NoError(t, err) - require.NotEmpty(t, versions) - var commitHash string - // Make sure commit hash is from the stacks branch - for _, version := range versions { - if version.Type != nil && *version.Type == "branch" && version.Name != nil && *version.Name == "stacks" { - commitHash = *version.CommitHash - break - } - } - // If we have a tag, it should be used - useCases, _, err := m.ListStackUseCases(config.Org, testStackRef, "stack-e2e-stackforms/v1", "", "") - require.NoError(t, err) - require.NotEmpty(t, useCases) - - // If we have a branch, it should be used - useCases, _, err = m.ListStackUseCases(config.Org, testStackRef, "", "stacks", "") - require.NoError(t, err) - require.NotEmpty(t, useCases) - - // If we have a commit hash, it should be used - useCases, _, err = m.ListStackUseCases(config.Org, testStackRef, "", "", commitHash) - require.NoError(t, err) - require.NotEmpty(t, useCases) - }) -} diff --git a/cmd/cycloid/middleware/user.go b/cmd/cycloid/middleware/user.go deleted file mode 100644 index e2222b8d3..000000000 --- a/cmd/cycloid/middleware/user.go +++ /dev/null @@ -1,101 +0,0 @@ -package middleware - -import ( - "net/http" - "net/url" - - "github.com/go-openapi/strfmt" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) UserSignup(username, email, password, fullName string) (*http.Response, error) { - // Use a raw struct to match the actual API field names. - // The swagger model uses given_name+family_name but the backend still accepts full_name. - body := map[string]string{ - "username": username, - "email": email, - "password": password, - "full_name": fullName, - } - - resp, err := m.GenericRequest(Request{ - Method: "POST", - NoAuth: true, - Route: []string{"user"}, - Body: body, - }, nil) - return resp, err -} - -func (m *middleware) RefreshToken(org, childOrg *string, token string) (*models.UserSession, *http.Response, error) { - query := url.Values{} - if org != nil { - query.Set("organization_canonical", *org) - } - if childOrg != nil { - query.Set("child_canonical", *childOrg) - } - - // RefreshToken uses the provided token directly, not from config - var result *models.UserSession - resp, err := m.GenericRequest(Request{ - Method: "GET", - Route: []string{"user", "refresh_token"}, - Query: query, - Headers: map[string]string{"Authorization": "Bearer " + token}, - NoAuth: true, // We manually set the Authorization header above - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UserLogin(org, email *string, password string) (*models.UserSession, *http.Response, error) { - body := models.UserLogin{ - Password: (*strfmt.Password)(&password), - } - - if email != nil { - emailFmt := strfmt.Email(*email) - body.Email = &emailFmt - } - - if org != nil { - body.OrganizationCanonical = *org - } - - var result *models.UserSession - resp, err := m.GenericRequest(Request{ - Method: "POST", - NoAuth: true, - Route: []string{"user", "login"}, - Body: &body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -func (m *middleware) UserLoginToOrg(org, email, password string) (*models.UserSession, *http.Response, error) { - emailFmt := strfmt.Email(email) - body := models.UserLogin{ - Email: &emailFmt, - OrganizationCanonical: org, - Password: (*strfmt.Password)(&password), - } - - var result *models.UserSession - resp, err := m.GenericRequest(Request{ - Method: "POST", - NoAuth: true, - Route: []string{"user", "login", org}, - Body: &body, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} diff --git a/cmd/cycloid/middleware/user_test.go b/cmd/cycloid/middleware/user_test.go deleted file mode 100644 index f3c79c018..000000000 --- a/cmd/cycloid/middleware/user_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestRefreshToken(t *testing.T) { - m := config.Middleware - - session, _, err := m.RefreshToken(&config.Org, nil, config.APIKey) - require.NoError(t, err) - assert.NotNil(t, session) - assert.NotEmpty(t, session.Token) -} diff --git a/cmd/cycloid/middleware/utils.go b/cmd/cycloid/middleware/utils.go deleted file mode 100644 index 0bdb972fa..000000000 --- a/cmd/cycloid/middleware/utils.go +++ /dev/null @@ -1,84 +0,0 @@ -package middleware - -import ( - "fmt" - "regexp" - "strings" - - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -// from https://github.com/cycloidio/youdeploy-http-api/blob/develop/utils/convert.go - -func convertInterfaceArray(ia []any) []any { - res := make([]any, len(ia)) - for i, v := range ia { - res[i] = ConvertMapInterfaceToMapString(v) - } - return res -} - -func convertInterfaceMap(mii map[any]any) map[string]any { - ms := make(map[string]any) - for k, v := range mii { - ms[fmt.Sprintf("%v", k)] = ConvertMapInterfaceToMapString(v) - } - return ms -} - -// ConvertMapInterfaceToMapString is a method necessary to have JSON marshal -// working properly JSON doesn't know how to handle map[any]any -// so instead of keeping it, we are conveting it to map[string]any. -// If the interface p isn't a map then we simply return it as it is. -func ConvertMapInterfaceToMapString(p any) any { - switch v := p.(type) { - case []any: - return convertInterfaceArray(v) - case map[any]any: - return convertInterfaceMap(v) - case string: - return v - default: - return v - } -} - -var allowedCanonicalCharRegex = regexp.MustCompile("[^a-zA-Z0-9-_]") - -// ToCanonical convert a name to a valid canonical -func ToCanonical(name string) string { - replacer := strings.NewReplacer( - " ", "_", - ) - - replaced := replacer.Replace(name) - filtered := allowedCanonicalCharRegex.ReplaceAllString(replaced, "") - trimmed := strings.Trim(filtered, "-_") - return strings.ToLower(trimmed) -} - -// NameOrCanonical will process name and canonical argument and return both -// if name is set, the canonical will be inferred from it -// if canonical is set, name will be a Capitalized version of the canonical -// if both are empty, you will get an error -func NameOrCanonical(name, canonical *string) (string, string, error) { - if name == nil && canonical == nil { - return "", "", fmt.Errorf("name or canonical is required, both are empty") - } - - nameValue := ptr.Value(name) - canonicalValue := ptr.Value(canonical) - if nameValue == "" && canonicalValue == "" { - return "", "", fmt.Errorf("name or canonical is required, both are empty") - } - - if canonicalValue == "" { - return nameValue, ToCanonical(nameValue), nil - } - - if nameValue == "" { - return strings.ToUpper(canonicalValue[:1]) + canonicalValue[1:], canonicalValue, nil - } - - return nameValue, canonicalValue, nil -} diff --git a/cmd/cycloid/middleware/utils_test.go b/cmd/cycloid/middleware/utils_test.go deleted file mode 100644 index 0bc92a8ee..000000000 --- a/cmd/cycloid/middleware/utils_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func TestToCanonical(t *testing.T) { - testCanonicals := []struct { - testCase string - name string - expect string - }{ - {"AllowedChar", "azAZ02-azAZ02", "azaz02-azaz02"}, - {"SpaceConversionChar", "azAZ02 azAZ02", "azaz02_azaz02"}, - {"RemoveUnallowedChar", "az@@$$02 azŷùù&éZ02", "az02_azz02"}, - {"EndWith-", "canonical-", "canonical"}, - {"StartWith-", "-canonical", "canonical"}, - {"EndWith_", "canonical_", "canonical"}, - {"StartWith_", "_canonical", "canonical"}, - } - - for _, tc := range testCanonicals { - t.Run(tc.testCase, func(t *testing.T) { - assert.Equal(t, tc.expect, middleware.ToCanonical(tc.name)) - }) - } -} - -func TestNameOrCanonical(t *testing.T) { - testCases := []struct { - name string - inputName string - inputCanonical string - expectedName string - expectedCan string - expectErr bool - }{ - { - name: "name-only infers canonical", - inputName: "My Cool Project", - expectedName: "My Cool Project", - expectedCan: "my_cool_project", - expectErr: false, - }, - { - name: "canonical-only infers name", - inputCanonical: "my-project", - expectedName: "My-project", - expectedCan: "my-project", - expectErr: false, - }, - { - name: "both provided keep values", - inputName: "Existing Name", - inputCanonical: "existing-canonical", - expectedName: "Existing Name", - expectedCan: "existing-canonical", - expectErr: false, - }, - { - name: "both empty return error", - expectErr: true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - gotName, gotCanonical, err := middleware.NameOrCanonical(&tc.inputName, &tc.inputCanonical) - if tc.expectErr { - assert.Error(t, err) - return - } - - assert.NoError(t, err) - assert.Equal(t, tc.expectedName, gotName) - assert.Equal(t, tc.expectedCan, gotCanonical) - }) - } -} diff --git a/cmd/cycloid/oidc/cmd.go b/cmd/cycloid/oidc/cmd.go deleted file mode 100644 index c4fd5c47b..000000000 --- a/cmd/cycloid/oidc/cmd.go +++ /dev/null @@ -1,27 +0,0 @@ -package oidc - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/oidc/integration" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/oidc/mappings" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/oidc/settings" -) - -// NewCommands returns the top-level `oidc` cobra command. -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "oidc", - Short: "Manage OIDC group mappings and settings", - Long: `Manage OIDC group-to-team mappings and per-organization reconciliation -settings.`, - } - - cmd.AddCommand( - integration.NewCommands(), - mappings.NewCommands(), - settings.NewCommands(), - ) - - return cmd -} diff --git a/cmd/cycloid/oidc/integration/cmd.go b/cmd/cycloid/oidc/integration/cmd.go deleted file mode 100644 index 9c02d3ce3..000000000 --- a/cmd/cycloid/oidc/integration/cmd.go +++ /dev/null @@ -1,22 +0,0 @@ -package integration - -import ( - "github.com/spf13/cobra" -) - -// NewCommands returns the `integration` subcommand group. -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "integration", - Aliases: []string{"config"}, - Short: "Manage the org's OIDC SSO integration", - Long: `Create or update the AuthenticationOIDC SSO integration for the organization.`, - } - - cmd.AddCommand( - NewGetCommand(), - NewSetCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/oidc/integration/get.go b/cmd/cycloid/oidc/integration/get.go deleted file mode 100644 index 29b25dd29..000000000 --- a/cmd/cycloid/oidc/integration/get.go +++ /dev/null @@ -1,55 +0,0 @@ -package integration - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var integrationTableOptions = printer.Options{ - Columns: []string{ - "Enabled", - "OidcDisplayName", - "OidcClientID", - "OidcIssuer", - "OidcDiscoveryURL", - "OidcGroupsClaimName", - "OidcSessionTTLSeconds", - "HasSecret", - "HasCaCertificate", - }, -} - -// NewGetCommand returns the `integration get` command. -func NewGetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get", - Args: cobra.NoArgs, - Short: "Get the org's OIDC SSO integration config", - Example: ` - # Get the OIDC SSO integration for my-org - cy --org my-org oidc integration get -`, - RunE: getIntegration, - } - - cyout.RegisterModel(cmd, middleware.OIDCIntegration{}) - return cmd -} - -func getIntegration(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, _, err := m.GetOIDCIntegration(org) - return cyout.PrintWithOptions(cmd, result, err, "unable to get OIDC integration", integrationTableOptions) -} diff --git a/cmd/cycloid/oidc/integration/set.go b/cmd/cycloid/oidc/integration/set.go deleted file mode 100644 index 72e7c9fee..000000000 --- a/cmd/cycloid/oidc/integration/set.go +++ /dev/null @@ -1,225 +0,0 @@ -package integration - -import ( - "errors" - "net/http" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -// NewSetCommand returns the `integration set` command. -func NewSetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "set", - Args: cobra.NoArgs, - Short: "Create or update the org's OIDC SSO integration", - Long: `Create or update the AuthenticationOIDC SSO integration for the organization. - -Only the flags you pass are changed; unset flags keep their current value -(read-merge-write). The backend always requires 'type' and 'enabled' — they -are always included in the update payload. - -Secrets (--client-secret, --ca-cert) are write-only: the GET never returns -them. Omitting them preserves the stored value; passing an empty string is -equivalent to omitting them (the backend ignores blank secrets). - -The client secret can also be supplied via the CY_OIDC_CLIENT_SECRET -environment variable; the CA certificate via CY_OIDC_CA_CERT.`, - Example: ` - # Recommended: pass the secret via env var to keep it out of shell history - export CY_OIDC_CLIENT_SECRET="$(cat ./oidc-secret)" - cy --org my-org oidc integration set \ - --enabled \ - --issuer https://idp.example.com \ - --client-id my-client-id - - # Flag form (secret is visible in shell history / process list — avoid on shared hosts) - cy --org my-org oidc integration set --client-secret "$MY_SECRET" - - # Update only the groups claim name (all other settings unchanged) - cy --org my-org oidc integration set --groups-claim-name groups - - # Use the alias 'config' instead of 'integration' - cy --org my-org oidc config set --enabled=false -`, - RunE: setIntegration, - } - - cyargs.AddOIDCEnabledFlag(cmd) - cyargs.AddOIDCIssuerFlag(cmd) - cyargs.AddOIDCClientIDFlag(cmd) - cyargs.AddOIDCClientSecretFlag(cmd) - cyargs.AddOIDCDisplayNameFlag(cmd) - cyargs.AddOIDCIconFlag(cmd) - cyargs.AddOIDCDiscoveryURLFlag(cmd) - cyargs.AddOIDCGroupsClaimNameFlag(cmd) - cyargs.AddOIDCSessionTTLSecondsFlag(cmd) - cyargs.AddOIDCClientSecretJwtFlag(cmd) - cyargs.AddOIDCUseCaCertFlag(cmd) - cyargs.AddOIDCCaCertFlag(cmd) - cyargs.AddOIDCSkipTLSVerifyFlag(cmd) - cyargs.AddOIDCAllowInsecureDiscoveryFlag(cmd) - cyargs.AddOIDCAdoptManualMembersFlag(cmd) - - cyout.RegisterModel(cmd, middleware.OIDCIntegration{}) - return cmd -} - -func setIntegration(cmd *cobra.Command, args []string) error { - // Hard Rule 4: ALL flags parsed before NewAPI / NewMiddleware. - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - enabled, err := cyargs.GetOIDCEnabled(cmd) - if err != nil { - return err - } - issuer, err := cyargs.GetOIDCIssuer(cmd) - if err != nil { - return err - } - clientID, err := cyargs.GetOIDCClientID(cmd) - if err != nil { - return err - } - clientSecret, err := cyargs.GetOIDCClientSecret(cmd) - if err != nil { - return err - } - displayName, err := cyargs.GetOIDCDisplayName(cmd) - if err != nil { - return err - } - icon, err := cyargs.GetOIDCIcon(cmd) - if err != nil { - return err - } - discoveryURL, err := cyargs.GetOIDCDiscoveryURL(cmd) - if err != nil { - return err - } - groupsClaimName, err := cyargs.GetOIDCGroupsClaimName(cmd) - if err != nil { - return err - } - sessionTTL, err := cyargs.GetOIDCSessionTTLSeconds(cmd) - if err != nil { - return err - } - clientSecretJwt, err := cyargs.GetOIDCClientSecretJwt(cmd) - if err != nil { - return err - } - useCaCert, err := cyargs.GetOIDCUseCaCert(cmd) - if err != nil { - return err - } - caCert, err := cyargs.GetOIDCCaCert(cmd) - if err != nil { - return err - } - skipTLSVerify, err := cyargs.GetOIDCSkipTLSVerify(cmd) - if err != nil { - return err - } - allowInsecureDiscovery, err := cyargs.GetOIDCAllowInsecureDiscovery(cmd) - if err != nil { - return err - } - adoptManualMembers, err := cyargs.GetOIDCAdoptManualMembers(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // Read-merge-write: fetch current config so we can preserve 'enabled' when - // the user does not explicitly pass --enabled. A 404 means the integration - // does not exist yet — treat as a fresh create (current == nil). - var current *middleware.OIDCIntegration - current, _, err = m.GetOIDCIntegration(org) - if err != nil { - var apiErr *middleware.APIResponseError - if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound { - return cyout.Print(cmd, nil, err, "unable to read current OIDC integration") - } - // 404 → create path; current stays nil - } - - // Always required by the backend. - config := map[string]interface{}{ - "type": "AuthenticationOIDC", - } - - // enabled: use the flag value if explicitly changed; otherwise carry forward - // the current value; default to true for a fresh create. - if cmd.Flags().Changed(cyargs.OIDCEnabledFlagName) { - config["enabled"] = enabled - } else if current != nil { - config["enabled"] = current.Enabled - } else { - config["enabled"] = true - } - - // For each optional field: only include in the payload when the user - // explicitly passed the flag, so the backend merge keeps untouched values. - if cmd.Flags().Changed(cyargs.OIDCIssuerFlagName) { - config["oidc_issuer"] = issuer - } - if cmd.Flags().Changed(cyargs.OIDCClientIDFlagName) { - config["oidc_client_id"] = clientID - } - if cmd.Flags().Changed(cyargs.OIDCDisplayNameFlagName) { - config["oidc_display_name"] = displayName - } - if cmd.Flags().Changed(cyargs.OIDCIconFlagName) { - config["oidc_icon"] = icon - } - if cmd.Flags().Changed(cyargs.OIDCDiscoveryURLFlagName) { - config["oidc_discovery_url"] = discoveryURL - } - if cmd.Flags().Changed(cyargs.OIDCGroupsClaimNameFlagName) { - config["oidc_groups_claim_name"] = groupsClaimName - } - if cmd.Flags().Changed(cyargs.OIDCSessionTTLSecondsFlagName) { - config["oidc_session_ttl_seconds"] = sessionTTL - } - if cmd.Flags().Changed(cyargs.OIDCClientSecretJwtFlagName) { - config["oidc_client_secret_jwt"] = clientSecretJwt - } - if cmd.Flags().Changed(cyargs.OIDCUseCaCertFlagName) { - config["oidc_use_ca_cert"] = useCaCert - } - if cmd.Flags().Changed(cyargs.OIDCSkipTLSVerifyFlagName) { - config["oidc_skip_tls_verify"] = skipTLSVerify - } - if cmd.Flags().Changed(cyargs.OIDCAllowInsecureDiscoveryFlagName) { - config["oidc_allow_insecure_discovery"] = allowInsecureDiscovery - } - if cmd.Flags().Changed(cyargs.OIDCAdoptManualMembersFlagName) { - config["oidc_adopt_manual_members"] = adoptManualMembers - } - - // Secrets: send only when a non-empty value was supplied (via --client-secret - // flag or CY_OIDC_CLIENT_SECRET env var). The backend preserves the stored - // secret when the key is absent or the value is empty. Note: if the env var - // is set in the shell, the secret will be sent on every invocation — this is - // intentional (the user opted in by exporting the var). - if clientSecret != "" { - config["oidc_client_secret"] = clientSecret - } - if caCert != "" { - config["oidc_ca_cert"] = caCert - } - - result, _, err := m.UpdateOIDCIntegration(org, config) - return cyout.PrintWithOptions(cmd, result, err, "unable to update OIDC integration", integrationTableOptions) -} diff --git a/cmd/cycloid/oidc/mappings/cmd.go b/cmd/cycloid/oidc/mappings/cmd.go deleted file mode 100644 index f0a74f727..000000000 --- a/cmd/cycloid/oidc/mappings/cmd.go +++ /dev/null @@ -1,22 +0,0 @@ -package mappings - -import ( - "github.com/spf13/cobra" -) - -// NewCommands returns the `mappings` subcommand group. -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "mappings", - Aliases: []string{"mapping"}, - Short: "Manage OIDC group-to-team mappings", - } - - cmd.AddCommand( - NewListCommand(), - NewCreateCommand(), - NewDeleteCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/oidc/mappings/create.go b/cmd/cycloid/oidc/mappings/create.go deleted file mode 100644 index 35fe3bfa2..000000000 --- a/cmd/cycloid/oidc/mappings/create.go +++ /dev/null @@ -1,53 +0,0 @@ -package mappings - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -// NewCreateCommand returns the `mappings create` command. -func NewCreateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "create", - Args: cobra.NoArgs, - Short: "Create an OIDC group-to-team mapping", - Example: ` - # Map OIDC group "devs" to team "dev-team" in my-org - cy --org my-org oidc mappings create --group-name devs --team dev-team -`, - RunE: createMapping, - } - - cmd.MarkFlagRequired(cyargs.AddOIDCGroupNameFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddTeamFlag(cmd)) - - cyout.RegisterModel(cmd, middleware.OIDCGroupMapping{}) - return cmd -} - -func createMapping(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - groupName, err := cyargs.GetOIDCGroupName(cmd) - if err != nil { - return err - } - - team, err := cyargs.GetTeam(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, _, err := m.CreateOIDCGroupMapping(org, groupName, team) - return cyout.PrintWithOptions(cmd, result, err, "unable to create OIDC group mapping", mappingTableOptions) -} diff --git a/cmd/cycloid/oidc/mappings/delete.go b/cmd/cycloid/oidc/mappings/delete.go deleted file mode 100644 index 28e4bab86..000000000 --- a/cmd/cycloid/oidc/mappings/delete.go +++ /dev/null @@ -1,46 +0,0 @@ -package mappings - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -// NewDeleteCommand returns the `mappings delete` command. -func NewDeleteCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "delete", - Aliases: []string{"rm"}, - Args: cobra.NoArgs, - Short: "Delete an OIDC group-to-team mapping by ID", - Example: ` - # Delete OIDC group mapping with ID 42 in my-org - cy --org my-org oidc mappings delete --mapping-id 42 -`, - RunE: deleteMapping, - } - - cmd.MarkFlagRequired(cyargs.AddOIDCMappingIDFlag(cmd)) - return cmd -} - -func deleteMapping(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - id, err := cyargs.GetOIDCMappingID(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - _, err = m.DeleteOIDCGroupMapping(org, id) - return cyout.Print(cmd, nil, err, "unable to delete OIDC group mapping") -} diff --git a/cmd/cycloid/oidc/mappings/list.go b/cmd/cycloid/oidc/mappings/list.go deleted file mode 100644 index 0019ca9ca..000000000 --- a/cmd/cycloid/oidc/mappings/list.go +++ /dev/null @@ -1,46 +0,0 @@ -package mappings - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var mappingTableOptions = printer.Options{ - Columns: []string{"ID", "GroupName", "Team.Canonical", "Team.Name"}, - Identifier: "ID", -} - -// NewListCommand returns the `mappings list` command. -func NewListCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "List OIDC group-to-team mappings", - Example: ` - # List all OIDC group mappings for my-org - cy --org my-org oidc mappings list -`, - RunE: listMappings, - } - - cyout.RegisterModel(cmd, middleware.OIDCGroupMapping{}) - return cmd -} - -func listMappings(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, _, err := m.ListOIDCGroupMappings(org) - return cyout.PrintWithOptions(cmd, result, err, "unable to list OIDC group mappings", mappingTableOptions) -} diff --git a/cmd/cycloid/oidc/settings/cmd.go b/cmd/cycloid/oidc/settings/cmd.go deleted file mode 100644 index c2a5b7f6c..000000000 --- a/cmd/cycloid/oidc/settings/cmd.go +++ /dev/null @@ -1,20 +0,0 @@ -package settings - -import ( - "github.com/spf13/cobra" -) - -// NewCommands returns the `settings` subcommand group. -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "settings", - Short: "Manage OIDC organization settings", - } - - cmd.AddCommand( - NewGetCommand(), - NewSetCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/oidc/settings/get.go b/cmd/cycloid/oidc/settings/get.go deleted file mode 100644 index ef23cb0db..000000000 --- a/cmd/cycloid/oidc/settings/get.go +++ /dev/null @@ -1,45 +0,0 @@ -package settings - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var settingsTableOptions = printer.Options{ - Columns: []string{"DefaultRoleCanonical", "OIDCManaged", "OIDCNoMatchPolicy"}, -} - -// NewGetCommand returns the `settings get` command. -func NewGetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get", - Args: cobra.NoArgs, - Short: "Get OIDC organization settings", - Example: ` - # Get OIDC settings for my-org - cy --org my-org oidc settings get -`, - RunE: getSettings, - } - - cyout.RegisterModel(cmd, middleware.OIDCOrganizationSettings{}) - return cmd -} - -func getSettings(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, _, err := m.GetOIDCOrganizationSettings(org) - return cyout.PrintWithOptions(cmd, result, err, "unable to get OIDC organization settings", settingsTableOptions) -} diff --git a/cmd/cycloid/oidc/settings/set.go b/cmd/cycloid/oidc/settings/set.go deleted file mode 100644 index 64c905a43..000000000 --- a/cmd/cycloid/oidc/settings/set.go +++ /dev/null @@ -1,101 +0,0 @@ -package settings - -import ( - "errors" - "net/http" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -// NewSetCommand returns the `settings set` command. -func NewSetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "set", - Args: cobra.NoArgs, - Short: "Set OIDC organization settings", - Long: `Update OIDC reconciliation settings for the organization. - -Only the flags you pass are changed; unset flags keep their current value -(read-merge-write). Note: --no-match-policy=eject requires --oidc-managed=true; -the API returns HTTP 422 otherwise.`, - Example: ` - # Enable OIDC-managed mode and eject members with no matching group - cy --org my-org oidc settings set --oidc-managed --no-match-policy eject - - # Set a default role for OIDC-provisioned members (other settings untouched) - cy --org my-org oidc settings set --default-role organization-member -`, - RunE: setSettings, - } - - cyargs.AddOIDCManagedFlag(cmd) - cyargs.AddOIDCNoMatchPolicyFlag(cmd) - cyargs.AddOIDCDefaultRoleFlag(cmd) - - cyout.RegisterModel(cmd, middleware.OIDCOrganizationSettings{}) - return cmd -} - -func setSettings(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - oidcManaged, err := cyargs.GetOIDCManaged(cmd) - if err != nil { - return err - } - - noMatchPolicy, err := cyargs.GetOIDCNoMatchPolicy(cmd) - if err != nil { - return err - } - - defaultRole, err := cyargs.GetOIDCDefaultRole(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // The settings endpoint is a full-replace PUT. Read the current settings and - // override only the flags the user explicitly set, so an unspecified flag - // never silently resets live state. A not-yet-configured org (404) starts - // from defaults. - // Default for fresh-create (404 on read). Must stay in sync with the - // server-side default in the OIDC organization settings endpoint. - merged := middleware.UpdateOIDCOrganizationSettings{ - OIDCNoMatchPolicy: "keep_membership", - } - current, _, err := m.GetOIDCOrganizationSettings(org) - if err != nil { - var apiErr *middleware.APIResponseError - if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound { - return cyout.Print(cmd, nil, err, "unable to read current OIDC organization settings") - } - } else if current != nil { - merged.OIDCManaged = current.OIDCManaged - merged.OIDCNoMatchPolicy = current.OIDCNoMatchPolicy - merged.DefaultRoleCanonical = current.DefaultRoleCanonical - } - - if cmd.Flags().Changed(cyargs.OIDCManagedFlagName) { - merged.OIDCManaged = oidcManaged - } - if cmd.Flags().Changed(cyargs.OIDCNoMatchPolicyFlagName) { - merged.OIDCNoMatchPolicy = noMatchPolicy - } - if cmd.Flags().Changed(cyargs.OIDCDefaultRoleFlagName) { - merged.DefaultRoleCanonical = defaultRole - } - - result, _, err := m.UpdateOIDCOrganizationSettings(org, merged) - return cyout.PrintWithOptions(cmd, result, err, "unable to update OIDC organization settings", settingsTableOptions) -} diff --git a/cmd/cycloid/organizations/cmd.go b/cmd/cycloid/organizations/cmd.go deleted file mode 100644 index 4e76931bc..000000000 --- a/cmd/cycloid/organizations/cmd.go +++ /dev/null @@ -1,32 +0,0 @@ -package organizations - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/organizations/licence" -) - -func NewCommands() *cobra.Command { - var cmd = &cobra.Command{ - Use: "organization", - Aliases: []string{ - "org", - "organizations", - "o", - }, - Short: "Manage the organizations", - } - cmd.AddCommand( - NewCreateCommand(), - NewUpdateCommand(), - NewListCommand(), - NewListWorkersCommand(), - NewDeleteCommand(), - NewListChildrensCommand(), - NewCreateChildCommand(), - NewGetCommand(), - NewSubscriptionCommands(), - licence.NewCommands(), - ) - return cmd -} diff --git a/cmd/cycloid/organizations/create.go b/cmd/cycloid/organizations/create.go deleted file mode 100644 index 027202f42..000000000 --- a/cmd/cycloid/organizations/create.go +++ /dev/null @@ -1,97 +0,0 @@ -package organizations - -import ( - stderrors "errors" - "fmt" - "net/http" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -// This command have been Hidden because it is not compatible with API key login. -// Advanced user still can use it passing a user token in CY_API_KEY env var during a login. -func NewCreateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "create", - Args: cobra.NoArgs, - Short: "create an organization", - Long: `Create an organization in the Cycloid console. -Created organization are at root level by default. - -If you want to create a child org, you need to specify the parent organization canonical -using the --parent-canonical (-p) flag. - -Check the documentation at: https://docs.cycloid.io/reference/organizations/ - -See examples below.`, - Example: `# create an organization foo -cy organization create --name foo - -# create a child organization bar with parent foo -cy organization create --name bar --parent-canonical foo -`, - RunE: create, - } - - cmd.MarkFlagRequired(cyargs.AddOrgNameFlag(cmd)) - cyargs.AddOrgChildOfFlag(cmd) - cmd.Flags().Bool("update", false, "update the organization display name if it already exists (same canonical as derived from --name)") - return cmd -} - -func create(cmd *cobra.Command, args []string) error { - name, err := cyargs.GetOrgName(cmd) - if err != nil { - return err - } - - parentOrg, err := cyargs.GetOrgParentCanonical(cmd) - if err != nil { - return err - } - - update, err := cmd.Flags().GetBool("update") - if err != nil { - return err - } - - canonical := common.GenerateCanonical(name) - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - _, _, getErr := m.GetOrganization(canonical) - exists := getErr == nil - if getErr != nil { - var apiErr *middleware.APIResponseError - if !stderrors.As(getErr, &apiErr) || apiErr.StatusCode != http.StatusNotFound { - return cyout.PrintWithOptions(cmd, nil, getErr, "failed to check if organization exists", printer.Options{}) - } - } - - if exists && !update { - return cyout.PrintWithOptions(cmd, nil, - fmt.Errorf("organization %q already exists; use --update to change its display name", canonical), - "failed to create organization", printer.Options{}) - } - - var outOrg *models.Organization - if exists { - outOrg, _, err = m.UpdateOrganization(canonical, name) - return cyout.PrintWithOptions(cmd, outOrg, err, "failed to update organization", printer.Options{}) - } - - if parentOrg != "" { - outOrg, _, err = m.CreateOrganizationChild(parentOrg, canonical, &name) - } else { - outOrg, _, err = m.CreateOrganization(name) - } - return cyout.PrintWithOptions(cmd, outOrg, err, "failed to create org named '"+name+"'", printer.Options{}) -} diff --git a/cmd/cycloid/organizations/create_children.go b/cmd/cycloid/organizations/create_children.go deleted file mode 100644 index 7e848c2db..000000000 --- a/cmd/cycloid/organizations/create_children.go +++ /dev/null @@ -1,45 +0,0 @@ -package organizations - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateChildCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "create-child", - Args: cobra.NoArgs, - Short: "create a child organization", - RunE: createChild, - Deprecated: "this function is replaced by `cy org create --org --child-of `", - Hidden: true, - } - - cmd.PersistentFlags().String("parent-org", "", "parent organization canonical") - cmd.MarkPersistentFlagRequired("parent-org") - - return cmd -} - -func createChild(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - porg, err := cmd.Flags().GetString("parent-org") - if err != nil { - return err - } - - oc, _, err := m.CreateOrganizationChild(org, porg, nil) - return cyout.PrintWithOptions(cmd, oc, err, "unable to create a child organization", printer.Options{}) -} diff --git a/cmd/cycloid/organizations/delete.go b/cmd/cycloid/organizations/delete.go deleted file mode 100644 index 3f4fd817c..000000000 --- a/cmd/cycloid/organizations/delete.go +++ /dev/null @@ -1,53 +0,0 @@ -package organizations - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewDeleteCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "delete [canonical...]", - Args: cobra.ArbitraryArgs, - Short: "delete an organization (require root API_KEY)", - Example: ` - # delete the organization set via --org flag - # The API_KEY must be obtained from the root organization - cy organization delete --org my-org - - # delete multiple organizations by canonical - cy organization delete my-org-a my-org-b -`, - RunE: del, - } - - return cmd -} - -func del(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - var orgs []string - if len(args) > 0 { - orgs = args - } else { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - orgs = []string{org} - } - - for _, org := range orgs { - _, err := m.DeleteOrganization(org) - if err != nil { - return cyout.Print(cmd, nil, err, "unable to delete organization "+org) - } - } - return nil -} diff --git a/cmd/cycloid/organizations/get.go b/cmd/cycloid/organizations/get.go deleted file mode 100644 index 11c3eb09e..000000000 --- a/cmd/cycloid/organizations/get.go +++ /dev/null @@ -1,68 +0,0 @@ -package organizations - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var orgTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name"}, - Identifier: "Canonical", -} - -func NewGetCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get [canonical...]", - Args: cobra.ArbitraryArgs, - Short: "get an organization", - Example: ` - # get the organization set via --org flag - cy organization get --org my-org -o yaml - - # get multiple organizations by canonical - cy organization get my-org-a my-org-b -`, - RunE: get, - } - - cyout.RegisterModel(cmd, models.Organization{}) - return cmd -} - -func get(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // Multi-arg - if len(args) > 1 { - results := make([]*models.Organization, 0, len(args)) - for _, canonical := range args { - o, _, err := m.GetOrganization(canonical) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to get organization "+canonical, orgTableOptions) - } - results = append(results, o) - } - return cyout.PrintWithOptions(cmd, results, nil, "", orgTableOptions) - } - - var org string - if len(args) == 1 { - org = args[0] - } else { - var err error - org, err = cyargs.GetOrg(cmd) - if err != nil { - return err - } - } - - o, _, err := m.GetOrganization(org) - return cyout.PrintWithOptions(cmd, o, err, "unable to get organization", orgTableOptions) -} diff --git a/cmd/cycloid/organizations/licence/activate.go b/cmd/cycloid/organizations/licence/activate.go deleted file mode 100644 index 2d1b19b04..000000000 --- a/cmd/cycloid/organizations/licence/activate.go +++ /dev/null @@ -1,53 +0,0 @@ -package licence - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewActivateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "activate", - Short: "Activate or replace the Cycloid licence on this organization", - Long: `Activate (or replace) the Cycloid licence on this organization. - -The API overwrites any existing licence in place; running this command twice -is safe and the second run replaces the first. - -Examples: - cy organization licence activate --org root-org --key eyJhbG... - cy organization licence activate --org root-org --key-file ./licence.jwt - cat licence.jwt | cy organization licence activate --org root-org`, - Args: cobra.NoArgs, - RunE: activate, - } - - cyargs.AddLicenceKeyFlag(cmd) - cyargs.AddLicenceKeyFileFlag(cmd) - cmd.MarkFlagsMutuallyExclusive("key", "key-file") - - return cmd -} - -func activate(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - key, err := cyargs.GetLicenceKey(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - _, err = m.ActivateLicence(org, key) - return cyout.PrintWithOptions(cmd, nil, err, "failed to activate licence", printer.Options{}) -} diff --git a/cmd/cycloid/organizations/licence/cmd.go b/cmd/cycloid/organizations/licence/cmd.go deleted file mode 100644 index 7e6033458..000000000 --- a/cmd/cycloid/organizations/licence/cmd.go +++ /dev/null @@ -1,17 +0,0 @@ -package licence - -import "github.com/spf13/cobra" - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "licence", - Aliases: []string{"license"}, - Short: "Manage the organization's Cycloid licence", - Args: cobra.NoArgs, - } - cmd.AddCommand( - NewActivateCommand(), - NewGetCommand(), - ) - return cmd -} diff --git a/cmd/cycloid/organizations/licence/get.go b/cmd/cycloid/organizations/licence/get.go deleted file mode 100644 index 99a5248db..000000000 --- a/cmd/cycloid/organizations/licence/get.go +++ /dev/null @@ -1,43 +0,0 @@ -package licence - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var licenceTableOptions = printer.Options{ - Columns: []string{"CompanyName", "EmailAddress", "ExpiresAt", "MembersCount", "Version", "Key"}, - Identifier: "CompanyName", -} - -func NewGetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get", - Short: "Get the currently active licence", - Example: `cy organization licence get --org root-org -o yaml`, - Args: cobra.NoArgs, - RunE: get, - } - - cyout.RegisterModel(cmd, models.Licence{}) - return cmd -} - -func get(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - licence, _, err := m.GetLicence(org) - return cyout.PrintWithOptions(cmd, licence, err, "failed to get licence", licenceTableOptions) -} diff --git a/cmd/cycloid/organizations/list-children.go b/cmd/cycloid/organizations/list-children.go deleted file mode 100644 index 3c15f6c7c..000000000 --- a/cmd/cycloid/organizations/list-children.go +++ /dev/null @@ -1,38 +0,0 @@ -package organizations - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListChildrensCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list-children", - Args: cobra.NoArgs, - Aliases: []string{ - "list-childrens", - }, - Short: "list the organization children", - RunE: listChildrens, - } - - return cmd -} - -func listChildrens(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - oc, _, err := m.ListOrganizationChildrens(org) - return cyout.PrintWithOptions(cmd, oc, err, "unable to list organization childrens", printer.Options{}) -} diff --git a/cmd/cycloid/organizations/list-workers.go b/cmd/cycloid/organizations/list-workers.go deleted file mode 100644 index b555a45d0..000000000 --- a/cmd/cycloid/organizations/list-workers.go +++ /dev/null @@ -1,35 +0,0 @@ -package organizations - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListWorkersCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list-workers", - Args: cobra.NoArgs, - Short: "list the organization workers", - RunE: listWorkers, - } - - return cmd -} - -func listWorkers(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - ws, _, err := m.ListOrganizationWorkers(org) - return cyout.PrintWithOptions(cmd, ws, err, "unable to list organization workers", printer.Options{}) -} diff --git a/cmd/cycloid/organizations/list.go b/cmd/cycloid/organizations/list.go deleted file mode 100644 index a34cce297..000000000 --- a/cmd/cycloid/organizations/list.go +++ /dev/null @@ -1,35 +0,0 @@ -package organizations - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "list the organizations", - RunE: list, - Hidden: true, - Example: ` - # list the organizations - cy o list --output json -`, - } - cyout.RegisterModel(cmd, models.Organization{}) - return cmd - -} - -func list(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - orgs, _, err := m.ListOrganizations() - return cyout.PrintWithOptions(cmd, orgs, err, "unable to list organizations", orgTableOptions) -} diff --git a/cmd/cycloid/organizations/subscription.go b/cmd/cycloid/organizations/subscription.go deleted file mode 100644 index 744fb6707..000000000 --- a/cmd/cycloid/organizations/subscription.go +++ /dev/null @@ -1,17 +0,0 @@ -package organizations - -import "github.com/spf13/cobra" - -func NewSubscriptionCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "subscription", - Aliases: []string{"subscriptions"}, - Short: "Manage organization's subscriptions", - Args: cobra.NoArgs, - } - cmd.AddCommand( - NewCreateOrUpdateSubscriptionCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/organizations/subscription_create_or_update.go b/cmd/cycloid/organizations/subscription_create_or_update.go deleted file mode 100644 index 021ecfa7c..000000000 --- a/cmd/cycloid/organizations/subscription_create_or_update.go +++ /dev/null @@ -1,85 +0,0 @@ -package organizations - -import ( - "fmt" - "strings" - "time" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateOrUpdateSubscriptionCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "create", - Short: "Add a subscription to an organization, requires an Admin API Key from a parent org.", - Long: "Related docs: https://docs.cycloid.io/reference/organizations/concepts/licencing", - Aliases: []string{"update"}, - Args: cobra.NoArgs, - RunE: createOrUpdateSubscription, - } - - cmd.Flags().BoolP("update", "u", false, "allow update if a subscription exists") - cmd.Flags().Uint64P("member-count", "c", 5, "number of member to attribute to this organization, default to 5.") - defaultDate := time.Now().AddDate(0, 3, 0) - cmd.Flags().TimeP("expires-at", "t", defaultDate, []string{time.RFC3339}, "Add an expiration time for the subscription, default in three month ("+defaultDate.Format(time.RFC3339)+")") - cmd.MarkFlagRequired("expire-at") - cmd.Flags().StringP("plan", "p", middleware.PlatformTeam, "Select a plan, default to `platform_teams`") - cmd.RegisterFlagCompletionFunc("plan", func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - var completions = []cobra.Completion{} - for _, p := range middleware.AvailableSubscriptionPlans { - if strings.HasPrefix(p, toComplete) { - completions = append(completions, p) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp - }) - - return cmd -} - -func createOrUpdateSubscription(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - update, err := cmd.Flags().GetBool("update") - if err != nil { - return err - } - if cmd.Name() == "update" { - update = true - } - - memberCount, err := cmd.Flags().GetUint64("member-count") - if err != nil { - return err - } - - expiresAt, err := cmd.Flags().GetTime("expires-at") - if err != nil { - return err - } - - plan, err := cmd.Flags().GetString("plan") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - subscription, _, err := m.CreateOrUpdateSubscription(org, plan, expiresAt, memberCount, update) - if err != nil { - return fmt.Errorf("failed to update subscription for org %q: %w", org, err) - } - - return cyout.PrintWithOptions(cmd, subscription, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/organizations/update.go b/cmd/cycloid/organizations/update.go deleted file mode 100644 index 2f453f1da..000000000 --- a/cmd/cycloid/organizations/update.go +++ /dev/null @@ -1,49 +0,0 @@ -package organizations - -import ( - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -// This command have been Hidden because it is not compatible with API key login. -// Advanced user still can use it passing a user token in CY_API_KEY env var during a login. -func NewUpdateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "update", - Args: cobra.NoArgs, - Short: "update an organization", - Example: ` - # update an organization foo - cy organization update --org org --name foo -`, - RunE: update, - } - - cmd.MarkFlagRequired(cyargs.AddOrgNameFlag(cmd)) - - return cmd -} - -func update(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - name, err := cyargs.GetOrgName(cmd) - if err != nil { - return err - } - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return errors.Wrap(err, "unable get org flag") - } - - o, _, err := m.UpdateOrganization(org, name) - return cyout.PrintWithOptions(cmd, o, err, "unable to update organization", printer.Options{}) -} diff --git a/cmd/cycloid/output/cmd.go b/cmd/cycloid/output/cmd.go deleted file mode 100644 index 2eda376bf..000000000 --- a/cmd/cycloid/output/cmd.go +++ /dev/null @@ -1,92 +0,0 @@ -package output - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/config" - "github.com/cycloidio/cycloid-cli/internal/cyargs" -) - -// NewOutputCmd returns the cobra command for managing the default output format. -func NewOutputCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "output", - Short: "Manage the default output format", - Long: `Manage the default --output format persisted in the config file. - -The effective output format is resolved in this priority order: - 1. --jq flag - 2. --output / -o flag - 3. CY_OUTPUT environment variable - 4. Value stored by 'cy output set' (config file) - 5. "table" (built-in default)`, - Args: cobra.NoArgs, - } - cmd.AddCommand( - newSetCmd(), - newGetCmd(), - newResetCmd(), - ) - return cmd -} - -func newSetCmd() *cobra.Command { - return &cobra.Command{ - Use: "set ", - Short: "Persist a default output format", - Args: cobra.ExactArgs(1), - Example: `cy output set table:border -cy output set json -cy output set table=canonical,name`, - RunE: func(cmd *cobra.Command, args []string) error { - conf, _ := config.Read() - if conf == nil { - conf = &config.Config{} - } - conf.Output = args[0] - if err := config.Write(conf); err != nil { - return fmt.Errorf("unable to save output config: %w", err) - } - fmt.Fprintf(cmd.OutOrStdout(), "Default output set to %q\n", args[0]) - return nil - }, - } -} - -func newGetCmd() *cobra.Command { - return &cobra.Command{ - Use: "get", - Short: "Show the current effective default output format", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - effective, err := cyargs.GetOutput(cmd) - if err != nil { - return err - } - fmt.Fprintln(cmd.OutOrStdout(), effective) - return nil - }, - } -} - -func newResetCmd() *cobra.Command { - return &cobra.Command{ - Use: "reset", - Short: "Remove the persisted default output format", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - conf, _ := config.Read() - if conf == nil { - conf = &config.Config{} - } - conf.Output = "" - if err := config.Write(conf); err != nil { - return fmt.Errorf("unable to save output config: %w", err) - } - fmt.Fprintln(cmd.OutOrStdout(), "Default output reset to \"table\"") - return nil - }, - } -} diff --git a/cmd/cycloid/pipelines/build_cmd.go b/cmd/cycloid/pipelines/build_cmd.go deleted file mode 100644 index 0064561d8..000000000 --- a/cmd/cycloid/pipelines/build_cmd.go +++ /dev/null @@ -1,32 +0,0 @@ -package pipelines - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewBuildsCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "builds", - Aliases: []string{ - "b", - "build", - }, - Short: "manage pipeline builds", - Args: cobra.NoArgs, - } - - cmd.AddCommand( - NewBuildCreateCommand(), - NewBuildListCommand(), - NewBuildGetCommand(), - NewBuildLogsCommand(), - ) - return cmd -} - -var buildTableOptions = printer.Options{ - Columns: []string{"ID", "Name", "Status", "JobName", "StartTime"}, - Identifier: "ID", -} diff --git a/cmd/cycloid/pipelines/build_get.go b/cmd/cycloid/pipelines/build_get.go deleted file mode 100644 index eeaa75540..000000000 --- a/cmd/cycloid/pipelines/build_get.go +++ /dev/null @@ -1,59 +0,0 @@ -package pipelines - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewBuildGetCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get", - Short: "Get a build information.", - RunE: getBuild, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cyargs.AddPipelineJob(cmd) - cyargs.AddPipelineBuildID(cmd) - cyout.RegisterModel(cmd, models.Build{}) - return cmd -} - -func getBuild(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - job, err := cyargs.GetPipelineJob(cmd) - if err != nil { - return err - } - - buildID, err := cyargs.GetPipelineBuildID(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - build, _, err := m.GetBuild(org, project, env, component, pipeline, job, buildID) - errMsg := fmt.Sprintf("failed to fetch build with ID '%s', in pipeline '%s' of project '%s', env '%s', component '%s'", - buildID, pipeline, project, env, component) - return cyout.PrintWithOptions(cmd, build, err, errMsg, buildTableOptions) -} diff --git a/cmd/cycloid/pipelines/build_list.go b/cmd/cycloid/pipelines/build_list.go deleted file mode 100644 index d902aa65d..000000000 --- a/cmd/cycloid/pipelines/build_list.go +++ /dev/null @@ -1,53 +0,0 @@ -package pipelines - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewBuildListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Short: "list builds of a pipeline", - Example: `cy --org my-org pp list-builds --project my-project --env env --component component --job my-job`, - RunE: listBuilds, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cmd.MarkFlagRequired(cyargs.AddPipelineJob(cmd)) - cyout.RegisterModel(cmd, models.Build{}) - return cmd -} - -func listBuilds(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - // Those args are optional filters, we don't care about err - _, project, env, component, _ := cyargs.GetCyContext(cmd) - job, _ := cyargs.GetPipelineJob(cmd) - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - builds, _, err := m.GetBuilds(org, project, env, component, pipeline, job) - errMsg := fmt.Sprintf("failed to get builds of pipeline '%s', in project '%s', in env '%s', in component '%s'", - pipeline, project, env, component) - return cyout.PrintWithOptions(cmd, builds, err, errMsg, buildTableOptions) -} diff --git a/cmd/cycloid/pipelines/build_logs.go b/cmd/cycloid/pipelines/build_logs.go deleted file mode 100644 index 1fb405ac0..000000000 --- a/cmd/cycloid/pipelines/build_logs.go +++ /dev/null @@ -1,106 +0,0 @@ -package pipelines - -import ( - "context" - "strings" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/buildwatch" - "github.com/cycloidio/cycloid-cli/internal/cyargs" -) - -func NewBuildLogsCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "logs", - Aliases: []string{"log"}, - Short: "stream the event log of a pipeline build", - Example: ` - # Dump all available logs for a past build and exit - cy pp builds logs --project p --env e --component c --pipeline pp --job j --build-id 42 - - # Tail logs for an in-progress build (keeps streaming until the build finishes) - cy pp builds logs --project p --env e --component c --pipeline pp --job j --build-id 42 --watch -`, - RunE: streamBuildLogs, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cmd.MarkFlagRequired(cyargs.AddPipelineJob(cmd)) - cmd.MarkFlagRequired(cyargs.AddPipelineBuildID(cmd)) - cmd.Flags().Bool("watch", false, "keep tailing the event stream (useful for in-progress builds)") - return cmd -} - -func streamBuildLogs(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - job, err := cyargs.GetPipelineJob(cmd) - if err != nil { - return err - } - - buildID, err := cyargs.GetPipelineBuildID(cmd) - if err != nil { - return err - } - - output, err := cyargs.GetOutput(cmd) - if err != nil { - return errors.Wrap(err, "unable to get output flag") - } - - watch, err := cmd.Flags().GetBool("watch") - if err != nil { - return errors.Wrap(err, "unable to get --watch flag") - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - outMode := buildwatch.OutputHuman - if strings.EqualFold(output, "json") { - outMode = buildwatch.OutputRaw - } - - theme := buildwatch.StreamTheme{} - stripLogANSI := false - if outMode == buildwatch.OutputHuman { - if buildwatch.IsTerminalWriter(cmd.OutOrStdout()) { - theme = buildwatch.DefaultStreamTheme - } else { - stripLogANSI = true - } - } - - verbose := strings.EqualFold(viper.GetString("verbosity"), "debug") - - return buildwatch.StreamLogs( - context.Background(), - m, - org, project, env, component, pipeline, job, buildID, - buildwatch.Options{ - Watch: watch, - LogWriter: cmd.OutOrStdout(), - Output: outMode, - Verbose: verbose, - Theme: theme, - StripLogANSI: stripLogANSI, - StatusWriter: cmd.ErrOrStderr(), - }, - ) -} diff --git a/cmd/cycloid/pipelines/build_trigger.go b/cmd/cycloid/pipelines/build_trigger.go deleted file mode 100644 index 1e4ee43cb..000000000 --- a/cmd/cycloid/pipelines/build_trigger.go +++ /dev/null @@ -1,162 +0,0 @@ -package pipelines - -import ( - "context" - "fmt" - "io" - "strings" - "time" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/buildwatch" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewBuildCreateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "trigger", - Aliases: []string{ - "create", - "run", - }, - Short: "trigger a pipeline build", - Example: `cy pipeline build trigger --project my-project --env my-env --component my-component --job my-job`, - RunE: createBuild, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cmd.MarkFlagRequired(cyargs.AddPipelineJob(cmd)) - cmd.Flags().Bool("watch", false, "watch the build until completion") - cmd.Flags().Int("timeout", 0, "timeout in seconds when used with --watch (0 means no timeout)") - cmd.Flags().Bool("watch-cancel-on-timeout", false, "with --watch, abort the build when --timeout is reached") - return cmd -} - -func createBuild(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - job, err := cyargs.GetPipelineJob(cmd) - if err != nil { - return err - } - - output, err := cyargs.GetOutput(cmd) - if err != nil { - return errors.Wrap(err, "unable to get output flag") - } - - watch, err := cmd.Flags().GetBool("watch") - if err != nil { - return errors.Wrap(err, "unable to get watch flag") - } - timeoutSeconds, err := cmd.Flags().GetInt("timeout") - if err != nil { - return errors.Wrap(err, "unable to get timeout flag") - } - cancelOnTimeout, err := cmd.Flags().GetBool("watch-cancel-on-timeout") - if err != nil { - return errors.Wrap(err, "unable to get watch-cancel-on-timeout flag") - } - - if timeoutSeconds < 0 { - return errors.New("--timeout must be greater than or equal to 0") - } - if !watch && timeoutSeconds > 0 { - return errors.New("--timeout can only be used with --watch") - } - if !watch && cancelOnTimeout { - return errors.New("--watch-cancel-on-timeout can only be used with --watch") - } - if watch && cancelOnTimeout && timeoutSeconds == 0 { - return errors.New("--watch-cancel-on-timeout requires --timeout to be set") - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - build, _, err := m.CreateBuild(org, project, env, component, pipeline, job) - if err != nil { - return fmt.Errorf("failed to trigger build in context project %q, env %q, component %q with pipeline %q in job %q: %w", project, env, component, pipeline, job, err) - } - - if watch { - if build == nil || build.ID == nil { - return errors.New("triggered build payload is missing id") - } - - // Human vs raw watch stream: docs/pipeline-build-watch-output.md (quick rollback: force OutputRaw). - outMode := buildwatch.OutputHuman - if strings.EqualFold(output, "json") { - outMode = buildwatch.OutputRaw - } - - theme := buildwatch.StreamTheme{} - stripLogANSI := false - if outMode == buildwatch.OutputHuman { - if buildwatch.IsTerminalWriter(cmd.OutOrStdout()) { - theme = buildwatch.DefaultStreamTheme - } else { - stripLogANSI = true - } - } - - watchVerbose := strings.EqualFold(viper.GetString("verbosity"), "debug") - - buildID := fmt.Sprintf("%d", *build.ID) - writeBuildWatchIntro(cmd.ErrOrStderr(), resolveConsoleURL(), org, project, env, component, pipeline, job, buildID) - fmt.Fprintln(cmd.ErrOrStderr(), "Note: first Ctrl+C requests a remote build abort; second Ctrl+C exits watch immediately.") - - return buildwatch.Watch( - context.Background(), - m, - org, - project, - env, - component, - pipeline, - job, - buildID, - buildwatch.Options{ - Timeout: time.Duration(timeoutSeconds) * time.Second, - CancelOnTimeout: cancelOnTimeout, - LogWriter: cmd.OutOrStdout(), - Output: outMode, - Verbose: watchVerbose, - Theme: theme, - StripLogANSI: stripLogANSI, - StatusWriter: cmd.ErrOrStderr(), - }, - ) - } - - return cyout.Print(cmd, build, nil, "") -} - -// resolveConsoleURL returns CY_CONSOLE_URL when set, otherwise the default (https://console.cycloid.io). -func resolveConsoleURL() string { - return strings.TrimSpace(viper.GetString("console_url")) -} - -func writeBuildWatchIntro(w io.Writer, consoleBase, org, project, env, component, pipeline, job, buildID string) { - if link, ok := common.PipelineBuildConsoleURL(consoleBase, org, project, env, component, pipeline, job, buildID); ok { - fmt.Fprintf(w, "Watching build %s: %s\n", buildID, link) - return - } - fmt.Fprintln(w, "No console URL is available (CY_CONSOLE_URL is empty); cannot print a link to this build.") -} diff --git a/cmd/cycloid/pipelines/jobs_cmd.go b/cmd/cycloid/pipelines/jobs_cmd.go deleted file mode 100644 index 7bf5b5270..000000000 --- a/cmd/cycloid/pipelines/jobs_cmd.go +++ /dev/null @@ -1,66 +0,0 @@ -package pipelines - -import ( - "strconv" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewJobsCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "job", - Aliases: []string{ - "jobs", - "j", - }, - Short: "Manage pipeline jobs", - Example: `# list jobs from a pipeline -cy pipeline job list --project my-project --env my-env --component my-component --pipeline my-pipeline - -# get a specific job from a pipeline -cy pipeline job get --project my-project --env my-env --component my-component --pipeline my-pipeline --job my-job`, - Args: cobra.NoArgs, - } - - cmd.AddCommand( - NewJobsGetCommand(), - NewJobsListCommand(), - NewJobsPauseCommand(), - NewJobsUnpauseCommand(), - NewJobLogsCommand(), - ) - - return cmd -} - -var jobTableOptions = printer.Options{ - Columns: []string{"Name", "Paused", "PipelineName", "CurrentBuildID"}, - Identifier: "Name", - Transform: func(obj interface{}) map[string]string { - j, ok := obj.(*models.Job) - if !ok { - return map[string]string{} - } - name := "" - if j.Name != nil { - name = *j.Name - } - paused := strconv.FormatBool(j.Paused) - currentBuildID := "" - switch { - case j.NextBuild != nil && j.NextBuild.ID != nil: - currentBuildID = strconv.FormatUint(*j.NextBuild.ID, 10) - case j.FinishedBuild != nil && j.FinishedBuild.ID != nil: - currentBuildID = strconv.FormatUint(*j.FinishedBuild.ID, 10) - } - return map[string]string{ - "Name": name, - "Paused": paused, - "PipelineName": j.PipelineName, - "CurrentBuildID": currentBuildID, - } - }, -} diff --git a/cmd/cycloid/pipelines/jobs_get.go b/cmd/cycloid/pipelines/jobs_get.go deleted file mode 100644 index 5d181bcd8..000000000 --- a/cmd/cycloid/pipelines/jobs_get.go +++ /dev/null @@ -1,50 +0,0 @@ -package pipelines - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewJobsGetCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get", - Short: "get a pipeline's job", - Example: `cy --org my-org pp job get --project my-project --env env --component component --pipeline pipeline --job my-job -o json`, - RunE: getJob, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cyargs.AddPipelineJob(cmd) - cyout.RegisterModel(cmd, models.Job{}) - return cmd -} - -func getJob(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - job, err := cyargs.GetPipelineJob(cmd) - if err != nil { - return err - } - - outJob, _, err := m.GetJob(org, project, env, component, pipeline, job) - return cyout.PrintWithOptions(cmd, outJob, err, "failed to fetch job: "+job, jobTableOptions) -} diff --git a/cmd/cycloid/pipelines/jobs_list.go b/cmd/cycloid/pipelines/jobs_list.go deleted file mode 100644 index ac6a7d9a5..000000000 --- a/cmd/cycloid/pipelines/jobs_list.go +++ /dev/null @@ -1,47 +0,0 @@ -package pipelines - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewJobsListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Short: "list a pipeline's jobs", - Example: `cy --org my-org pp job list --project my-project --env env --component component --pipeline pipeline -o json`, - RunE: listJobs, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cyout.RegisterModel(cmd, models.Job{}) - return cmd -} - -func listJobs(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - jobs, _, err := m.GetJobs(org, project, env, component, pipeline) - errMsg := fmt.Sprintf("failed to fetch jobs for pipeline %q", pipeline) - return cyout.PrintWithOptions(cmd, jobs, err, errMsg, jobTableOptions) -} diff --git a/cmd/cycloid/pipelines/jobs_logs.go b/cmd/cycloid/pipelines/jobs_logs.go deleted file mode 100644 index abcfabc59..000000000 --- a/cmd/cycloid/pipelines/jobs_logs.go +++ /dev/null @@ -1,210 +0,0 @@ -package pipelines - -import ( - "context" - "fmt" - "sort" - "strings" - "time" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/buildwatch" - "github.com/cycloidio/cycloid-cli/internal/cyargs" -) - -const defaultJobLogsPollInterval = 5 * time.Second - -func NewJobLogsCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "logs", - Aliases: []string{"log"}, - Short: "stream logs for the latest build of a pipeline job", - Example: ` - # Print available logs for the latest build of a job and exit - cy pp job logs --project p --env e --component c --pipeline pp --job j - - # Watch: stream latest build, then tail future builds continuously (Ctrl+C to stop) - cy pp job logs --project p --env e --component c --pipeline pp --job j --watch - - # Control poll interval when waiting for a new build in --watch mode - cy pp job logs --project p --env e --component c --pipeline pp --job j --watch --poll-interval 10s -`, - RunE: streamJobLogs, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cmd.MarkFlagRequired(cyargs.AddPipelineJob(cmd)) - cmd.Flags().Bool("watch", false, "after the current build ends, poll for new builds and stream them") - cmd.Flags().Duration("poll-interval", defaultJobLogsPollInterval, "how often to check for a new build when --watch is waiting") - return cmd -} - -func streamJobLogs(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - job, err := cyargs.GetPipelineJob(cmd) - if err != nil { - return err - } - - output, err := cyargs.GetOutput(cmd) - if err != nil { - return errors.Wrap(err, "unable to get output flag") - } - - watch, err := cmd.Flags().GetBool("watch") - if err != nil { - return errors.Wrap(err, "unable to get --watch flag") - } - - pollInterval, err := cmd.Flags().GetDuration("poll-interval") - if err != nil { - return errors.Wrap(err, "unable to get --poll-interval flag") - } - if pollInterval <= 0 { - return errors.New("--poll-interval must be a positive duration") - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - outMode := buildwatch.OutputHuman - if strings.EqualFold(output, "json") { - outMode = buildwatch.OutputRaw - } - - theme := buildwatch.StreamTheme{} - stripLogANSI := false - if outMode == buildwatch.OutputHuman { - if buildwatch.IsTerminalWriter(cmd.OutOrStdout()) { - theme = buildwatch.DefaultStreamTheme - } else { - stripLogANSI = true - } - } - - verbose := strings.EqualFold(viper.GetString("verbosity"), "debug") - - streamOpts := buildwatch.Options{ - LogWriter: cmd.OutOrStdout(), - Output: outMode, - Verbose: verbose, - Theme: theme, - StripLogANSI: stripLogANSI, - StatusWriter: cmd.ErrOrStderr(), - } - - // Find the latest build for this job (sort by ID descending; highest ID = newest). - buildID, err := latestBuildID(m, org, project, env, component, pipeline, job) - if err != nil { - return err - } - if buildID == "" { - // No builds yet — nothing to show. - return nil - } - - if !watch { - return buildwatch.StreamLogs( - context.Background(), - m, - org, project, env, component, pipeline, job, buildID, - streamOpts, - ) - } - - // Watch mode: stream current build, then poll for new builds. - ctx := context.Background() - lastBuildID := buildID - for { - fmt.Fprintf(cmd.ErrOrStderr(), "[job logs] streaming build %s\n", lastBuildID) - streamOpts.Watch = true - if err := buildwatch.StreamLogs(ctx, m, org, project, env, component, pipeline, job, lastBuildID, streamOpts); err != nil { - // ExitError with code 130 means the user pressed Ctrl+C. - var exitErr *buildwatch.ExitError - if errors.As(err, &exitErr) && exitErr.ExitCode() == 130 { - return err - } - // Other exit errors (failed, aborted) are informational in watch mode — - // log and continue polling for the next build. - fmt.Fprintf(cmd.ErrOrStderr(), "[job logs] build %s ended: %v\n", lastBuildID, err) - } - - // Poll until a new build ID appears. - nextBuildID, err := pollForNewBuild(ctx, m, org, project, env, component, pipeline, job, lastBuildID, pollInterval, cmd.ErrOrStderr()) - if err != nil { - return err - } - lastBuildID = nextBuildID - } -} - -// latestBuildID lists builds for the job and returns the ID of the most recent -// one (highest numeric build ID). Returns "" if no builds exist. -func latestBuildID(m middleware.Middleware, org, project, env, component, pipeline, job string) (string, error) { - builds, _, err := m.GetBuilds(org, project, env, component, pipeline, job) - if err != nil { - return "", fmt.Errorf("listing builds for job %q: %w", job, err) - } - if len(builds) == 0 { - return "", nil - } - - // Sort by Concourse build ID descending (highest = newest). - sort.Slice(builds, func(i, j int) bool { - if builds[i].ID == nil { - return false - } - if builds[j].ID == nil { - return true - } - return *builds[i].ID > *builds[j].ID - }) - - if builds[0].ID == nil { - return "", nil - } - return fmt.Sprintf("%d", *builds[0].ID), nil -} - -// pollForNewBuild polls GetBuilds until a build ID different from lastBuildID -// appears. It returns the new build ID. -func pollForNewBuild( - ctx context.Context, - m middleware.Middleware, - org, project, env, component, pipeline, job, lastBuildID string, - interval time.Duration, - statusWriter interface{ Write([]byte) (int, error) }, -) (string, error) { - fmt.Fprintf(statusWriter, "[job logs] waiting for next build (polling every %s)...\n", interval) - for { - select { - case <-ctx.Done(): - return "", ctx.Err() - case <-time.After(interval): - } - - nextID, err := latestBuildID(m, org, project, env, component, pipeline, job) - if err != nil { - return "", err - } - if nextID != "" && nextID != lastBuildID { - return nextID, nil - } - } -} diff --git a/cmd/cycloid/pipelines/jobs_pause.go b/cmd/cycloid/pipelines/jobs_pause.go deleted file mode 100644 index e1b256e1b..000000000 --- a/cmd/cycloid/pipelines/jobs_pause.go +++ /dev/null @@ -1,49 +0,0 @@ -package pipelines - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewJobsPauseCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "pause", - Short: "pause a pipeline job", - Example: `cy pp job pause --project my-project --env env --component component --pipeline pipeline --job my-job`, - RunE: pauseJob, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cyargs.AddPipelineJob(cmd) - return cmd -} - -func pauseJob(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - job, err := cyargs.GetPipelineJob(cmd) - if err != nil { - return err - } - - _, err = m.PauseJob(org, project, env, component, pipeline, job) - return cyout.PrintWithOptions(cmd, nil, err, "unable to pause the job", printer.Options{}) -} diff --git a/cmd/cycloid/pipelines/jobs_unpause.go b/cmd/cycloid/pipelines/jobs_unpause.go deleted file mode 100644 index c4bdceb04..000000000 --- a/cmd/cycloid/pipelines/jobs_unpause.go +++ /dev/null @@ -1,49 +0,0 @@ -package pipelines - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewJobsUnpauseCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "unpause", - Short: "unpause a pipeline job", - RunE: unpauseJob, - Example: `cy pp job unpause --project my-project --env env --component component --pipeline pipeline --job my-job`, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cyargs.AddPipelineJob(cmd) - return cmd -} - -func unpauseJob(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - job, err := cyargs.GetPipelineJob(cmd) - if err != nil { - return err - } - - _, err = m.UnPauseJob(org, project, env, component, pipeline, job) - return cyout.PrintWithOptions(cmd, nil, err, "unable to unpause the job", printer.Options{}) -} diff --git a/cmd/cycloid/pipelines/pipeline_clear_task_cache.go b/cmd/cycloid/pipelines/pipeline_clear_task_cache.go deleted file mode 100644 index 604e79dc9..000000000 --- a/cmd/cycloid/pipelines/pipeline_clear_task_cache.go +++ /dev/null @@ -1,55 +0,0 @@ -package pipelines - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewPipelineClearTaskCacheCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "clear-task-cache", - Short: "clear cache for a task", - Example: `cy pp clear-task-cache --project my-project --job my-job --env my-env --step my-task`, - RunE: cleartaskCache, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cyargs.AddPipelineJob(cmd) - cyargs.AddPipelineStep(cmd) - return cmd -} - -func cleartaskCache(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - job, err := cyargs.GetPipelineJob(cmd) - if err != nil { - return err - } - - step, err := cyargs.GetPipelineStep(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - out, _, err := m.ClearTaskCache(org, project, env, component, pipeline, job, step) - return cyout.PrintWithOptions(cmd, out, err, "unable to clear task cache", printer.Options{}) -} diff --git a/cmd/cycloid/pipelines/pipeline_cmd.go b/cmd/cycloid/pipelines/pipeline_cmd.go deleted file mode 100644 index 9aec5831d..000000000 --- a/cmd/cycloid/pipelines/pipeline_cmd.go +++ /dev/null @@ -1,77 +0,0 @@ -package pipelines - -import ( - "strconv" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCommands() *cobra.Command { - var cmd = &cobra.Command{ - Use: "pipeline", - Aliases: []string{ - "pp", - "pipelines", - }, - Short: "Manage the pipelines", - Args: cobra.NoArgs, - } - - cmd.AddCommand( - NewBuildsCommand(), - NewJobsCommand(), - NewPipelineClearTaskCacheCommand(), - NewPipelineDiffCommand(), - NewPipelineGetCommand(), - NewPipelineLastUsedCommand(), - NewPipelineListCommand(), - NewPipelinePauseCommand(), - NewPipelineSyncedCommand(), - NewPipelineUnpauseCommand(), - NewPipelineUpdateCommand(), - ) - - return cmd -} - -var pipelineTableOptions = printer.Options{ - Columns: []string{"Name", "Status", "Paused", "Project", "Environment", "Component"}, - Identifier: "Name", - Transform: func(obj interface{}) map[string]string { - pp, ok := obj.(*models.Pipeline) - if !ok { - return map[string]string{} - } - name := "" - if pp.Name != nil { - name = *pp.Name - } - paused := "" - if pp.Paused != nil { - paused = strconv.FormatBool(*pp.Paused) - } - project := "" - if pp.Project != nil && pp.Project.Canonical != nil { - project = *pp.Project.Canonical - } - env := "" - if pp.Environment != nil && pp.Environment.Canonical != nil { - env = *pp.Environment.Canonical - } - comp := "" - if pp.Component != nil && pp.Component.Canonical != nil { - comp = *pp.Component.Canonical - } - return map[string]string{ - "Name": name, - "Status": pp.Status, - "Paused": paused, - "Project": project, - "Environment": env, - "Component": comp, - } - }, -} diff --git a/cmd/cycloid/pipelines/pipeline_diff.go b/cmd/cycloid/pipelines/pipeline_diff.go deleted file mode 100644 index 672a810ca..000000000 --- a/cmd/cycloid/pipelines/pipeline_diff.go +++ /dev/null @@ -1,67 +0,0 @@ -package pipelines - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewPipelineDiffCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "diff", - Short: "diff the remote pipeline with a local config", - RunE: diff, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cyargs.AddPipelineConfig(cmd) - cyargs.AddPipelineVars(cmd) - return cmd -} - -func diff(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - varsPath, err := cyargs.GetPipelineVars(cmd) - if err != nil { - return err - } - - pipelinePath, err := cyargs.GetPipelineConfig(cmd) - if err != nil { - return err - } - - rawPipeline, err := os.ReadFile(pipelinePath) - if err != nil { - return fmt.Errorf("failed to open pipeline config at path %q: %w", pipelinePath, err) - } - - rawVars, err := os.ReadFile(varsPath) - if err != nil { - return fmt.Errorf("failed to read pipeline variables files at path %q: %w", varsPath, err) - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - pipelineDiff, _, err := m.DiffPipeline(org, project, env, component, pipeline, string(rawPipeline), string(rawVars), false) - return cyout.PrintWithOptions(cmd, pipelineDiff, err, "failed to get pipeline diff", printer.Options{}) -} diff --git a/cmd/cycloid/pipelines/pipeline_get.go b/cmd/cycloid/pipelines/pipeline_get.go deleted file mode 100644 index 005e8e68d..000000000 --- a/cmd/cycloid/pipelines/pipeline_get.go +++ /dev/null @@ -1,47 +0,0 @@ -package pipelines - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewPipelineGetCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get", - Short: "get a pipeline", - Example: `cy pipeline get --project my-project --env env --component component --pipeline pipeline_name`, - RunE: getPipeline, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cyout.RegisterModel(cmd, models.Pipeline{}) - return cmd -} - -func getPipeline(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - outPipeline, _, err := m.GetPipeline(org, project, env, component, pipeline) - errMsg := fmt.Sprintf("failed to get pipeline %q in context project %q, env %q, component %q", pipeline, project, env, component) - return cyout.PrintWithOptions(cmd, outPipeline, err, errMsg, pipelineTableOptions) -} diff --git a/cmd/cycloid/pipelines/pipeline_last_used.go b/cmd/cycloid/pipelines/pipeline_last_used.go deleted file mode 100644 index 86ed86c02..000000000 --- a/cmd/cycloid/pipelines/pipeline_last_used.go +++ /dev/null @@ -1,119 +0,0 @@ -package pipelines - -import ( - "slices" - "time" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewPipelineLastUsedCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "last-used", - Short: "output the last trigger date of all pipelines in the selected organization.", - Example: `cy pipelines last-used --since-days 10`, - RunE: lastUsed, - Args: cobra.NoArgs, - } - - cmd.PersistentFlags().Int64P("since-days", "s", 0, "filter pipelines that didn't ran since x days.") - return cmd -} - -type LastUsedPipeline struct { - PipelineName string - Project string - Environment string - Component string - LastUsed LastUsed -} - -type LastUsed struct { - Timestamp uint64 - DateRFC3339 string -} - -func lastUsed(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - sinceDays, err := cmd.Flags().GetInt64("since-days") - if err != nil { - return err - } - - var result = []LastUsedPipeline{} - maxTimestamp := uint64(0) - pps, _, err := m.GetOrgPipelines(org, nil, nil, nil, nil) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "failed to list pipelines", printer.Options{}) - } - - for _, pipeline := range pps { - lastestJob := slices.MaxFunc(pipeline.Jobs, func(a, b *models.Job) int { - if a.FinishedBuild == nil && b.FinishedBuild == nil { - return int(maxTimestamp) - } else if a.FinishedBuild == nil && b.FinishedBuild != nil { - return int(b.FinishedBuild.StartTime) - } else if a.FinishedBuild != nil && b.FinishedBuild == nil { - return int(a.FinishedBuild.StartTime) - } - - if a.FinishedBuild.StartTime > b.FinishedBuild.StartTime { - return int(a.FinishedBuild.StartTime) - } - - return int(b.FinishedBuild.StartTime) - }) - - if pipeline.Name == nil { - return errors.Errorf("Missing pipeline name in:\n%v", pipeline) - } - - if pipeline.Project == nil { - return errors.Errorf("Missing pipeline project in:\n%v", pipeline) - } - - if pipeline.Environment == nil { - return errors.Errorf("Missing pipeline environment in:\n%v", pipeline) - } - - if pipeline.Component == nil { - return errors.Errorf("Missing pipeline component in:\n%v", pipeline) - } - - lastUsedTimestamp := maxTimestamp - if lastestJob.FinishedBuild != nil { - lastUsedTimestamp = lastestJob.FinishedBuild.StartTime - } - - timestamp := time.Unix(int64(lastUsedTimestamp), 0) - - if timestamp.Unix() < (time.Now().Unix() - (sinceDays * 60 * 60 * 24)) { - result = append(result, LastUsedPipeline{ - PipelineName: *pipeline.Name, - Project: *pipeline.Project.Canonical, - Environment: *pipeline.Environment.Canonical, - Component: *pipeline.Component.Canonical, - LastUsed: LastUsed{ - Timestamp: lastUsedTimestamp, - DateRFC3339: timestamp.Format(time.RFC3339), - }, - }) - } - } - - return cyout.PrintWithOptions(cmd, result, nil, "unable to list pipelines", printer.Options{}) -} diff --git a/cmd/cycloid/pipelines/pipeline_list.go b/cmd/cycloid/pipelines/pipeline_list.go deleted file mode 100644 index ab3e14f7e..000000000 --- a/cmd/cycloid/pipelines/pipeline_list.go +++ /dev/null @@ -1,46 +0,0 @@ -package pipelines - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewPipelineListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Short: "list all pipelines of the organization", - Args: cobra.NoArgs, - RunE: list, - } - - cyargs.AddProjectFlag(cmd) - cyargs.AddEnvFlag(cmd) - cyargs.AddPipelineStatuses(cmd) - cyargs.AddPipeline(cmd) - cyout.RegisterModel(cmd, models.Pipeline{}) - return cmd -} - -func list(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - // Those args are filters and optional - project, _ := cyargs.GetProject(cmd) - env, _ := cyargs.GetEnv(cmd) - statuses, _ := cyargs.GetPipelineStatuses(cmd) - pipelineName, _ := cyargs.GetPipeline(cmd) - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - pps, _, err := m.GetOrgPipelines(org, &pipelineName, &project, &env, statuses) - return cyout.PrintWithOptions(cmd, pps, err, "unable to list pipelines", pipelineTableOptions) -} diff --git a/cmd/cycloid/pipelines/pipeline_pause.go b/cmd/cycloid/pipelines/pipeline_pause.go deleted file mode 100644 index 276527e0b..000000000 --- a/cmd/cycloid/pipelines/pipeline_pause.go +++ /dev/null @@ -1,43 +0,0 @@ -package pipelines - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewPipelinePauseCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "pause", - Short: "pause a pipeline", - Example: `cy --org my-org pipeline pause --project my-project --env env --component component --pipeline pipeline-name`, - RunE: pause, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - return cmd -} - -func pause(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - _, err = m.PausePipeline(org, project, env, component, pipeline) - return cyout.PrintWithOptions(cmd, nil, err, "failed to pause pipeline", printer.Options{}) -} diff --git a/cmd/cycloid/pipelines/pipeline_synced.go b/cmd/cycloid/pipelines/pipeline_synced.go deleted file mode 100644 index 3d348069d..000000000 --- a/cmd/cycloid/pipelines/pipeline_synced.go +++ /dev/null @@ -1,43 +0,0 @@ -package pipelines - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewPipelineSyncedCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "synced", - Short: "Check if a pipeline is synced with its stacks.", - Example: `cy --org my-org pipeline synced --project my-project --env env`, - RunE: synced, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - return cmd -} - -func synced(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - pp, _, err := m.SyncedPipeline(org, project, env, component, pipeline) - return cyout.PrintWithOptions(cmd, pp, err, "unable to pipeline sync status", printer.Options{}) -} diff --git a/cmd/cycloid/pipelines/pipeline_unpause.go b/cmd/cycloid/pipelines/pipeline_unpause.go deleted file mode 100644 index d6ee2bc53..000000000 --- a/cmd/cycloid/pipelines/pipeline_unpause.go +++ /dev/null @@ -1,43 +0,0 @@ -package pipelines - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewPipelineUnpauseCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "unpause", - Short: "unpause a pipeline", - Example: `cy --org my-org pipeline unpause --project my-project --env env --component component --pipeline pipeline-name`, - RunE: unpause, - Args: cobra.NoArgs, - } - - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - return cmd -} - -func unpause(cmd *cobra.Command, args []string) error { - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - _, err = m.UnpausePipeline(org, project, env, component, pipeline) - return cyout.PrintWithOptions(cmd, nil, err, "failed to unpause pipeline", printer.Options{}) -} diff --git a/cmd/cycloid/pipelines/pipeline_update.go b/cmd/cycloid/pipelines/pipeline_update.go deleted file mode 100644 index ede26d61e..000000000 --- a/cmd/cycloid/pipelines/pipeline_update.go +++ /dev/null @@ -1,70 +0,0 @@ -package pipelines - -import ( - "os" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewPipelineUpdateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "update", - Short: "update a running pipeline", - Example: ` - # update a running pipeline - cy --org my-org pp update --project my-project --env my-env --vars /path/to/vars.yml --pipeline /path/to/pipeline.yml -`, - RunE: update, - Args: cobra.NoArgs, - } - cyargs.AddCyContext(cmd) - cyargs.AddPipeline(cmd) - cyargs.AddPipelineConfig(cmd) - cyargs.AddPipelineVars(cmd) - return cmd -} - -func update(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, project, env, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - pipeline, err := cyargs.GetPipeline(cmd) - if err != nil { - return err - } - - pipelinePath, err := cyargs.GetPipelineConfig(cmd) - if err != nil { - return err - } - - pipelineVarsPath, err := cyargs.GetPipelineVars(cmd) - if err != nil { - return err - } - - rawPipeline, err := os.ReadFile(pipelinePath) - if err != nil { - return errors.Wrap(err, "unable to read pipeline file") - } - - rawVars, err := os.ReadFile(pipelineVarsPath) - if err != nil { - return errors.Wrap(err, "unable to read variables file") - } - - resp, _, err := m.UpdatePipeline(org, project, env, component, pipeline, string(rawPipeline), string(rawVars), false) - return cyout.PrintWithOptions(cmd, resp, err, "unable to update pipeline", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/cmd.go b/cmd/cycloid/plugins/cmd.go deleted file mode 100644 index 2763b7cde..000000000 --- a/cmd/cycloid/plugins/cmd.go +++ /dev/null @@ -1,78 +0,0 @@ -package plugins - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/plugins/component" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/plugins/manager" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/plugins/registry" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/plugins/widget" -) - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "plugin", - Aliases: []string{"plugins"}, - Short: "Manage plugins", - Long: `Manage plugins in your organization. - -Concepts and dependency order: - - Registry An external source of plugins (Docker-registry-compatible). - Must exist before any plugin can be installed. - → cy plugin registry - - Plugin A plugin definition published to a registry. Has a name, - description, and one or more versions. - → cy plugin registry plugin - - Version A specific release of a plugin. Bundles a Docker image and - a manifest that declares: required configuration fields, - widgets (UI panels), and data queries. - → cy plugin registry plugin version - - Manager The agent that deploys and runs plugin containers in your - infrastructure. Required before the first install. - → cy plugin manager - - Install Running instance of a plugin version, deployed by the manager - with org-specific configuration (API keys, endpoints, etc.). - This is what appears in 'cy plugin list'. - → cy plugin registry plugin version install - - Widget A UI panel backed by a running plugin. Each widget wraps one - pre-configured query from the plugin manifest. Widgets are - created automatically from the manifest on install. - → cy plugin widget - -To install a plugin for the first time: - - # 1. Add a registry - cy plugin registry add --url https://registry.example.com - - # 2. Browse available plugins and versions - cy plugin registry plugin list my-registry - cy plugin registry plugin version list my-registry my-plugin - - # 3. Install (configuration keys are declared in the version manifest) - cy plugin registry plugin version install my-registry my-plugin \ - --config api_url=https://api.example.com \ - --config api_token=secret - -Once installed, use 'cy plugin upgrade' to change version or reconfigure, -and 'cy plugin uninstall' to remove.`, - } - - cmd.AddCommand( - NewListCommand(), - NewGetCommand(), - NewUpgradeCommand(), - NewUninstallCommand(), - NewLogsCommand(), - component.NewCommands(), - manager.NewCommands(), - registry.NewCommands(), - widget.NewCommands(), - ) - return cmd -} diff --git a/cmd/cycloid/plugins/component/cmd.go b/cmd/cycloid/plugins/component/cmd.go deleted file mode 100644 index 1a7ba2b6f..000000000 --- a/cmd/cycloid/plugins/component/cmd.go +++ /dev/null @@ -1,22 +0,0 @@ -package component - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/plugins/component/widget" -) - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "component", - Aliases: []string{"components"}, - Short: "Manage component-plugin relations", - } - - cmd.AddCommand( - NewListCommand(), - NewRelationSetCommand(), - widget.NewCommands(), - ) - return cmd -} diff --git a/cmd/cycloid/plugins/component/list.go b/cmd/cycloid/plugins/component/list.go deleted file mode 100644 index c324adcff..000000000 --- a/cmd/cycloid/plugins/component/list.go +++ /dev/null @@ -1,56 +0,0 @@ -package component - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "List plugins available to a component", - Example: ` - cy plugin component list --project my-project --env production --component my-component -`, - RunE: listComponentPlugins, - } - - cyargs.AddProjectFlag(cmd) - cyargs.AddEnvFlag(cmd) - cyargs.AddComponentFlag(cmd) - return cmd -} - -func listComponentPlugins(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProject(cmd) - if err != nil { - return err - } - - env, err := cyargs.GetEnv(cmd) - if err != nil { - return err - } - - component, err := cyargs.GetComponent(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, _, err := m.ListComponentPlugins(org, project, env, component) - return cyout.PrintWithOptions(cmd, result, err, "unable to list component plugins", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/component/relation_set.go b/cmd/cycloid/plugins/component/relation_set.go deleted file mode 100644 index 39e9d20d6..000000000 --- a/cmd/cycloid/plugins/component/relation_set.go +++ /dev/null @@ -1,69 +0,0 @@ -package component - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewRelationSetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "relation-set ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginInstallID, - Short: "Enable or disable a plugin for a component", - Example: ` - cy plugin component relation-set my-plugin --project my-project --env production --component my-component --enabled - cy plugin component relation-set 42 --project my-project --env production --component my-component --no-enabled -`, - RunE: setComponentPluginRelation, - } - - cyargs.AddProjectFlag(cmd) - cyargs.AddEnvFlag(cmd) - cyargs.AddComponentFlag(cmd) - cmd.Flags().Bool("enabled", true, "Enable or disable the plugin for the component") - return cmd -} - -func setComponentPluginRelation(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProject(cmd) - if err != nil { - return err - } - - env, err := cyargs.GetEnv(cmd) - if err != nil { - return err - } - - component, err := cyargs.GetComponent(cmd) - if err != nil { - return err - } - - enabled, err := cmd.Flags().GetBool("enabled") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - pluginInstallID, err := cyargs.ResolvePluginInstallID(org, args[0], m) - if err != nil { - return err - } - - result, _, err := m.SetComponentPluginRelation(org, project, env, component, pluginInstallID, enabled) - return cyout.PrintWithOptions(cmd, result, err, "unable to set component plugin relation", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/component/widget/cmd.go b/cmd/cycloid/plugins/component/widget/cmd.go deleted file mode 100644 index d7fe8d662..000000000 --- a/cmd/cycloid/plugins/component/widget/cmd.go +++ /dev/null @@ -1,19 +0,0 @@ -package widget - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "widget", - Aliases: []string{"widgets"}, - Short: "Manage component-level plugin widgets", - } - - cmd.AddCommand( - NewListCommand(), - NewQueryCommand(), - ) - return cmd -} diff --git a/cmd/cycloid/plugins/component/widget/list.go b/cmd/cycloid/plugins/component/widget/list.go deleted file mode 100644 index 7b8925017..000000000 --- a/cmd/cycloid/plugins/component/widget/list.go +++ /dev/null @@ -1,56 +0,0 @@ -package widget - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "List plugin widgets for a component", - Example: ` - cy plugin component widget list --project my-project --env production --component my-component -`, - RunE: listComponentPluginWidgets, - } - - cyargs.AddProjectFlag(cmd) - cyargs.AddEnvFlag(cmd) - cyargs.AddComponentFlag(cmd) - return cmd -} - -func listComponentPluginWidgets(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProject(cmd) - if err != nil { - return err - } - - env, err := cyargs.GetEnv(cmd) - if err != nil { - return err - } - - component, err := cyargs.GetComponent(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, _, err := m.ListComponentPluginWidgets(org, project, env, component) - return cyout.PrintWithOptions(cmd, result, err, "unable to list component plugin widgets", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/component/widget/query.go b/cmd/cycloid/plugins/component/widget/query.go deleted file mode 100644 index 0bce73409..000000000 --- a/cmd/cycloid/plugins/component/widget/query.go +++ /dev/null @@ -1,65 +0,0 @@ -package widget - -import ( - "fmt" - "strconv" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewQueryCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "query ", - Args: cobra.ExactArgs(1), - Short: "Query data for a component-level plugin widget", - Example: ` - cy plugin component widget query 42 --project my-project --env production --component my-component -`, - RunE: queryComponentPluginWidget, - } - - cyargs.AddProjectFlag(cmd) - cyargs.AddEnvFlag(cmd) - cyargs.AddComponentFlag(cmd) - return cmd -} - -func queryComponentPluginWidget(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProject(cmd) - if err != nil { - return err - } - - env, err := cyargs.GetEnv(cmd) - if err != nil { - return err - } - - component, err := cyargs.GetComponent(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - n, err := strconv.ParseUint(args[0], 10, 32) - if err != nil { - return fmt.Errorf("invalid widget-id %q: must be a positive integer", args[0]) - } - widgetID := uint32(n) - - result, _, err := m.QueryComponentPluginWidget(org, project, env, component, widgetID) - return cyout.PrintWithOptions(cmd, result, err, "unable to query component plugin widget", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/get.go b/cmd/cycloid/plugins/get.go deleted file mode 100644 index f8a274822..000000000 --- a/cmd/cycloid/plugins/get.go +++ /dev/null @@ -1,43 +0,0 @@ -package plugins - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewGetCommand() *cobra.Command { - return &cobra.Command{ - Use: "get ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginInstallID, - Short: "Get a plugin install", - Example: ` - cy plugin get 42 - cy plugin get my-plugin -`, - RunE: getPlugin, - } -} - -func getPlugin(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - id, err := cyargs.ResolvePluginInstallID(org, args[0], m) - if err != nil { - return err - } - - result, _, err := m.GetPlugin(org, id) - return cyout.PrintWithOptions(cmd, result, err, "unable to get plugin", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/list.go b/cmd/cycloid/plugins/list.go deleted file mode 100644 index f2f7074e4..000000000 --- a/cmd/cycloid/plugins/list.go +++ /dev/null @@ -1,37 +0,0 @@ -package plugins - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListCommand() *cobra.Command { - return &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "List installed plugins", - Example: ` - # List installed plugins in my-org - cy plugin list --org my-org -`, - RunE: listPlugins, - } -} - -func listPlugins(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, _, err := m.ListPlugins(org) - return cyout.PrintWithOptions(cmd, result, err, "unable to list plugins", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/logs.go b/cmd/cycloid/plugins/logs.go deleted file mode 100644 index 3395fc624..000000000 --- a/cmd/cycloid/plugins/logs.go +++ /dev/null @@ -1,112 +0,0 @@ -package plugins - -import ( - "fmt" - "time" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewLogsCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "logs ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginInstallID, - Short: "Show deployment logs for a plugin install", - Long: `Show deployment and runtime logs for a plugin install. - -Use --watch (-w) to poll continuously for new log entries. Useful for -following an ongoing deployment. Ctrl-C to stop.`, - Example: ` - cy plugin logs 42 - cy plugin logs my-plugin - - # Follow logs as they arrive (poll every 5s) - cy plugin logs my-plugin --watch - - # Custom polling interval - cy plugin logs my-plugin --watch --watch-interval 10s -`, - RunE: pluginLogs, - } - cmd.Flags().BoolP("watch", "w", false, "Poll for new log entries until interrupted") - cmd.Flags().Duration("watch-interval", 5*time.Second, "Polling interval when --watch is set") - return cmd -} - -func pluginLogs(cmd *cobra.Command, args []string) error { - watch, err := cmd.Flags().GetBool("watch") - if err != nil { - return err - } - interval, err := cmd.Flags().GetDuration("watch-interval") - if err != nil { - return err - } - if interval < 500*time.Millisecond { - return fmt.Errorf("--watch-interval must be at least 500ms, got %s", interval) - } - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - id, err := cyargs.ResolvePluginInstallID(org, args[0], m) - if err != nil { - return err - } - - if !watch { - result, _, err := m.ListPluginLogs(org, id) - return cyout.PrintWithOptions(cmd, result, err, "unable to get plugin logs", printer.Options{}) - } - - // Watch mode: poll and print only new entries. - var seenInstall, seenRuntime int - for { - result, _, err := m.ListPluginLogs(org, id) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to get plugin logs", printer.Options{}) - } - if result != nil { - newInstall, newRuntime := logSlicesDelta(result, seenInstall, seenRuntime) - if len(newInstall) > 0 || len(newRuntime) > 0 { - partial := &models.PluginLogs{ - InstallLogs: newInstall, - RuntimeLogs: newRuntime, - } - if printErr := cyout.PrintWithOptions(cmd, partial, nil, "", printer.Options{}); printErr != nil { - return printErr - } - seenInstall += len(newInstall) - seenRuntime += len(newRuntime) - } - } - time.Sleep(interval) - } -} - -// logSlicesDelta returns the unseen portion of each log slice. -func logSlicesDelta(logs *models.PluginLogs, seenInstall, seenRuntime int) ([]*models.PluginInstallDeploymentLog, []*models.PluginInstallRuntimeLog) { - var newInstall []*models.PluginInstallDeploymentLog - var newRuntime []*models.PluginInstallRuntimeLog - - if seenInstall < len(logs.InstallLogs) { - newInstall = logs.InstallLogs[seenInstall:] - } - if seenRuntime < len(logs.RuntimeLogs) { - newRuntime = logs.RuntimeLogs[seenRuntime:] - } - return newInstall, newRuntime -} diff --git a/cmd/cycloid/plugins/manager/accept.go b/cmd/cycloid/plugins/manager/accept.go deleted file mode 100644 index a92aeba1e..000000000 --- a/cmd/cycloid/plugins/manager/accept.go +++ /dev/null @@ -1,47 +0,0 @@ -package manager - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewAcceptCommand() *cobra.Command { - return &cobra.Command{ - Use: "accept ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginManagerID, - Short: "Accept a plugin manager invitation", - Example: ` - cy plugin manager accept 1 - cy plugin manager accept my-manager -`, - RunE: acceptPluginManager, - } -} - -func acceptPluginManager(cmd *cobra.Command, args []string) error { - return updateInviteStatus(cmd, args, "accepted") -} - -func updateInviteStatus(cmd *cobra.Command, args []string, status string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - id, err := cyargs.ResolvePluginManagerID(org, args[0], m) - if err != nil { - return err - } - - result, _, err := m.UpdatePluginManager(org, id, status) - return cyout.PrintWithOptions(cmd, result, err, "unable to update plugin manager", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/manager/cmd.go b/cmd/cycloid/plugins/manager/cmd.go deleted file mode 100644 index 83c07e0f5..000000000 --- a/cmd/cycloid/plugins/manager/cmd.go +++ /dev/null @@ -1,21 +0,0 @@ -package manager - -import "github.com/spf13/cobra" - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "manager", - Aliases: []string{"managers"}, - Short: "Manage plugin managers", - } - - cmd.AddCommand( - NewListCommand(), - NewGetCommand(), - NewCreateCommand(), - NewAcceptCommand(), - NewRejectCommand(), - NewDeleteCommand(), - ) - return cmd -} diff --git a/cmd/cycloid/plugins/manager/create.go b/cmd/cycloid/plugins/manager/create.go deleted file mode 100644 index 0c289d6bf..000000000 --- a/cmd/cycloid/plugins/manager/create.go +++ /dev/null @@ -1,82 +0,0 @@ -package manager - -import ( - "fmt" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "create", - Args: cobra.NoArgs, - Short: "Register a plugin manager with the organization", - Example: ` - cy plugin manager create --name my-manager --url https://pm.example.com - cy plugin manager create --name my-manager --url https://pm.example.com --update -`, - RunE: createPluginManager, - } - - _ = cmd.MarkFlagRequired(cyargs.AddNameFlag(cmd)) - cyargs.AddURLFlag(cmd, "URL of the plugin manager instance (required)") - _ = cmd.MarkFlagRequired("url") - cmd.Flags().Bool("update", false, "if the plugin manager already exists, return it without failing (idempotent create)") - return cmd -} - -func createPluginManager(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - url, err := cyargs.GetURL(cmd) - if err != nil { - return errors.Wrap(err, "unable to get --url flag") - } - - update, err := cmd.Flags().GetBool("update") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // Check if a manager with this name already exists. - existingID, resolveErr := cyargs.ResolvePluginManagerID(org, name, m) - exists := resolveErr == nil - if resolveErr != nil && !cyargs.IsNoMatchError(resolveErr) { - return cyout.PrintWithOptions(cmd, nil, resolveErr, "failed to check if plugin manager exists", printer.Options{}) - } - - if exists && !update { - return cyout.PrintWithOptions(cmd, nil, - fmt.Errorf("plugin manager %q already exists; use --update for an idempotent create", name), - "unable to create plugin manager", printer.Options{}) - } - - if exists { - if cmd.Flags().Changed("url") { - fmt.Fprintln(cmd.ErrOrStderr(), "note: --url cannot be changed via the API; existing URL is kept") - } - result, _, err := m.GetPluginManager(org, existingID) - return cyout.PrintWithOptions(cmd, result, err, "unable to get existing plugin manager", printer.Options{}) - } - - result, _, err := m.CreatePluginManager(org, name, url, true) - return cyout.PrintWithOptions(cmd, result, err, "unable to create plugin manager", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/manager/delete.go b/cmd/cycloid/plugins/manager/delete.go deleted file mode 100644 index 0cca0fcfc..000000000 --- a/cmd/cycloid/plugins/manager/delete.go +++ /dev/null @@ -1,49 +0,0 @@ -package manager - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewDeleteCommand() *cobra.Command { - return &cobra.Command{ - Use: "delete ...", - Args: cobra.MinimumNArgs(1), - ValidArgsFunction: cyargs.CompletePluginManagerID, - Short: "Delete a plugin manager", - Example: ` - cy plugin manager delete 1 - cy plugin manager delete my-manager - cy plugin manager delete my-manager-a my-manager-b -`, - RunE: deletePluginManager, - } -} - -func deletePluginManager(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - for _, arg := range args { - id, err := cyargs.ResolvePluginManagerID(org, arg, m) - if err != nil { - return err - } - - _, err = m.DeletePluginManager(org, id) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to delete plugin manager "+arg, printer.Options{}) - } - } - return cyout.PrintWithOptions(cmd, nil, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/manager/get.go b/cmd/cycloid/plugins/manager/get.go deleted file mode 100644 index 896be864a..000000000 --- a/cmd/cycloid/plugins/manager/get.go +++ /dev/null @@ -1,43 +0,0 @@ -package manager - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewGetCommand() *cobra.Command { - return &cobra.Command{ - Use: "get ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginManagerID, - Short: "Get a plugin manager", - Example: ` - cy plugin manager get 1 - cy plugin manager get my-manager -`, - RunE: getPluginManager, - } -} - -func getPluginManager(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - id, err := cyargs.ResolvePluginManagerID(org, args[0], m) - if err != nil { - return err - } - - result, _, err := m.GetPluginManager(org, id) - return cyout.PrintWithOptions(cmd, result, err, "unable to get plugin manager", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/manager/list.go b/cmd/cycloid/plugins/manager/list.go deleted file mode 100644 index c2e529bd2..000000000 --- a/cmd/cycloid/plugins/manager/list.go +++ /dev/null @@ -1,36 +0,0 @@ -package manager - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListCommand() *cobra.Command { - return &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "List plugin managers", - Example: ` - cy plugin manager list --org my-org -`, - RunE: listPluginManagers, - } -} - -func listPluginManagers(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, _, err := m.ListPluginManagers(org) - return cyout.PrintWithOptions(cmd, result, err, "unable to list plugin managers", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/manager/reject.go b/cmd/cycloid/plugins/manager/reject.go deleted file mode 100644 index 71ae6fe67..000000000 --- a/cmd/cycloid/plugins/manager/reject.go +++ /dev/null @@ -1,25 +0,0 @@ -package manager - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/internal/cyargs" -) - -func NewRejectCommand() *cobra.Command { - return &cobra.Command{ - Use: "reject ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginManagerID, - Short: "Reject a plugin manager invitation", - Example: ` - cy plugin manager reject 1 - cy plugin manager reject my-manager -`, - RunE: rejectPluginManager, - } -} - -func rejectPluginManager(cmd *cobra.Command, args []string) error { - return updateInviteStatus(cmd, args, "rejected") -} diff --git a/cmd/cycloid/plugins/registry/cmd.go b/cmd/cycloid/plugins/registry/cmd.go deleted file mode 100644 index dadc304fb..000000000 --- a/cmd/cycloid/plugins/registry/cmd.go +++ /dev/null @@ -1,25 +0,0 @@ -package registry - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/plugins/registry/plugin" -) - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "registry", - Aliases: []string{"registries"}, - Short: "Manage plugin registries", - } - - cmd.AddCommand( - NewListCommand(), - NewGetCommand(), - NewCreateCommand(), - NewUpdateCommand(), - NewDeleteCommand(), - plugin.NewCommands(), - ) - return cmd -} diff --git a/cmd/cycloid/plugins/registry/create.go b/cmd/cycloid/plugins/registry/create.go deleted file mode 100644 index afae1681d..000000000 --- a/cmd/cycloid/plugins/registry/create.go +++ /dev/null @@ -1,84 +0,0 @@ -package registry - -import ( - "fmt" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "create", - Aliases: []string{"add"}, - Args: cobra.NoArgs, - Short: "Create a plugin registry", - Example: ` - cy plugin registry create --name my-registry --url https://registry.example.com - cy plugin registry create --name my-registry --url https://registry.example.com --update -`, - RunE: createPluginRegistry, - } - - _ = cmd.MarkFlagRequired(cyargs.AddNameFlag(cmd)) - cyargs.AddURLFlag(cmd, "URL of the plugin registry (required)") - _ = cmd.MarkFlagRequired("url") - cmd.Flags().Bool("update", false, "update the plugin registry if it already exists") - return cmd -} - -func createPluginRegistry(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - url, err := cyargs.GetURL(cmd) - if err != nil { - return errors.Wrap(err, "unable to get --url flag") - } - - update, err := cmd.Flags().GetBool("update") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // Check if a registry with this name already exists. - existingID, resolveErr := cyargs.ResolvePluginRegistryID(org, name, m) - exists := resolveErr == nil - if resolveErr != nil && !cyargs.IsNoMatchError(resolveErr) { - // List failure or ambiguous match — surface it. - return cyout.PrintWithOptions(cmd, nil, resolveErr, "failed to check if plugin registry exists", printer.Options{}) - } - - if exists && !update { - return cyout.PrintWithOptions(cmd, nil, - fmt.Errorf("plugin registry %q already exists; use --update or `cy plugin registry update`", name), - "unable to create plugin registry", printer.Options{}) - } - - if exists { - if cmd.Flags().Changed("url") { - fmt.Fprintln(cmd.ErrOrStderr(), "note: --url cannot be changed via the API; existing URL is kept") - } - result, _, err := m.UpdatePluginRegistry(org, existingID, name) - return cyout.PrintWithOptions(cmd, result, err, "unable to update plugin registry", printer.Options{}) - } - - result, _, err := m.CreatePluginRegistry(org, name, url) - return cyout.PrintWithOptions(cmd, result, err, "unable to create plugin registry", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/delete.go b/cmd/cycloid/plugins/registry/delete.go deleted file mode 100644 index 2276983c4..000000000 --- a/cmd/cycloid/plugins/registry/delete.go +++ /dev/null @@ -1,49 +0,0 @@ -package registry - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewDeleteCommand() *cobra.Command { - return &cobra.Command{ - Use: "delete ...", - Args: cobra.MinimumNArgs(1), - ValidArgsFunction: cyargs.CompletePluginRegistryID, - Short: "Delete a plugin registry", - Example: ` - cy plugin registry delete 1 - cy plugin registry delete my-registry - cy plugin registry delete my-registry-a my-registry-b -`, - RunE: deletePluginRegistry, - } -} - -func deletePluginRegistry(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - for _, arg := range args { - id, err := cyargs.ResolvePluginRegistryID(org, arg, m) - if err != nil { - return err - } - - _, err = m.DeletePluginRegistry(org, id) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to delete plugin registry "+arg, printer.Options{}) - } - } - return cyout.PrintWithOptions(cmd, nil, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/get.go b/cmd/cycloid/plugins/registry/get.go deleted file mode 100644 index 8be715583..000000000 --- a/cmd/cycloid/plugins/registry/get.go +++ /dev/null @@ -1,44 +0,0 @@ -package registry - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewGetCommand() *cobra.Command { - return &cobra.Command{ - Use: "get ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginRegistryID, - Short: "Get a plugin registry", - Example: ` - cy plugin registry get 1 - cy plugin registry get my-registry - cy plugin registry get https://registry.example.com -`, - RunE: getPluginRegistry, - } -} - -func getPluginRegistry(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - id, err := cyargs.ResolvePluginRegistryID(org, args[0], m) - if err != nil { - return err - } - - result, _, err := m.GetPluginRegistry(org, id) - return cyout.PrintWithOptions(cmd, result, err, "unable to get plugin registry", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/list.go b/cmd/cycloid/plugins/registry/list.go deleted file mode 100644 index d3a15daba..000000000 --- a/cmd/cycloid/plugins/registry/list.go +++ /dev/null @@ -1,36 +0,0 @@ -package registry - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListCommand() *cobra.Command { - return &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "List plugin registries", - Example: ` - cy plugin registry list --org my-org -`, - RunE: listPluginRegistries, - } -} - -func listPluginRegistries(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, _, err := m.ListPluginRegistries(org) - return cyout.PrintWithOptions(cmd, result, err, "unable to list plugin registries", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/plugin/cmd.go b/cmd/cycloid/plugins/registry/plugin/cmd.go deleted file mode 100644 index 06b0c14d0..000000000 --- a/cmd/cycloid/plugins/registry/plugin/cmd.go +++ /dev/null @@ -1,25 +0,0 @@ -package plugin - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/plugins/registry/plugin/version" -) - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "plugin", - Aliases: []string{"plugins"}, - Short: "Manage plugins within a registry", - } - - cmd.AddCommand( - NewListCommand(), - NewGetCommand(), - NewCreateCommand(), - NewUpdateCommand(), - NewDeleteCommand(), - version.NewCommands(), - ) - return cmd -} diff --git a/cmd/cycloid/plugins/registry/plugin/create.go b/cmd/cycloid/plugins/registry/plugin/create.go deleted file mode 100644 index 3a75dbcda..000000000 --- a/cmd/cycloid/plugins/registry/plugin/create.go +++ /dev/null @@ -1,77 +0,0 @@ -package plugin - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "create ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginRegistryID, - Short: "Create a plugin in a registry", - Example: ` - cy plugin registry plugin create my-registry --name my-plugin - cy plugin registry plugin create my-registry --name my-plugin --update -`, - RunE: createRegistryPlugin, - } - - _ = cmd.MarkFlagRequired(cyargs.AddNameFlag(cmd)) - cmd.Flags().Bool("update", false, "update the plugin if it already exists in the registry") - return cmd -} - -func createRegistryPlugin(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - update, err := cmd.Flags().GetBool("update") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - registryID, err := cyargs.ResolvePluginRegistryID(org, args[0], m) - if err != nil { - return err - } - - // Check if a plugin with this name already exists in the registry. - existingID, resolveErr := cyargs.ResolveRegistryPluginID(org, registryID, name, m) - exists := resolveErr == nil - if resolveErr != nil && !cyargs.IsNoMatchError(resolveErr) { - return cyout.PrintWithOptions(cmd, nil, resolveErr, "failed to check if registry plugin exists", printer.Options{}) - } - - if exists && !update { - return cyout.PrintWithOptions(cmd, nil, - fmt.Errorf("plugin %q already exists in this registry; use --update or `cy plugin registry plugin update`", name), - "unable to create registry plugin", printer.Options{}) - } - - if exists { - result, _, err := m.UpdateRegistryPlugin(org, registryID, existingID, name) - return cyout.PrintWithOptions(cmd, result, err, "unable to update registry plugin", printer.Options{}) - } - - result, _, err := m.CreateRegistryPlugin(org, registryID, name) - return cyout.PrintWithOptions(cmd, result, err, "unable to create registry plugin", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/plugin/delete.go b/cmd/cycloid/plugins/registry/plugin/delete.go deleted file mode 100644 index 2e7879087..000000000 --- a/cmd/cycloid/plugins/registry/plugin/delete.go +++ /dev/null @@ -1,47 +0,0 @@ -package plugin - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewDeleteCommand() *cobra.Command { - return &cobra.Command{ - Use: "delete ", - Args: cobra.ExactArgs(2), - ValidArgsFunction: cyargs.CompleteRegistryPluginID, - Short: "Delete a plugin from a registry", - Example: ` - cy plugin registry plugin delete my-registry my-plugin -`, - RunE: deleteRegistryPlugin, - } -} - -func deleteRegistryPlugin(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - registryID, err := cyargs.ResolvePluginRegistryID(org, args[0], m) - if err != nil { - return err - } - - pluginID, err := cyargs.ResolveRegistryPluginID(org, registryID, args[1], m) - if err != nil { - return err - } - - _, err = m.DeleteRegistryPlugin(org, registryID, pluginID) - return cyout.PrintWithOptions(cmd, nil, err, "unable to delete registry plugin", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/plugin/get.go b/cmd/cycloid/plugins/registry/plugin/get.go deleted file mode 100644 index e7b4de6f7..000000000 --- a/cmd/cycloid/plugins/registry/plugin/get.go +++ /dev/null @@ -1,72 +0,0 @@ -package plugin - -import ( - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewGetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get ...", - Args: cobra.MinimumNArgs(1), - ValidArgsFunction: cyargs.CompletePluginIDFromRegistryFlag, - Short: "Get one or more plugins from a registry", - Example: ` - cy plugin registry plugin get my-plugin --registry my-registry - cy plugin registry plugin get plugin-a plugin-b --registry my-registry - cy plugin registry plugin get 42 --registry 1 -`, - RunE: getRegistryPlugin, - } - _ = cmd.MarkFlagRequired(cyargs.AddRegistryFlag(cmd)) - return cmd -} - -func getRegistryPlugin(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - registryStr, err := cyargs.GetRegistry(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - registryID, err := cyargs.ResolvePluginRegistryID(org, registryStr, m) - if err != nil { - return err - } - - if len(args) == 1 { - pluginID, err := cyargs.ResolveRegistryPluginID(org, registryID, args[0], m) - if err != nil { - return err - } - result, _, err := m.GetRegistryPlugin(org, registryID, pluginID) - return cyout.PrintWithOptions(cmd, result, err, "unable to get registry plugin", printer.Options{}) - } - - results := make([]*models.Plugin, 0, len(args)) - for _, nameOrID := range args { - pluginID, err := cyargs.ResolveRegistryPluginID(org, registryID, nameOrID, m) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to resolve plugin "+nameOrID, printer.Options{}) - } - p, _, err := m.GetRegistryPlugin(org, registryID, pluginID) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to get plugin "+nameOrID, printer.Options{}) - } - results = append(results, p) - } - return cyout.PrintWithOptions(cmd, results, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/plugin/list.go b/cmd/cycloid/plugins/registry/plugin/list.go deleted file mode 100644 index 64f3a6fa4..000000000 --- a/cmd/cycloid/plugins/registry/plugin/list.go +++ /dev/null @@ -1,43 +0,0 @@ -package plugin - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListCommand() *cobra.Command { - return &cobra.Command{ - Use: "list ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginRegistryID, - Short: "List plugins in a registry", - Example: ` - cy plugin registry plugin list my-registry - cy plugin registry plugin list 1 -`, - RunE: listRegistryPlugins, - } -} - -func listRegistryPlugins(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - registryID, err := cyargs.ResolvePluginRegistryID(org, args[0], m) - if err != nil { - return err - } - - result, _, err := m.ListRegistryPlugins(org, registryID) - return cyout.PrintWithOptions(cmd, result, err, "unable to list registry plugins", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/plugin/update.go b/cmd/cycloid/plugins/registry/plugin/update.go deleted file mode 100644 index 1f49e854d..000000000 --- a/cmd/cycloid/plugins/registry/plugin/update.go +++ /dev/null @@ -1,56 +0,0 @@ -package plugin - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUpdateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "update ", - Args: cobra.ExactArgs(2), - ValidArgsFunction: cyargs.CompleteRegistryPluginID, - Short: "Update a plugin in a registry", - Example: ` - cy plugin registry plugin update my-registry my-plugin --name new-name - cy plugin registry plugin update 1 42 --name renamed -`, - RunE: updateRegistryPlugin, - } - - _ = cmd.MarkFlagRequired(cyargs.AddNameFlag(cmd)) - return cmd -} - -func updateRegistryPlugin(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - registryID, err := cyargs.ResolvePluginRegistryID(org, args[0], m) - if err != nil { - return err - } - - pluginID, err := cyargs.ResolveRegistryPluginID(org, registryID, args[1], m) - if err != nil { - return err - } - - result, _, err := m.UpdateRegistryPlugin(org, registryID, pluginID, name) - return cyout.PrintWithOptions(cmd, result, err, "unable to update registry plugin", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/plugin/version/cmd.go b/cmd/cycloid/plugins/registry/plugin/version/cmd.go deleted file mode 100644 index 12a8175be..000000000 --- a/cmd/cycloid/plugins/registry/plugin/version/cmd.go +++ /dev/null @@ -1,22 +0,0 @@ -package version - -import "github.com/spf13/cobra" - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "version", - Aliases: []string{"versions"}, - Short: "Manage plugin versions within a registry", - } - - cmd.AddCommand( - NewListCommand(), - NewGetCommand(), - NewPublishCommand(), - NewDeleteCommand(), - NewInstallCommand(), - NewLogsCommand(), - NewRetryCommand(), - ) - return cmd -} diff --git a/cmd/cycloid/plugins/registry/plugin/version/delete.go b/cmd/cycloid/plugins/registry/plugin/version/delete.go deleted file mode 100644 index 52447fd29..000000000 --- a/cmd/cycloid/plugins/registry/plugin/version/delete.go +++ /dev/null @@ -1,50 +0,0 @@ -package version - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewDeleteCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "delete ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginVersionID, - Short: "Delete a plugin version", - Example: ` - cy plugin registry plugin version delete 7 --registry my-registry --plugin my-plugin -`, - RunE: deleteVersion, - } - _ = cmd.MarkFlagRequired(cyargs.AddRegistryFlag(cmd)) - _ = cmd.MarkFlagRequired(cyargs.AddPluginFlag(cmd)) - return cmd -} - -func deleteVersion(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - versionID, err := parseVersionID(args[0]) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - registryID, pluginID, err := resolveRegistryAndPlugin(org, cmd, m) - if err != nil { - return err - } - - _, err = m.DeletePluginVersion(org, registryID, pluginID, versionID) - return cyout.PrintWithOptions(cmd, nil, err, "unable to delete plugin version", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/plugin/version/get.go b/cmd/cycloid/plugins/registry/plugin/version/get.go deleted file mode 100644 index b919da74e..000000000 --- a/cmd/cycloid/plugins/registry/plugin/version/get.go +++ /dev/null @@ -1,50 +0,0 @@ -package version - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewGetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginVersionID, - Short: "Get a specific plugin version", - Example: ` - cy plugin registry plugin version get 7 --registry my-registry --plugin my-plugin -`, - RunE: getVersion, - } - _ = cmd.MarkFlagRequired(cyargs.AddRegistryFlag(cmd)) - _ = cmd.MarkFlagRequired(cyargs.AddPluginFlag(cmd)) - return cmd -} - -func getVersion(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - versionID, err := parseVersionID(args[0]) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - registryID, pluginID, err := resolveRegistryAndPlugin(org, cmd, m) - if err != nil { - return err - } - - result, _, err := m.GetPluginVersion(org, registryID, pluginID, versionID) - return cyout.PrintWithOptions(cmd, result, err, "unable to get plugin version", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/plugin/version/helpers.go b/cmd/cycloid/plugins/registry/plugin/version/helpers.go deleted file mode 100644 index 576db30fb..000000000 --- a/cmd/cycloid/plugins/registry/plugin/version/helpers.go +++ /dev/null @@ -1,41 +0,0 @@ -package version - -import ( - "fmt" - "strconv" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" -) - -// resolveRegistryAndPlugin resolves --registry and --plugin flags to their numeric IDs. -func resolveRegistryAndPlugin(org string, cmd *cobra.Command, m middleware.Middleware) (registryID, pluginID uint32, err error) { - registryStr, err := cyargs.GetRegistry(cmd) - if err != nil { - return 0, 0, err - } - registryID, err = cyargs.ResolvePluginRegistryID(org, registryStr, m) - if err != nil { - return 0, 0, err - } - pluginStr, err := cyargs.GetPlugin(cmd) - if err != nil { - return 0, 0, err - } - pluginID, err = cyargs.ResolveRegistryPluginID(org, registryID, pluginStr, m) - if err != nil { - return 0, 0, err - } - return registryID, pluginID, nil -} - -// parseVersionID parses a version ID string to uint32. -func parseVersionID(s string) (uint32, error) { - n, err := strconv.ParseUint(s, 10, 32) - if err != nil { - return 0, fmt.Errorf("invalid version ID %q: must be a positive integer", s) - } - return uint32(n), nil -} diff --git a/cmd/cycloid/plugins/registry/plugin/version/install.go b/cmd/cycloid/plugins/registry/plugin/version/install.go deleted file mode 100644 index d14f0ea36..000000000 --- a/cmd/cycloid/plugins/registry/plugin/version/install.go +++ /dev/null @@ -1,112 +0,0 @@ -package version - -import ( - "net/http" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewInstallCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "install ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginVersionID, - Short: "Install a plugin version into your organization", - Long: `Install a specific plugin version into your organization. - -This deploys the plugin container via the plugin manager and registers the -plugin as a running install in your org. The version's manifest declares which -configuration fields are required — check them first with: - - cy plugin registry plugin version get --registry --plugin - -Configuration is supplied as key=value pairs (--config) or as a JSON file -(--config-file). Both can be combined: the file provides base values and ---config flags override individual keys. This is useful in CI/CD pipelines -where non-secret config lives in a committed file and secrets are injected -at runtime. - -Once installed, the plugin appears in 'cy plugin list' and its widgets become -available under 'cy plugin widget list'. Use 'cy plugin upgrade' to change -version or update configuration. Use 'cy plugin uninstall' to remove it. - -A plugin manager must be configured and accepted before running this command. -See 'cy plugin manager --help'. - -Use --retry to make the install idempotent: if the plugin version is already -installed, the command retries the installation instead of failing. Safe to use -in CI/CD pipelines where the command may run more than once.`, - Example: ` - # List versions to find the one you want - cy plugin registry plugin version list --registry my-registry --plugin my-plugin - - # Check what configuration fields a version requires - cy plugin registry plugin version get 7 --registry my-registry --plugin my-plugin - - # Install with inline configuration - cy plugin registry plugin version install 7 \ - --registry my-registry --plugin my-plugin \ - --config api_url=https://api.example.com \ - --config api_token=secret - - # Install with a config file (non-secret values committed to repo) - cy plugin registry plugin version install 7 \ - --registry my-registry --plugin my-plugin \ - --config-file ./plugin-config.json \ - --config api_token=secret - - # Idempotent install (safe to run in CI/CD pipelines) - cy plugin registry plugin version install 7 \ - --registry my-registry --plugin my-plugin \ - --config-file ./plugin-config.json --retry -`, - RunE: installVersion, - } - _ = cmd.MarkFlagRequired(cyargs.AddRegistryFlag(cmd)) - _ = cmd.MarkFlagRequired(cyargs.AddPluginFlag(cmd)) - cyargs.AddPluginConfigFlags(cmd) - cmd.Flags().Bool("retry", false, "If the plugin version is already installed, retry the installation instead of failing") - return cmd -} - -func installVersion(cmd *cobra.Command, args []string) error { - retry, err := cmd.Flags().GetBool("retry") - if err != nil { - return err - } - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - versionID, err := parseVersionID(args[0]) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - registryID, pluginID, err := resolveRegistryAndPlugin(org, cmd, m) - if err != nil { - return err - } - - configuration, err := cyargs.GetPluginConfig(cmd) - if err != nil { - return err - } - - resp, installErr := m.InstallPluginVersion(org, registryID, pluginID, versionID, configuration) - if installErr != nil && retry && resp != nil && resp.StatusCode == http.StatusConflict { - _, installErr = m.RetryPluginVersion(org, registryID, pluginID, versionID) - } - return cyout.PrintWithOptions(cmd, nil, installErr, "unable to trigger plugin version install", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/plugin/version/list.go b/cmd/cycloid/plugins/registry/plugin/version/list.go deleted file mode 100644 index 3b5c60a72..000000000 --- a/cmd/cycloid/plugins/registry/plugin/version/list.go +++ /dev/null @@ -1,45 +0,0 @@ -package version - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - ValidArgsFunction: cyargs.CompletePluginVersionID, - Short: "List versions of a plugin", - Example: ` - cy plugin registry plugin version list --registry my-registry --plugin my-plugin -`, - RunE: listVersions, - } - _ = cmd.MarkFlagRequired(cyargs.AddRegistryFlag(cmd)) - _ = cmd.MarkFlagRequired(cyargs.AddPluginFlag(cmd)) - return cmd -} - -func listVersions(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - registryID, pluginID, err := resolveRegistryAndPlugin(org, cmd, m) - if err != nil { - return err - } - - result, _, err := m.ListPluginVersions(org, registryID, pluginID) - return cyout.PrintWithOptions(cmd, result, err, "unable to list plugin versions", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/plugin/version/logs.go b/cmd/cycloid/plugins/registry/plugin/version/logs.go deleted file mode 100644 index bddabb838..000000000 --- a/cmd/cycloid/plugins/registry/plugin/version/logs.go +++ /dev/null @@ -1,50 +0,0 @@ -package version - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewLogsCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "logs ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginVersionID, - Short: "Show installation logs for a plugin version", - Example: ` - cy plugin registry plugin version logs 7 --registry my-registry --plugin my-plugin -`, - RunE: versionLogs, - } - _ = cmd.MarkFlagRequired(cyargs.AddRegistryFlag(cmd)) - _ = cmd.MarkFlagRequired(cyargs.AddPluginFlag(cmd)) - return cmd -} - -func versionLogs(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - versionID, err := parseVersionID(args[0]) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - registryID, pluginID, err := resolveRegistryAndPlugin(org, cmd, m) - if err != nil { - return err - } - - result, _, err := m.ListPluginVersionLogs(org, registryID, pluginID, versionID) - return cyout.PrintWithOptions(cmd, result, err, "unable to get plugin version logs", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/plugin/version/publish.go b/cmd/cycloid/plugins/registry/plugin/version/publish.go deleted file mode 100644 index cd7656533..000000000 --- a/cmd/cycloid/plugins/registry/plugin/version/publish.go +++ /dev/null @@ -1,75 +0,0 @@ -package version - -import ( - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewPublishCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "publish", - Args: cobra.NoArgs, - ValidArgsFunction: cyargs.CompletePluginVersionID, - Short: "Publish a new version of a plugin", - Example: ` - # Publish an archive-based plugin version - cy plugin registry plugin version publish --registry my-registry --plugin my-plugin --url https://example.com/plugin-v1.2.tar.gz - - # Publish a Docker image-based plugin version - cy plugin registry plugin version publish --registry my-registry --plugin my-plugin --docker-image docker-registry:5000/org/plugin:42 -`, - RunE: publishVersion, - } - - _ = cmd.MarkFlagRequired(cyargs.AddRegistryFlag(cmd)) - _ = cmd.MarkFlagRequired(cyargs.AddPluginFlag(cmd)) - cyargs.AddURLFlag(cmd, "URL of the plugin version archive (mutually exclusive with --docker-image)") - cyargs.AddDockerImageFlag(cmd) - return cmd -} - -func publishVersion(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - url, err := cyargs.GetURL(cmd) - if err != nil { - return errors.Wrap(err, "unable to get --url flag") - } - - dockerImage, err := cyargs.GetDockerImage(cmd) - if err != nil { - return errors.Wrap(err, "unable to get --docker-image flag") - } - - if url == "" && dockerImage == "" { - return errors.New("one of --url or --docker-image is required") - } - if url != "" && dockerImage != "" { - return errors.New("--url and --docker-image are mutually exclusive") - } - - versionURL := url - if dockerImage != "" { - versionURL = dockerImage - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - registryID, pluginID, err := resolveRegistryAndPlugin(org, cmd, m) - if err != nil { - return err - } - - result, _, err := m.CreatePluginVersion(org, registryID, pluginID, versionURL) - return cyout.PrintWithOptions(cmd, result, err, "unable to publish plugin version", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/plugin/version/retry.go b/cmd/cycloid/plugins/registry/plugin/version/retry.go deleted file mode 100644 index a779f592a..000000000 --- a/cmd/cycloid/plugins/registry/plugin/version/retry.go +++ /dev/null @@ -1,50 +0,0 @@ -package version - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewRetryCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "retry ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginVersionID, - Short: "Retry a failed plugin version installation", - Example: ` - cy plugin registry plugin version retry 7 --registry my-registry --plugin my-plugin -`, - RunE: retryVersion, - } - _ = cmd.MarkFlagRequired(cyargs.AddRegistryFlag(cmd)) - _ = cmd.MarkFlagRequired(cyargs.AddPluginFlag(cmd)) - return cmd -} - -func retryVersion(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - versionID, err := parseVersionID(args[0]) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - registryID, pluginID, err := resolveRegistryAndPlugin(org, cmd, m) - if err != nil { - return err - } - - _, err = m.RetryPluginVersion(org, registryID, pluginID, versionID) - return cyout.PrintWithOptions(cmd, nil, err, "unable to retry plugin version install", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/registry/update.go b/cmd/cycloid/plugins/registry/update.go deleted file mode 100644 index bea5e1305..000000000 --- a/cmd/cycloid/plugins/registry/update.go +++ /dev/null @@ -1,51 +0,0 @@ -package registry - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUpdateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "update ", - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginRegistryID, - Short: "Update a plugin registry", - Example: ` - cy plugin registry update 1 --name new-name - cy plugin registry update my-registry --name renamed -`, - RunE: updatePluginRegistry, - } - - _ = cmd.MarkFlagRequired(cyargs.AddNameFlag(cmd)) - return cmd -} - -func updatePluginRegistry(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - id, err := cyargs.ResolvePluginRegistryID(org, args[0], m) - if err != nil { - return err - } - - result, _, err := m.UpdatePluginRegistry(org, id, name) - return cyout.PrintWithOptions(cmd, result, err, "unable to update plugin registry", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/uninstall.go b/cmd/cycloid/plugins/uninstall.go deleted file mode 100644 index 9a63514fc..000000000 --- a/cmd/cycloid/plugins/uninstall.go +++ /dev/null @@ -1,49 +0,0 @@ -package plugins - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUninstallCommand() *cobra.Command { - return &cobra.Command{ - Use: "uninstall ...", - Args: cobra.MinimumNArgs(1), - ValidArgsFunction: cyargs.CompletePluginInstallID, - Short: "Uninstall a plugin", - Example: ` - cy plugin uninstall 42 - cy plugin uninstall my-plugin - cy plugin uninstall my-plugin-a my-plugin-b -`, - RunE: uninstallPlugin, - } -} - -func uninstallPlugin(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - for _, arg := range args { - id, err := cyargs.ResolvePluginInstallID(org, arg, m) - if err != nil { - return err - } - - _, err = m.DeletePlugin(org, id) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to uninstall plugin "+arg, printer.Options{}) - } - } - return cyout.PrintWithOptions(cmd, nil, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/upgrade.go b/cmd/cycloid/plugins/upgrade.go deleted file mode 100644 index b4c567c46..000000000 --- a/cmd/cycloid/plugins/upgrade.go +++ /dev/null @@ -1,60 +0,0 @@ -package plugins - -import ( - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUpgradeCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "upgrade ", - Aliases: []string{"update"}, - Args: cobra.ExactArgs(1), - ValidArgsFunction: cyargs.CompletePluginInstallID, - Short: "Upgrade a plugin to a new version", - Example: ` - cy plugin upgrade 42 --version-id 7 --config host=localhost - cy plugin upgrade my-plugin --version-id 7 --config-file ./config.json -`, - RunE: upgradePlugin, - } - - cyargs.AddPluginVersionIDFlag(cmd) - _ = cmd.MarkFlagRequired("version-id") - cyargs.AddPluginConfigFlags(cmd) - return cmd -} - -func upgradePlugin(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - versionID, err := cyargs.GetPluginVersionID(cmd) - if err != nil { - return errors.Wrap(err, "unable to get --version-id flag") - } - - config, err := cyargs.GetPluginConfig(cmd) - if err != nil { - return errors.Wrap(err, "unable to get plugin configuration") - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - id, err := cyargs.ResolvePluginInstallID(org, args[0], m) - if err != nil { - return err - } - - result, _, err := m.UpdatePlugin(org, id, *versionID, config) - return cyout.PrintWithOptions(cmd, result, err, "unable to upgrade plugin", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/widget/cmd.go b/cmd/cycloid/plugins/widget/cmd.go deleted file mode 100644 index 98f6c40a2..000000000 --- a/cmd/cycloid/plugins/widget/cmd.go +++ /dev/null @@ -1,19 +0,0 @@ -package widget - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "widget", - Aliases: []string{"widgets"}, - Short: "Manage org-level plugin widgets", - } - - cmd.AddCommand( - NewListCommand(), - NewQueryCommand(), - ) - return cmd -} diff --git a/cmd/cycloid/plugins/widget/list.go b/cmd/cycloid/plugins/widget/list.go deleted file mode 100644 index 7a44ab4ac..000000000 --- a/cmd/cycloid/plugins/widget/list.go +++ /dev/null @@ -1,44 +0,0 @@ -package widget - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "List org-level plugin widgets", - Example: ` - cy plugin widget list --placement sideMenuPage - cy plugin widget list --placement component -`, - RunE: listPluginWidgets, - } - cmd.Flags().String("placement", "sideMenuPage", "filter widgets by placement type (e.g. sideMenuPage, component)") - return cmd -} - -func listPluginWidgets(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - placement, err := cmd.Flags().GetString("placement") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - result, _, err := m.ListPluginWidgets(org, placement) - return cyout.PrintWithOptions(cmd, result, err, "unable to list plugin widgets", printer.Options{}) -} diff --git a/cmd/cycloid/plugins/widget/query.go b/cmd/cycloid/plugins/widget/query.go deleted file mode 100644 index 120e0006c..000000000 --- a/cmd/cycloid/plugins/widget/query.go +++ /dev/null @@ -1,62 +0,0 @@ -package widget - -import ( - "fmt" - "strconv" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewQueryCommand() *cobra.Command { - return &cobra.Command{ - Use: "query ", - Args: cobra.ExactArgs(1), - Short: "Execute the data query configured for a plugin widget", - Long: `Execute the data query pre-configured for a plugin widget and return its results. - -Each plugin widget is an instance of a query defined in the plugin manifest. -A single plugin may expose multiple queries; each becomes a separate widget with -its own ID. This command executes the query bound to the given widget and returns -whatever data the plugin produces — the shape is plugin-defined. - -Only widgets of type "table" are supported. The associated plugin must be running. - -Use 'cy plugin widget list' to discover widget IDs and their configured queries.`, - Example: ` - # List available widgets to find the ID you want - cy plugin widget list - - # Execute the query for widget 42 and print results as a table - cy plugin widget query 42 - - # Get the raw JSON output - cy plugin widget query 42 --output json -`, - RunE: queryPluginWidget, - } -} - -func queryPluginWidget(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - n, err := strconv.ParseUint(args[0], 10, 32) - if err != nil { - return fmt.Errorf("invalid widget-id %q: must be a positive integer", args[0]) - } - widgetID := uint32(n) - - result, _, err := m.QueryPluginWidget(org, widgetID) - return cyout.PrintWithOptions(cmd, result, err, "unable to query plugin widget", printer.Options{}) -} diff --git a/cmd/cycloid/projects/cmd.go b/cmd/cycloid/projects/cmd.go deleted file mode 100644 index faf0e6817..000000000 --- a/cmd/cycloid/projects/cmd.go +++ /dev/null @@ -1,26 +0,0 @@ -package projects - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - var cmd = &cobra.Command{ - Use: "project", - Aliases: []string{ - "p", - "projects", - }, - Short: "Manage the projects", - } - - cmd.AddCommand(NewDeleteCommand(), - NewCreateCommand(), - NewGetCommand(), - NewUpdateCommand(), - NewListCommand(), - NewListEnvCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/projects/create.go b/cmd/cycloid/projects/create.go deleted file mode 100644 index b60253960..000000000 --- a/cmd/cycloid/projects/create.go +++ /dev/null @@ -1,133 +0,0 @@ -package projects - -import ( - "fmt" - "slices" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "create", - Args: cobra.NoArgs, - Short: "create a project", - Example: `cy --org my-org project create --project "my-project"`, - RunE: create, - } - - cyargs.AddNameFlag(cmd) - cyargs.AddProjectFlag(cmd) - cyargs.AddDescriptionFlag(cmd) - cyargs.AddIconFlag(cmd) - cyargs.AddColorFlag(cmd) - cyargs.AddOwnerFlag(cmd) - cyargs.AddConfigRepositoryFlag(cmd) - cmd.Flags().Bool("update", false, "if set, will update the project if it exists.") - return cmd -} - -func create(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProjectOrEmpty(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - name, project, err = middleware.NameOrCanonical(&name, &project) - if err != nil { - return err - } - - description, err := cyargs.GetDescription(cmd) - if err != nil { - return err - } - - icon, err := cyargs.GetIcon(cmd) - if err != nil { - return err - } - - color, err := cyargs.GetColor(cmd) - if err != nil { - return err - } - - owner, err := cyargs.GetOwner(cmd) - if err != nil { - return err - } - - configRepository, err := cyargs.GetDefaultConfigRepository(cmd) - if err != nil { - return err - } - - update, err := cmd.Flags().GetBool("update") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - if update { - projects, _, err := m.ListProjects(org) - if err != nil { - return fmt.Errorf("failed to create --update project, cannot check is project %q exists: %w", project, err) - } - - currentIndex := slices.IndexFunc(projects, func(p *models.Project) bool { return *p.Canonical == project }) - if currentIndex != -1 { - // Make the update use the current color if not explicitly set by the user - current := projects[currentIndex] - if color == cyargs.DefaultColor { - if current.Color != nil { - color = *current.Color - } else { - // Use a random one if none is set - color = cyargs.PickRandomColor(nil) - } - } - - if icon == cyargs.DefaultIcon { - if current.Icon != nil { - icon = *current.Icon - } else { - // Use a random one if none is set - icon = cyargs.PickRandomIcon(nil) - } - } - - resp, _, err := m.UpdateProject(org, name, project, description, configRepository, owner, "", color, icon, "") - return cyout.PrintWithOptions(cmd, resp, err, "", printer.Options{}) - } - } - - if color == cyargs.DefaultColor { - color = cyargs.PickRandomColor(nil) - } - - if icon == cyargs.DefaultIcon { - icon = cyargs.PickRandomIcon(nil) - } - - resp, _, err := m.CreateProject(org, name, project, description, configRepository, owner, "", color, icon) - return cyout.PrintWithOptions(cmd, resp, err, "", printer.Options{}) -} diff --git a/cmd/cycloid/projects/delete.go b/cmd/cycloid/projects/delete.go deleted file mode 100644 index 8ac46c9c8..000000000 --- a/cmd/cycloid/projects/delete.go +++ /dev/null @@ -1,77 +0,0 @@ -package projects - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewDeleteCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "delete [canonical...]", - Args: cyargs.RequireArgsOrFlag("project"), - Aliases: []string{"del", "rm"}, - ValidArgsFunction: cyargs.CompleteProject, - Short: "delete a project", - Example: ` - # delete a project by canonical - cy --org my-org project delete my-project - - # delete multiple projects at once - cy --org my-org project delete proj-one proj-two - - # delete using the --project flag - cy --org my-org project delete --project my-project -`, - RunE: deleteProject, - } - - cyargs.AddProjectFlag(cmd) - cyargs.AddDeleteFlags(cmd) - return cmd -} - -func deleteProject(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - force, skipHooks, ignoreConfigFilesErr, err := cyargs.GetDeleteFlags(cmd) - if err != nil { - return err - } - - if projectFlag, err := cyargs.GetProjectOrEmpty(cmd); err != nil { - return err - } else if projectFlag != "" { - found := false - for _, a := range args { - if a == projectFlag { - found = true - break - } - } - if !found { - args = append(args, projectFlag) - } - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - opts := middleware.DeleteOptions{Force: force, SkipHooks: skipHooks, IgnoreConfigFilesErr: ignoreConfigFilesErr} - deleted := make([]string, 0, len(args)) - for _, project := range args { - _, err = m.DeleteProject(org, project, opts) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to delete project "+project, printer.Options{}) - } - deleted = append(deleted, project) - } - return cyout.PrintWithOptions(cmd, deleted, nil, "", printer.Options{Columns: []string{"Canonical"}}) -} diff --git a/cmd/cycloid/projects/get.go b/cmd/cycloid/projects/get.go deleted file mode 100644 index d1297425a..000000000 --- a/cmd/cycloid/projects/get.go +++ /dev/null @@ -1,75 +0,0 @@ -package projects - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewGetCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get [canonical...]", - Args: cyargs.RequireArgsOrFlag("project"), - ValidArgsFunction: cyargs.CompleteProject, - Short: "get a project", - Example: ` - # get a project by canonical - cy --org my-org project get my-project - - # get multiple projects - cy --org my-org project get proj-a proj-b - - # get a project using the --project flag or CY_PROJECT env var - cy --org my-org project get --project my-project -o yaml -`, - RunE: get, - } - - cyargs.AddProjectFlag(cmd) - cyout.RegisterModel(cmd, models.Project{}) - return cmd -} - -func get(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - if projectFlag, err := cyargs.GetProjectOrEmpty(cmd); err != nil { - return err - } else if projectFlag != "" { - found := false - for _, a := range args { - if a == projectFlag { - found = true - break - } - } - if !found { - args = append(args, projectFlag) - } - } - - if len(args) == 1 { - proj, _, err := m.GetProject(org, args[0]) - return cyout.PrintWithOptions(cmd, proj, err, "unable to get project", projectTableOptions) - } - - results := make([]*models.Project, 0, len(args)) - for _, canonical := range args { - proj, _, err := m.GetProject(org, canonical) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to get project "+canonical, projectTableOptions) - } - results = append(results, proj) - } - return cyout.PrintWithOptions(cmd, results, nil, "", projectTableOptions) -} diff --git a/cmd/cycloid/projects/list-env.go b/cmd/cycloid/projects/list-env.go deleted file mode 100644 index 021e9a91d..000000000 --- a/cmd/cycloid/projects/list-env.go +++ /dev/null @@ -1,41 +0,0 @@ -package projects - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewListEnvCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list-env", - Args: cobra.NoArgs, - Short: "List environments in the current project", - Example: `cy --org my-org projects list-env -p project -o json`, - RunE: listEnv, - } - - cyargs.AddProjectFlag(cmd) - return cmd -} - -func listEnv(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProject(cmd) - if err != nil { - return err - } - - projectEnvs, _, err := m.ListProjectEnvs(org, project) - return cyout.Print(cmd, projectEnvs, err, "unable to listenv project") -} diff --git a/cmd/cycloid/projects/list.go b/cmd/cycloid/projects/list.go deleted file mode 100644 index 04d6aaf41..000000000 --- a/cmd/cycloid/projects/list.go +++ /dev/null @@ -1,43 +0,0 @@ -package projects - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var projectTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "Description", "Owner.Username"}, - Identifier: "Canonical", -} - -func NewListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Short: "list the projects within the organization", - Example: `# list projects in 'my-org' and display result in JSON -cy --org my-org projects list -o json`, - RunE: list, - } - cyout.RegisterModel(cmd, models.Project{}) - return cmd -} - -func list(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - projects, _, err := m.ListProjects(org) - return cyout.PrintWithOptions(cmd, projects, err, "unable to list projects", projectTableOptions) -} diff --git a/cmd/cycloid/projects/update.go b/cmd/cycloid/projects/update.go deleted file mode 100644 index b722dca3b..000000000 --- a/cmd/cycloid/projects/update.go +++ /dev/null @@ -1,107 +0,0 @@ -package projects - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUpdateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "update", - Args: cobra.NoArgs, - Short: "update a project", - Example: `cy --org my-org project update --project "my-project" --name "NewName"`, - RunE: update, - } - - cyargs.AddNameFlag(cmd) - cyargs.AddProjectFlag(cmd) - cyargs.AddDescriptionFlag(cmd) - cyargs.AddIconFlag(cmd) - cyargs.AddColorFlag(cmd) - cyargs.AddOwnerFlag(cmd) - cyargs.AddConfigRepositoryFlag(cmd) - return cmd -} - -func update(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - project, err := cyargs.GetProject(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - description, err := cyargs.GetDescription(cmd) - if err != nil { - return err - } - - owner, err := cyargs.GetOwner(cmd) - if err != nil { - return err - } - - color, err := cyargs.GetColor(cmd) - if err != nil { - return err - } - - icon, err := cyargs.GetIcon(cmd) - if err != nil { - return err - } - - configRepository, err := cyargs.GetDefaultConfigRepository(cmd) - if err != nil { - return err - } - - currentProject, _, err := m.GetProject(org, project) - if err != nil { - return cyout.PrintWithOptions(cmd, currentProject, err, "project not found", printer.Options{}) - } - - if name == "" { - name = *currentProject.Name - } - - if description == "" { - description = currentProject.Description - } - - if color == "" && currentProject.Color != nil { - color = *currentProject.Color - } - - if icon == "" && currentProject.Icon != nil { - icon = *currentProject.Icon - } - - if owner == "" && currentProject.Owner != nil { - owner = *currentProject.Owner.Username - } - - if configRepository == "" { - configRepository = currentProject.ConfigRepositoryCanonical - } - - resp, _, err := m.UpdateProject(org, name, project, description, configRepository, owner, "", color, icon, "") - return cyout.PrintWithOptions(cmd, resp, err, "", printer.Options{}) -} diff --git a/cmd/cycloid/roles/cmd.go b/cmd/cycloid/roles/cmd.go deleted file mode 100644 index 90a2d2eeb..000000000 --- a/cmd/cycloid/roles/cmd.go +++ /dev/null @@ -1,34 +0,0 @@ -package roles - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - var ( - example = ` - # Manage roles of my-org organization - cy --org my-org roles [list|get|create|update|delete] - ` - short = "Manage roles from the organization" - long = short - ) - - var cmd = &cobra.Command{ - Use: "roles", - Aliases: []string{"role"}, - Example: example, - Short: short, - Long: long, - } - - cmd.AddCommand( - NewListCommand(), - NewGetCommand(), - NewCreateCommand(), - NewUpdateCommand(), - NewDeleteCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/roles/cmd_test.go b/cmd/cycloid/roles/cmd_test.go deleted file mode 100644 index 81fe16d05..000000000 --- a/cmd/cycloid/roles/cmd_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package roles - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestRolesCommandTree(t *testing.T) { - t.Parallel() - root := NewCommands() - assert.Equal(t, "roles", root.Name()) - - names := make(map[string]int) - for _, c := range root.Commands() { - names[c.Name()]++ - } - - require.Equal(t, 1, names["list"]) - require.Equal(t, 1, names["get"]) - require.Equal(t, 1, names["create"]) - require.Equal(t, 1, names["update"]) - require.Equal(t, 1, names["delete"], "delete must be registered exactly once") -} - -func TestRolesCreateHasUpdateFlag(t *testing.T) { - t.Parallel() - cmd := NewCreateCommand() - f := cmd.Flags().Lookup("update") - require.NotNil(t, f) - assert.Equal(t, "bool", f.Value.Type()) -} - -func TestRolesUpdateCommandNoUpdateFlag(t *testing.T) { - t.Parallel() - cmd := NewUpdateCommand() - // update subcommand is always upsert; no --update flag - assert.Nil(t, cmd.Flags().Lookup("update")) -} diff --git a/cmd/cycloid/roles/common.go b/cmd/cycloid/roles/common.go deleted file mode 100644 index 424b9d3b2..000000000 --- a/cmd/cycloid/roles/common.go +++ /dev/null @@ -1,92 +0,0 @@ -package roles - -import ( - stderrors "errors" - "fmt" - "net/http" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -// runRoleWrite creates or updates a role. upsert: if true, update when role exists; if false, error when it exists. -func runRoleWrite(cmd *cobra.Command, upsert bool) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - roleName, err := cyargs.GetRoleName(cmd) - if err != nil { - return err - } - - roleCan, err := cyargs.GetRoleCanonical(cmd) - if err != nil { - return err - } - - deprecatedCan, err := cmd.Flags().GetString("canonical") - if err != nil { - return err - } - - if roleCan == "" && deprecatedCan != "" { - roleCan = deprecatedCan - } - - name, role, err := middleware.NameOrCanonical(&roleName, &roleCan) - if err != nil { - return err - } - - rulesJSON, err := cyargs.GetRoleRulesJSON(cmd) - if err != nil { - return err - } - - rulesFiles, err := cyargs.GetRoleRulesFiles(cmd) - if err != nil { - return err - } - - rules := append(rulesJSON, rulesFiles...) - - description, err := cyargs.GetDescription(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - _, _, err = m.GetRole(org, role) - exists := err == nil - if err != nil { - var apiErr *middleware.APIResponseError - if stderrors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound { - exists = false - } else { - return cyout.PrintWithOptions(cmd, nil, err, "unable to check if role exists", printer.Options{}) - } - } - - if exists && !upsert { - return cyout.PrintWithOptions(cmd, nil, - fmt.Errorf("role %q already exists; use --update or `cy roles update` to update it", role), - "failed to create role", printer.Options{}) - } - - if exists { - outRole, _, err := m.UpdateRole(org, role, &name, &role, &description, rules) - return cyout.PrintWithOptions(cmd, outRole, err, "failed to update role", printer.Options{}) - } - - outRole, _, err := m.CreateRole(org, &name, &role, &description, rules) - return cyout.PrintWithOptions(cmd, outRole, err, "failed to create role", printer.Options{}) -} diff --git a/cmd/cycloid/roles/create.go b/cmd/cycloid/roles/create.go deleted file mode 100644 index e129dc802..000000000 --- a/cmd/cycloid/roles/create.go +++ /dev/null @@ -1,49 +0,0 @@ -package roles - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/internal/cyargs" -) - -func NewCreateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "create", - Args: cobra.NoArgs, - Example: ` cy --org my-org roles create --name "New role" --description "My cool role." \ - --rule-json '{"action": "organization:delete", "effect": "allow", "resources": []}' --rule-file my_rule_file.json - - cy --org my-org roles create --update --role my-role --name "My role" \ - --rule-json '{"action": "organization:list", "effect": "allow", "resources": []}'`, - Short: "Create a new role.", - Long: `Please check the API for rules specifications: https://docs.cycloid.io/api/#tag/Organization-Roles/operation/createRole `, - RunE: createRole, - } - - cmd.MarkFlagsOneRequired( - cyargs.AddRoleNameFlag(cmd), - cyargs.AddRoleCanonicalFlag(cmd), - ) - - cmd.MarkFlagsOneRequired( - cyargs.AddRoleRulesJSONFlag(cmd), - cyargs.AddRoleRulesFilesFlag(cmd), - ) - cyargs.AddDescriptionFlag(cmd) - cmd.Flags().Bool("update", false, "If set, update the role when it already exists.") - - // keep legacy flag just in case - // TODO: deprecate in next update - cmd.Flags().String("canonical", "", "the role canonical") - _ = cmd.Flags().MarkHidden("canonical") - - return cmd -} - -func createRole(cmd *cobra.Command, args []string) error { - update, err := cmd.Flags().GetBool("update") - if err != nil { - return err - } - return runRoleWrite(cmd, update) -} diff --git a/cmd/cycloid/roles/delete.go b/cmd/cycloid/roles/delete.go deleted file mode 100644 index ce2ef1a81..000000000 --- a/cmd/cycloid/roles/delete.go +++ /dev/null @@ -1,56 +0,0 @@ -package roles - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewDeleteCommand() *cobra.Command { - var ( - example = `cy --org my-org roles delete [role_canonicals...]` - short = "Delete one or more roles from the organization" - long = short - ) - - var cmd = &cobra.Command{ - Use: "delete", - Aliases: []string{"rm"}, - Args: cobra.MinimumNArgs(1), - ValidArgsFunction: cyargs.CompleteRoleCanonical, - Example: example, - Short: short, - Long: long, - RunE: deleteRole, - } - - return cmd -} - -func deleteRole(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - deleted := make([]string, 0, len(args)) - for _, role := range args { - _, err := m.DeleteRole(org, role) - if err != nil { - return cyout.PrintWithOptions(cmd, deleted, err, fmt.Sprintf("failed to delete role %q", role), printer.Options{}) - } - - deleted = append(deleted, role) - } - - return cyout.PrintWithOptions(cmd, deleted, nil, "", printer.Options{Columns: []string{"Canonical"}}) -} diff --git a/cmd/cycloid/roles/get.go b/cmd/cycloid/roles/get.go deleted file mode 100644 index caca5e97b..000000000 --- a/cmd/cycloid/roles/get.go +++ /dev/null @@ -1,88 +0,0 @@ -package roles - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewGetCommand() *cobra.Command { - var ( - example = ` - # get a single role - cy --org my-org roles get my-role - - # get multiple roles - cy --org my-org roles get role-a role-b -` - short = "Get a role specification." - long = short - ) - - var cmd = &cobra.Command{ - Use: "get [canonical...]", - Args: cyargs.RequireArgsOrFlag("role"), - Example: example, - Short: short, - Long: long, - RunE: getRole, - ValidArgsFunction: cyargs.CompleteRoleCanonical, - } - - cyargs.AddRoleCanonicalFlag(cmd) - - // keep legacy flag just in case - // TODO: deprecate in next update - cmd.Flags().String("canonical", "", "the role canonical") - cmd.Flags().MarkHidden("canonical") - - cyout.RegisterModel(cmd, models.Role{}) - return cmd -} - -func getRole(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - role, err := cyargs.GetRoleCanonical(cmd) - if err != nil { - return err - } - - if role != "" { - found := false - for _, a := range args { - if a == role { - found = true - break - } - } - if !found { - args = append(args, role) - } - } - - if len(args) == 1 { - mb, _, err := m.GetRole(org, args[0]) - return cyout.PrintWithOptions(cmd, mb, err, "unable to get role", roleTableOptions) - } - - results := make([]*models.Role, 0, len(args)) - for _, canonical := range args { - mb, _, err := m.GetRole(org, canonical) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to get role "+canonical, roleTableOptions) - } - results = append(results, mb) - } - return cyout.PrintWithOptions(cmd, results, nil, "", roleTableOptions) -} diff --git a/cmd/cycloid/roles/list.go b/cmd/cycloid/roles/list.go deleted file mode 100644 index 984484c29..000000000 --- a/cmd/cycloid/roles/list.go +++ /dev/null @@ -1,49 +0,0 @@ -package roles - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var roleTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "Description", "Default"}, - Identifier: "Canonical", -} - -func NewListCommand() *cobra.Command { - var ( - example = `cy --org my-org roles list` - short = "Get the list of the current organization roles" - long = short - ) - - var cmd = &cobra.Command{ - Use: "list", - Args: cobra.NoArgs, - Example: example, - Short: short, - Long: long, - RunE: listRoles, - } - cyout.RegisterModel(cmd, models.Role{}) - return cmd -} - -func listRoles(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - roles, _, err := m.ListRoles(org) - return cyout.PrintWithOptions(cmd, roles, err, "unable to list roles", roleTableOptions) -} diff --git a/cmd/cycloid/roles/update.go b/cmd/cycloid/roles/update.go deleted file mode 100644 index cffe5f9cb..000000000 --- a/cmd/cycloid/roles/update.go +++ /dev/null @@ -1,37 +0,0 @@ -package roles - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/internal/cyargs" -) - -func NewUpdateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "update", - Args: cobra.NoArgs, - Example: ` cy --org my-org roles update --role my-role --name "My role" \ - --rule-json '{"action": "organization:list", "effect": "allow", "resources": []}'`, - Short: "Create or update a role (same as roles create --update).", - Long: `Updates an existing role or creates it if missing. Same behavior as cy roles create --update. See API: https://docs.cycloid.io/api/#tag/Organization-Roles/operation/updateRole`, - RunE: func(cmd *cobra.Command, args []string) error { - return runRoleWrite(cmd, true) - }, - } - - cmd.MarkFlagsOneRequired( - cyargs.AddRoleNameFlag(cmd), - cyargs.AddRoleCanonicalFlag(cmd), - ) - - cmd.MarkFlagsOneRequired( - cyargs.AddRoleRulesJSONFlag(cmd), - cyargs.AddRoleRulesFilesFlag(cmd), - ) - cyargs.AddDescriptionFlag(cmd) - - cmd.Flags().String("canonical", "", "the role canonical") - _ = cmd.Flags().MarkHidden("canonical") - - return cmd -} diff --git a/cmd/cycloid/stacks/cmd.go b/cmd/cycloid/stacks/cmd.go deleted file mode 100644 index bc3b89d34..000000000 --- a/cmd/cycloid/stacks/cmd.go +++ /dev/null @@ -1,27 +0,0 @@ -package stacks - -import ( - "github.com/spf13/cobra" -) - -func NewCommands() *cobra.Command { - var cmd = &cobra.Command{ - Use: "stack", - Aliases: []string{ - "s", - "stacks", - }, - Short: "Manage the stacks", - } - - cmd.AddCommand( - NewListCommand(), - NewGetCommand(), - NewUpdateCommand(), - NewCreateFromBlueprintCommand(), - NewFormsCommands(), - NewStacksGetComponentStackConfig(), - ) - - return cmd -} diff --git a/cmd/cycloid/stacks/create.go b/cmd/cycloid/stacks/create.go deleted file mode 100644 index 3ff53bc97..000000000 --- a/cmd/cycloid/stacks/create.go +++ /dev/null @@ -1,107 +0,0 @@ -package stacks - -import ( - "fmt" - "slices" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateFromBlueprintCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "create", - Short: "create a new stack from a blueprint", - Example: `cy stack create --name "My Stack" --stack my-stack --catalog-repository my-catalog --blueprint-ref org:blueprint --use-case production`, - RunE: createFromBlueprint, - Args: cobra.NoArgs, - } - - cmd.MarkFlagRequired(cyargs.AddStackNameFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddBlueprintRefFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddStackFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddCatalogRepositoryFlag(cmd)) - cmd.MarkFlagRequired(cyargs.AddUseCaseFlag(cmd)) - cmd.Flags().Bool("update", false, "if the stack canonical already exists, return it without failing (idempotent create)") - return cmd -} - -func createFromBlueprint(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - blueprintRef, err := cyargs.GetBlueprintRef(cmd) - if err != nil { - return err - } - - name, err := cyargs.GetName(cmd) - if err != nil { - return err - } - - stack, err := cyargs.GetStack(cmd) - if err != nil { - return err - } - - displayName, stackCanonical, err := middleware.NameOrCanonical(&name, &stack) - if err != nil { - return err - } - - catalogRepository, err := cyargs.GetCatalogRepository(cmd) - if err != nil { - return err - } - - useCasePtr, err := cyargs.GetUseCase(cmd) - if err != nil { - return err - } - useCase := useCasePtr - - update, err := cmd.Flags().GetBool("update") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - stacksList, _, err := m.ListStacks(org) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "failed to list stacks to check if stack exists", printer.Options{}) - } - - idx := slices.IndexFunc(stacksList, func(s *models.ServiceCatalog) bool { - return s.Canonical != nil && *s.Canonical == stackCanonical - }) - if idx != -1 { - ref := ptr.Value(stacksList[idx].Ref) - if ref == "" { - return cyout.PrintWithOptions(cmd, nil, - fmt.Errorf("stack with canonical %q has no ref", stackCanonical), - "failed to create stack from blueprint", printer.Options{}) - } - if update { - outStack, _, err := m.GetStack(org, ref) - return cyout.PrintWithOptions(cmd, outStack, err, "failed to get existing stack", printer.Options{}) - } - return cyout.PrintWithOptions(cmd, nil, - fmt.Errorf("stack %q already exists; use --update for an idempotent create", stackCanonical), - "failed to create stack from blueprint", printer.Options{}) - } - - createdStack, _, err := m.CreateStackFromBlueprint(org, blueprintRef, displayName, stackCanonical, catalogRepository, useCase) - return cyout.PrintWithOptions(cmd, createdStack, err, "failed to create stack from blueprint", printer.Options{}) -} diff --git a/cmd/cycloid/stacks/forms.go b/cmd/cycloid/stacks/forms.go deleted file mode 100644 index 7c1d7ffb7..000000000 --- a/cmd/cycloid/stacks/forms.go +++ /dev/null @@ -1,22 +0,0 @@ -package stacks - -import "github.com/spf13/cobra" - -func NewFormsCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "forms", - Aliases: []string{ - "form", - "stackform", - "stackforms", - }, - Args: cobra.NoArgs, - Short: "use and manage Stackforms .forms.yml definition", - } - - cmd.AddCommand( - NewFormsValidateCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/stacks/forms_validate.go b/cmd/cycloid/stacks/forms_validate.go deleted file mode 100644 index 3121625ff..000000000 --- a/cmd/cycloid/stacks/forms_validate.go +++ /dev/null @@ -1,92 +0,0 @@ -package stacks - -import ( - "fmt" - "os" - "path/filepath" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewFormsValidateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "validate [file...]", - Args: cobra.ArbitraryArgs, - ValidArgsFunction: cyargs.ValidateForms, - Short: "validate one or more .forms.yml files", - Example: ` - # validate a specific forms file - cy stack forms validate .forms.yml - - # validate multiple files - cy stack forms validate .forms.yml other/.forms.yaml - - # validate all .forms.y*ml files in the current directory (default) - cy stack forms validate`, - RunE: validateForm, - } - - return cmd -} - -func validateForm(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - // Default: glob .forms.y*ml in cwd - if len(args) == 0 { - matches, err := filepath.Glob(".forms.yml") - if err == nil && len(matches) > 0 { - args = append(args, matches...) - } - matches, err = filepath.Glob(".forms.yaml") - if err == nil && len(matches) > 0 { - args = append(args, matches...) - } - if len(args) == 0 { - return fmt.Errorf("no .forms.yml or .forms.yaml found in current directory; pass a file path explicitly") - } - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - var hasErrors bool - for _, formsPath := range args { - rawForm, err := os.ReadFile(formsPath) - if err != nil { - return errors.Wrapf(err, "unable to read the form file at path '%s'", formsPath) - } - - validation, _, err := m.ValidateForm(org, rawForm) - if err != nil { - return cyout.PrintWithOptions(cmd, validation, err, fmt.Sprintf("form validation failed for %s", formsPath), printer.Options{}) - } - - if len(validation.Errors) == 0 { - if err := cyout.PrintWithOptions(cmd, nil, nil, fmt.Sprintf("%s: ok", formsPath), printer.Options{}); err != nil { - return err - } - continue - } - - hasErrors = true - if err := cyout.PrintWithOptions(cmd, validation, nil, "", printer.Options{}); err != nil { - return err - } - } - - if hasErrors { - return fmt.Errorf("one or more forms files failed validation") - } - return nil -} diff --git a/cmd/cycloid/stacks/get.go b/cmd/cycloid/stacks/get.go deleted file mode 100644 index 800b7a855..000000000 --- a/cmd/cycloid/stacks/get.go +++ /dev/null @@ -1,43 +0,0 @@ -package stacks - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewGetCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get", - Args: cobra.NoArgs, - Short: "get information on a stack", - Example: `cy --org my-org stacks get --ref my:stack-ref`, - RunE: get, - } - - cmd.MarkFlagRequired(cyargs.AddStackRefFlag(cmd)) - return cmd -} - -func get(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - ref, err := cyargs.GetStackRef(cmd) - if err != nil { - return err - } - - // Initialize middleware after all arguments are collected - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - s, _, err := m.GetStack(org, ref) - return cyout.PrintWithOptions(cmd, s, err, "failed to get stack from API", printer.Options{}) -} diff --git a/cmd/cycloid/stacks/get_config.go b/cmd/cycloid/stacks/get_config.go deleted file mode 100644 index 80795ae65..000000000 --- a/cmd/cycloid/stacks/get_config.go +++ /dev/null @@ -1,69 +0,0 @@ -package stacks - -import ( - "fmt" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewStacksGetComponentStackConfig() *cobra.Command { - var cmd = &cobra.Command{ - Use: "get-config -p project -e env -c component [flags]", - Short: "Output a stack configuration in JSON", - Example: ` -cy --org my-org stacks get-config -p my-project -e my-env -c my-component my-usecase -`, - RunE: getConfig, - Args: cobra.MaximumNArgs(1), - } - cyargs.AddCyContext(cmd) - cyargs.AddUseCaseFlag(cmd) - cyargs.AddStackVersionFlags(cmd) - cyargs.AddStackFormsInputFlags(cmd) - - return cmd -} - -func getConfig(cmd *cobra.Command, args []string) error { - org, project, environment, component, err := cyargs.GetCyContext(cmd) - if err != nil { - return err - } - - useCase, _ := cyargs.GetUseCase(cmd) - if len(args) >= 1 && useCase == "" { - useCase = args[0] - } else if useCase == "" { - return fmt.Errorf("missing use-case argument") - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // Resolve stack version: --stack-version (new) or legacy flags. - // Bare --stack-version requires prefix form (tag:/branch:/sha:) since no stack-ref is available here. - tag, branch, hash, err := cyargs.ResolveStackVersionArg(cmd, m, org, "") - if err != nil { - return errors.Wrap(err, "failed to read stack version flags") - } - - stackConfigs, _, err := m.GetComponentStackConfig(org, project, environment, component, useCase, tag, branch, hash) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to get the stack configuration", printer.Options{}) - } - - useCaseConfig, err := common.FormUseCaseToFormVars(stackConfigs, useCase) - if err != nil { - return fmt.Errorf("failed to parse default form values for component %q with use-case %q: %w", component, useCase, err) - } - - config, err := cyargs.GetStackformsVars(cmd, useCaseConfig) - return cyout.PrintWithOptions(cmd, config, err, "failed to fetch stack config.", printer.Options{}) -} diff --git a/cmd/cycloid/stacks/list.go b/cmd/cycloid/stacks/list.go deleted file mode 100644 index 0fe0d7e0e..000000000 --- a/cmd/cycloid/stacks/list.go +++ /dev/null @@ -1,84 +0,0 @@ -package stacks - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/custommodels" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewListCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "list", - Aliases: []string{ - "ls", - }, - Args: cobra.NoArgs, - Short: "list stacks available in the current org.", - Example: `cy my-org stack list`, - RunE: list, - } - - cmd.Flags().Bool("blueprint", false, "list blueprint stacks") - return cmd -} - -func list(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - blueprint, err := cmd.Flags().GetBool("blueprint") - if err != nil { - return err - } - - // Initialize middleware after all arguments are collected - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // list standard stacks - if !blueprint { - stacks, _, err := m.ListStacks(org) - return cyout.PrintWithOptions(cmd, stacks, err, "failed to list stacks from API", printer.Options{}) - } - - // list --blueprints - stacks, _, err := m.ListBlueprints(org) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "failed to list blueprints from API", printer.Options{}) - } - - var blueprints = make([]*custommodels.Blueprint, len(stacks)) - for index, stack := range stacks { - blueprints[index] = &custommodels.Blueprint{ - ServiceCatalog: *stack, - UseCases: &[]string{}, - } - - if stack.Ref != nil { - // Pass empty version flags to use default/latest version - stackUseCases, _, err := m.ListStackUseCases(org, *stack.Ref, "", "", "") - if err != nil { - fmt.Fprintf(cmd.OutOrStderr(), "error: failed to fetch use cases for blueprint '%s': %s\n", *stack.Ref, err.Error()) - continue - } - - var useCases []string - for _, useCase := range stackUseCases { - useCases = append(useCases, *useCase.UseCase) - } - - blueprints[index].UseCases = &useCases - } - } - - return cyout.PrintWithOptions(cmd, blueprints, nil, "failed to list blueprints from API", printer.Options{}) -} diff --git a/cmd/cycloid/stacks/update.go b/cmd/cycloid/stacks/update.go deleted file mode 100644 index b12559f26..000000000 --- a/cmd/cycloid/stacks/update.go +++ /dev/null @@ -1,86 +0,0 @@ -package stacks - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUpdateCommand() *cobra.Command { - var cmd = &cobra.Command{ - Use: "update", - Args: cobra.NoArgs, - Short: "update the visibility of a stack", - Example: `cy stacks update --stack-ref org:myStack --visibility shared - -# Full args example -cy stacks update \ - --stack-ref my:stack-ref \ - --visibility "hidden" \ - --team "teamCanonical" -`, - RunE: update, - } - - cmd.MarkFlagRequired(cyargs.AddStackRefFlag(cmd)) - cyargs.AddVisibilityFlag(cmd) - cyargs.AddTeamFlag(cmd) - return cmd -} - -func update(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - stackRef, err := cyargs.GetStackRef(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // Fetch the current stack state - stack, _, err := m.GetStack(org, stackRef) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, fmt.Sprintf("failed to retrieve the stack with stack ref: %s", stackRef), printer.Options{}) - } - - // Manage optional parameters - flagSet := cmd.Flags() - - var visibility *string - var team string - if flagSet.Changed("visibility") { - visibilityStr, err := cyargs.GetVisibility(cmd) - if err != nil { - return err - } - visibility = &visibilityStr - } else { - visibility = stack.Visibility - } - - if flagSet.Changed("team") { - team, err = cyargs.GetTeam(cmd) - if err != nil { - return err - } - } else { - if stack.Team != nil { - team = *stack.Team.Canonical - } - } - - // Send request - s, _, err := m.UpdateStack(org, stackRef, team, visibility) - return cyout.PrintWithOptions(cmd, s, err, fmt.Sprintf("fail to update stack with ref: %s", stackRef), printer.Options{}) -} diff --git a/cmd/cycloid/status.go b/cmd/cycloid/status.go deleted file mode 100644 index fd5afd870..000000000 --- a/cmd/cycloid/status.go +++ /dev/null @@ -1,61 +0,0 @@ -package cycloid - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewStatusCmd() *cobra.Command { - return &cobra.Command{ - Use: "status", - Short: "Get the status of the Cycloid services", - Example: ` - # show the status of Cycloid services - cy status -`, - RunE: getStatus, - } -} - -func getStatus(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - services, _, err := m.GetStatus() - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, "unable to get status", printer.Options{}) - } - - output, _ := cyargs.GetOutput(cmd) - - // for a better table display, we process the result - // in order to add some colors following the service - // state - if output == "table" { - var ( - // green - success = "\033[0;32mSuccess\033[0m" - // orange - unknown = "\033[0;33mUnknown\033[0m" - // red - errColor = "\033[0;31mError\033[0m" - ) - for _, service := range services.Checks { - switch *service.Status { - case "Success": - service.Status = &success - case "Unknown": - service.Status = &unknown - case "Error": - service.Status = &errColor - } - } - } - - return cyout.PrintWithOptions(cmd, services.Checks, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/teams/cmd.go b/cmd/cycloid/teams/cmd.go deleted file mode 100644 index 2350e00fe..000000000 --- a/cmd/cycloid/teams/cmd.go +++ /dev/null @@ -1,63 +0,0 @@ -package teams - -import ( - "strconv" - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewTeamsCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "teams", - Aliases: []string{"team"}, - Short: "Commands to manage teams", - } - cmd.AddCommand( - NewTeamMembersCommand(), - NewCreateTeamCommand(), - NewUpdateTeamCommand(), - NewGetTeamCommand(), - NewDeleteTeamCommand(), - NewListTeamCommand(), - ) - return cmd -} - -var teamTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "MemberCount", "Roles"}, - Identifier: "Canonical", - Transform: func(obj interface{}) map[string]string { - t, ok := obj.(*models.Team) - if !ok { - return map[string]string{} - } - canonical := "" - if t.Canonical != nil { - canonical = *t.Canonical - } - name := "" - if t.Name != nil { - name = *t.Name - } - memberCount := "" - if t.MemberCount != nil { - memberCount = strconv.FormatUint(uint64(*t.MemberCount), 10) - } - roleNames := make([]string, 0, len(t.Roles)) - for _, r := range t.Roles { - if r.Name != nil { - roleNames = append(roleNames, *r.Name) - } - } - return map[string]string{ - "Canonical": canonical, - "Name": name, - "MemberCount": memberCount, - "Roles": strings.Join(roleNames, ", "), - } - }, -} diff --git a/cmd/cycloid/teams/create.go b/cmd/cycloid/teams/create.go deleted file mode 100644 index 920d254eb..000000000 --- a/cmd/cycloid/teams/create.go +++ /dev/null @@ -1,96 +0,0 @@ -package teams - -import ( - stderrors "errors" - "net/http" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/internal/utils" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewCreateTeamCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "create", - Short: "Create a team.", - Example: `cy team create --name "My cool team" --role organization-admin`, - RunE: createTeam, - Args: cobra.NoArgs, - } - - cmd.Flags().Bool("update", false, "allow update if team exists") - cmd.MarkFlagsOneRequired( - cyargs.AddTeamNameFlag(cmd), - cyargs.AddTeamFlag(cmd), - ) - cmd.MarkFlagRequired(cyargs.AddTeamRolesFlag(cmd)) - cyargs.AddTeamOwnerFlag(cmd) - return cmd -} - -func createTeam(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - team, err := cyargs.GetTeam(cmd) - if err != nil { - return err - } - - teamName, err := cyargs.GetTeamName(cmd) - if err != nil { - return err - } - - teamOwner, err := cyargs.GetTeamOwner(cmd) - if err != nil { - return err - } - - displayName, teamCanonical, err := middleware.NameOrCanonical(&teamName, &team) - if err != nil { - return err - } - - roles, err := cyargs.GetTeamRoles(cmd) - if err != nil { - return err - } - - allowUpdate, err := cmd.Flags().GetBool("update") - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - var newTeam *models.Team - - if allowUpdate { - currentTeam, _, err := m.GetTeam(org, teamCanonical) - if err != nil { - var apiErr *middleware.APIResponseError - if !stderrors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound { - return cyout.PrintWithOptions(cmd, nil, err, "failed to get team to check if it exists", printer.Options{}) - } - } else { - newTeam, _, err = m.UpdateTeam( - org, ptr.Ptr(utils.CoalesceNonZero(displayName, ptr.Value(currentTeam.Name))), - currentTeam.Canonical, ptr.Ptr(utils.CoalesceNonZero(teamOwner, ptr.Value(ptr.Value(currentTeam.Owner).Username))), roles, - ) - return cyout.PrintWithOptions(cmd, newTeam, err, "failed to UpdateTeam", printer.Options{}) - } - } - - newTeam, _, err = m.CreateTeam(org, &displayName, &teamCanonical, &teamOwner, roles) - return cyout.PrintWithOptions(cmd, newTeam, err, "failed to CreateTeam", printer.Options{}) -} diff --git a/cmd/cycloid/teams/delete.go b/cmd/cycloid/teams/delete.go deleted file mode 100644 index 4e7f0c748..000000000 --- a/cmd/cycloid/teams/delete.go +++ /dev/null @@ -1,47 +0,0 @@ -package teams - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewDeleteTeamCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "delete [team_canonicals...]", - Short: "Delete a team and output the deleted teams canonicals", - RunE: deleteTeam, - Args: cobra.MinimumNArgs(1), - ValidArgsFunction: cyargs.CompleteTeam, - } - - return cmd -} - -func deleteTeam(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - var deleted = make([]string, len(args)) - for i, team := range args { - _, err = m.DeleteTeam(org, team) - if err != nil { - return cyout.PrintWithOptions(cmd, deleted, err, fmt.Sprintf("failed to delete team %q: %s", team, err.Error()), printer.Options{}) - } - - deleted[i] = team - } - - return cyout.PrintWithOptions(cmd, deleted, nil, "", printer.Options{Columns: []string{"Canonical"}}) -} diff --git a/cmd/cycloid/teams/get.go b/cmd/cycloid/teams/get.go deleted file mode 100644 index 5119cd3c5..000000000 --- a/cmd/cycloid/teams/get.go +++ /dev/null @@ -1,52 +0,0 @@ -package teams - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" -) - -func NewGetTeamCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get [team_canonicals...]", - Short: "Get one or more teams information", - RunE: getTeam, - Args: cobra.MinimumNArgs(1), - ValidArgsFunction: cyargs.CompleteTeam, - } - cyout.RegisterModel(cmd, models.Team{}) - return cmd -} - -func getTeam(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - teams := make([]*models.Team, len(args)) - for i, canonical := range args { - team, _, err := m.GetTeam(org, canonical) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, - fmt.Sprintf("failed to get team %q", canonical), teamTableOptions) - } - - if len(args) == 1 { - return cyout.PrintWithOptions(cmd, team, nil, "", teamTableOptions) - } - - teams[i] = team - } - - return cyout.PrintWithOptions(cmd, teams, nil, "", teamTableOptions) -} diff --git a/cmd/cycloid/teams/list.go b/cmd/cycloid/teams/list.go deleted file mode 100644 index 702f1b5a1..000000000 --- a/cmd/cycloid/teams/list.go +++ /dev/null @@ -1,69 +0,0 @@ -package teams - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/internal/utils" -) - -func NewListTeamCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "list", - Short: "List teams in current organization.", - RunE: listTeam, - Args: cobra.NoArgs, - ValidArgsFunction: cyargs.CompleteTeam, - } - - cyargs.AddTeamNameFlag(cmd) - cyargs.AddTeamCreatedAt(cmd) - cyargs.AddTeamOwnerFlag(cmd) - cyargs.AddTeamMemberIDFlag(cmd) - cyargs.AddTeamOrderBy(cmd) - cyout.RegisterModel(cmd, models.Team{}) - return cmd -} - -func listTeam(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - teamName, err := cyargs.GetTeamName(cmd) - if err != nil { - return err - } - - teamCreatedAt, err := cyargs.GetTeamCreatedAt(cmd) - if err != nil { - return err - } - - teamMemberID, err := cyargs.GetTeamMemberID(cmd) - if err != nil { - return err - } - - teamOrderBy, err := cyargs.GetTeamOrderBy(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - teams, _, err := m.ListTeams( - org, utils.CoalesceNonZeroPtr(teamName), - teamCreatedAt, utils.CoalesceNonZeroPtr(teamMemberID), teamOrderBy, - ) - errMsg := fmt.Sprintf("failed to list teams: %v", err) - return cyout.PrintWithOptions(cmd, teams, err, errMsg, teamTableOptions) -} diff --git a/cmd/cycloid/teams/members.go b/cmd/cycloid/teams/members.go deleted file mode 100644 index c25ada6c6..000000000 --- a/cmd/cycloid/teams/members.go +++ /dev/null @@ -1,18 +0,0 @@ -package teams - -import "github.com/spf13/cobra" - -func NewTeamMembersCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "members", - Aliases: []string{"member"}, - Short: "Manage team members.", - } - cmd.AddCommand( - NewTeamMemberGetCommand(), - NewTeamMemberListCommand(), - NewTeamMemberAssignCommand(), - NewTeamMemberUnAssignCommand(), - ) - return cmd -} diff --git a/cmd/cycloid/teams/members_assign.go b/cmd/cycloid/teams/members_assign.go deleted file mode 100644 index e233ec96b..000000000 --- a/cmd/cycloid/teams/members_assign.go +++ /dev/null @@ -1,61 +0,0 @@ -package teams - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewTeamMemberAssignCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "assign [usernames|emails...]", - Short: "Assign an organization member to a team by username or email.", - Example: "cy team member assign --team my-team member1 member@example.org", - Args: cobra.MinimumNArgs(1), - ValidArgsFunction: cyargs.CompleteTeamMemberEmailOrUsername, - RunE: assignTeamMember, - } - - cmd.MarkFlagRequired(cyargs.AddTeamFlag(cmd)) - return cmd -} - -func assignTeamMember(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - team, err := cyargs.GetTeam(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - var outMembers = make([]*models.MemberTeam, len(args)) - for i, id := range args { - var username, email *string = nil, nil - if strings.Contains(id, "@") { - email = &id - } else { - username = &id - } - - outMembers[i], _, err = m.AssignMemberToTeam(org, team, username, email) - if err != nil { - return cyout.PrintWithOptions(cmd, outMembers, fmt.Errorf("failed to assign member %q in team %q: %w", id, team, err), "", printer.Options{}) - } - } - - return cyout.PrintWithOptions(cmd, outMembers, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/teams/members_get.go b/cmd/cycloid/teams/members_get.go deleted file mode 100644 index 8f4019401..000000000 --- a/cmd/cycloid/teams/members_get.go +++ /dev/null @@ -1,70 +0,0 @@ -package teams - -import ( - "fmt" - "slices" - "strconv" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewTeamMemberGetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get [member_id]", - Short: "Get a team member data.", - Example: "cy team member get --team my-team 17281 member1 member@example.org", - Args: cobra.MinimumNArgs(1), - ValidArgsFunction: cyargs.CompleteTeamMemberAny, - RunE: getTeamMember, - } - - return cmd -} - -func getTeamMember(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - team, err := cyargs.GetTeam(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - var outMembers = make([]*models.MemberTeam, len(args)) - currentMembers, _, err := m.ListTeamMembers(org, team) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, fmt.Errorf("failed to list members of team %q: %w", team, err), "", printer.Options{}) - } - - for i, memberArg := range args { - if index := slices.IndexFunc(currentMembers, func(m *models.MemberTeam) bool { - emailStr := "" - if m.Email != nil { - emailStr = m.Email.String() - } - return memberArg == strconv.Itoa(int(ptr.Value(m.ID))) || - memberArg == m.Username || - memberArg == emailStr - }); index != -1 { - outMembers[i] = currentMembers[i] - } - } - - if len(args) == 1 { - return cyout.PrintWithOptions(cmd, outMembers[0], nil, "", printer.Options{}) - } - return cyout.PrintWithOptions(cmd, outMembers, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/teams/members_list.go b/cmd/cycloid/teams/members_list.go deleted file mode 100644 index c8532cfb7..000000000 --- a/cmd/cycloid/teams/members_list.go +++ /dev/null @@ -1,55 +0,0 @@ -package teams - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewTeamMemberListCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "list [team_canonical]", - Short: "List members of a team", - Example: "cy team member list --team my-team", - Args: cobra.MaximumNArgs(1), - ValidArgsFunction: cyargs.CompleteTeam, - RunE: listTeamMember, - } - - cyargs.AddTeamFlag(cmd) - return cmd -} - -func listTeamMember(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - team, err := cyargs.GetTeam(cmd) - if err != nil { - return err - } - - if team == "" && len(args) == 1 { - team = args[0] - } else { - return fmt.Errorf("missing team canonical parameter, give it by argument or flag") - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - members, _, err := m.ListTeamMembers(org, team) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, fmt.Errorf("failed to list members of team %q: %w", team, err), "", printer.Options{}) - } - - return cyout.PrintWithOptions(cmd, members, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/teams/members_unassign.go b/cmd/cycloid/teams/members_unassign.go deleted file mode 100644 index 57162eede..000000000 --- a/cmd/cycloid/teams/members_unassign.go +++ /dev/null @@ -1,60 +0,0 @@ -package teams - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewTeamMemberUnAssignCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "unassign [usernames|emails...]", - Short: "Unassign a member from a team.", - Example: "cy team member unassign --team my-team member1 member@example.org", - Args: cobra.MinimumNArgs(1), - ValidArgsFunction: cyargs.CompleteTeamMemberAny, - RunE: unassignTeamMember, - } - - cmd.MarkFlagRequired(cyargs.AddTeamFlag(cmd)) - return cmd -} - -func unassignTeamMember(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - team, err := cyargs.GetTeam(cmd) - if err != nil { - return err - } - - members, err := anyMembersToID(org, team, args) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - var outUnassigned = make([]*uint32, len(members)) - for i, member := range members { - _, err = m.UnAssignMemberFromTeam(org, team, ptr.Value(member)) - if err != nil { - return cyout.PrintWithOptions(cmd, outUnassigned, fmt.Errorf("failed to unassign member with ID %d in team %q: %w", member, team, err), "", printer.Options{}) - } - - outUnassigned[i] = member - } - - return cyout.PrintWithOptions(cmd, outUnassigned, nil, "", printer.Options{}) -} diff --git a/cmd/cycloid/teams/update.go b/cmd/cycloid/teams/update.go deleted file mode 100644 index f6c10c630..000000000 --- a/cmd/cycloid/teams/update.go +++ /dev/null @@ -1,78 +0,0 @@ -package teams - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/internal/ptr" - "github.com/cycloidio/cycloid-cli/internal/utils" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewUpdateTeamCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "update", - Short: "Update an existing team.", - Args: cobra.NoArgs, - RunE: updateTeam, - } - - cmd.MarkFlagsOneRequired( - cyargs.AddTeamNameFlag(cmd), - cyargs.AddTeamFlag(cmd), - ) - cmd.MarkFlagRequired(cyargs.AddTeamRolesFlag(cmd)) - cyargs.AddTeamOwnerFlag(cmd) - return cmd -} - -func updateTeam(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - team, err := cyargs.GetTeam(cmd) - if err != nil { - return err - } - - teamName, err := cyargs.GetTeamName(cmd) - if err != nil { - return err - } - - teamOwner, err := cyargs.GetTeamOwner(cmd) - if err != nil { - return err - } - - roles, err := cyargs.GetTeamRoles(cmd) - if err != nil { - return err - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - _, canonical, err := middleware.NameOrCanonical(ptr.Ptr(teamName), ptr.Ptr(team)) - if err != nil { - return fmt.Errorf("failed to infer canonical: %w", err) - } - - currentTeam, _, err := m.GetTeam(org, canonical) - if err != nil { - return fmt.Errorf("failed to Get the team to update with canonical %q: %w", canonical, err) - } - - newTeam, _, err := m.UpdateTeam( - org, ptr.Ptr(utils.CoalesceNonZero(teamName, ptr.Value(currentTeam.Name))), - currentTeam.Canonical, ptr.Ptr(utils.CoalesceNonZero(teamOwner, ptr.Value(ptr.Value(currentTeam.Owner).Username))), roles, - ) - return cyout.PrintWithOptions(cmd, newTeam, err, "failed to UpdateTeam", printer.Options{}) -} diff --git a/cmd/cycloid/teams/utils.go b/cmd/cycloid/teams/utils.go deleted file mode 100644 index 44f5330bd..000000000 --- a/cmd/cycloid/teams/utils.go +++ /dev/null @@ -1,52 +0,0 @@ -package teams - -import ( - "fmt" - "strconv" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -// anyMemberToID convert map any valid member Username or Email to its ID -func anyMembersToID(org, team string, members []string) ([]*uint32, error) { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - teamMembers, _, err := m.ListTeamMembers(org, team) - if err != nil { - return nil, fmt.Errorf("failed to convert members to ID, cannot list current team members: %w", err) - } - - result := make([]*uint32, len(members)) - for i, member := range members { - for _, teamMember := range teamMembers { - emailStr := "" - if teamMember.Email != nil { - emailStr = teamMember.Email.String() - } - if member == teamMember.Username || member == emailStr { - result[i] = teamMember.ID - break - } - - id, err := strconv.ParseUint(member, 10, 32) - if err != nil { - // not a uint - continue - } - - if uint32(id) == ptr.Value(teamMember.ID) { - result[i] = teamMember.ID - break - } - } - - if result[i] == nil { - return result, fmt.Errorf("failed to match identifier %q to any member from team %q in org %q", member, team, org) - } - } - - return result, nil -} diff --git a/cmd/cycloid/terracost/cmd.go b/cmd/cycloid/terracost/cmd.go deleted file mode 100644 index 17eee9adb..000000000 --- a/cmd/cycloid/terracost/cmd.go +++ /dev/null @@ -1,20 +0,0 @@ -package terracost - -import ( - "github.com/spf13/cobra" -) - -// NewCommands returns an implementation of Terracost commands -func NewCommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "terracost", - Example: ` - # estimate the cost of a Terraform plan - cy --org my-org terracost estimate --plan-path ./plan.json -`, - Short: "Use terracost feature", - } - - cmd.AddCommand(NewEstimateCommand()) - return cmd -} diff --git a/cmd/cycloid/terracost/common.go b/cmd/cycloid/terracost/common.go deleted file mode 100644 index eedcad9e4..000000000 --- a/cmd/cycloid/terracost/common.go +++ /dev/null @@ -1,11 +0,0 @@ -package terracost - -import "github.com/spf13/cobra" - -var planPath string - -// WithFlagPlanPath binds the `planPath` variable to its flag -func WithFlagPlanPath(cmd *cobra.Command) string { - cmd.PersistentFlags().StringVar(&planPath, "plan-path", "", "Path to the terraform plan file") - return "plan-path" -} diff --git a/cmd/cycloid/terracost/estimate.go b/cmd/cycloid/terracost/estimate.go deleted file mode 100644 index 062e9cbcb..000000000 --- a/cmd/cycloid/terracost/estimate.go +++ /dev/null @@ -1,46 +0,0 @@ -package terracost - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -// NewEstimateCommands returns a cobra implementation -// of the cost estimation -func NewEstimateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "estimate", - Args: cobra.NoArgs, - RunE: estimate, - } - common.RequiredFlag(WithFlagPlanPath, cmd) - return cmd -} - -func estimate(cmd *cobra.Command, args []string) error { - org, err := cyargs.GetOrg(cmd) - if err != nil { - return fmt.Errorf("unable to validate org flag: %w", err) - } - planPath, err := cmd.Flags().GetString("plan-path") - if err != nil { - return fmt.Errorf("unable to get plan path flag: %w", err) - } - plan, err := os.ReadFile(planPath) - if err != nil { - return fmt.Errorf("unable to read terraform plan file: %w", err) - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - res, _, err := m.CostEstimation(org, plan) - return cyout.PrintWithOptions(cmd, res, err, "unable to estimate terraform plan file", printer.Options{}) -} diff --git a/cmd/cycloid/uri/cmd.go b/cmd/cycloid/uri/cmd.go deleted file mode 100644 index 3b26088f0..000000000 --- a/cmd/cycloid/uri/cmd.go +++ /dev/null @@ -1,19 +0,0 @@ -package uri - -import ( - "github.com/spf13/cobra" -) - -func NewURICommands() *cobra.Command { - cmd := &cobra.Command{ - Use: "uri", - Short: "Use URI schemes with Cycloid", - } - - cmd.AddCommand( - NewGetCommand(), - NewInterpolateCommand(), - ) - - return cmd -} diff --git a/cmd/cycloid/uri/expand.go b/cmd/cycloid/uri/expand.go deleted file mode 100644 index 9e728bf17..000000000 --- a/cmd/cycloid/uri/expand.go +++ /dev/null @@ -1,101 +0,0 @@ -package uri - -import ( - "errors" - "fmt" - "io/fs" - "os" - "path/filepath" - "regexp" - "slices" - "strings" -) - -// RecurseFS will walk through each paths excluding paths that matches -// all the ignores patterns. This function is ment to process the paths -// for commands that uses --recurse and --ignore flags. -func RecurseFS(paths []string, ignores []string) ([]string, error) { - var result []string - - var outErr error - cleanPaths := slices.DeleteFunc(paths, func(path string) bool { - ignored, err := IsIgnored(path, ignores) - if err != nil { - outErr = errors.Join(outErr, err) - return false - } - - return ignored - }) - - for _, path := range cleanPaths { - fileInfo, err := os.Stat(path) - if err != nil { - return nil, fmt.Errorf("invalid path %q: %w", path, err) - } - - if !fileInfo.IsDir() { - result = append(result, path) - continue - } - - if err := filepath.WalkDir(path, func(child string, d fs.DirEntry, err error) error { - if err != nil { - return err - } - - ignore, err := IsIgnored(d.Name(), ignores) - if err != nil { - return err - } - - if ignore { - if d.IsDir() { - return filepath.SkipDir - } - return nil - } - - if !d.IsDir() { - result = append(result, child) - } - - return nil - }); err != nil { - return nil, fmt.Errorf("failed to crawl path %q: %w", path, err) - } - } - - return result, nil -} - -func IsIgnored(path string, ignores []string) (bool, error) { - pathIsAbs := filepath.IsAbs(path) - for _, ignore := range ignores { - if strings.HasPrefix(ignore, "/") && !pathIsAbs { - pwd, err := os.Getwd() - if err != nil { - return false, fmt.Errorf("failed to get current directory: %w", err) - } - - relPath, err := filepath.Rel(pwd, path) - if err != nil { - // In that case, the path and ignore pattern won't match - return false, nil - } - - path = relPath - } - - re, err := regexp.Compile(ignore) - if err != nil { - return false, fmt.Errorf("ignore pattern %q is an invalid regex: %w", ignore, err) - } - - if re.MatchString(path) { - return true, nil - } - } - - return false, nil -} diff --git a/cmd/cycloid/uri/expand_test.go b/cmd/cycloid/uri/expand_test.go deleted file mode 100644 index 2671d04d5..000000000 --- a/cmd/cycloid/uri/expand_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package uri - -import ( - "testing" -) - -func TestIsIgnored(t *testing.T) { - type args struct { - path string - ignores []string - } - tests := []struct { - name string - args args - want bool - wantErr bool - }{ - { - "TestSimpleRelPathOk", - args{ - "ignore-me/", - []string{ - "ignore-me/", - }, - }, - true, - false, - }, - { - "TestSimpleAbsOk", - args{ - "/home/toto", - []string{ - "/home/toto", - }, - }, - true, - false, - }, - { - "TestAbsPatternOk", - args{ - "/home/toto/something", - []string{ - "/home/toto/*", - }, - }, - true, - false, - }, - { - "TestAbsPatternNestedOk", - args{ - "/home/toto/something/else", - []string{ - "/home/toto/*", - }, - }, - true, - false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := IsIgnored(tt.args.path, tt.args.ignores) - if (err != nil) != tt.wantErr { - t.Errorf("IsIgnored() error = %v, wantErr %v", err, tt.wantErr) - return - } - if got != tt.want { - t.Errorf("IsIgnored() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/cmd/cycloid/uri/get.go b/cmd/cycloid/uri/get.go deleted file mode 100644 index 6b317956f..000000000 --- a/cmd/cycloid/uri/get.go +++ /dev/null @@ -1,47 +0,0 @@ -package uri - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/interpolator" - "github.com/cycloidio/cycloid-cli/interpolator/resolvers/httpresolver" -) - -func NewGetCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "get [uri]", - Short: "Get Cycloid resources by using its URI", - Long: strings.Join([]string{ - "Get a cycloid resource by its URI Path.", - interpolator.Docs, - }, "\n"), - Args: cobra.ExactArgs(1), - Example: `Fetch a credential by its canonical as JSON - cy get cy://organizations/my-org/credentials/my-cred?output=json - -Fetch an ssh_key - cy get cy://organizations/my-org/credentials/my-ssh?key=.raw.ssh_key -`, - RunE: get, - } - - return cmd -} - -func get(cmd *cobra.Command, args []string) error { - resolver, err := httpresolver.NewHTTPResolver() - if err != nil { - return err - } - - out, err := resolver.Interpolate(args[0]) - if err != nil { - return err - } - - fmt.Fprint(cmd.OutOrStdout(), out) - return nil -} diff --git a/cmd/cycloid/uri/interpolate.go b/cmd/cycloid/uri/interpolate.go deleted file mode 100644 index 2761cd03b..000000000 --- a/cmd/cycloid/uri/interpolate.go +++ /dev/null @@ -1,171 +0,0 @@ -package uri - -import ( - "fmt" - "io" - "os" - "path/filepath" - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/interpolator" - "github.com/cycloidio/cycloid-cli/interpolator/parsers" - "github.com/cycloidio/cycloid-cli/interpolator/resolvers/httpresolver" -) - -func NewInterpolateCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "interpolate [files...]", - Short: "Interpolate Cycloid URI references in a file.", - Long: `This command will parse files for Cycloid URI references and interpolate -them with the requested resource - -This command is meant to inject values like credentials, inventory values, terraform outputs -or any Cycloid API resource at runtime (for example in pipelines). -` + interpolator.Docs, - Example: `Interpolate from stdin and output content on stdout - echo "ssh: |- cy://org/some_org/credentials/some_ssh?key=.raw.ssh_key" | cy uri interpolate - -Inject credential in multiple files in place - cy uri interpolate -i file1.yaml file2.yaml - -Crawl through all the files in the current directory, ignore .git directory - cy uri interpolate --in-place --recurse . --ignore .git -`, - Args: cobra.MatchAll( - cyargs.ValidateFSArguments, - ), - RunE: interpolate, - } - - cyargs.AddFSRecurseFlag(cmd) - cyargs.AddFSIgnoreFlag(cmd) - cyargs.AddInPlaceFlag(cmd) - cyargs.AddOutputDirectoryFlag(cmd) - return cmd -} - -func interpolate(cmd *cobra.Command, args []string) error { - recurse, err := cyargs.GetFSRecurseFlag(cmd) - if err != nil { - return err - } - - ignores, err := cyargs.GetFSIgnoreFlag(cmd) - if err != nil { - return err - } - - paths := args - if recurse { - paths, err = RecurseFS(args, ignores) - if err != nil { - return err - } - } - - inPlace, err := cyargs.GetInPlaceFlag(cmd) - if err != nil { - return err - } - - targetDir, err := cyargs.GetOutputDirectoryFlag(cmd) - if err != nil { - return err - } - - // Ensure the target dir is created - if targetDir != "" { - err = os.MkdirAll(targetDir, 0750) - if err != nil { - return fmt.Errorf("failed to create target directory %q: %w", targetDir, err) - } - } - - resolver, err := httpresolver.NewHTTPResolver() - if err != nil { - return err - } - - // Manage stdin input - if len(args) == 0 { - if !common.DetectStdinInput() { - return fmt.Errorf("stdin looks empty, please fill stdin or a filename as argument") - } - - stdin, err := io.ReadAll(cmd.InOrStdin()) - if err != nil { - return err - } - - if len(stdin) == 0 { - return fmt.Errorf("failed to read from stdin, looks empty") - } - - out, err := parsers.ReplaceFile(resolver, string(stdin)) - if err != nil { - return fmt.Errorf("failed to interpolate from stdin: %w", err) - } - cleanedOut := strings.TrimRight(out, " \t\n") - - _, err = fmt.Fprintln(cmd.OutOrStdout(), cleanedOut) - if err != nil { - return fmt.Errorf("failed to print result to stdout: %w", err) - } - - return nil - } - - output := []string{} - for _, filename := range paths { - // wrap logic in a func to trigger defers on end of loop - stats, err := os.Stat(filename) - if err != nil { - return fmt.Errorf("file not found for interpolation %q: %w", stats, err) - } - - content, err := os.ReadFile(filename) - if err != nil { - return fmt.Errorf("failed to open file named %q: %w", filename, err) - } - - out, err := parsers.ReplaceFile(resolver, string(content)) - if err != nil { - return fmt.Errorf("failed to interpolate file %q: %w", filename, err) - } - - if inPlace { - err := os.WriteFile(filename, []byte(out+"\n"), stats.Mode()) - if err != nil { - return fmt.Errorf("failed to write to file %q during interpolation, file content may be lost: %w", filename, err) - } - } else if targetDir != "" { - // Send to target dir - var target string - if filepath.IsLocal(filename) { - target = filepath.Join(targetDir, filename) - } else { - target = filepath.Join(targetDir, filepath.Base(filename)) - } - - err = os.WriteFile(target, []byte(out+"\n"), 0640) - if err != nil { - return fmt.Errorf("failed to write file %q in dir %q: %w", filename, targetDir, err) - } - } else { - output = append(output, out) - } - } - - if !inPlace { - _, err := fmt.Fprintln(cmd.OutOrStdout(), strings.Join(output, "\n")) - if err != nil { - return fmt.Errorf("failed to print result to stdout: %w", err) - } - } - - return nil -} diff --git a/cmd/cycloid/version.go b/cmd/cycloid/version.go deleted file mode 100644 index e50e48187..000000000 --- a/cmd/cycloid/version.go +++ /dev/null @@ -1,32 +0,0 @@ -package cycloid - -import ( - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -func NewVersionCmd() *cobra.Command { - var cmd = &cobra.Command{ - Use: "version", - Args: cobra.NoArgs, - Short: "Get the version of the consumed API", - Example: ` - # get the version in JSON format - cy version -o json -`, - RunE: getVersion, - } - return cmd -} - -func getVersion(cmd *cobra.Command, args []string) error { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - d, _, err := m.GetAppVersion() - return cyout.PrintWithOptions(cmd, d, err, "unable to get API version", printer.Options{}) -} diff --git a/cmd/cycloid/version_integration_test.go b/cmd/cycloid/version_integration_test.go deleted file mode 100644 index e04dc0753..000000000 --- a/cmd/cycloid/version_integration_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package cycloid_test - -import ( - "bytes" - "strings" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/cmd" -) - -// TestVersion_JSONWithBadAPIURL runs `cy version -o json` against a non-API host. -// The response body is HTML; errors are always shown in human-readable format on stderr -// regardless of --output flag, so the HTML content should appear in the error block. -func TestVersion_JSONWithBadAPIURL(t *testing.T) { - t.Setenv("CY_API_URL", "http://google.com") - t.Setenv("CY_API_KEY", "") - - root := cmd.NewRootCommand() - var stdout, stderr bytes.Buffer - root.SetOut(&stdout) - root.SetErr(&stderr) - root.SetArgs([]string{"version", "-o", "json"}) - - err := root.Execute() - require.Error(t, err) - - rawErr := strings.TrimSpace(stderr.String()) - require.NotEmpty(t, rawErr, "expected error output on stderr (stdout=%q)", stdout.String()) - - // Errors are always rendered as a human-readable block, not JSON - lower := strings.ToLower(rawErr) - require.True(t, - strings.Contains(lower, "api error"), - "expected 'API Error' header in error output, got: %q", truncateRunes(rawErr, 200)) - - require.True(t, - strings.Contains(lower, ", . Use --jq as shorthand for jq=.`) - rootCmd.PersistentFlags().String("jq", "", `Shorthand for --output jq=. Runs a jq expression over the full JSON response.`) - viper.BindPFlag("output", rootCmd.PersistentFlags().Lookup("output")) - rootCmd.RegisterFlagCompletionFunc("output", func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - base := []cobra.Completion{"json", "yaml", "table", "table=", "table:", "table:border", "table:noheader", "jq="} - fields := cyout.GetModelFields(cmd) - - switch { - case strings.HasPrefix(toComplete, "jq="): - // After jq=. or jq=[]., suggest field names - dotPos := strings.LastIndex(toComplete, ".") - if dotPos >= 0 { - stem := toComplete[:dotPos+1] - comps := make([]cobra.Completion, len(fields)) - for i, f := range fields { - comps[i] = stem + f - } - return comps, cobra.ShellCompDirectiveNoSpace - } - return nil, cobra.ShellCompDirectiveNoSpace - - case strings.HasPrefix(toComplete, "table=") || strings.HasPrefix(toComplete, "table:cols="): - // After table= or table:cols=, suggest field names; after comma, keep stem - stem := toComplete - if comma := strings.LastIndex(toComplete, ","); comma >= 0 { - stem = toComplete[:comma+1] - } - comps := make([]cobra.Completion, len(fields)) - for i, f := range fields { - comps[i] = stem + f - } - return comps, cobra.ShellCompDirectiveNoSpace - - case strings.HasPrefix(toComplete, "table:"): - return []cobra.Completion{"table:noheader", "table:cols="}, cobra.ShellCompDirectiveNoSpace - - default: - // Offer static printers + model field names (for -o canonical, -o name, etc.) - return append(base, fields...), cobra.ShellCompDirectiveNoSpace - } - }) - - rootCmd.PersistentFlags().StringP("verbosity", "v", "warning", "Override the default verbosity for this command. VERBOSITY must be one of: debug, info, warning, error, critical, none.") - viper.BindPFlag("verbosity", rootCmd.PersistentFlags().Lookup("verbosity")) - viper.SetDefault("verbosity", "warning") - - rootCmd.PersistentFlags().String("api-url", "https://http-api.cycloid.io", "Specify the HTTP url of Cycloid API to use eg https://http-api.cycloid.io. This can also be given by CY_API_URL environment variable.") - viper.BindPFlag("api-url", rootCmd.PersistentFlags().Lookup("api-url")) - - rootCmd.PersistentFlags().Bool("insecure", false, "Decide to skip or not TLS verification") - viper.BindPFlag("insecure", rootCmd.PersistentFlags().Lookup("insecure")) - - rootCmd.PersistentFlags().String("org", "", "Specify the org to use. override CY_ORG env var. Required for all Org scoped endpoint.") - viper.BindPFlag("org", rootCmd.PersistentFlags().Lookup("org")) - - // Remove usage on error, this is annoying in scripting - rootCmd.SilenceUsage = true - - // Disable file completion fallback by default - rootCmd.CompletionOptions.SetDefaultShellCompDirective(cobra.ShellCompDirectiveNoFileComp) - - AttachCommands(rootCmd) - - return rootCmd -} - -func AttachCommands(cmd *cobra.Command) { - cmd.AddCommand( - root.NewVersionCmd(), - root.NewStatusCmd(), - root.NewCompletionCmd(), - root.NewGetCommand(), - apikey.NewCommands(), - catalogrepositories.NewCommands(), - configrepositories.NewCommands(), - credentials.NewCommands(), - events.NewCommands(), - externalbackends.NewCommands(), - members.NewCommands(), - organizations.NewCommands(), - pipelines.NewCommands(), - plugins.NewCommands(), - projects.NewCommands(), - environments.NewCommands(), - environmenttypes.NewCommands(), - cloudaccounts.NewCommands(), - components.NewCommands(), - kpis.NewCommands(), - roles.NewCommands(), - stacks.NewCommands(), - login.NewCommands(), - output.NewOutputCmd(), - terracost.NewCommands(), - beta.NewCommands(), - oidc.NewCommands(), - uri.NewURICommands(), - teams.NewTeamsCommands(), - ) -} diff --git a/compose.yml b/compose.yml deleted file mode 100644 index 9d68f61a7..000000000 --- a/compose.yml +++ /dev/null @@ -1,536 +0,0 @@ -services: - # Override API service to create an API from a builded docker image. - youdeploy-api: - image: rg.fr-par.scw.cloud/cycloidio/cycloid-backend:${BACKEND_TAG:-staging} - healthcheck: - test: - - "CMD-SHELL" - - | - test \ - "$(curl -s http://localhost:3001/status \ - | jq -r '.data.checks | map(select((.canonical | contains("database", "pipeline", "secret")) and .status == "Success")) | length' \ - )" = "3" - start_period: 5s - interval: 3s - timeout: 45s - retries: 30 - - ports: - - 3001:3001 - ulimits: - nproc: 65535 - nofile: - soft: 20000 - hard: 40000 - - working_dir: /go/src/github.com/cycloidio/youdeploy-http-api - configs: - - source: youdeploy-config.yml - target: /ci/config.yml - entrypoint: - - bash - - -ec - - | - echo -e "# \e[33mDB migrate ...\e[0m" - timeout 120 bash -c ' - until /go/youdeploy-http-api migrate up --config-file /ci/config.yml --migrations-dir /opt/migrations --db-name=youdeploy_fake && echo "ok"; do - >&2 echo -e "\e[36mWaiting for DB migrations\e[0m" - sleep 1 - done - ' - - echo -e "# \e[33mRunning Cycloid API ...\e[0m" - exec /go/youdeploy-http-api server --config-file /ci/config.yml - - networks: - - cycloid - - depends_on: - database: - condition: service_healthy - redis: &service_started - condition: service_started - concourse-web: *service_started - concourse-db: *service_started - - ## Mysql - database: - restart: always - image: mysql:9.3.0 - platform: linux/x86_64 - configs: - - source: my.cnf - target: /etc/my.cnf - environment: - MYSQL_ROOT_PASSWORD: youdeploy - MYSQL_DATABASE: youdeploy - healthcheck: - test: ["CMD", "mysqladmin", "ping", "-h", "database", "-P3306", "-p=${MYSQL_ROOT_PASSWORD:-youdeploy}"] - start_period: 5s - interval: 1s - timeout: 30s - retries: 30 - tmpfs: [/var/lib/mysql] - networks: - - cycloid - - ## Email - email-smtp-no-tls-auth: - image: axllent/mailpit:v1.27.3 - attach: false - restart: always - environment: - MP_SMTP_AUTH: admin:admin - MP_SMTP_AUTH_ALLOW_INSECURE: "1" - networks: - - cycloid - - ## Vault - vault: - image: hashicorp/vault:1.19 - restart: always - configs: [policy.hcl] - environment: - VAULT_DEV_ROOT_TOKEN_ID: root_token - VAULT_ADDR: http://0.0.0.0:8200 - VAULT_TOKEN: root_token - cap_add: [IPC_LOCK] - tmpfs: [/vault/file] - networks: - - cycloid - - # Override vault entrypoint adding a post script to init our approles - vault-init: - image: hashicorp/vault:1.19 - configs: [policy.hcl] - tmpfs: [/vault/file] - depends_on: [vault] - environment: - VAULT_ADDR: "http://vault:8200" - VAULT_TOKEN: root_token - VAULT_SKIP_VERIFY: true - entrypoint: - - sh - - -ec - - | - # This script must be idempotent - until vault login "$${VAULT_TOKEN:?}" ; do - >&2 echo -e "Waiting for Vault..." - sleep 1 - done - - vault auth enable approle || true - vault write sys/mounts/cycloid type=kv >/dev/null 2>&1 || true - vault write sys/policy/cycloid policy=@policy.hcl >/dev/null 2>&1 - vault write auth/approle/role/cycloid token_ttl=20m token_max_ttl=1h policies=cycloid >/dev/null 2>&1 - vault write auth/approle/role/cycloid/role-id role_id=custom-role-id >/dev/null 2>&1 - vault write auth/approle/role/cycloid/custom-secret-id secret_id=custom-secret-id >/dev/null 2>&1 || true - - networks: - - cycloid - - - redis: - image: redis:8.0.2 - command: - # Port 6379 defaults to TLS, change ports to keep tests pass - - --port - - "6379" - - --tls-port - - "6383" - # Provide self-signed certificate to REDIS TLS - - --tls-ca-cert-file - - /etc/redis/tls/cert - - --tls-cert-file - - /etc/redis/tls/cert - - --tls-key-file - - /etc/redis/tls/key - - --tls-auth-clients - - no - # Configuration Environment for REDIS with self-signed TLS - # Didn't found anything for that - # - ALLOW_EMPTY_PASSWORD=true - configs: - - source: redisTLSCert - target: /etc/redis/tls/cert - - source: redisTLSKey - target: /etc/redis/tls/key - tmpfs: [/data] - networks: - - cycloid - - - git-server: - image: cycloid/backend-tests-git-server:latest - attach: false - restart: always - networks: - - cycloid - tmpfs: - - /git-server/repos:exec - - /git-server/keys - - ## Concourse - concourse-db: - image: postgres:17 - attach: false - environment: - POSTGRES_DB: concourse - POSTGRES_USER: concourse - POSTGRES_PASSWORD: concourse - # warning: starting at version 18, change this path to /var/lib/postgresql - tmpfs: [/var/lib/postgresql/data] - networks: - - cycloid - - concourse-web: - image: concourse/concourse:7.9.1 - links: [concourse-db] - command: web - depends_on: [concourse-db, vault, vault-init] - attach: false - networks: - - cycloid - configs: - - source: base_resource_types_defaults.yml - target: /brt/base_resource_types_defaults.yml - - source: authorized_worker_keys - target: /concourse-keys/authorized_worker_keys - - source: session_signing_key - target: /concourse-keys/session_signing_key - - source: session_signing_key.pub - target: /concourse-keys/session_signing_key.pub - - source: tsa_host_key - target: /concourse-keys/tsa_host_key - - source: tsa_host_key.pub - target: /concourse-keys/tsa_host_key.pub - restart: unless-stopped # required so that it retries until concourse-db comes up - environment: - CONCOURSE_ADD_LOCAL_USER: concourse:concourse - CONCOURSE_MAIN_TEAM_LOCAL_USER: concourse - CONCOURSE_BIND_PORT: 8080 - # Important CF https://github.com/concourse/concourse/issues/2463 "error : named cookie not present" - CONCOURSE_EXTERNAL_URL: "http://localhost:8080" - CONCOURSE_POSTGRES_HOST: "concourse-db" - CONCOURSE_POSTGRES_USER: concourse - CONCOURSE_POSTGRES_PASSWORD: concourse - CONCOURSE_POSTGRES_DATABASE: concourse - CONCOURSE_BASE_RESOURCE_TYPE_DEFAULTS: /brt/base_resource_types_defaults.yml - CONCOURSE_VAULT_URL: "http://vault:8200" - CONCOURSE_VAULT_AUTH_BACKEND: token - CONCOURSE_VAULT_CLIENT_TOKEN: root_token - CONCOURSE_VAULT_PATH_PREFIX: /cycloid - CONCOURSE_VAULT_AUTH_BACKEND_MAX_TTL: 3600s - CONCOURSE_CLUSTER_NAME: dev - - ## Plugin registry (docker image store for plugins) - docker-registry: - image: registry:3.0.0 - ports: - - "${DOCKER_REGISTRY_HOST_PORT:-5000}:5000" - volumes: - - ./docker/auth:/auth - environment: - REGISTRY_AUTH: htpasswd - REGISTRY_AUTH_HTPASSWD_REALM: cycloid - REGISTRY_AUTH_HTPASSWD_PATH: /auth/htpasswd - networks: - - cycloid - - ## Plugin registry service - plugin-registry: - image: cycloid/plugin-registry:latest - environment: - PORT: "4000" - DB_HOST: database - DB_PORT: "3306" - DB_USER: root - DB_PASSWORD: youdeploy - DB_NAME: registry_develop - REDIS_URI: redis://redis:6379 - ORGS_CANS: cycloid - CY_URL: http://youdeploy-api:3001 - REGISTRY_URI: docker-registry:5000 - REGISTRY_USERNAME: cycloid - REGISTRY_PASSWORD: cycloid123 - RUN_MIGRATIONS: "true" - privileged: true - networks: - - cycloid - depends_on: - database: - condition: service_healthy - youdeploy-api: - condition: service_healthy - - ## Plugin manager service - plugin-manager: - image: cycloid/plugin-manager:latest - ports: - - "${PLUGIN_MANAGER_HOST_PORT:-4000}:4000" - environment: - LOG_LEVEL: debug - PORT: "4000" - DB_HOST: database - DB_PORT: "3306" - DB_USER: root - DB_PASSWORD: youdeploy - DB_NAME: manager_develop - REDIS_URI: redis://redis:6379 - CY_URL: http://youdeploy-api:3001 - CY_TOKEN_SECRET: local-test-secret - ORGS_CANS: cycloid - ADMIN_USERNAME: cycloid - ADMIN_PASSWORD: cycloid123 - RUN_MIGRATIONS: "true" - PLUGIN_MANAGER_NAME: test-plugin-manager - PLUGIN_MANAGER_BASE_URL: http://plugin-manager:4000 - privileged: true - networks: - - cycloid - depends_on: - database: - condition: service_healthy - youdeploy-api: - condition: service_healthy - -configs: - ## Mysql - my.cnf: - content: | - [client] - default-character-set = utf8mb4 - - [mysql] - default-character-set = utf8mb4 - - [mysqld] - collation_server = utf8mb4_unicode_ci - character_set_server = utf8mb4 - - ## Concourse - base_resource_types_defaults.yml: - content: | - registry-image: - registry_mirror: - host: 'registry-mirror.owl.cycloid.io' - - docker-image: - registry_mirror: 'https://registry-mirror.owl.cycloid.io' - - authorized_worker_keys: - content: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDo7QaU+1NrYGhiE6XDnkcWYP5w/rUt32VnFemo9XyX8sPUcQwMOh+xVwlqLlSlNZGeZ7zWY+eopR+T9Un5tFILjSpsx83t8fTHBYwno2m0kHw5EixIJY3S6wBs4gm8D2IRHLjT0GDcv39sgfug4PnpIDK/WFLJrJaVbQrMpJ03tm7LjpCWk+uL3gmkU8pglNWehPcGM3KEmlgUVIsAiNXJKYEGPVSrD8TmebaNygwELV9rjuxQcmmYGhJRl01S5mZvfVs7Xj0jW6vBUZHcNkKAjHUOjS4ag1NEr5mA1SRgVKCEGlF0PpQyxgHeYW9pa05iMl1XZpGIC08up1sktNZH ugo@dragonfly - - session_signing_key: - content: | - -----BEGIN RSA PRIVATE KEY----- - MIIEpQIBAAKCAQEA96VDmpRMpzaKl7D1FYsbQLi9jFr2J0EY1MPhvxM4vg8RhgXj - cunyepk3g2ZFFzhR6H9i/p17naDSN99eTl5MGS2HDaqZ8BLAoK/oZx7JLnAkWLIm - QPRfiERQmtUmmVYfdUHeJ7oSQuLuCop/5WUoPSHuqFqqc+uEixQAoF3i0ASRLmS9 - QQg5ZKTAu3ah9j4y8SMWOcKIYe9pg1PcK9HIw6AjknyFyG5rEIylJy/6AWqekavd - filc1JZ8BEBGO4K+4dkXU8Z7RA4MPGA2HpKQBiz0aQCjeJg+BFmpQK1RVMSVYF2b - URQd7fO3mH7OfO+mtARrRDdivgWVEYI0D8x7DQIDAQABAoIBAQDHP2+iGnmF+8sM - ezLlb3Ow4jKXj8QHF0gcP7IM4zE/Ma5+r5Qtq+8NFuNkVE94fDbiokOK6jhAPdmF - XLFqylHd3BSSOVX7o4rafk21Uj65nz6PIl7G2hdW8ugLez3AF1veIu3T9tCkgiLV - 1lNKxNXYQcncKH6GH9MXdzN906wegkkCOzBkg4QJx/HIuzSHBzlqlfEKfPYonAF1 - PmTDR36rqPE9NUBao7NkxZKWAMfXCWYOPrK5yyNNN0PEfXML9s5ddD/79UbvBXtV - byY3bNpfWRXvEhhjLQ2qihxKJzvvBEFPgTcXbCevoImSiI/4XN/Bs5wD4+PYuS3S - 4DkcHzx9AoGBAP37gUzCFrd9/l+D3aWgRqC1OA3IQAbf01S9lGHpoxqRASZFYzwj - ph9X4JAy4/pR+1/MAxc/1dKNS6V53IFdwOH8qmsyrIyokGJW59dwaNd+Vx3LO812 - yKE5W4aSH3b9Eh7nYuJ3Q3Ag3W6QnOe8+F5EvBg05g2etV/eZkmO5TmvAoGBAPmc - 31a6Fm1X6aDvmkfdNuIfzQzb/+hiGYvnT7cS8ljyo4KNFx/cqdDbrVAzuw7Ws2PE - 37u4Ywqv4FQvRk5h6pNOeZBN4Liahw5vNF9KDWDUI6ruHAjd66ucx2fejtVMB5RM - T4qGq/5waJsdOXMKaxgHBPKs+ZqLyK1tzlGD+ZIDAoGBAIgbrTomVSg2ZAhp0XE+ - CDt9gjGYm/9TGZyzD/68x0SoarZIvxpufEsVu+lq7FOsdYrr+MgP1JXGVMC0IqBN - Tt2MmwNhn6iteNrKeeoxem3pbeQwkrbULkaAR3VBf40zp+9ZzttQUJqZcjEbXIqv - 8WYLbcWHK7Ym1EoxFB3dbyhPAoGAVc6QlB66UPJUtOdJEQVBtbAa7B3AtiDrCUYG - CDgyKVOX0+wuk9xmYA70YEq4NhymZFisVLrJCUZ2hloOACn22paygWHUK4GrhdHC - njM1sCCc9kiOSJoJRuBJSDKgxUAyps8o1MUA4SHBQ/li42IkeIkJMWc3EuKUpNHH - iAwnQgMCgYEA2eAOj9kRZE0nC2aXeU/EbhSHNVuz7OBvROMJMmYBb9DQxw5g1vcV - Df2ty+b+5eIl6mivv4dmp2D1YLyYyUXkI/ccfZ7fmQrjKdWywKTlTP2G+rklCSHk - N9aORmeB+s3V4c5lRHYslRevdIOxSd/H0Z45T8s/bEMojozG3swrXSc= - -----END RSA PRIVATE KEY----- - - session_signing_key.pub: - content: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD3pUOalEynNoqXsPUVixtAuL2MWvYnQRjUw+G/Ezi+DxGGBeNy6fJ6mTeDZkUXOFHof2L+nXudoNI3315OXkwZLYcNqpnwEsCgr+hnHskucCRYsiZA9F+IRFCa1SaZVh91Qd4nuhJC4u4Kin/lZSg9Ie6oWqpz64SLFACgXeLQBJEuZL1BCDlkpMC7dqH2PjLxIxY5wohh72mDU9wr0cjDoCOSfIXIbmsQjKUnL/oBap6Rq91+KVzUlnwEQEY7gr7h2RdTxntEDgw8YDYekpAGLPRpAKN4mD4EWalArVFUxJVgXZtRFB3t87eYfs5876a0BGtEN2K+BZURgjQPzHsN ugo@dragonfly - - tsa_host_key: - content: | - -----BEGIN RSA PRIVATE KEY----- - MIIEowIBAAKCAQEAtDaLAcvpkR79VL5M3BtYHUm1rJUSwvNGn0JxBFvjzG+Ni/pv - QUJ9n+CYTNVcmEcB4t0hMTNsrEp1kn1L8QWMC0oQAB796rgHp2kV87UmJuth4ezY - THwp2dvC/ITZ6dn3GSV6koWBEhdC8cNUtS4Zvzq/IQptLVC9twIGM6IlH8WTgTVS - 88MbXJtrzOU5eNgxIxn+FHoh8QHT1CW1FuKdJN0XKP+HPiqzaNb+LcyuEl3bVtoQ - uaGEKT8/QuPLNuq/PzASwu+Kj/7U51BTlNAnLHDtS4m1xI43QLMrE5Uk9KbbCi9a - C/lsR26+pLt9fqevUyOc5KiiTud0OuySLTdbsQIDAQABAoIBACdT19YWh+wxlRtP - RDqshPgvQ8Rb6/I7YOgUedF3tCjDF2K6zlixh/TB8LqjvUdGB7VYiIvSKx8WSL4l - NdNtYHh+Oyurl8IHUzRHjJDYsXDA4WWKaFGYrxFqEg1FeMC93lzQfwVGuToXdXaJ - KA05+EhxK5CsU9MV0bEEchIGio96EmR9IWWKIfgUg597momwfeNyUKOxNJu/9rJP - dUFl2YuC5UDCGHPB7KKxTfw/mFOcXRp7/ARtzSuYIDlECRGGZKBuw81tgmZhsqsJ - yTZQ0wlI51d36xswciloxWqC/z+h8HsSpooqyqAaPsy+94W3dB9zA5lwws9bFfAi - Di3Nc5kCgYEA69DZNsqLljoa2pdfM28dMbIAIfJ/rMBj3kcH2DokWR963zJHw4Tz - k7LXr6IkeWpMD1c/LHFf0/j6FMajo/dRIzJj98UHYIT2NnVa0dNn5uCXkcxSg6p4 - CfyzRMsaW8/qBIx2n6hiK+0rdnaTeOyDtRUq/3dWdeXCBywt0AdnewsCgYEAw6NW - Ylnphb1TNwft4Gz7sctiB46Yiqb+pRHbdohqlgxkddS4YyPRjfYdXbJT42gVgdfZ - NYn8tdsLfylMmv691ewoyQtFtemYcPeNr0pNfCaMIJnBjJ5D52yLG5nYAtcs4yVZ - VIaUH2a9vB26igSb3zKREJ7le4+GWNhUm7Ow2bMCgYEAhq5TQL3Rl008RRgrIT8W - 12koNjs/vDRtVWgQDOi4Fcaq8IrQ/dQTIYoFMaRTXJzfL+vOgt2Fs5UBj5gboewA - hS+kdMAtBG0sCdJgunIZZ31iU7z0a4qS4HFZGbM+LK3EpDBtF6ad2ySrrA7xDyFV - 37hlRF6uHMvKUzpiN+viqB0CgYBUY+rpdfuD001IGcWE374aza61r88hUDPcJL3U - fbfsjd/v7Bi1u0ezwwyb1EbXe5h7cA6kR6eZEqn86mW/Hk/pLXvSbWhetisp379g - c97ExSQBFBInhEWqWGoRN+W0I/ma6guEqKDQgtMpiHFlA+Pw/bERyFkZWaoMPRUS - LQsGfQKBgAdWOVC6Nk3gO1T6r2Lmy2mFD++g/+pmEnPVH9snsNJmh9aw4f9lptHA - H3Q8JR44XozKfo/874Uv5q1BoWyD0vC8mhZoDiwsJ0M1LWXS4CIKVS3gkj2mLpoE - Xpwf1oIKDxZfiIxWtGLbQj1aMclohJ2qvzuNnx6YnASKVHw25EUg - -----END RSA PRIVATE KEY----- - - tsa_host_key.pub: - content: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC0NosBy+mRHv1UvkzcG1gdSbWslRLC80afQnEEW+PMb42L+m9BQn2f4JhM1VyYRwHi3SExM2ysSnWSfUvxBYwLShAAHv3quAenaRXztSYm62Hh7NhMfCnZ28L8hNnp2fcZJXqShYESF0Lxw1S1Lhm/Or8hCm0tUL23AgYzoiUfxZOBNVLzwxtcm2vM5Tl42DEjGf4UeiHxAdPUJbUW4p0k3Rco/4c+KrNo1v4tzK4SXdtW2hC5oYQpPz9C48s26r8/MBLC74qP/tTnUFOU0CcscO1LibXEjjdAsysTlST0ptsKL1oL+WxHbr6ku31+p69TI5zkqKJO53Q67JItN1ux ugo@dragonfly - - ## Vault - policy.hcl: - content: | - path "cycloid/*" { - capabilities = ["create", "read", "update", "delete", "list"] - } - - path "sys/policy/cycloid/*" { - capabilities = ["create", "read", "update", "delete", "list"] - } - - path "auth/approle/role/cycloid-*" { - capabilities = ["create", "read", "update", "delete", "list"] - } - - path "auth/approle/role/" { - capabilities = ["read", "list"] - } - - path "policies" { - capabilities = ["read", "list"] - } - - path "auth/token/create" { - capabilities = ["create"] - } - - path "auth/token/renew-self" { - capabilities = ["create"] - } - - youdeploy-config.yml: - content: | - start-timeout: 10s - max-header-size: "1MB" - port: 3001 - host: 0.0.0.0 - schema: - - http - cleanup-timeout: 1ms - - log-dev-mode: false - log-level: "INFO" - log-svc-level: "INFO" - - db-host: database - db-port: 3306 - db-user: root - db-pwd: youdeploy - db-name: youdeploy - db-max-conns: 15 - db-max-idle-conns: 10 - db-max-lifetime-conn: 5m - - concourse-url: "http://concourse-web" - concourse-port: 8080 - concourse-username: concourse - concourse-password: concourse - concourse-team: main - - vault-role-id: custom-role-id - vault-secret-id: custom-secret-id - vault-url: "http://vault:8200" - - frontend-base-url: "http://localhost:3000" - backend-base-url: "http://youdeploy-api:3001" - - redis-uri: "redis://redis:6379" - - email-smtp-svr-addr: "email-smtp-no-tls-auth:1025" - email-smtp-username: admin - email-smtp-password: admin - email-addr-from: "Cycloid Platform " - email-addr-return-path: "admin+ydbounce@cycloid.io" - email-dev-mode: true - crypto-signing-key: totally-random-secret-key - jwt-keys: - - 2f2122de-63f2-4eec-9c6f-c6abb3e1f007:7cdyHps2tYDp6e7VKPEstE5sDMQbK6WLyN3GmTsF7x7QpE6ZP5ra6yfVSkvXakbB - local-auth-enabled: true - - contact-us-form-url: https://www.cycloid.io/contact-us - tell-us-why-licence-form-url: https://www.cycloid.io/contact-us - - worker-queues: [emails,hubspot,cost_explorer,checks,terracost] - worker-run-internal: true - worker-run-scheduler: true - - redisTLSCert: - content: | - -----BEGIN CERTIFICATE----- - MIID1TCCAr2gAwIBAgIUDFcFTeEQSIK32cpl5/Ca4gxgAKowDQYJKoZIhvcNAQEL - BQAwgZIxCzAJBgNVBAYTAkZSMQ4wDAYDVQQIDAVQYXJpczEOMAwGA1UEBwwFUGFy - aXMxFDASBgNVBAoMC0N5Y2xvaWQgU0FTMRAwDgYDVQQLDAdCYWNrZW5kMRYwFAYD - VQQDDA1MbGFtYSBEZWwgUmV5MSMwIQYJKoZIhvcNAQkBFhRjeWNsb2lkaW9AY3lj - bG9pZC5pbzAeFw0yNTAxMjkxNzA3NTZaFw0yNTAyMjgxNzA3NTZaMIGSMQswCQYD - VQQGEwJGUjEOMAwGA1UECAwFUGFyaXMxDjAMBgNVBAcMBVBhcmlzMRQwEgYDVQQK - DAtDeWNsb2lkIFNBUzEQMA4GA1UECwwHQmFja2VuZDEWMBQGA1UEAwwNTGxhbWEg - RGVsIFJleTEjMCEGCSqGSIb3DQEJARYUY3ljbG9pZGlvQGN5Y2xvaWQuaW8wggEi - MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCbqtopbLmkSf1My6SPuAZcd0rP - mF33XxQb3/DM0lf0HIiBy9gyaVBTvZvceIxWnUb72qHir8x52CFei9mSLUY30uVK - labtTwTWmaE7bylp2NGucRsB88u2SCkmepkaYugLppD908Ua9+PCQVrC34PGnIMG - ZjxhNtDBq/jqDoRpBuK0XwHuvQPvFWaX2OV73cHgFwtKrDdwuuhR/HLQwXwP9tts - wDGn0Lfr1bET0yztpeMz55SJLFcCOMn0/vfELLEIgegHOSRDAslJpAybcHDXtMUW - LGNZ/UXp28LVWJdNcqIKTGfsXL9R6bNfD4If3ukJwXB/DR0BquTrZK2oKxRzAgMB - AAGjITAfMB0GA1UdDgQWBBTo2BtkBMqcNKkwmKGTk02dgyTObTANBgkqhkiG9w0B - AQsFAAOCAQEAVASa88dwuyI6tNyvJGusynBW7gqcOtr+AmYTBDdSulkblaAbcSjQ - jEYS1dZDCzLb35mZVDcs/z3E4ZFtaXjBERrxa5sRfOqHpYPT5jx4LFP/LS+XIpqa - psX6rSmdO84sc14D4xXlewZ6CnA2NNSqkJbxxoTm0mqd/MV9kKXHXkKgKDOeWM3U - roLaJZq5QDukVrMGPUQS6D9pSrTj0oZgxnN0r5o+xy6FMVXK0vJej6x5LH7/i1nk - 3omuCMM6iZSNbMotlK0jy5QPP1g+i+JX2PawFv0rZIDj4NfDBxHt4BIOToyZSrZa - RUwxOeyu4/4XTbtxnIMJwv0avllw2wpVUQ== - -----END CERTIFICATE----- - - redisTLSKey: - content: | - -----BEGIN PRIVATE KEY----- - MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCbqtopbLmkSf1M - y6SPuAZcd0rPmF33XxQb3/DM0lf0HIiBy9gyaVBTvZvceIxWnUb72qHir8x52CFe - i9mSLUY30uVKlabtTwTWmaE7bylp2NGucRsB88u2SCkmepkaYugLppD908Ua9+PC - QVrC34PGnIMGZjxhNtDBq/jqDoRpBuK0XwHuvQPvFWaX2OV73cHgFwtKrDdwuuhR - /HLQwXwP9ttswDGn0Lfr1bET0yztpeMz55SJLFcCOMn0/vfELLEIgegHOSRDAslJ - pAybcHDXtMUWLGNZ/UXp28LVWJdNcqIKTGfsXL9R6bNfD4If3ukJwXB/DR0BquTr - ZK2oKxRzAgMBAAECggEACAdDwScuW97FBZTrI85l5ZbxcMt27S8mJlniXW3rw1dF - YwxUViVAU1FQHIrLEhyCcLLR7pMKhK406l9kFTnoiTCDStl1BoAwy7CYtCwDgsX/ - 6nNC5VLhisEl/ioMg2Pee9tXVv/5Bm8KfBZKzAojDbc8urPDIXBmS9bGu6uMAK6Z - mZgGNU23CxcMF0qHiIBaXbrc26Ud+yqxdoFpalMRD1PZE9o7BLdUj8WBrVM5uBRY - 2Tn1bIOjDSszfs+7j2zvEWNLbS/MaYJ+qyWIg/SIQ5kjTIqraL/IBnSSvz1cySir - OK1jwO7hPqvrjwaxH2sV/U+uJa/sO+yDVsYq4VUEIQKBgQDUDp014UeWEVJzvbOO - 2J8BovSN63K7S6Dj2vOhLPqet3/pnSemmRxZHlhuH1Pt+EkpjajpLf6mbWKICKQ/ - XHrjlcEe4cwjkZjlxgIwWopoXQeWh8+gOyJ6EOo5dfeObiGnMVjpjX1TExXdLbGH - n5iSEs/3+ooa7aBngqCskGrULQKBgQC77NRK5EMcnMUhojP4MCElknnZSAzTra9U - DWMbR1aDfQ3JikVQqozjkQs9SY9gCJhWdne6URm6Nw1YfiLL27C0bgedyWKUvZ1g - 0JGGtNozfUwEA8Lc6oEP1/1CzCIEcKBTgyrnBLHQaD6cteR7GUDHopgjle0zeN6d - 4TqjhDfPHwKBgBlQEUYQOSpZsPzt5RQlGX3phMW4GD7xPShVx4UyyEvP3a32O3hw - iGi+7ZFfnfYnEByssz/6ZI5bOkrAtVJ26JhoFOBp1aNdSuIKq9I3zJO+nxxB4+/d - fzUQ9dScF0viK5Q4mMNwR0h2W8LGJI3q6BxvsHGKb5fdS6tvdVyD9KyVAoGAQM96 - n6F9a769Vc4k8jFXHSgZEdCBa/d4ghpj1aKSuaJFQP6IzTskf88j+y0FX29XampM - /Fq/7rLRzXUi9v97P566zbYIY5fJUPxdVAHHRv6tWq0ZZSsS+63X0FOqX7Gf+W1B - PI8n6+InxdANTk71QmRW597rAVdsHzLwEDinLq0CgYBeUrIVRQDYRqmSiI0JRXk7 - Xn0Dx1J5cpYpCQADo6jdddcHZQsOfVqGFIq2sn/omi+Xyq/N7I5bbm09jNwtf3Zi - cPJlbRttQ1YxFH4KzMOdzeh2jKF8uNXW211Adk/VXNqlN95Ky4kSm7Lrpy92+uux - pVy90/uiPe/6CsFk7ceoDA== - -----END PRIVATE KEY----- - -networks: - cycloid: {} - diff --git a/config/config.go b/config/config.go deleted file mode 100644 index e40e4bc7a..000000000 --- a/config/config.go +++ /dev/null @@ -1,81 +0,0 @@ -package config - -import ( - "fmt" - "os" - - "github.com/adrg/xdg" - "github.com/pkg/errors" - "gopkg.in/yaml.v3" -) - -var ( - appName = "cycloid-cli" - path = "config.yaml" -) - -// Config is the structure handling the config -// of the CLI -type Config struct { - // Organizations is the list of Organization where the user - // is currently logged in - Organizations map[string]Organization `yaml:"organizations"` - // Output is the default output format (e.g. "table", "json", "table:border"). - // Overridden by CY_OUTPUT env var or the --output / --jq flags at runtime. - Output string `yaml:"output,omitempty"` -} - -// Organization is an organization where the user -// is logged in -type Organization struct { - // Organization token - Token string `yaml:"token"` -} - -func GetConfigPath() (string, error) { - configFilePath, err := xdg.ConfigFile(fmt.Sprintf("%s/%s", appName, path)) - if err != nil { - return "", err - } - - return configFilePath, nil -} - -// Read will read the config from the -// path and returns a config struct -func Read() (*Config, error) { - configFilePath, err := xdg.ConfigFile(fmt.Sprintf("%s/%s", appName, path)) - if err != nil { - return &Config{ - Organizations: make(map[string]Organization), - }, errors.Wrap(err, "unable to find XDG config path") - } - content, err := os.ReadFile(configFilePath) - if err != nil { - // we return an empty Config in case it's the first time we try to access - // the config and it does not exist yet - return &Config{ - Organizations: make(map[string]Organization), - }, errors.Wrap(err, "unable to read config from file") - } - var c Config - if err := yaml.Unmarshal(content, &c); err != nil { - return nil, errors.Wrap(err, "unable to decode config from file") - } - return &c, nil -} - -// Write will write the config into the -// path location -func Write(c *Config) error { - content, err := yaml.Marshal(c) - if err != nil { - return errors.Wrap(err, "unable to marshal config structure") - } - configFilePath, err := xdg.ConfigFile(fmt.Sprintf("%s/%s", appName, path)) - if err != nil { - return errors.Wrap(err, "unable to find XDG config path") - } - - return os.WriteFile(configFilePath, content, 0600) -} diff --git a/docker/auth/htpasswd b/docker/auth/htpasswd deleted file mode 100644 index f62e96a31..000000000 --- a/docker/auth/htpasswd +++ /dev/null @@ -1,2 +0,0 @@ -cycloid:$2y$05$sNTvLFbEI0nZzjV3wAgpROU7kIM07zm1MtUH5RBEteXhLnknSrMH2 - diff --git a/docs/adding-a-command.md b/docs/adding-a-command.md deleted file mode 100644 index 25e4bc53c..000000000 --- a/docs/adding-a-command.md +++ /dev/null @@ -1,374 +0,0 @@ -# Adding a Command - -This walkthrough adds a hypothetical `GET /organizations/{org}/widgets/{widget}` endpoint as a concrete example. - -## 1. Find the endpoint - -Check the Cycloid API reference at https://docs.cycloid.io/api/index.html. Note: - -- The HTTP method and path -- Required vs optional parameters -- The response model name (e.g., `Widget`) - -## 2. Ensure the model exists - -Models live in `client/models/` — auto-generated from `swagger.yaml`. If the model already exists, skip this step. - -If `swagger.yaml` was updated: - -```bash -make client-generate # regenerates client/models/ and client/ from swagger.yaml -``` - -Never edit files in `client/models/` by hand. - -## 3. Add middleware interface methods (prefer idempotent flows) - -Open `cmd/cycloid/middleware/middleware.go` and add the required signatures to the `Middleware` interface. -When the resource can be managed idempotently, also expose a `CreateOrUpdateX` helper: - -```go -// cmd/cycloid/middleware/middleware.go -GetWidget(org, widget string) (*models.Widget, *http.Response, error) -CreateWidget(org string, newWidget *models.NewWidget) (*models.Widget, *http.Response, error) -UpdateWidget(org, widget string, update *models.UpdateWidget) (*models.Widget, *http.Response, error) -CreateOrUpdateWidget(org string, widget string, payload *models.NewWidget) (*models.Widget, *http.Response, error) -``` - -Return type conventions: -- Get/Create → `(*models.X, *http.Response, error)` -- List → `([]*models.X, *http.Response, error)` -- Delete/void → `(*http.Response, error)` - -## 4. Implement middleware methods - -Create or extend the feature file. Keep the category name aligned with the API docs tag/category. -For an org-scoped resource in the `Organization` category, use `organization_widgets.go`: - -```go -// cmd/cycloid/middleware/organization_widgets.go -package middleware - -import ( - "net/http" - "github.com/cycloidio/cycloid-cli/client/models" -) - -func (m *middleware) GetWidget(org, widget string) (*models.Widget, *http.Response, error) { - var result *models.Widget - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "widgets", widget}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} - -// Prefer idempotent flows when possible: detect state, then create or update. -func (m *middleware) CreateOrUpdateWidget(org, widget string, payload *models.NewWidget) (*models.Widget, *http.Response, error) { - current, resp, err := m.GetWidget(org, widget) - if err == nil && current != nil { - update := &models.UpdateWidget{ - Name: payload.Name, - } - return m.UpdateWidget(org, widget, update) - } - if resp != nil && resp.StatusCode == http.StatusNotFound { - return m.CreateWidget(org, payload) - } - return nil, resp, err -} -``` - -Key points: -- `Organization: &org` enables auth token lookup -- `Route` segments are path-joined onto `CY_API_URL` -- `GenericRequest` unwraps `{"data": ...}` automatically; pass `&result` directly -- Return `nil, resp, err` on error so callers can inspect the HTTP response -- If no dedicated idempotent API route exists, implement idempotency in middleware (`Get`/`List` then `Create` or `Update`) - -## 5. Follow the `cmd/cycloid/teams` command pattern - -`cmd/cycloid/teams` is the reference pattern for subcommands. The important logic: - -- `cmd.go` defines the category command and wires all subcommands in one place (`AddCommand(...)`). -- Subcommands explicitly define `Args` (`cobra.NoArgs`, `cobra.MinimumNArgs(1)`, etc.) for consistent completion and UX. -- `get` and `delete` support multiple identifiers via positional args and return either one resource or a list. -- `create` supports idempotent behavior with `--update` and can update an existing resource when requested. -- Shared flag/completion logic lives in `internal/cyargs`; command files consume `cyargs.Add*Flag` / `cyargs.Get*`. -- Nested domains are modeled with nested commands (e.g. `teams members ...`). - -## 6. Add cobra command files - -Use a command directory name that matches the API docs category/tag naming. - -``` -cmd/cycloid/widgets/ - cmd.go ← registers subcommands, called from cmd/root.go - get.go ← accepts identifiers as args and/or --widget - create.go ← supports --update idempotent behavior - update.go ← can delegate to create --update flow - delete.go ← accepts one or many identifiers -``` - -```go -// cmd/cycloid/widgets/get.go -package widgets - -import ( - "fmt" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/cyout" - "github.com/cycloidio/cycloid-cli/printer" -) - -var widgetTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "Description"}, - Identifier: "Canonical", -} - -func NewGetWidget() *cobra.Command { - cmd := &cobra.Command{ - Use: "get [widget_identifiers...]", - Short: "Get one or more widgets", - Args: cobra.ArbitraryArgs, - ValidArgsFunction: cyargs.CompleteWidget, - Example: ` -cy --org my-org widgets get my-widget -cy --org my-org widgets get my-widget another-widget -cy --org my-org widgets get --widget my-widget -`, - RunE: getWidget, - } - cyargs.AddOrgFlag(cmd) - cyargs.AddWidgetFlag(cmd) - cyout.RegisterModel(cmd, models.Widget{}) - return cmd -} - -func getWidget(cmd *cobra.Command, args []string) error { - // Step 1: retrieve ALL flags before NewAPI/NewMiddleware - org, err := cyargs.GetOrg(cmd) - if err != nil { - return err - } - - widget, err := cyargs.GetWidget(cmd) - if err != nil { - return err - } - - identifiers := append([]string{}, args...) - if widget != "" { - identifiers = append(identifiers, widget) - } - if len(identifiers) == 0 { - return errors.New("provide at least one widget identifier (arg or --widget)") - } - - // Step 2: build API + middleware - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // Step 3: call middleware + print - if len(identifiers) == 1 { - result, _, err := m.GetWidget(org, identifiers[0]) - return cyout.PrintWithOptions(cmd, result, err, "unable to get widget", widgetTableOptions) - } - - results := make([]*models.Widget, 0, len(identifiers)) - for _, id := range identifiers { - w, _, err := m.GetWidget(org, id) - if err != nil { - return cyout.PrintWithOptions(cmd, nil, err, fmt.Sprintf("unable to get widget %q", id), widgetTableOptions) - } - results = append(results, w) - } - return cyout.PrintWithOptions(cmd, results, nil, "", widgetTableOptions) -} -``` - -Global command directives to follow: - -- `get`: accept canonical/identifier from args and/or flag; show both styles in `Example`; multiple args return `[]*models.Widget`. -- `create`/`update`: share logic for idempotency (`create --update`); `update` should also allow creation. -- `delete`: accept canonical/identifier from args and/or flag; support multiple values; print deleted identifier(s) only. -- Shared flags/completion must live in `internal/cyargs` (except simple bool flags like `--update`, or truly command-specific flags). - -## 7. Register in `cmd.go` - -```go -// cmd/cycloid/widgets/cmd.go -package widgets - -import "github.com/spf13/cobra" - -func NewWidgetsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "widgets", - Short: "Manage widgets", - Args: cobra.NoArgs, - } - cmd.AddCommand(NewGetWidget()) - // cmd.AddCommand(NewListWidgets()) - // cmd.AddCommand(NewCreateWidget()) - return cmd -} -``` - -Register in `cmd/root.go`: - -```go -rootCmd.AddCommand(widgets.NewWidgetsCmd()) -``` - -## 8. Add flags - -**Shared flags** (used by multiple commands) belong in `internal/cyargs/`: - -```go -// internal/cyargs/widgets.go -const widgetFlagName = "widget" - -func AddWidgetFlag(cmd *cobra.Command) string { - cmd.Flags().String(widgetFlagName, "", "Widget canonical or identifier") - _ = cmd.RegisterFlagCompletionFunc(widgetFlagName, CompleteWidget) - return widgetFlagName -} - -func GetWidget(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(widgetFlagName) -} -``` - -**Feature-specific flags** (one command only) can be inline in the command file: - -```go -cmd.Flags().String("format", "json", "Output format for widget data") -``` - -Register shared flags in the constructor: - -```go -func NewGetWidget() *cobra.Command { - cmd := &cobra.Command{...} - cyargs.AddOrgFlag(cmd) - widgetFlag := cyargs.AddWidgetFlag(cmd) - _ = widgetFlag // Example: cmd.MarkFlagRequired(widgetFlag) when needed - return cmd -} -``` - -## 9. Write a middleware unit test - -```go -// cmd/cycloid/middleware/organization_widgets_test.go -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGetWidget(t *testing.T) { - m := NewTestMiddleware() // helper from middleware_test package - result, _, err := m.GetWidget(config.Org, "my-widget") - require.NoError(t, err) - assert.NotNil(t, result) -} -``` - -The `config` global is set up by `TestMain` in `middleware_test.go`. See `docs/testing.md`. - -## 10. Write an e2e test - -```go -// e2e/widgets_test.go -package e2e_test - -import ( - "encoding/json" - "testing" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestWidgets(t *testing.T) { - widgetCanonical := testcfg.RandomCanonical("test-widget") - - t.Run("SuccessWidgetCreate", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "widgets", "create", - "--name", widgetCanonical, - }) - require.NoError(t, cmdErr) - defer t.Run("SuccessWidgetDelete", func(t *testing.T) { - _, deleteErr := executeCommand([]string{ - "--output", "json", "--org", config.Org, - "widgets", "delete", "--widget", widgetCanonical, - }) - require.NoError(t, deleteErr) - }) - - var widget models.Widget - err := json.Unmarshal([]byte(cmdOut), &widget) - require.NoError(t, err) - require.NotNil(t, widget.Canonical) - assert.Equal(t, widgetCanonical, *widget.Canonical) - - t.Run("SuccessWidgetGet", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", "--org", config.Org, - "widgets", "get", "--widget", widgetCanonical, - }) - require.NoError(t, cmdErr) - var got models.Widget - err := json.Unmarshal([]byte(cmdOut), &got) - require.NoError(t, err) - require.NotNil(t, got.Canonical) - assert.Equal(t, widgetCanonical, *got.Canonical) - }) - }) -} -``` - -Pattern: create → nested subtests → deferred delete. - -## 11. Verify - -```bash -make format # fix formatting -make lint # catch issues -go test ./cmd/cycloid/middleware/... -run TestGetWidget # unit test -go test ./e2e/... -run TestWidgets # e2e test (requires make be-reset) -go build -o cy . # confirm it builds -``` - -## File naming checklist - -``` -cmd/cycloid// - cmd.go ← registers subcommands with cobra - list.go ← ListX command - get.go ← GetX command - create.go ← CreateX command - update.go ← UpdateX command - delete.go ← DeleteX command - common.go ← shared helpers (optional) -``` diff --git a/docs/architecture.md b/docs/architecture.md deleted file mode 100644 index f5c63fbe4..000000000 --- a/docs/architecture.md +++ /dev/null @@ -1,220 +0,0 @@ -# Architecture - -## Request lifecycle - -``` -cmd/cycloid//verb.go - │ (cobra RunE) - ▼ -cyargs.Get*() ← parse ALL flags first (required — see CLAUDE.md Hard Rules) - │ -common.NewAPI() ← build API config (URL, token) from flags/env/config file - │ -middleware.NewMiddleware() ← construct middleware struct with HTTP client - │ -m.GetX / m.ListX / ... ← middleware method in cmd/cycloid/middleware/.go - │ -m.GenericRequest(Request{...}, &result) - │ - ▼ -HTTP → Cycloid REST API - │ - ▼ -JSON {"data": } ← GenericRequest unwraps envelope; &result receives payload - │ -cyout.PrintWithOptions() ← stdout (success) or stderr (error); dispatches to printer -``` - -## The `Request` struct - -Defined in `cmd/cycloid/middleware/http_client.go`: - -```go -type Request struct { - Method string - Organization *string // used for auth token lookup; nil = no org context - NoAuth bool // set true to skip Authorization header - Route []string // joined onto base URL path: ["organizations", org, "projects"] - Query any // struct with `url` tags, or url.Values - Headers map[string]string // extra headers merged into request - Accept *string // overrides default Accept header - Body any // JSON-marshalled when non-nil -} -``` - -`Route` segments are path-joined onto the base URL (e.g., `CY_API_URL`). The route should not start with `/`. - -## `GenericRequest` behaviour - -Defined in `cmd/cycloid/middleware/generic_client.go`. - -1. Builds the full URL from `m.api.Config.URL` + `req.Route` -2. Encodes `req.Query` via struct tags (`url:"param_name"`) -3. JSON-marshals `req.Body` -4. Sets `Content-Type: application/json` and (unless `NoAuth`) `Authorization: Bearer ` -5. Executes the HTTP call -6. On non-2xx: returns `*APIResponseError` -7. On 2xx: unwraps the `{"data": ...}` JSON envelope into `response` (the second argument) - — callers pass `&result` directly, not a `struct{ Data *X }` wrapper - -```go -// Correct pattern: -func (m *middleware) GetProject(org, project string) (*models.Project, *http.Response, error) { - var result *models.Project - resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project}, - }, &result) - if err != nil { - return nil, resp, err - } - return result, resp, nil -} -``` - -## Envelope unwrapping - -The Cycloid API wraps all responses: - -```json -{ "data": { ... } } -``` - -`GenericRequest` strips this envelope before deserializing into `response`. If the response body is not envelope-shaped, it falls back to direct unmarshal. - -Pass `nil` as `response` to discard the body (e.g., DELETE calls). - -## Authentication - -`m.api.GetToken(org)` resolves the bearer token in this priority order: - -1. `--api-key` flag -2. `CY_API_KEY` env var -3. `CY_API_TOKEN` env var (legacy) -4. Per-org token stored in the config file (`~/.cy/config.yml`) - -Pass `Organization: &org` in `Request` to allow token lookup. Set `NoAuth: true` for unauthenticated endpoints (e.g., login). - -## Error taxonomy - -| Type | Cause | Go type | -|------|-------|---------| -| API error | Server returned non-2xx | `*APIResponseError` | -| Network error | Transport failure (DNS, TLS, timeout) | `*url.Error` or stdlib | -| Unexpected error | Anything else | `error` (do not wrap) | - -### `APIResponseError` - -```go -type APIResponseError struct { - StatusCode int - Status string - Body []byte // raw response body - Payload *models.ErrorPayload // parsed if body was valid JSON error - Path string // request path (+ query) for fallback errors -} - -// Error() format: -// - payload message available: "API error 422: " -// - fallback body/path: "API error 422 on "/path?query": " -``` - -Check with `errors.As`: - -```go -var apiErr *middleware.APIResponseError -if errors.As(err, &apiErr) { - if apiErr.StatusCode == 409 { - // conflict - } -} -``` - -Common status codes: 400 bad request, 401 unauthorized, 403 forbidden, 404 not found, 409 conflict, 422 unprocessable entity. - -### JSON output and API error diagnostics - -Errors that implement `printer.ErrHTTPResponse` attach the HTTP status code and raw response body (`*APIResponseError` for non-2xx, plus the decode error type returned by `GenericRequest` when a 2xx body cannot be unmarshaled). When `--output json` is used, the JSON printer first tries to marshal the value normally. If marshaling fails but the value is an error satisfying `ErrHTTPResponse`, it prints a small JSON object instead: `cli_marshal_error`, `http_status`, `api_response_preview` (first 10 lines of the body), and optionally `request_path` when the error also implements `printer.RequestPather` (as `*APIResponseError` does). - -## Why `client/client/` is unused - -The repository used to use the go-swagger generated operations package (`client/client/`). It was removed in the middleware refactor (see `docs/middleware-refactor.md`) in favour of `GenericRequest`: - -- Generated operations had inconsistent error handling -- Every API change required re-running the full swagger codegen cycle -- `GenericRequest` gives explicit control over routing, auth, headers, and response decoding - -The `client/models/` package (data types) is still auto-generated from `swagger.yaml` and must not be edited manually. - -## `--output` system - -The `--output` flag (default: `table`) controls how results are rendered. It is parsed by `printer/factory/factory.go` into a `printer.Printer` implementation. - -### Grammar - -| Value | Result | -|-------|--------| -| `table` | Default curated table (columns defined per command) | -| `table=col1,col2` | Table with explicit column selection | -| `table:noheader` | Table without the header row | -| `table=col1,col2:noheader` | Combined column selection + no header | -| `json` | Full JSON (pretty-printed) | -| `yaml` | Full YAML | -| `jq=` | Run jq expression over full JSON; strings printed raw, objects as pretty JSON | -| `` | Extract named field, one value per line (case-insensitive, dot notation OK) | - -`--jq ` is a shorthand flag for `-o jq=` and resolves identically. - -### Field extraction examples - -```sh -cy project list -o canonical # one canonical per line -cy project list -o owner.username # nested field -cy project list -o "jq=.[].canonical" # equivalent via jq -cy project delete $(cy project list -o canonical) # pipe pattern -``` - -### Shell completion - -Commands call `cyout.RegisterModel(cmd, models.X{})` in their constructor to register their model's fields. The global `--output` completion function reads these and suggests field names alongside `json`, `yaml`, `table`, and `jq=`: - -```sh -cy project list -o → json yaml table table= jq= canonical name id ... -cy project list -o table= → table=canonical table=name table=id ... -cy project list -o can → canonical -``` - -### Adding table columns to a command - -Define a `printer.Options` var in the command package and pass it to `cyout.PrintWithOptions`: - -```go -var widgetTableOptions = printer.Options{ - Columns: []string{"Canonical", "Name", "Description"}, - Identifier: "Canonical", // never dropped when terminal is narrow -} - -// in RunE: -return cyout.PrintWithOptions(cmd, result, err, "unable to get widget", widgetTableOptions) -``` - -Column names support dot notation for nested fields (`"Owner.Username"`). The `Identifier` column is always shown even when the terminal is too narrow to show all columns. - -### `cyout` package - -`internal/cyout/` provides two helpers that replace the 3-line `GetOutput`/`GetPrinter`/`SmartPrint` boilerplate: - -```go -// Simple (no column customisation): -cyout.Print(cmd, obj, err, "unable to do X") - -// With column options: -cyout.PrintWithOptions(cmd, obj, err, "unable to do X", tableOptions) -``` - -Errors are routed to `cmd.ErrOrStderr()`, results to `cmd.OutOrStdout()`. - -## Pipeline build watch (human SSE formatting) - -`cy pipeline build trigger --watch` streams build events while polling until the build finishes. Human vs raw NDJSON formatting lives in `internal/buildwatch`; the cobra command only passes options and calls `buildwatch.Watch`. If it causes problems, see [pipeline-build-watch-output.md](./pipeline-build-watch-output.md) for how to disable or remove it without touching the HTTP client. diff --git a/docs/middleware-refactor.md b/docs/middleware-refactor.md deleted file mode 100644 index d9c7e1309..000000000 --- a/docs/middleware-refactor.md +++ /dev/null @@ -1,119 +0,0 @@ -# Middleware Refactor - -## What changed - -The middleware layer was rewritten to remove the go-swagger generated operations package (`client/client/`) in favour of a single generic HTTP client (`GenericRequest` in `cmd/cycloid/middleware/generic_client.go`). - -### Before - -Each API endpoint was represented by a generated operation struct in `client/client/`: - -```go -// OLD — do not use -params := operations.NewGetOrganizationsOrgProjectsProjectParams() -params.SetOrganizationCanonical(org) -params.SetProjectCanonical(project) -resp, err := m.api.Client.Organizations.GetOrganizationsOrgProjectsProject(params, auth) -``` - -### After - -All API calls go through `GenericRequest`: - -```go -// NEW — current pattern -var result *models.Project -resp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "projects", project}, -}, &result) -``` - -## Why the change - -| Pain point | Old (generated operations) | New (GenericRequest) | -|------------|--------------------------|---------------------| -| Error handling | Inconsistent per-operation types | Single `*APIResponseError` | -| Auth | Per-call auth parameter | Automatic via `Organization` field | -| API changes | Full codegen cycle required | Update route string + model | -| Routing | Opaque generated code | Explicit `Route` slice | -| Testing | Required generated mocks | Direct HTTP testing | -| `{"data":...}` envelope | Handled inconsistently | Always unwrapped in one place | - -## New invariants - -Every middleware method follows the same contract: - -```go -// Delete / void -func (m *middleware) DeleteX(org, x string) (*http.Response, error) - -// Get / Create -func (m *middleware) GetX(org, x string) (*models.X, *http.Response, error) - -// List -func (m *middleware) ListX(org string) ([]*models.X, *http.Response, error) -``` - -- Always return `(*http.Response, error)` at minimum so callers can inspect status codes -- Callers assign `_` to the response if they don't need it -- On error, return `nil, resp, err` (include resp so caller can check status) -- Do not validate payloads in middleware — validate in commands or leave it to the API - -## The `client/models/` exception - -Only the **operations** layer was removed. The **models** layer (`client/models/`) is still generated from `swagger.yaml` and is still used everywhere. - -``` -client/ - models/ ← STILL generated, DO NOT edit manually - client/ ← REMOVED (operations layer, do not use) -``` - -If you see an import like `"github.com/cycloidio/cycloid-cli/client/client/..."`, remove it and replace with `GenericRequest`. - -## Local model types - -Some models were removed from the swagger spec but are still needed by the CLI. These live directly in the middleware package: - -```go -// cmd/cycloid/middleware/http_client.go -type StackVersion struct { ... } -type StackUseCase struct { ... } -``` - -This is intentional — do not move them to `client/models/`. - -## Debug logging - -`GenericRequest` emits HTTP debug logs when `CY_VERBOSITY=debug` (set via `--verbosity debug` or the env var). Logs include: - -- Method, full URL, headers, body -- Response status, headers, body, elapsed time -- `Authorization` header is redacted: `Bearer ***XXXXX` (last 5 chars only) - -During tests: `CY_TEST_VERBOSITY=debug` — `TestMain` propagates it to `CY_VERBOSITY`. - -> ⚠️ Debug logs may contain sensitive data in request/response bodies beyond credentials. - -## Migration reference - -If you find code still using the old generated operations client, replace it: - -```go -// OLD — remove -import "github.com/cycloidio/cycloid-cli/client/client/operations" -params := operations.NewGetSomethingParams().WithOrg(org) -resp, err := m.api.Client.Operations.GetSomething(params, auth) -return resp.Payload.Data, nil, err - -// NEW — replace with -var result *models.Something -httpResp, err := m.GenericRequest(Request{ - Method: "GET", - Organization: &org, - Route: []string{"organizations", org, "somethings", id}, -}, &result) -return result, httpResp, err -``` diff --git a/docs/pipeline-build-watch-output.md b/docs/pipeline-build-watch-output.md deleted file mode 100644 index ccfbac601..000000000 --- a/docs/pipeline-build-watch-output.md +++ /dev/null @@ -1,108 +0,0 @@ -# Pipeline build watch: human-formatted SSE output - -This document describes the **optional presentation layer** for `cy pipeline build trigger --watch` (aliases: `pp build create|run --watch`). It lives in `internal/buildwatch`; `cmd/cycloid/pipelines` only wires flags and calls `buildwatch.Watch`. The layer exists so interactive use is readable; it is **not** required for correctness of the watch loop or API. - -If this layer causes regressions (missing lines, wrong parsing, terminal quirks, CI noise), use **Quick disable** below first, then **Full removal** if you want it gone entirely. - ---- - -## User-facing behavior - -| Situation | Stream written to stdout | -|-----------|---------------------------| -| `--watch` and **not** `--output json` | **Human**: one-line prefixes (`[build]`, `[task]`, `[stdout]` / `[stderr]`, `[res]` in verbose mode). Concourse JSON events are parsed and filtered. | -| `--watch` and `--output json` | **Raw**: NDJSON lines exactly as in the SSE `data:` payloads (legacy scripting behavior). | -| TTY + human | ANSI colors from `buildwatch.DefaultStreamTheme` in `internal/buildwatch/theme.go`. | -| Non-TTY or piped stdout + human | No ANSI; ANSI in log payloads is stripped. | -| Global `--verbosity debug` (or `-v debug`) + human + `--watch` | Emits extra “plumbing” events (image checks, workers, etc.). No effect when output is raw JSON (`--output json`). | - -**Log noise control:** Whitespace-only log payloads and blank lines inside a payload are skipped so empty Concourse log events do not print spacer lines. - -**Build link (stderr, before the stream):** With `--watch`, the CLI prints the build id and a console deep link on **stderr** so stdout can stay clean (e.g. raw JSON). The link uses: - -`{console_url}/organizations/{org}/projects/{project}/environments/{env}/components/{component}/pipelines/{pipeline}/jobs/{job}/builds/{build_id}` - -The default `console_url` is `https://console.cycloid.io`. Override with **`CY_CONSOLE_URL`** only (no CLI flag). If `CY_CONSOLE_URL` is set to an empty value, a stderr line explains that no link can be printed. - -**Ctrl+C reminder:** Before the stream, stderr also notes: first Ctrl+C requests a remote build abort; second exits watch immediately (see below). - -## Ctrl+C while watching - -Handled in `internal/buildwatch/watch.go` (not the cobra layer): - -1. **First Ctrl+C:** sends a **build abort** request (`AbortBuild`) so the remote build can stop gracefully. A short hint is printed to stderr (via `StatusWriter`): press Ctrl+C again to leave watch immediately. -2. **Second Ctrl+C:** **cancels** the local watch (stops polling and the event stream). The process exits with code **130** (`watch interrupted`), matching the usual `128 + SIGINT` convention. - -Disable this for tests with `Options.DisableInterruptHandler`. - ---- - -## Code map (files to inspect or delete) - -| File | Role | -|------|------| -| `cmd/cycloid/pipelines/build_trigger.go` | Cobra only: chooses `buildwatch.OutputHuman` vs `OutputRaw`, TTY theme, `StripLogANSI`, verbosity→`Verbose`, calls `buildwatch.Watch`. | -| `internal/buildwatch/watch.go` | `Watch`, `Client`, `Options`, `ExitError`, SSE consumption, reconnect loop, polling, Ctrl+C handling. | -| `internal/buildwatch/format.go` | Human line rendering, `formatHumanBuildEvent`, `paintLogLines`, ANSI stripping in payloads. | -| `internal/buildwatch/theme.go` | `StreamTheme`, `DefaultStreamTheme` (edit here to change colors only). | -| `internal/buildwatch/events.go` | JSON structs for Concourse event envelopes. | -| `internal/buildwatch/watch_test.go` | Tests for formatters and watch wiring. | - -Middleware `OpenBuildEventsStream` (`cmd/cycloid/middleware/component_pipelines_jobs_builds.go`) is unchanged: it still returns `text/event-stream`. - ---- - -## Quick disable (keep package, force raw stream) - -To make **`--watch` always behave like raw NDJSON** regardless of `--output` (fastest rollback): - -1. Open `cmd/cycloid/pipelines/build_trigger.go`. -2. In the `if watch {` block, force raw output mode, for example: - -```go -outMode := buildwatch.OutputRaw -// Was: human unless --output json; temporarily forcing raw — see docs/pipeline-build-watch-output.md -``` - -3. You can drop the `theme` / `stripLogANSI` / `IsTerminalWriter` block when `outMode` is always `OutputRaw` (optional cleanup). - -4. Run `make format && make lint` and `go test ./internal/buildwatch/... ./cmd/cycloid/pipelines/...`. - -Debug verbosity then only affects HTTP logging elsewhere, not the watch stream (already raw). - ---- - -## Full removal (restore passthrough-only watch) - -1. **Delete** (or revert in git) the package directory: - - `internal/buildwatch/` (all `.go` files) - -2. **`cmd/cycloid/pipelines/build_trigger.go`** - - Remove `internal/buildwatch` import. - - Inline a minimal watch loop **or** copy a slim `watch.go` back under `cmd/cycloid/pipelines` that only passthrough-writes SSE `data:` payloads (see git history before `internal/buildwatch`). - -3. **`go.mod`** - - Run `go mod tidy` if `golang.org/x/term` is no longer referenced. - -4. **Docs** - - Delete this file and remove links from `docs/architecture.md`, `CLAUDE.md`, and `AGENTS.md`. - ---- - -## Flags reference - -| Flag | Meaning | -|------|---------| -| `--watch` | Wait for build completion while streaming build events. | -| `--timeout` | With `--watch`, max seconds before giving up (see `--watch-cancel-on-timeout`). | -| `--watch-cancel-on-timeout` | With `--watch`, call abort when `--timeout` elapses. | -| `--output json` | Watch stream stays machine-readable NDJSON. | -| `--verbosity debug` | With human watch output, print all parsed event types. | - ---- - -## Maintenance notes - -- **Do not** tie this to `cyargs` project `--color`; watch colors are isolated in `internal/buildwatch/theme.go`. -- Parser failures on a `data:` line fall back to writing that line unchanged (plus newline), so unknown event shapes still surface as text. -- Changing Concourse event schemas may require updates to `internal/buildwatch/events.go` and the `switch` in `formatHumanBuildEvent` (`format.go`). diff --git a/docs/testing.md b/docs/testing.md deleted file mode 100644 index 752156b02..000000000 --- a/docs/testing.md +++ /dev/null @@ -1,307 +0,0 @@ -# Testing - -## Overview - -There are two test layers: - -| Layer | Location | Runs against | -|-------|----------|--------------| -| Middleware unit tests | `cmd/cycloid/middleware/*_test.go` | Real backend (via `testcfg`) | -| E2E tests | `e2e/*_test.go` | Real backend (via `testcfg`) | - -Both layers require a running Cycloid backend. See [Running tests](#running-tests). - -## Running tests - -```bash -# Start the backend -make be-reset - -# Run all tests -make test -# or -go test ./... - -# Run a specific middleware test -go test ./cmd/cycloid/middleware/... -run TestGetProject - -# Run a specific e2e test -go test ./e2e/... -run TestProjects - -# Stop the backend when done -make be-stop -``` - -`make be-reset` is preferred for test runs because it starts from a clean backend state. - -E2E tests are **not run in parallel** — the backend uses git under the hood and cannot handle concurrent writes. - -## Environment variables - -| Variable | Purpose | -|----------|---------| -| `CY_TEST_API_URL` | Backend URL (default: `http://localhost:3001` — youdeploy-api host port mapped by compose) | -| `CY_API_KEY` | API key for authentication | -| `CY_TEST_ROOT_ORG` | Root org canonical for provisioning | -| `API_LICENCE_KEY` | Licence key (required by some backend features) | -| `CY_TEST_PROVISION_API` | Set to `true` to provision test fixtures via API | -| `CY_TEST_VERBOSITY` | Set to `debug` to enable HTTP debug logs | - -### Generating `.env` from prod credentials - -The repo ships an `.env.sample` with `cy://` URIs that resolve to real secrets. Generate a local `.env` by interpolating against your prod org: - -```bash -# 1. Point cy at prod (uses bao-backed cyset shell function) -cyset API_prod_cycloid - -# 2. Interpolate — resolves cy:// URIs to real values -cy uri interpolate .env.sample > .env -``` - -`.env` is git-ignored. Re-run step 2 whenever secrets rotate. The file is sourced automatically by `docker compose` when you run `make be-reset`. - -The compose stack now uses Docker auto-IPAM (no static `192.168.10.0/24`); services -talk to each other via service DNS names (e.g. `youdeploy-api:3001`, -`docker-registry:5000`). Only `youdeploy-api` (port `3001`) and `docker-registry` -(port `${DOCKER_REGISTRY_HOST_PORT:-5000}`) are bound to the host — everything -else is internal-only. - -`CY_TEST_VERBOSITY=debug` propagates to `CY_VERBOSITY=debug` inside `TestMain`, enabling full request/response logging. Logs include credentials (redacted to last 5 chars of the token). - -## `testcfg` package - -`pkg/testcfg` manages test fixture provisioning. It creates a real org, project, environment, and component against the backend. - -### `NewConfig(name string)` - -```go -config, err := testcfg.NewConfig("middleware") -defer config.Cleanup() -``` - -After a successful call, `config` exposes: - -| Field | Type | Description | -|-------|------|-------------| -| `config.Org` | `string` | Organization canonical | -| `config.APIUrl` | `string` | Backend URL | -| `config.APIKey` | `string` | API key scoped to this test run | -| `config.Project` | `*models.Project` | Pre-created project | -| `config.Environment` | `*models.Environment` | Pre-created environment | -| `config.Component` | `*models.Component` | Pre-created component | -| `config.ConfigRepo` | `*models.ExternalBackend` | Pre-created config repository | -| `config.CatalogRepo` | `*models.ServiceCatalogSource` | Pre-created catalog repository | - -### Cleanup - -`config.Cleanup()` deletes all provisioned resources. Always defer it immediately after `NewConfig`: - -```go -config, err := testcfg.NewConfig("middleware") -defer config.Cleanup() -``` - -### `AppendCleanup` - -Register additional teardown for resources created inside a test: - -```go -config.AppendCleanup(func() { - m.DeleteProject(config.Org, projectCanonical) -}) -``` - -### `RandomCanonical` - -```go -canonical := testcfg.RandomCanonical("prefix") -// returns something like "prefix-a1b2c3" -``` - -Use this for test resource names to avoid conflicts across parallel test runs (different packages). - -## Middleware unit tests - -### Setup - -Each test package has a `TestMain` in `middleware_test.go`: - -```go -var config *testcfg.Config - -func runMain(ctx context.Context, main *testing.M) (int, error) { - var err error - config, err = testcfg.NewConfig("middleware") - defer config.Cleanup() - if err != nil { - return 1, fmt.Errorf("config setup failed: %w", err) - } - - os.Setenv("CY_API_URL", config.APIUrl) - os.Setenv("CY_API_KEY", config.APIKey) - os.Setenv("CY_ORG", config.Org) - - if v := os.Getenv("CY_TEST_VERBOSITY"); v != "" { - viper.Set("verbosity", v) - } - return main.Run(), nil -} -``` - -### Writing a middleware test - -```go -// cmd/cycloid/middleware/organization_projects_test.go -package middleware_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGetProject(t *testing.T) { - m := NewTestMiddleware() // helper from middleware_test package - result, _, err := m.GetProject(config.Org, *config.Project.Canonical) - require.NoError(t, err) - require.NotNil(t, result) - assert.Equal(t, *config.Project.Canonical, *result.Canonical) -} -``` - -Focus on the happy path. Error paths are implicitly covered by e2e tests. - -## E2E tests - -### Setup - -`e2e/e2e_test.go` has its own `TestMain` with the same `testcfg.NewConfig` pattern. Fixtures from `testcfg` are available via the package-level `config` variable. - -### Helpers - -```go -// Execute a CLI command and return stdout, error -cmdOut, cmdErr := executeCommand([]string{"--org", config.Org, "project", "list"}) - -// Execute with stdin input -cmdOut, cmdErr := executeCommandStdin(stdin, []string{"--org", config.Org, "pipeline", "update"}) - -// Write a temporary file -WriteFile(path, content) - -// Random canonical -canonical := randomCanonical("prefix") // local alias for testcfg.RandomCanonical -``` - -### Pattern: create → test → deferred delete - -```go -import ( - "encoding/json" - "testing" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestWidgets(t *testing.T) { - canonical := testcfg.RandomCanonical("test-widget") - - t.Run("SuccessWidgetCreate", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", "--org", config.Org, - "widgets", "create", "--name", canonical, - }) - require.NoError(t, cmdErr) - - defer t.Run("SuccessWidgetDelete", func(t *testing.T) { - _, err := executeCommand([]string{ - "--output", "json", "--org", config.Org, - "widgets", "delete", "--widget", canonical, - }) - require.NoError(t, err) - }) - - var widget models.Widget - err := json.Unmarshal([]byte(cmdOut), &widget) - require.NoError(t, err) - require.NotNil(t, widget.Canonical) - assert.Equal(t, canonical, *widget.Canonical) - - t.Run("SuccessWidgetGet", func(t *testing.T) { ... }) - t.Run("SuccessWidgetUpdate", func(t *testing.T) { ... }) - }) -} -``` - -The `defer` on `SuccessWidgetDelete` ensures cleanup even if inner tests fail. - -### `create --update` (upsert) coverage - -When you add or change idempotent `create --update` behavior, extend **existing** e2e files for that resource in the same change. Examples in this repo: - -| Area | File | Notes | -|------|------|--------| -| Teams | `e2e/teams_test.go` | Name-only upsert (`SuccessTeamCreateUpdateWithNameOnly`) | -| Projects / envs | `e2e/projects_test.go`, `e2e/environments_test.go` | Already cover inferred canonical + `--update` | -| Child orgs | `e2e/organizations_test.go` | Duplicate create errors; `create --update` succeeds | -| Catalog repos | `e2e/catalog_repositories_test.go` | Nested in `SuccessCatalogRepositoriesCreate`: duplicate create errors; `create --update` succeeds | -| Stacks (blueprint) | `e2e/stacks_test.go` | Existing canonical + `--update` returns same stack | - -`e2e/config_repositories_test.go` is currently skipped (BE-981); when it is re-enabled, add matching `--update` cases there. - -### Known skipped tests - -| Test | File | Reason | -|------|------|--------| -| `SuccessOrganizationsList` | `organizations_test.go` | Requires user token; e2e uses API key (422) | -| `TestInfraPolicies` | `infra_policies_test.go` | Skipped pending backend availability | -| `PipelineClearTaskCacheOk` | `pipelines_test.go` | Pending backend support | -| `TestConfigRepositories` (some subtests) | `config_repositories_test.go` | See BE-981 | - -### JSON helpers - -```go -// Extract field values from a JSON array by matching another field -ids, err := JSONListExtractFields(listOut, "id", "email", "^admin@cycloid.io$") -// Returns []string of "id" values where "email" matches the regex -``` - -## Fixtures - -Shared test fixtures are defined in `e2e/helpers_test.go`: - -- `TestPipelineSample` — minimal Concourse pipeline YAML -- `TestPipelineVariables` — matching pipeline vars YAML -- `TestInfraPolicySample` — Rego policy -- `TestTerraformPlanSample` — minimal Terraform JSON plan (used by terracost + infra policies) - -## Plugin services - -`make be-reset` brings up three additional services for plugin testing: - -| Service | Port (internal) | Host port | Purpose | -|---|---|---|---| -| `plugin-manager` | 4000 | — | Schedules plugin containers via containerd (privileged) | -| `plugin-registry` | 4000 | — | REST API metadata store for plugin definitions | -| `docker-registry` | 5000 | `${DOCKER_REGISTRY_HOST_PORT:-5000}` | OCI image store (htpasswd auth) | - -The docker-registry uses basic auth seeded from `docker/auth/htpasswd` -(`cycloid` / `cycloid123`). The plugin-manager auto-registers itself on -startup as `test-plugin-manager` against the youdeploy-api at -`http://youdeploy-api:3001` using `CY_URL` from compose. - -Smoke-test the plugin lifecycle with: - -```bash -docker login localhost:5000 -u cycloid -p cycloid123 -docker pull docker.io/cycloid/plugin-hello-world -docker tag docker.io/cycloid/plugin-hello-world localhost:5000/plugin-hello-world:1.0.0 -docker push localhost:5000/plugin-hello-world:1.0.0 -``` - -Plugin version tags **must** match `\d+\.\d+\.\d+` — `latest` is rejected by -`plugin registry plugin version publish`. diff --git a/e2e/api_keys_test.go b/e2e/api_keys_test.go deleted file mode 100644 index 3a06ad293..000000000 --- a/e2e/api_keys_test.go +++ /dev/null @@ -1,184 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "slices" - "testing" - - "github.com/sanity-io/litter" - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func TestAPIKeysCmd(t *testing.T) { - var ( - testKeyCanonical = randomCanonical("test-admin") - createdAPIKey models.APIKey - ) - t.Run("CreateAPIKeyAdminOk", func(t *testing.T) { - args := []string{ - "--output", "json", - "--org", config.Org, - "api-key", "create", - "--canonical", testKeyCanonical, - "--description", "hello world", - "--rules", `[{"action":"organization:**","effect":"allow","resources":[]}]`, - } - createOut, createErr := executeCommand(args) - if createErr != nil { - t.Errorf("failed to create api key admin: %s", createErr) - } - - defer t.Run("DeleteAPIKeyOk", func(t *testing.T) { - args := []string{ - "--output", "json", - "--org", config.Org, - "api-key", "delete", - "--canonical", testKeyCanonical, - } - _, deleteErr := executeCommand(args) - if deleteErr != nil { - t.Errorf("failed to delete api key admin: %s", deleteErr) - } - }) - - err := json.Unmarshal([]byte(createOut), &createdAPIKey) - if err != nil { - t.Errorf("CLI output can't be serialize to models.APIKey, out:\n%s\nerr:\n%s", createOut, err) - } - - assert.Equal(t, *createdAPIKey.Canonical, testKeyCanonical) - - var APIKeyList []*models.APIKey - t.Run("ListAPIKeyOk", func(t *testing.T) { - args := []string{ - "--output", "json", - "--org", config.Org, - "api-key", "list", - } - listOut, listErr := executeCommand(args) - if listErr != nil { - t.Errorf("failed to list api keys: %s", listErr) - } - - err := json.Unmarshal([]byte(listOut), &APIKeyList) - if err != nil { - t.Errorf("failed to parse cli output as list of api keys, out: %s\nerr: %s", listOut, err) - } - - if index := slices.IndexFunc(APIKeyList, func(a *models.APIKey) bool { - return *a.Canonical == testKeyCanonical - }); index == -1 { - t.Errorf("failed to find the API key with can '%s' in list: %s", testKeyCanonical, litter.Sdump(APIKeyList)) - } - }) - - t.Run("GetAPIKeyOk", func(t *testing.T) { - args := []string{ - "--output", "json", - "--org", config.Org, - "api-key", "get", - "--canonical", testKeyCanonical, - } - getOut, getErr := executeCommand(args) - if getErr != nil { - t.Errorf("failed to get api key: %s", getErr) - } - - var gotKey models.APIKey - if err := json.Unmarshal([]byte(getOut), &gotKey); err != nil { - t.Errorf("CLI output can't be serialized to models.APIKey, out:\n%s\nerr:\n%s", getOut, err) - } - assert.Equal(t, testKeyCanonical, *gotKey.Canonical) - }) - - t.Run("GetWithPositionalArg", func(t *testing.T) { - args := []string{ - "--output", "json", - "--org", config.Org, - "api-key", "get", - testKeyCanonical, // positional, no --canonical - } - getOut, getErr := executeCommand(args) - if getErr != nil { - t.Errorf("failed to get api key via positional arg: %s", getErr) - } - - var gotKey models.APIKey - if err := json.Unmarshal([]byte(getOut), &gotKey); err != nil { - t.Errorf("CLI output can't be serialized to models.APIKey, out:\n%s\nerr:\n%s", getOut, err) - } - assert.Equal(t, testKeyCanonical, *gotKey.Canonical) - }) - - t.Run("RecreateAPIKey", func(t *testing.T) { - tmpCan := randomCanonical("test-recreate") - rules := `[{"action":"organization:**","effect":"allow","resources":[]}]` - - // Create - _, err := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "api-key", "create", - "--canonical", tmpCan, - "--rules", rules, - }) - if err != nil { - t.Errorf("setup: failed to create api key for recreate test: %s", err) - } - - defer t.Run("RecreateCleanup", func(t *testing.T) { - executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "api-key", "delete", - tmpCan, - }) - }) - - // Second create without --recreate should fail - _, dupErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "api-key", "create", - "--canonical", tmpCan, - "--rules", rules, - }) - assert.Error(t, dupErr, "second create without --recreate should fail") - - // Third create with --recreate should succeed - _, recreateErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "api-key", "create", - "--canonical", tmpCan, - "--rules", rules, - "--recreate", - }) - assert.NoError(t, recreateErr, "create --recreate should succeed for existing api key") - }) - - t.Run("DeleteWithPositionalArg", func(t *testing.T) { - tmpCan := randomCanonical("test-del-pos") - _, err := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "api-key", "create", - "--canonical", tmpCan, - "--rules", `[{"action":"organization:**","effect":"allow","resources":[]}]`, - }) - if err != nil { - t.Errorf("setup: failed to create api key: %s", err) - } - - _, deleteErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "api-key", "delete", - tmpCan, // positional, no --canonical - }) - assert.NoError(t, deleteErr, "delete via positional arg should succeed") - }) - }) -} diff --git a/e2e/catalog_repositories_test.go b/e2e/catalog_repositories_test.go deleted file mode 100644 index 7a168c963..000000000 --- a/e2e/catalog_repositories_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func TestCatalogRepositories(t *testing.T) { - defer t.Run("SuccessCatalogRepositoriesDelete", func(t *testing.T) { - // Cleanup just in case - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "delete", - "--canonical", "step-by-step", - }) - - assert.Nil(t, cmdErr, "failed to delete test catalog repo:", cmdOut) - }) - - t.Run("SuccessCatalogRepositoriesCreate", func(t *testing.T) { - // Cleanup just in case - executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "delete", - "--canonical", "step-by-step", - }) - - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "create", - "--branch", "stack-aws", - "--url", "https://github.com/cycloid-community-catalog/docs-step-by-step-stack.git", - "--name", "step-by-step", - }) - - require.Nil(t, cmdErr) - - assert.Contains(t, cmdOut, "canonical\": \"stack-aws-sample") - - t.Run("SuccessCatalogRepositoriesCreateDuplicateWithoutUpdateErrors", func(t *testing.T) { - _, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "create", - "--branch", "stack-aws", - "--url", "https://github.com/cycloid-community-catalog/docs-step-by-step-stack.git", - "--name", "step-by-step", - }) - require.Error(t, cmdErr, "second create without --update should fail when catalog repo already exists") - }) - - t.Run("SuccessCatalogRepositoriesCreateWithUpdate", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "create", - "--update", - "--branch", "stack-aws", - "--url", "https://github.com/cycloid-community-catalog/docs-step-by-step-stack.git", - "--name", "step-by-step", - }) - require.NoError(t, cmdErr, "create --update should succeed for existing catalog repo") - - var repo models.ServiceCatalogSource - err := json.Unmarshal([]byte(cmdOut), &repo) - require.NoError(t, err, "output should deserialize, got: %s", cmdOut) - require.NotNil(t, repo.Canonical) - assert.Equal(t, "step-by-step", *repo.Canonical) - require.NotNil(t, repo.Name) - assert.Equal(t, "step-by-step", *repo.Name) - }) - }) - - t.Run("SuccessCatalogRepositoriesList", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "list", - }) - - require.Nil(t, cmdErr) - assert.Contains(t, cmdOut, "canonical\": \"step-by-step") - }) - - t.Run("SuccessCatalogRepositoriesGet", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "get", - "--canonical", "step-by-step", - }) - - require.Nil(t, cmdErr) - assert.Contains(t, cmdOut, "canonical\": \"stack-aws-sample") - }) - - t.Run("SuccessCatalogRepositoriesRefresh", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "refresh", - "--canonical", "step-by-step", - }) - - require.Nil(t, cmdErr) - assert.Contains(t, cmdOut, "updated") - }) - - t.Run("SuccessCatalogRepositoryUpdate", func(t *testing.T) { - updatedName := "step-by-step-updated" - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "update", - "--canonical", "step-by-step", - "--name", updatedName, - "--branch", "stack-aws", - "--url", "https://github.com/cycloid-community-catalog/docs-step-by-step-stack.git", - "--cred", "", - }) - - require.Nil(t, cmdErr) - var updatedRepo models.ServiceCatalogSource - err := json.Unmarshal([]byte(cmdOut), &updatedRepo) - require.Nil(t, err, "output should deserialize to ServiceCatalogSource, out: %s", cmdOut) - assert.Equal(t, updatedName, *updatedRepo.Name) - }) - - // Positional-arg tests — verify the new interface works alongside deprecated --canonical - - t.Run("GetWithPositionalArg", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "get", - "step-by-step", // positional, no --canonical - }) - require.Nil(t, cmdErr) - assert.Contains(t, cmdOut, "step-by-step") - }) - - t.Run("RefreshWithPositionalArg", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "refresh", - "step-by-step", // positional, no --canonical - }) - require.Nil(t, cmdErr) - assert.Contains(t, cmdOut, "updated") - }) - - t.Run("DeleteWithPositionalArg", func(t *testing.T) { - // Create a temporary repo to be deleted via positional arg - tmpCan := randomCanonical("cat-repo-pos") - _, createErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "create", - "--branch", "stack-aws", - "--url", "https://github.com/cycloid-community-catalog/docs-step-by-step-stack.git", - "--name", tmpCan, - }) - require.Nil(t, createErr, "setup: create catalog repo for delete test") - - _, deleteErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "delete", - tmpCan, // positional, no --canonical - }) - require.Nil(t, deleteErr) - }) -} diff --git a/e2e/components_test.go b/e2e/components_test.go deleted file mode 100644 index 46acbd1f1..000000000 --- a/e2e/components_test.go +++ /dev/null @@ -1,482 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "errors" - "os" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func TestComponentCmd(t *testing.T) { - var ( - componentName = "Test Component" - component = randomCanonical("e2e-component") - componentDescription = "My cool component" - stackRef = config.Org + ":stack-e2e-stackforms" - description = "Testing components" - ) - - t.Run("CreateReadListDelete", func(t *testing.T) { - // create - testJSON := `{"types": {"tests": {"map": {"hello": "world", "int": 1, "bool": true}}}}` - testJSONFileContent := `{"types": {"tests": {"string": "myString"}}}` - testJSONStdin := `{"types": {"tests": {"array": ["hello", false, 1, 1.1]}}}` - filename, err := WriteTempFile(testJSONFileContent) - if err != nil { - t.Errorf("comp create setup failed: %v", err) - } - - var stdout, stderr string - args := []string{ - "--output", "json", - "--org", config.Org, - "components", "create", - "--name", componentName, - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - "-d", componentDescription, - // test raw var flag - "-j", testJSON, - // test stdin - "-f", "-", - // test file flag - "-f", filename, - // Test var=value flag - "-V", `section with spaces.group with spaces.no_spaces="osef"`, - "-s", stackRef, - "-u", "default", - "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, - } - stdout, stderr, err = executeCommandStdin(testJSONStdin, args) - if err != nil { - t.Logf("component creation failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) - t.FailNow() - } - - // delete - defer t.Run("DeleteCreateComp", func(t *testing.T) { - out, err := executeCommand([]string{ - "--org", config.Org, - "components", "delete", - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - }) - if err != nil { - t.Errorf("failed to delete and cleanup component '%s' from Create test: %v\nstdout: %s", component, err, out) - } - }) - - // get - args = []string{ - "--output", "json", - "--org", config.Org, - "components", "get", - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - } - out, err := executeCommand(args) - if err != nil { - t.Errorf("failed to execute cmd '%s': %s", strings.Join(args, " "), err) - } - - var comp models.Component - err = json.Unmarshal([]byte(out), &comp) - if err != nil { - t.Errorf("failed to parse output of cy comp get command: %v\noutput: %s", err, out) - } - - assert.NotNil(t, comp) - assert.NotNil(t, comp.Canonical) - assert.Equal(t, component, *comp.Canonical) - assert.Equal(t, componentName, *comp.Name) - - // list - args = []string{ - "--output", "json", - "--org", config.Org, - "components", "list", - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - } - out, err = executeCommand(args) - if err != nil { - t.Errorf("failed to execute cmd '%s': %s", strings.Join(args, " "), err) - } - - var comps []models.Component - err = json.Unmarshal([]byte(out), &comps) - if err != nil { - t.Errorf("failed to parse output of cy comp get command: %v\noutput: %s", err, out) - } - }) - - t.Run("CreateWithUpdateNew", func(t *testing.T) { - var newComp = randomCanonical("e2e-new") - args := []string{ - "--output", "json", - "--org", config.Org, - "components", "create", - "--name", componentName, - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", newComp, - "-d", componentDescription, - "-V", `section with spaces.group with spaces.no_spaces="new"`, - "-s", stackRef, - "-u", "default", - "--update", - "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, - } - var err, errList error - var stdout, stderr string - for range 3 { - stdout, stderr, err = executeCommandStdin("", args) - if err != nil { - errList = errors.Join(errList, err) - continue - } - errList = nil - break - } - - if errList != nil { - t.Errorf("component creation failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) - } - - defer t.Run("DeleteCreateWithUpdateComp", func(t *testing.T) { - out, err := executeCommand([]string{ - "--org", config.Org, - "components", "delete", - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", newComp, - }) - if err != nil { - t.Errorf("failed to delete and cleanup component '%s' from '%s' test: %v\nstdout: %s", component, t.Name(), err, out) - } - }) - }) - - t.Run("CreateWithUpdateAndConfig", func(t *testing.T) { - // create - testJSON := `{"types": {"tests": {"map": {"hello": "world", "int": 1, "bool": true}}}}` - testJSONFileContent := `{"types": {"tests": {"string": "myString"}}}` - testJSONStdin := `{"types": {"tests": {"array": ["hello", false, 1, 1.1]}}}` - filename, err := WriteTempFile(testJSONFileContent) - if err != nil { - t.Errorf("comp create setup failed: %v", err) - } - defer os.Remove(filename) - - args := []string{ - "--output", "json", - "--org", config.Org, - "components", "create", - "--name", componentName, - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - "-d", componentDescription, - // test raw var flag - "-j", testJSON, - // test stdin - "-f", "-", - // test file flag - "-f", filename, - // Test var=value flag - "-V", `section with spaces.group with spaces.no_spaces="osef"`, - "-s", stackRef, - "-u", "default", - "--update", - "--stack-branch", config.CatalogRepo.Branch, - } - stdout, stderr, err := executeCommandStdin(testJSONStdin, args) - if err != nil { - t.Errorf("component creation failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) - } - defer t.Run("DeleteCreateWithUpdateComp", func(t *testing.T) { - out, err := executeCommand([]string{ - "--org", config.Org, - "components", "delete", - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - }) - if err != nil { - t.Errorf("failed to delete and cleanup component '%s' from '%s' test: %v\nstdout: %s", component, t.Name(), err, out) - } - }) - - // create with update - testJSON = `{"types": {"tests": {"map": {"update": true}}}}` - testJSONFileContent = `{"types": {"tests": {"string": "updated"}}}` - testJSONStdin = `{"types": {"tests": {"array": []}}}` - filename, err = WriteTempFile(testJSONFileContent) - if err != nil { - t.Errorf("comp create setup failed: %v", err) - } - defer os.Remove(filename) - - args = []string{ - "--output", "json", - "--org", config.Org, - "components", "create", - "--name", componentName, - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - "-d", description, - // test raw var flag - "-j", testJSON, - // test stdin - "-f", "-", - // test file flag - "-f", filename, - // Test var=value flag - "-V", `section with spaces.group with spaces.no_spaces=osef`, - "-s", stackRef, - "-u", "default", - "--update", - "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, - } - - stdout, stderr, err = executeCommandStdin(testJSONStdin, args) - if err != nil { - t.Errorf("component put failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) - } - - // get config - args = []string{ - "--output", "json", - "components", "config", "get", - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - } - stdout, stderr, err = executeCommandStdin(testJSONStdin, args) - if err != nil { - t.Errorf("component put failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) - } - - var outVars models.FormVariables - err = json.Unmarshal([]byte(stdout), &outVars) - if err != nil { - t.Errorf("failed to parse output of CLI as JSON:\n%s\n%s", stdout, err) - } - - value, _ := outVars["types"]["tests"]["map"].(map[string]any)["update"].(bool) - assert.Equal(t, true, value) - assert.Equal(t, "updated", outVars["types"]["tests"]["string"]) - assert.Equal(t, "osef", outVars["section with spaces"]["group with spaces"]["no_spaces"]) - - // update - testJSON = `{"types": {"tests": {"string": "update2"}}}` - testJSONFileContent = `{"types": {"tests": {"integer": 14}}}` - testJSONStdin = `{"types": {"tests": {"float": 2.2}}}` - filename, err = WriteTempFile(testJSONFileContent) - if err != nil { - t.Errorf("comp update setup failed: %v", err) - } - defer os.Remove(filename) - - args = []string{ - "--output", "json", - "--org", config.Org, - "components", "update", - "--name", componentName, - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - "-d", description, - // test raw var flag - "-j", testJSON, - // test stdin - "-f", "-", - // test file flag - "-f", filename, - // Test var=value flag - "-V", `section with spaces.group with spaces.no_spaces=update2`, - "-u", "default", - "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, - } - - stdout, stderr, err = executeCommandStdin(testJSONStdin, args) - if err != nil { - t.Errorf("component update failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) - } - - // check config after update - args = []string{ - "--output", "json", - "components", "config", "get", - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - } - stdout, stderr, err = executeCommandStdin(testJSONStdin, args) - if err != nil { - t.Errorf("component put failed: %v\nstdout:\n%s\nstderr\n%s", err, stdout, stderr) - } - - outVars = make(models.FormVariables) - err = json.Unmarshal([]byte(stdout), &outVars) - if err != nil { - t.Errorf("failed to parse output of CLI as JSON:\n%s\n%s", stdout, err) - } - - assert.Equal(t, "update2", outVars["types"]["tests"]["string"]) - assert.Equal(t, float64(14), outVars["types"]["tests"]["integer"].(float64)) - assert.Equal(t, 2.2, outVars["types"]["tests"]["float"]) - assert.Equal(t, "update2", outVars["section with spaces"]["group with spaces"]["no_spaces"]) - }) - - t.Run("TestVarsInvalidSectionsAndGroup", func(t *testing.T) { - args := []string{ - "--output", "json", - "--org", config.Org, - "components", "create", - "--update", - "--name", componentName, - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - "-d", description, - "-s", stackRef, - "-u", "default", - "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, - "-V", `section with spaces.thisgroupdoesnotexists.no_spaces=update2`, - "-V", `sectiondoesnotexists.thisgroupdoesnotexists.no_spaces=true`, - } - - cmdOut, cmdErr := executeCommand(args) - if cmdErr != nil { - // We just check that it doesn't panic for now - t.Errorf("component update failed, stdout:\n%s\nstderr\n%s", cmdOut, cmdErr) - } - }) - - t.Run("TestCreateWithUpdateOnNonConfiguredComponentOk", func(t *testing.T) { - component := randomCanonical("created-not-configured") - - m := config.Middleware - created, _, err := m.CreateOrUpdateComponent(config.Org, *config.Project.Canonical, - *config.Environment.Canonical, component, description, component, - stackRef, "", "", *config.CatalogRepoVersionStacks.CommitHash, "default", "", nil) - if err != nil { - t.Logf("test setup failed: component creation %q reported err: %v", component, err) - t.FailNow() - } - defer m.DeleteComponent(config.Org, *created.Project.Canonical, - *created.Environment.Canonical, *created.Canonical, middleware.DeleteOptions{}) - - args := []string{ - "--output", "json", - "--org", config.Org, - "components", "create", - "--update", - "--name", component, - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - "-d", description, - "-s", stackRef, - "-u", "default", - "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, - } - - cmdOut, cmdErr := executeCommand(args) - if cmdErr != nil { - // We just check that it doesn't panic for now - t.Errorf("component update failed, stdout:\n%s\nstderr\n%s", cmdOut, cmdErr) - } - }) - - t.Run("TestUpdateOnNonConfiguredComponentOk", func(t *testing.T) { - component := randomCanonical("created-not-configured") - - m := config.Middleware - created, _, err := m.CreateOrUpdateComponent(config.Org, *config.Project.Canonical, - *config.Environment.Canonical, component, description, component, - stackRef, "", "", *config.CatalogRepoVersionStacks.CommitHash, "default", "", nil) - if err != nil { - t.Logf("test setup failed: component creation %q reported err: %v", component, err) - t.FailNow() - } - defer m.DeleteComponent(config.Org, *created.Project.Canonical, - *created.Environment.Canonical, *created.Canonical, middleware.DeleteOptions{}) - - args := []string{ - "--output", "json", - "--org", config.Org, - "components", "update", - "--name", component, - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - "-d", description, - "-u", "default", - "--stack-commit-hash", *config.CatalogRepoVersionStacks.CommitHash, - } - - cmdOut, cmdErr := executeCommand(args) - if cmdErr != nil { - // We just check that it doesn't panic for now - t.Errorf("component update failed, stdout:\n%s\nstderr\n%s", cmdOut, cmdErr) - } - }) - - t.Run("TestUpdatePreservesStackVersionWhenNotSpecified", func(t *testing.T) { - // Regression test: cy component update without any --stack-branch/--stack-tag/ - // --stack-commit-hash flag was silently switching the component to the catalog's - // default branch instead of keeping the current version. - component := randomCanonical("preserve-version") - - m := config.Middleware - created, _, err := m.CreateOrUpdateComponent(config.Org, *config.Project.Canonical, - *config.Environment.Canonical, component, description, component, - stackRef, "", *config.CatalogRepoVersionStacks.Name, "", "default", "", nil) - if err != nil { - t.Logf("test setup failed: component creation %q reported err: %v", component, err) - t.FailNow() - } - defer m.DeleteComponent(config.Org, *created.Project.Canonical, - *created.Environment.Canonical, *created.Canonical, middleware.DeleteOptions{}) - - versionBefore := created.ServiceCatalog.Version - - // Update without specifying any version flag — version must be preserved. - args := []string{ - "--output", "json", - "--org", config.Org, - "components", "update", - "-p", *config.Project.Canonical, - "-e", *config.Environment.Canonical, - "-c", component, - "-d", description, - "-u", "default", - } - cmdOut, cmdErr := executeCommand(args) - if cmdErr != nil { - t.Errorf("component update failed, stdout:\n%s\nstderr\n%s", cmdOut, cmdErr) - t.FailNow() - } - - var updated models.Component - if err := json.Unmarshal([]byte(cmdOut), &updated); err != nil { - t.Errorf("failed to parse update output as JSON: %v\noutput: %s", err, cmdOut) - t.FailNow() - } - - assert.Equal(t, versionBefore, updated.ServiceCatalog.Version, - "stack version must not change when no version flag is specified") - }) -} diff --git a/e2e/config_repositories_test.go b/e2e/config_repositories_test.go deleted file mode 100644 index 6dc9de2db..000000000 --- a/e2e/config_repositories_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "slices" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func TestConfigRepositories(t *testing.T) { - // Bug: https://linear.app/cycloid/issue/BE-981/catalog-repository-creation-fail-on-staging - t.Skip() - // - - var ( - CRUrl = "git@github.com:cycloidio/cycloid-cli-test-catalog.git" - CRBranch = "config-e2e" - CRCanonical = "config-repo-e2e" - CRCred = config.ConfigRepo.CredentialCanonical - ) - - defer t.Run("SuccessConfigRepositoriesDelete", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "config-repo", - "delete", - "--canonical", CRCanonical, - }) - - assert.Nil(t, cmdErr) - require.Empty(t, cmdOut) - }) - - t.Run("SuccessConfigRepositoriesCreate", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "config-repo", - "create", - "--name", CRCanonical, - "--branch", CRBranch, - "--cred", CRCanonical, - "--url", CRUrl, - }) - - assert.Nil(t, cmdErr) - - var result models.ConfigRepository - err := json.Unmarshal([]byte(cmdOut), &result) - assert.NoError(t, err) - assert.Equal(t, CRUrl, *result.URL) - assert.Equal(t, CRBranch, result.Branch) - assert.Equal(t, CRCanonical, *result.Canonical) - assert.Equal(t, CRCred, result.CredentialCanonical) - }) - - t.Run("SuccessConfigRepositoriesList", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "config-repo", - "list", - }) - - assert.Nil(t, cmdErr) - var list []models.ConfigRepository - err := json.Unmarshal([]byte(cmdOut), &list) - assert.NoError(t, err) - - if index := slices.IndexFunc(list, func(cr models.ConfigRepository) bool { - return *cr.Canonical == CRCanonical - }); index != -1 { - result := list[index] - assert.Equal(t, CRUrl, *result.URL) - assert.Equal(t, CRBranch, result.Branch) - assert.Equal(t, CRCanonical, *result.Canonical) - assert.Equal(t, CRCred, result.CredentialCanonical) - } else { - t.Fatal("did not found our config repo in cmd output: " + cmdOut) - } - }) - - t.Run("SuccessConfigRepositoriesGet", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "config-repo", - "get", - "--canonical", CRCanonical, - }) - - assert.Nil(t, cmdErr) - - var result models.ConfigRepository - err := json.Unmarshal([]byte(cmdOut), &result) - assert.NoError(t, err) - assert.Equal(t, CRUrl, *result.URL) - assert.Equal(t, CRBranch, result.Branch) - assert.Equal(t, CRCanonical, *result.Canonical) - assert.Equal(t, CRCred, result.CredentialCanonical) - }) -} diff --git a/e2e/creds_test.go b/e2e/creds_test.go deleted file mode 100644 index 28380908a..000000000 --- a/e2e/creds_test.go +++ /dev/null @@ -1,190 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "os" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func TestCreds(t *testing.T) { - t.Run("SuccessCredsList", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "creds", - "list", - }) - - assert.Nil(t, cmdErr) - require.Contains(t, cmdOut, "canonical\": \"vault") - }) - - t.Run("SuccessCredsGet", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "creds", - "get", - "--canonical", "vault", - }) - - assert.Nil(t, cmdErr) - require.Contains(t, cmdOut, "canonical\": \"vault") - }) - - t.Run("SuccessCredsCreateCustom", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "creds", - "create", - "custom", - "--name", "cli-custom", - "--canonical", "cli-custom-canonical", - "--path", "cli-custom-path", - "--field", "foo=bar", - "--field", "int=1", - }) - - defer t.Run("SuccessDelete", func(t *testing.T) { - _, err := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "creds", - "delete", - "--canonical", "cli-custom-canonical", - }) - if err != nil { - t.Errorf("failed to delete cred cli-custom: %s", err.Error()) - } - }) - - assert.Nil(t, cmdErr) - var outCred *models.Credential - err := json.Unmarshal([]byte(cmdOut), &outCred) - if err != nil { - t.Errorf("should be able to marshal cli output to a credential, cmdOut: %s\ncmdErr: %s\nerr: %s", cmdOut, cmdErr, err.Error()) - } - - // Test that the flag works - assert.NotNil(t, outCred, "cli output should contain a credential:", cmdOut, cmdErr) - assert.NotNil(t, outCred.Name, "cli output should contain a name:", cmdOut, cmdErr, outCred) - assert.NotNil(t, outCred.Canonical, "cli output should contain a canonical:", cmdOut, cmdErr, outCred) - assert.NotNil(t, outCred.Path, "cli output should contain a path:", cmdOut, cmdErr, outCred) - assert.Equal(t, "cli-custom", *outCred.Name) - assert.Equal(t, "cli-custom-canonical", *outCred.Canonical) - assert.Equal(t, "cli-custom-path", *outCred.Path) - - t.Run("Update", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "creds", - "update", - "custom", - "--canonical", "cli-custom-canonical", - "--name", "cli-custom", - "--field", "foo=bar", - "--field", "int=1", - "--field", "new=field", - }) - - assert.Nil(t, cmdErr) - var outCred *models.Credential - err := json.Unmarshal([]byte(cmdOut), &outCred) - if err != nil { - t.Errorf("should be able to marshal cli output to a credential, cmdOut: %s\ncmdErr: %s\nerr: %s", cmdOut, cmdErr, err.Error()) - } - - cmdOut, cmdErr = executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "creds", - "get", - "--canonical", "cli-custom-canonical", - }) - assert.Nil(t, cmdErr) - require.Contains(t, cmdOut, "new\": \"field") - }) - - t.Run("SuccessCredsCreateCustomWithFile", func(t *testing.T) { - fileContent := "hello world" - fileName, err := WriteTempFile(fileContent) - if err != nil { - t.Errorf("failed to setup test, temp file write failed: %s", err.Error()) - } - defer os.Remove(fileName) - - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "creds", - "create", - "custom", - "--name", "cli-custom-file", - "--field", "foo=bar", - "--field-file", "key=" + fileName, - }) - assert.Nil(t, cmdErr) - defer t.Run("SuccessDelete", func(t *testing.T) { - _, err := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "creds", - "delete", - "--canonical", "cli-custom-file", - }) - if err != nil { - t.Errorf("failed to delete cred 'cli-custom-file'") - } - }) - - var outCred *models.Credential - err = json.Unmarshal([]byte(cmdOut), &outCred) - if err != nil { - t.Errorf("should be able to marshal cli output to a credential, cmdOut: %s\ncmdErr: %s\nerr: %s", cmdOut, cmdErr, err.Error()) - } - }) - - t.Run("SuccessCredsCreateSSH", func(t *testing.T) { - fileName, err := WriteTempFile(string(TestGitSSHKey)) - if err != nil { - t.Errorf("failed to setup test, temp file write failed: %s", err.Error()) - } - defer os.Remove(fileName) - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "creds", - "create", - "ssh", - "--name", "cli-ssh", - "--ssh-key", fileName, - }) - assert.Nil(t, cmdErr) - defer t.Run("SuccessDelete", func(t *testing.T) { - _, err := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "creds", - "delete", - "--canonical", "cli-ssh", - }) - if err != nil { - t.Errorf("failed to delete cred 'cli-ssh'") - } - }) - - var outCred *models.Credential - err = json.Unmarshal([]byte(cmdOut), &outCred) - if err != nil { - t.Errorf("should be able to marshal cli output to a credential, cmdOut: %s\ncmdErr: %s\nerr: %s", cmdOut, cmdErr, err.Error()) - } - }) - }) -} diff --git a/e2e/e2e.go b/e2e/e2e.go deleted file mode 100644 index 28249a0c8..000000000 --- a/e2e/e2e.go +++ /dev/null @@ -1,3 +0,0 @@ -package e2e - -// Fake package so that the e2e_test package can exists diff --git a/e2e/e2e_test.go b/e2e/e2e_test.go deleted file mode 100644 index b095d354b..000000000 --- a/e2e/e2e_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package e2e_test - -import ( - "fmt" - "log" - "os" - "testing" - - "github.com/spf13/viper" - - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -var config *testcfg.Config - -// Put any preparation code here so that defer() can work -func runMain(main *testing.M) (int, error) { - // We must wait a bit that the middleware test are done initializing the config - // Otherwise there will be conflcts -_- - var err error - config, err = testcfg.NewConfig("e2e") - defer config.Cleanup() - if err != nil { - return 1, fmt.Errorf("test config setup failed for e2e tests: %w", err) - } - - os.Setenv("CY_API_URL", config.APIUrl) - os.Setenv("CY_API_KEY", config.APIKey) - os.Setenv("CY_ORG", config.Org) - if v := os.Getenv("CY_TEST_VERBOSITY"); v != "" { - viper.Set("verbosity", v) - } - - return main.Run(), nil -} - -func TestMain(main *testing.M) { - code, err := runMain(main) - if err != nil { - log.Fatal(err) - } - - os.Exit(code) -} diff --git a/e2e/env_var_test.go b/e2e/env_var_test.go deleted file mode 100644 index cd72b8b4e..000000000 --- a/e2e/env_var_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package e2e_test - -import ( - "os" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestAPIKeyEnvVar(t *testing.T) { - for _, envVar := range []string{"CY_API_KEY", "CY_API_TOKEN", "TOKEN"} { - // We do a project list to check if we are authenticater - t.Run("SuccessProjectListWithEnvVarAuth", func(t *testing.T) { - os.Setenv(envVar, config.APIKey) - _, err := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "project", - "list", - }) - - assert.Nil(t, err, "Command should not fail using an env var for authentication") - os.Unsetenv(envVar) - }) - } -} diff --git a/e2e/environments_test.go b/e2e/environments_test.go deleted file mode 100644 index 28e2d82bf..000000000 --- a/e2e/environments_test.go +++ /dev/null @@ -1,251 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "os" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func TestEnvs(t *testing.T) { - os.Setenv("CY_API_URL", config.APIUrl) - os.Setenv("CY_API_KEY", config.APIKey) - os.Setenv("CY_ORG", config.Org) - - var ( - project = *config.Project.Canonical - envName = "Test E2E env" - env = randomCanonical("e2e") - ) - - t.Run("Create", func(t *testing.T) { - args := []string{ - "env", "create", - "--env", env, - "--name", envName, - } - _, err := executeCommand(args) - if err != nil { - t.Errorf("failed to create env %q: %v", env, err) - } - }) - - t.Run("Link", func(t *testing.T) { - args := []string{ - "env", "link", - "--project", project, - "--env", env, - } - _, err := executeCommand(args) - if err != nil { - t.Errorf("failed to link env %q: %v", env, err) - } - }) - - t.Run("CreateWithNameOnly", func(t *testing.T) { - var ( - nameOnly = "Environment Name " + randomCanonical("e2e") - inferred = middleware.ToCanonical(nameOnly) - ) - - args := []string{ - "--output", "json", - "env", "create", - "--name", nameOnly, - } - out, err := executeCommand(args) - if err != nil { - t.Errorf("failed to create env with name-only %q: %v", nameOnly, err) - } - - defer t.Run("DeleteNameOnlyEnv", func(t *testing.T) { - args := []string{ - "env", "delete", - "--env", inferred, - } - _, err := executeCommand(args) - if err != nil { - t.Errorf("failed to delete inferred env %q: %v", inferred, err) - } - }) - - var createdEnv models.Environment - err = json.Unmarshal([]byte(out), &createdEnv) - if err != nil { - t.Errorf("failed to parse json output for inferred env creation: %v\noutput: %s", err, out) - } - - assert.Equal(t, inferred, *createdEnv.Canonical) - assert.Equal(t, nameOnly, createdEnv.Name) - }) - - defer t.Run("Delete", func(t *testing.T) { - unlinkArgs := []string{ - "env", "unlink", - "-p", project, - "-e", env, - } - if _, err := executeCommand(unlinkArgs); err != nil { - t.Errorf("failed to unlink env %q: %v", env, err) - } - - args := []string{ - "env", "delete", - "-e", env, - } - _, err := executeCommand(args) - if err != nil { - t.Errorf("failed to delete env %q: %v", env, err) - } - }) - - t.Run("Get", func(t *testing.T) { - args := []string{ - "env", "get", - "--env", env, - "--output", "json", - } - cmdOut, err := executeCommand(args) - if err != nil { - t.Errorf("failed to get env %q: %v", env, err) - } - - var got models.Environment - err = json.Unmarshal([]byte(cmdOut), &got) - if err != nil { - t.Errorf("failed to marshal json cli output: %s\nerr: %s", cmdOut, err) - } - - assert.EqualValues(t, env, *got.Canonical) - }) - - t.Run("CreateWithUpdate", func(t *testing.T) { - createUpdateName := "helloUpdate" - args := []string{ - "-o", "json", - "env", "create", - "--env", env, - "--name", createUpdateName, - "--update", - } - out, err := executeCommand(args) - if err != nil { - t.Errorf("failed to create env %q: %v", env, err) - } - - var envResult models.Environment - err = json.Unmarshal([]byte(out), &envResult) - if err != nil { - t.Errorf("failed to parse json output from the CLI on create --update: %v\noutput: %s", err, out) - } - - assert.Equal(t, createUpdateName, envResult.Name) - }) - - t.Run("CreateWithUpdateNew", func(t *testing.T) { - newEnv := randomCanonical("e2e-env") - args := []string{ - "-o", "json", - "env", "create", - "--env", newEnv, - "--update", - } - _, err := executeCommand(args) - if err != nil { - t.Errorf("failed to create env %q: %v", newEnv, err) - } - - defer t.Run("DeleteCreateUpdate", func(t *testing.T) { - args := []string{ - "env", "delete", - "--env", newEnv, - } - _, err := executeCommand(args) - if err != nil { - t.Errorf("failed to delete env %q: %v", newEnv, err) - } - }) - }) - - t.Run("Update", func(t *testing.T) { - newName := "NewName" - args := []string{ - "-o", "json", - "env", "update", - "--name", newName, - "--env", env, - } - out, err := executeCommand(args) - if err != nil { - t.Errorf("failed to update env %q: %v", env, err) - } - - var envResult models.Environment - err = json.Unmarshal([]byte(out), &envResult) - if err != nil { - t.Errorf("failed to parse json output from the CLI on update: %v", err) - } - - assert.Equal(t, newName, envResult.Name) - }) - - t.Run("UpdateUpsertNew", func(t *testing.T) { - upsertEnv := randomCanonical("e2e-upsert") - upsertName := "Upserted Environment" - args := []string{ - "-o", "json", - "env", "update", - "--env", upsertEnv, - "--name", upsertName, - } - out, err := executeCommand(args) - if err != nil { - t.Errorf("failed to upsert env %q via update: %v", upsertEnv, err) - } - - defer t.Run("DeleteUpsertedEnv", func(t *testing.T) { - args := []string{ - "env", "delete", - "--env", upsertEnv, - } - _, err := executeCommand(args) - if err != nil { - t.Errorf("failed to delete upserted env %q: %v", upsertEnv, err) - } - }) - - var envResult models.Environment - err = json.Unmarshal([]byte(out), &envResult) - if err != nil { - t.Errorf("failed to parse json output from update upsert: %v\noutput: %s", err, out) - } - - assert.Equal(t, upsertEnv, *envResult.Canonical) - assert.Equal(t, upsertName, envResult.Name) - }) - - t.Run("UpdateExplicitEmptyCloudAccounts", func(t *testing.T) { - args := []string{ - "-o", "json", - "env", "update", - "--env", env, - "--cloud-account", "", - } - out, err := executeCommand(args) - if err != nil { - t.Errorf("failed to clear cloud accounts on env %q: %v", env, err) - } - - var envResult models.Environment - err = json.Unmarshal([]byte(out), &envResult) - if err != nil { - t.Errorf("failed to parse json output from explicit empty cloud-account update: %v\noutput: %s", err, out) - } - - assert.Empty(t, envResult.CloudAccounts) - }) -} diff --git a/e2e/events_test.go b/e2e/events_test.go deleted file mode 100644 index cf495f9d4..000000000 --- a/e2e/events_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func TestEvents(t *testing.T) { - t.Run("SuccessEventsSend", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "events", - "create", - "--tag", "foo=bar", - "--title", "CLI e2e", - "--message", "hello", - }) - - require.Nil(t, cmdErr) - assert.Equal(t, "", cmdOut) - }) - - t.Run("SuccessEventsList", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "events", - "list", - }) - - require.Nil(t, cmdErr) - var events []*models.Event - err := json.Unmarshal([]byte(cmdOut), &events) - require.Nil(t, err, "CLI output should deserialize to []*models.Event, out: %s", cmdOut) - }) -} diff --git a/e2e/external_backends_test.go b/e2e/external_backends_test.go deleted file mode 100644 index 3974c58f7..000000000 --- a/e2e/external_backends_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package e2e_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestExternalBackends(t *testing.T) { - // Prepare: create the AWS credential needed for the logs backend test - t.Run("CleanupAndPrepare", func(t *testing.T) { - // Clean external backends if exist - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "external-backends", - "list", - }) - - require.Nil(t, cmdErr) - cs, err := JSONListExtractFields(cmdOut, "id", "", "") - require.Nil(t, err) - - for _, c := range cs { - executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "eb", - "delete", - "--id", c, - }) - } - - // Create AWS credential for the CloudWatch logs test - executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "creds", - "create", - "aws", - "--name", "eb-aws", - "--access-key", "foo", - "--secret-key", "bar", - }) - }) - - t.Run("SuccessExternalBackendsCreateAWSRemoteTFState", func(t *testing.T) { - // TODO: Fix tests when components are implemented (BE-XXXX) - t.Skip("blocked: requires component-level infraview support") - - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "external-backends", - "create", - "infraview", - "AWSRemoteTFState", - "--bucket-name", "eb-ifraview-aws", - "--bucket-path", "/foo", - "--cred", "eb-aws", - "--project", *config.Project.Canonical, - "--env", *config.Environment.Canonical, - }) - - assert.Nil(t, cmdErr) - require.Contains(t, cmdOut, "purpose\": \"remote_tfstate") - }) - - t.Run("SuccessExternalBackendsCreateAWSCloudWatchLogs", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "external-backends", - "create", - "logs", - "AWSCloudWatchLogs", - "--cred", "eb-aws", - "--project", *config.Project.Canonical, - "--region", "eu-west-1", - }) - - assert.Nil(t, cmdErr) - require.Contains(t, cmdOut, "purpose\": \"logs") - }) - - t.Run("SuccessExternalBackendsList", func(t *testing.T) { - // TODO: Fix tests when components are implemented (BE-XXXX) - t.Skip("blocked: list expects remote_tfstate entry from skipped infraview test") - - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "external-backends", - "list", - }) - - assert.Nil(t, cmdErr) - require.Contains(t, cmdOut, "purpose\": \"remote_tfstate") - }) -} diff --git a/e2e/helpers_test.go b/e2e/helpers_test.go deleted file mode 100644 index c479bbfd8..000000000 --- a/e2e/helpers_test.go +++ /dev/null @@ -1,275 +0,0 @@ -package e2e_test - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "math/rand" - "os" - "regexp" - "strings" - "testing" - "time" - - "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/cmd" -) - -func TestExecuteCommandStdin(t *testing.T) { - cmd := &cobra.Command{ - RunE: func(cmd *cobra.Command, args []string) error { - in, err := io.ReadAll(cmd.InOrStdin()) - if err != nil { - return err - } - - cmd.OutOrStdout().Write(in) - return nil - }, - } - - expected := `My stdin` - stdoutBuf := new(bytes.Buffer) - reader := strings.NewReader(expected) - _, err := reader.Seek(0, 0) - if err != nil { - t.Fatal(err) - } - - cmd.SetIn(reader) - cmd.SetOut(stdoutBuf) - err = cmd.Execute() - if err != nil { - t.Errorf("command failed: %s", err) - } - - stdout, err := io.ReadAll(stdoutBuf) - if err != nil { - t.Errorf("failed to read cmd output: %s", err) - } - - assert.Equal(t, expected, string(stdout)) -} - -var ( - now = time.Now() - NowTimestamp = now.UnixNano() - - TestGitSSHKey = []byte(`-----BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW -QyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+AAAAJjCF9jzwhfY -8wAAAAtzc2gtZWQyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+A -AAAEC0ryBZ1uJQ2drmjsO+WpsC2E/5SWheJD/r8+Q4LghWxfw72aGSXkICIPQ0t5Byg9/V -25gciZCVOM5dwI6AeYL4AAAAE2N5Y2xvaWRAZXhhbXBsZS5jb20BAg== ------END OPENSSH PRIVATE KEY-----`) - - TestPipelineSample = []byte(`jobs: -- name: job-hello-world - build_logs_to_retain: 3 - plan: - - task: hello-world - config: - platform: linux - image_resource: - type: docker-image - source: {repository: busybox} - run: - path: /bin/sh - args: - - -ec - - | - echo ${MESSAGE} - params: - MESSAGE: ((message))`) - - TestPipelineVariables = []byte(`message: "hello world and especially to ($ organization_canonical $)"`) - - // TestTerraformPlanSample is a minimal valid Terraform plan JSON used for - // terracost estimate and infrapolicy validate tests. - TestTerraformPlanSample = []byte(`{ - "format_version": "1.1", - "terraform_version": "1.5.0", - "variables": {}, - "planned_values": {"root_module": {}}, - "resource_changes": [], - "prior_state": {"format_version": "1.0", "values": {"root_module": {}}}, - "configuration": {"root_module": {}} -}`) - - TestInfraPolicySample = []byte(` - package test - import input.tfplan as tfplan - resource_types = { "aws_instance" } - - tags_ok(index) { - tfplan.resource_changes[index].change.after.tags["env"] == "test" - } - - deny[reason] { - resources_not_ok := [resource_not_ok | resource_types[i] == tfplan.resource_changes[j].type - not tags_ok(j); - resource_not_ok := resource_types[i]] - reason = sprintf("tag not in env: %s %s", [(resources_not_ok), test]) - } -`) -) - -// executeCommandStdin will execute the command with args + stdin input -// and return stdin, stderr and err -func executeCommandStdin(stdin string, args []string) (string, string, error) { - cmd := cmd.NewRootCommand() - - stdoutBuf := new(bytes.Buffer) - stderrBuf := new(bytes.Buffer) - cmd.SetOut(stdoutBuf) - cmd.SetErr(stderrBuf) - - cmd.SetIn(strings.NewReader(stdin)) - oldStdin := os.Stdin - defer func() { - os.Stdin = oldStdin - }() - file, err := os.CreateTemp("", "stdin") - if err != nil { - return "", "", fmt.Errorf("test setup failed: %w", err) - } - defer file.Close() - defer os.Remove(file.Name()) - - err = os.WriteFile(file.Name(), []byte(stdin), 0666) - if err != nil { - return "", "", fmt.Errorf("test setup failed: %w", err) - } - os.Stdin = file - - cmd.SetArgs(args) - cmdErr := cmd.Execute() - stdout, err := io.ReadAll(stdoutBuf) - if err != nil { - return "", "", errors.Join(cmdErr, fmt.Errorf("failed to read stdout buffer from cli: %w", err)) - } - - stderr, err := io.ReadAll(stderrBuf) - if err != nil { - return string(stdout), "", errors.Join(cmdErr, fmt.Errorf("failed to read stderr buffer from cli: %w", err)) - } - - return string(stdout), string(stderr), cmdErr -} - -func executeCommand(args []string) (string, error) { - cmd := cmd.NewRootCommand() - - buf := new(bytes.Buffer) - errBuf := new(bytes.Buffer) - cmd.SetOut(buf) - cmd.SetErr(errBuf) - - cmd.SetArgs(args) - cmdErr := cmd.Execute() - cmdOut, err := io.ReadAll(buf) - if err != nil { - panic("Unable to read command output buffer") - } - return string(cmdOut), cmdErr -} - -// AddNowTimestamp add a timestamp suffix to a string -func AddNowTimestamp(txt string) string { - return fmt.Sprintf(txt, NowTimestamp) -} - -func WriteFile(path string, data []byte) { - err := os.WriteFile(path, data, 0644) - if err != nil { - panic(fmt.Sprintf("Test setup, unable to write file %q: %v", path, err)) - } -} - -// toString convert interface from default json unmarchal to string -func toString(value any) string { - out := "" - // Handle the value conversion based on unmarchal default types - switch v := value.(type) { - case string: - out = v - case float64: - out = fmt.Sprint(v) - default: - // Skip, unsuported - } - return out -} - -// JSONListExtractFields Extract a field from a json entity -func JSONListExtractFields(js string, field, filterField, filterRegex string) ([]string, error) { - var es []any - var out []string - - err := json.Unmarshal([]byte(js), &es) - if err != nil { - return nil, err - } - - for _, e := range es { - // Cast our map from default json unmarchal - m := e.(map[string]any) - - value := toString(m[field]) - - // Filter - if filterField != "" { - fv := toString(m[filterField]) - re := regexp.MustCompile(filterRegex) - if re.MatchString(fv) { - out = append(out, value) - } - } else { - out = append(out, value) - } - } - - return out, nil -} - -func JSONListFindObjectValue(list []map[string]any, key, value string) bool { - for _, item := range list { - if item[key] == value { - return true - } - } - - return false -} - -// WriteTempFile will write the content to a temporary file and -// return the file path. -func WriteTempFile(content string) (string, error) { - file, err := os.CreateTemp("", "cli-test-*") - if err != nil { - return "", fmt.Errorf("failed to create temp file: %w", err) - } - - _, err = file.WriteString(content) - if err != nil { - return "", fmt.Errorf("failed to write to temp file %q: %w", file.Name(), err) - } - - return file.Name(), nil -} - -// randomCanonical will add 4 random letter after the baseName -func randomCanonical(baseName string) string { - var size = 4 - var letterRunes = []rune("abcdefghijklmnopqrstuvwxyz") - - b := make([]rune, size) - for i := range b { - b[i] = letterRunes[rand.Intn(len(letterRunes))] - } - return baseName + "-" + strings.ToLower(string(b)) -} diff --git a/e2e/kpis_test.go b/e2e/kpis_test.go deleted file mode 100644 index 53dfb8c6f..000000000 --- a/e2e/kpis_test.go +++ /dev/null @@ -1,170 +0,0 @@ -package e2e_test - -import ( - "fmt" - "regexp" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var createdKpi string - -func TestKpis(t *testing.T) { - t.Skip() - - // Prepare a running project - t.Run("CleanupAndPrepare", func(t *testing.T) { - - // Clean kpi if exist - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "kpis", - "list", - }) - require.Nil(t, cmdErr) - cs, err := JSONListExtractFields(cmdOut, "canonical", "canonical", "^test-.*") - require.Nil(t, err) - - for _, c := range cs { - executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "kpis", - "delete", - "--canonical", c, - }) - } - - // Create ssh cred - WriteFile("/tmp/test_cli-ssh", TestGitSSHKey) - executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "creds", - "create", - "ssh", - "--name", "git-project-creds", - "--ssh-key", "/tmp/test_cli-ssh", - }) - - // // Create config repo - // executeCommand([]string{ - // "--output", "json", - // "--org", config.Org, - // "config-repo", - // "create", - // "--name", "project-config", - // "--branch", CY_TEST_GIT_CR_BRANCH, - // "--cred", "git-project-creds", - // "--url", CY_TEST_GIT_CR_URL, - // }) - - // Provide service catalog public - executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "catalog-repository", - "create", - "--branch", "master", - "--url", "https://github.com/cycloid-community-catalog/stack-dummy.git", - "--name", "dummy", - }) - - // Create project - WriteFile("/tmp/test_cli-pp-vars", TestPipelineVariables) - WriteFile("/tmp/test_cli-pp", TestPipelineSample) - executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "project", - "create", - "--name", "kpi-test", - "--description", "this is a test project", - "--stack-ref", fmt.Sprintf("%s:stack-dummy", config.Org), - "--config-repo", "project-config", - }) - - executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "project", - "create-env", - "--project", "kpi-test", - "--env", "test", - "--use-case", "default", - "--vars", "/tmp/test_cli-pp-vars", - "--pipeline", "/tmp/test_cli-pp", - "--config", "/tmp/test_cli-pp=/snowy/test/test_cli-pp", - }) - - // Ensure the catalog is present - cmdOut, cmdErr = executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "project", - "get", - "--project", "kpi-test", - }) - - assert.Nil(t, cmdErr) - require.Contains(t, cmdOut, "canonical\": \"kpi-test") - }) - - t.Run("SuccessKpisCreate", func(t *testing.T) { - // TODO: Fix tests when components are implemented - t.Skip() - - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "kpis", - "create", - "--name", "test", - "--type", "build_history", - "--widget", "history", - "--project", "kpi-test", - "--env", "test", - "--job", "job-hello-world", - }) - - require.Nil(t, cmdErr) - require.Contains(t, cmdOut, "canonical\": \"test-") - }) - - t.Run("SuccessKpisList", func(t *testing.T) { - // TODO: Fix tests when components are implemented - t.Skip() - - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "kpis", - "list", - }) - - require.Nil(t, cmdErr) - require.Contains(t, cmdOut, "canonical\": \"test-") - - re := regexp.MustCompile(`canonical": "(test-[^"]+)"`) - createdKpi = re.FindAllStringSubmatch(cmdOut, 1)[0][1] - }) - - t.Run("SuccessKpisDelete", func(t *testing.T) { - // TODO: Fix tests when components are implemented - t.Skip() - - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "kpis", - "delete", - "--canonical", createdKpi, - }) - - require.Nil(t, cmdErr) - assert.Equal(t, "", cmdOut) - }) -} diff --git a/e2e/licence_test.go b/e2e/licence_test.go deleted file mode 100644 index aacefc0dc..000000000 --- a/e2e/licence_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/matryer/is" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func TestLicence(t *testing.T) { - licenceKey, ok := os.LookupEnv("API_LICENCE_KEY") - require.True(t, ok, "API_LICENCE_KEY must be set for licence e2e tests") - - t.Run("SuccessLicenceActivateAndGet", func(t *testing.T) { - is := is.New(t) - - _, cmdErr := executeCommand([]string{ - "--org", config.Org, - "organization", "licence", "activate", - "--key", licenceKey, - }) - is.NoErr(cmdErr) - - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "organization", "licence", "get", - }) - is.NoErr(cmdErr) - - var out models.Licence - err := json.Unmarshal([]byte(cmdOut), &out) - is.NoErr(err) - require.NotNil(t, out.Key) - is.Equal(licenceKey, *out.Key) - }) - - t.Run("SuccessLicenceActivateFromFile", func(t *testing.T) { - is := is.New(t) - - dir := t.TempDir() - licenceFile := filepath.Join(dir, "licence.jwt") - err := os.WriteFile(licenceFile, []byte(licenceKey), 0o600) - require.NoError(t, err) - - _, cmdErr := executeCommand([]string{ - "--org", config.Org, - "organization", "licence", "activate", - "--key-file", licenceFile, - }) - is.NoErr(cmdErr) - }) - - t.Run("SuccessLicenceActivateFromStdin", func(t *testing.T) { - is := is.New(t) - - _, _, err := executeCommandStdin(licenceKey, []string{ - "--org", config.Org, - "organization", "licence", "activate", - }) - is.NoErr(err) - }) - - t.Run("SuccessLicenceActivateOverwrite", func(t *testing.T) { - is := is.New(t) - - _, cmdErr := executeCommand([]string{ - "--org", config.Org, - "organization", "licence", "activate", - "--key", licenceKey, - }) - is.NoErr(cmdErr) - - _, cmdErr = executeCommand([]string{ - "--org", config.Org, - "organization", "licence", "activate", - "--key", licenceKey, - }) - is.NoErr(cmdErr) - - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "organization", "licence", "get", - }) - is.NoErr(cmdErr) - is.True(strings.Contains(cmdOut, licenceKey)) - }) -} diff --git a/e2e/login_test.go b/e2e/login_test.go deleted file mode 100644 index 921c60687..000000000 --- a/e2e/login_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package e2e_test - -import ( - "os" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestLogin(t *testing.T) { - t.Run("SuccessOrgLoginLegacy", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "login", - "--org", config.Org, - "--api-key", config.APIKey, - }) - - require.Nil(t, cmdErr) - assert.Equal(t, "", cmdOut) - }) - - t.Run("SuccessOrgLogin", func(t *testing.T) { - err := os.Setenv("CY_API_KEY", config.APIKey) - require.Nil(t, err) - - cmdOut, cmdErr := executeCommand([]string{ - "login", - "--org", config.Org, - }) - - require.Nil(t, cmdErr) - assert.Equal(t, "", cmdOut) - }) -} diff --git a/e2e/members_test.go b/e2e/members_test.go deleted file mode 100644 index d33d7b9d7..000000000 --- a/e2e/members_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "fmt" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestMembers(t *testing.T) { - // Cleanup invites in case of a previous test - t.Run("CleanupPreviousInvites", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "members", - "list-invites", - }) - - require.Nil(t, cmdErr) - ids, err := JSONListExtractFields(cmdOut, "id", "email", "^foo@bli.fr$") - require.Nil(t, err) - - for _, id := range ids { - executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "members", - "delete-invite", - "--invite", id, - }) - } - }) - - t.Run("SuccessMembersList", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "members", - "list", - }) - - require.Nil(t, cmdErr) - - var memberList []map[string]interface{} - err := json.Unmarshal([]byte(cmdOut), &memberList) - require.Nil(t, err, "unmarshalling cli json output") - - ok := JSONListFindObjectValue(memberList, "email", "admin@cycloid.io") - assert.True(t, ok, fmt.Sprint("member with admin@cycloid.io email address not found in json:\n", cmdOut)) - }) - - t.Run("SuccessMembersGet", func(t *testing.T) { - // Look up the admin member's numeric ID from the list - listOut, listErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "members", - "list", - }) - require.Nil(t, listErr, "members list should not fail") - - ids, err := JSONListExtractFields(listOut, "id", "email", "^admin@cycloid.io$") - require.Nil(t, err) - require.NotEmpty(t, ids, "admin member should be in the list") - - adminID := ids[0] - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "members", - "get", - "--id", adminID, - }) - - require.Nil(t, cmdErr, "CLI should not error on members get") - - var member map[string]any - err = json.Unmarshal([]byte(cmdOut), &member) - require.Nil(t, err, "we should be able to serialize the CLI json output: ", cmdOut) - - assert.Equal(t, "admin@cycloid.io", member["email"], - "member with admin@cycloid.io email address not found in json:\n", cmdOut) - }) - - t.Run("SuccessMembersUpdate", func(t *testing.T) { - // Look up the admin member's numeric ID from the list - listOut, listErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "members", - "list", - }) - require.Nil(t, listErr, "members list should not fail") - - ids, err := JSONListExtractFields(listOut, "id", "email", "^admin@cycloid.io$") - require.Nil(t, err) - require.NotEmpty(t, ids, "admin member should be in the list") - - adminID := ids[0] - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "members", - "update", - "--id", adminID, - "--role", "organization-admin", - }) - - require.Nil(t, cmdErr, "members update should not fail") - assert.NotEmpty(t, cmdOut, "members update should return the updated member") - }) - - t.Run("SuccessMembersInvite", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "members", - "invite", - "--email", "foo@bli.fr", - "--role", "organization-admin", - }) - - require.Nil(t, cmdErr) - assert.NotEmpty(t, cmdOut, "invite should return the created invitation") - }) - - t.Run("SuccessMembersListInvite", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "members", - "list-invites", - }) - - require.Nil(t, cmdErr) - - var memberList []map[string]interface{} - err := json.Unmarshal([]byte(cmdOut), &memberList) - require.Nil(t, err, "unmarshalling cli json output") - - ok := JSONListFindObjectValue(memberList, "invitation_email", "foo@bli.fr") - assert.True(t, ok, fmt.Sprint("member with foo@bli.fr email address not found in json:\n", cmdOut)) - }) -} diff --git a/e2e/oidc_test.go b/e2e/oidc_test.go deleted file mode 100644 index 77ee35d91..000000000 --- a/e2e/oidc_test.go +++ /dev/null @@ -1,207 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "fmt" - "strconv" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func TestOIDC(t *testing.T) { - // -------------------------------------------------------------------- - // Mappings CRUD - // -------------------------------------------------------------------- - - // We need a team to map to. Reuse the fixture team created by TestTeams - // if available, or create a disposable one here. - teamCan := randomCanonical("oidc-team") - - t.Run("SetupTeam", func(t *testing.T) { - _, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "team", "create", - "--name", teamCan, - "--role", "organization-member", - }) - require.NoError(t, cmdErr, "setup: team create should succeed") - }) - - // defer t.Run ensures cleanup runs after all subtests, even on failure. - // This is safe because t is still alive when deferred functions execute. - defer t.Run("TeardownTeam", func(t *testing.T) { - executeCommand([]string{ //nolint:errcheck - "--output", "json", - "--org", config.Org, - "team", "delete", teamCan, - }) - }) - - var mappingID uint32 - - t.Run("SuccessOIDCMappingCreate", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "oidc", "mappings", "create", - "--group-name", "my-oidc-group", - "--team", teamCan, - }) - require.NoError(t, cmdErr, "mappings create should succeed") - - var m middleware.OIDCGroupMapping - err := json.Unmarshal([]byte(cmdOut), &m) - require.NoError(t, err, "output should be a valid OIDCGroupMapping JSON") - assert.NotZero(t, m.ID, "created mapping should have a non-zero ID") - assert.Equal(t, "my-oidc-group", m.GroupName, "group name should match") - require.NotNil(t, m.Team, "team should be set") - assert.Equal(t, teamCan, m.Team.Canonical, "team canonical should match") - - mappingID = m.ID - }) - - t.Run("SuccessOIDCMappingList", func(t *testing.T) { - require.NotZero(t, mappingID, "create test must have run successfully first") - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "oidc", "mappings", "list", - }) - require.NoError(t, cmdErr, "mappings list should succeed") - - var mappings []middleware.OIDCGroupMapping - err := json.Unmarshal([]byte(cmdOut), &mappings) - require.NoError(t, err, "output should be a valid JSON array of OIDCGroupMapping") - - found := false - for _, m := range mappings { - if m.ID == mappingID { - found = true - assert.Equal(t, "my-oidc-group", m.GroupName) - break - } - } - assert.True(t, found, fmt.Sprintf("mapping ID %d should appear in list output", mappingID)) - }) - - t.Run("SuccessOIDCMappingDelete", func(t *testing.T) { - require.NotZero(t, mappingID, "create test must have run successfully first") - _, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "oidc", "mappings", "delete", - "--mapping-id", strconv.FormatUint(uint64(mappingID), 10), - }) - require.NoError(t, cmdErr, "mappings delete should succeed") - }) - - // Verify deletion - t.Run("SuccessOIDCMappingListAfterDelete", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "oidc", "mappings", "list", - }) - require.NoError(t, cmdErr, "mappings list after delete should succeed") - - var mappings []middleware.OIDCGroupMapping - err := json.Unmarshal([]byte(cmdOut), &mappings) - require.NoError(t, err, "output should parse as JSON array") - - for _, m := range mappings { - assert.NotEqual(t, mappingID, m.ID, "deleted mapping should no longer appear in list") - } - }) - - // -------------------------------------------------------------------- - // Settings get / set - // -------------------------------------------------------------------- - - t.Run("SuccessOIDCSettingsGet", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "oidc", "settings", "get", - }) - require.NoError(t, cmdErr, "settings get should succeed") - - var s middleware.OIDCOrganizationSettings - err := json.Unmarshal([]byte(cmdOut), &s) - require.NoError(t, err, "output should be a valid OIDCOrganizationSettings JSON") - }) - - t.Run("SuccessOIDCSettingsSet", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "oidc", "settings", "set", - "--oidc-managed=false", - "--no-match-policy", "keep_membership", - }) - require.NoError(t, cmdErr, "settings set should succeed") - - var s middleware.OIDCOrganizationSettings - err := json.Unmarshal([]byte(cmdOut), &s) - require.NoError(t, err, "output should be a valid OIDCOrganizationSettings JSON") - assert.Equal(t, "keep_membership", s.OIDCNoMatchPolicy) - assert.False(t, s.OIDCManaged) - }) - - t.Run("SuccessOIDCSettingsGetAfterSet", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "oidc", "settings", "get", - }) - require.NoError(t, cmdErr, "settings get after set should succeed") - - var s middleware.OIDCOrganizationSettings - err := json.Unmarshal([]byte(cmdOut), &s) - require.NoError(t, err, "output should parse as JSON") - assert.Equal(t, "keep_membership", s.OIDCNoMatchPolicy, "no-match-policy should persist") - }) - - // -------------------------------------------------------------------- - // Integration get / set - // -------------------------------------------------------------------- - - t.Run("SuccessOIDCIntegrationSet", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "oidc", "integration", "set", - "--issuer", "https://idp.example.com", - "--client-id", "test-client", - "--enabled", - }) - require.NoError(t, cmdErr, "integration set should succeed") - - var i middleware.OIDCIntegration - err := json.Unmarshal([]byte(cmdOut), &i) - require.NoError(t, err, "output should be a valid OIDCIntegration JSON") - assert.True(t, i.Enabled, "integration should be enabled") - assert.Equal(t, "test-client", i.OidcClientID, "client ID should match") - assert.Equal(t, "https://idp.example.com", i.OidcIssuer, "issuer should match") - }) - - t.Run("SuccessOIDCIntegrationGet", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "oidc", "integration", "get", - }) - require.NoError(t, cmdErr, "integration get should succeed") - - var i middleware.OIDCIntegration - err := json.Unmarshal([]byte(cmdOut), &i) - require.NoError(t, err, "output should be a valid OIDCIntegration JSON") - assert.True(t, i.Enabled, "integration should still be enabled after get") - assert.Equal(t, "test-client", i.OidcClientID, "client ID should persist") - assert.Equal(t, "https://idp.example.com", i.OidcIssuer, "issuer should persist") - }) -} diff --git a/e2e/organizations_test.go b/e2e/organizations_test.go deleted file mode 100644 index 5df8df8f8..000000000 --- a/e2e/organizations_test.go +++ /dev/null @@ -1,175 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "slices" - "testing" - "time" - - "github.com/matryer/is" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/pkg/testcfg" -) - -func TestOrganizations(t *testing.T) { - t.Run("SuccessOrganizationsList", func(t *testing.T) { - // organization list requires a user token; it returns 422 when called with an API key. - // The e2e tests authenticate via API key, so this endpoint cannot be tested here. - t.Skip("organization list is not supported with API key authentication (422)") - }) - - t.Run("SuccessOrganizationsGet", func(t *testing.T) { - is := is.New(t) - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "organization", - "get", - }) - is.NoErr(cmdErr) // cmd should not fail - - var outOrg *models.Organization - err := json.Unmarshal([]byte(cmdOut), &outOrg) - is.NoErr(err) // JSON output should be a valid model - is.Equal(config.Org, *outOrg.Canonical) // org canonicals should match - }) - - childOrg := testcfg.RandomCanonical("e2e-child") - t.Run("SuccessOrganizationsCreateChild", func(t *testing.T) { - is := is.New(t) - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "organization", - "create", - "--name", childOrg, - "--parent-canonical", config.Org, - }) - is.NoErr(cmdErr) // command should not fail - defer t.Run("SuccessDeleteOrg", func(t *testing.T) { - is := is.New(t) - _, deleteErr := executeCommand([]string{ - "--output", "json", - "organization", - "delete", - "--org", childOrg, - }) - is.NoErr(deleteErr) // command should not fail - }) - - var outOrg *models.Organization - err := json.Unmarshal([]byte(cmdOut), &outOrg) - is.NoErr(err) // JSON output should be a valid model - is.Equal(childOrg, *outOrg.Canonical) // org canonicals should match - - t.Run("SuccessOrganizationsCreateChildDuplicateWithoutUpdateErrors", func(t *testing.T) { - _, cmdErr := executeCommand([]string{ - "--output", "json", - "organization", - "create", - "--name", childOrg, - "--parent-canonical", config.Org, - }) - require.Error(t, cmdErr, "second create without --update must fail") - }) - - t.Run("SuccessOrganizationsCreateChildWithUpdate", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "organization", - "create", - "--update", - "--name", childOrg, - "--parent-canonical", config.Org, - }) - require.NoError(t, cmdErr) - - var again *models.Organization - err := json.Unmarshal([]byte(cmdOut), &again) - require.NoError(t, err) - require.NotNil(t, again) - require.NotNil(t, again.Canonical) - assert.Equal(t, childOrg, *again.Canonical) - }) - - t.Run("SuccessOrganizationsUpdate", func(t *testing.T) { - is := is.New(t) - updatedName := childOrg + "-updated" - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", childOrg, - "organization", "update", - "--name", updatedName, - }) - is.NoErr(cmdErr) // update should not fail - - var outOrg *models.Organization - err := json.Unmarshal([]byte(cmdOut), &outOrg) - is.NoErr(err) // output should be deserializable - is.Equal(updatedName, *outOrg.Name) // name should be updated - }) - - t.Run("SuccessOrganizationsAddSubscription", func(t *testing.T) { - _, cmdErr := executeCommand([]string{ - "--output", "json", - "organization", "subscription", - "update", - "--org", childOrg, - "--member-count", "10", - "--expires-at", time.Now().AddDate(1, 0, 0).Format(time.RFC3339), - }) - assert.NoError(t, cmdErr, "command should be okay") - }) - - t.Run("SuccessOrganizationsAddSubscriptionOverwriteOk", func(t *testing.T) { - _, cmdErr := executeCommand([]string{ - "--output", "json", - "organization", "subscription", - "update", - "--update", - "--org", childOrg, - "--member-count", "5", - "--expires-at", time.Now().AddDate(1, 0, 0).Format(time.RFC3339), - }) - assert.NoError(t, cmdErr, "We should be able to overwrite the sub") - }) - - t.Run("SuccessOrganizationsListChildrens", func(t *testing.T) { - is := is.New(t) - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "organization", - "list-childrens", - "--org", config.Org, - }) - is.NoErr(cmdErr) // command should not fail - - var outOrgs []*models.Organization - err := json.Unmarshal([]byte(cmdOut), &outOrgs) - is.NoErr(err) // output should be deserializable orgs - - // We try to find the new child org - index := slices.IndexFunc(outOrgs, func(o *models.Organization) bool { - return *o.Canonical == childOrg - }) - is.True(index != -1) // if -1, means that we can't find our new child org in list. Should be there. - }) - - t.Run("SuccessOrganizationsListWorkers", func(t *testing.T) { - is := is.New(t) - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "organization", - "list-workers", - }) - is.NoErr(cmdErr) // cmd should not fail - - var workers []*models.Worker - err := json.Unmarshal([]byte(cmdOut), &workers) - is.NoErr(err) // output should be deserializable - }) - }) -} diff --git a/e2e/pipelines_test.go b/e2e/pipelines_test.go deleted file mode 100644 index d789a68d5..000000000 --- a/e2e/pipelines_test.go +++ /dev/null @@ -1,309 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "os" - "strconv" - "testing" - - "github.com/sanity-io/litter" - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func TestPipelines(t *testing.T) { - // Pipelines - var pipelineList []*models.Pipeline - t.Run("PipelineListOk", func(t *testing.T) { - listOut, listErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "pipelines", "list", - }) - if listErr != nil { - t.Errorf("List org pipeline should not err, out: %s\nerr: %s", listOut, listErr) - } - - err := json.Unmarshal([]byte(listOut), &pipelineList) - if err != nil { - t.Errorf("failed to unmarshall list test output, out: %s\nerr: %s", listOut, err) - } - - if len(pipelineList) == 0 { - t.Errorf("There should be at least one pipeline in this org:\n%s", listOut) - } - }) - - firstPipeline := *pipelineList[0] - t.Run("GetPipelineOk", func(t *testing.T) { - getOut, getErr := executeCommand([]string{ - "--output", "json", - "pipelines", "get", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - }) - if getErr != nil { - t.Errorf("get pipeline should not err, out: %s\nerr: %s", getOut, getErr) - } - - var getPipeline models.Pipeline - err := json.Unmarshal([]byte(getOut), &getPipeline) - if err != nil { - t.Errorf("Failed to parse json output of pipelines get cmd, out: %s\nerr: %s", getOut, err) - } - - if assert.ObjectsAreEqualValues(firstPipeline, getPipeline) { - t.Errorf("both pipelines should be equal:\nexpect: %v\ngot: %v", firstPipeline, getPipeline) - } - }) - - t.Run("PipelinePauseOk", func(t *testing.T) { - _, pauseErr := executeCommand([]string{ - "--output", "json", - "pipelines", "pause", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - }) - if pauseErr != nil { - t.Errorf("failed to pause pipeline '%s': %s", *firstPipeline.Name, pauseErr) - } - }) - - t.Run("PipelineUnpauseOk", func(t *testing.T) { - _, unpauseErr := executeCommand([]string{ - "--output", "json", - "pipelines", "unpause", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - }) - if unpauseErr != nil { - t.Errorf("failed to unpause pipeline '%s': %s", *firstPipeline.Name, unpauseErr) - } - }) - - t.Run("PipelineSynced", func(t *testing.T) { - _, syncedErr := executeCommand([]string{ - "--output", "json", - "pipelines", "synced", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - }) - if syncedErr != nil { - t.Errorf("failed to pause pipeline '%s': %s", *firstPipeline.Name, syncedErr) - } - }) - - t.Run("PipelineLastUsedOk", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "pipelines", "last-used", - "--since-days", "99", - }) - if cmdErr != nil { - t.Errorf("failed to list last-used pipelines, out: %s\nerr: %s", cmdOut, cmdErr) - } - }) - - t.Run("PipelineDiffOk", func(t *testing.T) { - if len(pipelineList) == 0 { - t.Skip("no pipelines available") - } - - pipelineFile, err := os.CreateTemp("", "test-pipeline-*.yml") - if err != nil { - t.Fatalf("failed to create temp pipeline file: %s", err) - } - defer os.Remove(pipelineFile.Name()) - WriteFile(pipelineFile.Name(), TestPipelineSample) - - varsFile, err := os.CreateTemp("", "test-pipeline-vars-*.yml") - if err != nil { - t.Fatalf("failed to create temp pipeline vars file: %s", err) - } - defer os.Remove(varsFile.Name()) - WriteFile(varsFile.Name(), TestPipelineVariables) - - _, diffErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "pipeline", "diff", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - "--pipeline-config", pipelineFile.Name(), - "--pipeline-vars", varsFile.Name(), - }) - if diffErr != nil { - t.Errorf("pipeline diff should not err: %s", diffErr) - } - }) - - // Jobs - var jobList []*models.Job - t.Run("ListJobsOk", func(t *testing.T) { - if len(pipelineList) == 0 { - t.Fatal("Test setup error: pipeline list length should not be 0.") - } - - firstPipeline := pipelineList[0] - listOut, listErr := executeCommand([]string{ - "--output", "json", - "pipeline", "jobs", "list", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - }) - if listErr != nil { - t.Errorf("List job in pipeline %q should not err, out: %s\nerr: %s", *firstPipeline.Name, listOut, listErr) - } - - err := json.Unmarshal([]byte(listOut), &jobList) - if err != nil { - t.Errorf("failed to marshal output of cy pp job list, out: %s\nerr: %s", listOut, err) - } - - if len(jobList) == 0 { - t.Errorf("job list should not be empty:\n%s", litter.Sdump(jobList)) - } - - firstJob := jobList[0] - t.Run("JobGetOk", func(t *testing.T) { - getOut, getErr := executeCommand([]string{ - "--output", "json", - "pipeline", "job", "get", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - "--job", *firstJob.Name, - }) - if getErr != nil { - t.Errorf("cy get job in pipeline '%s' should not fail, out: %s\nerr: %s", *firstJob.Name, getOut, getErr) - } - - var getJob *models.Job - err := json.Unmarshal([]byte(getOut), &getJob) - if err != nil { - t.Errorf("failed to unmarshall get job cmd output, out: %s\nerr: %s", getOut, err) - } - - assert.Equal(t, *firstJob.ID, *getJob.ID) - }) - - t.Run("PauseJobOk", func(t *testing.T) { - pauseOut, pauseErr := executeCommand([]string{ - "--output", "json", - "pipeline", "job", "pause", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - "--job", *firstJob.Name, - }) - if pauseErr != nil { - t.Errorf("cmd cy pp job pause failed for pipeline '%s', out: %s, err: %s", *firstPipeline.Name, pauseOut, pauseErr) - } - - t.Run("UnpauseJobOk", func(t *testing.T) { - unpauseOut, unpauseErr := executeCommand([]string{ - "--output", "json", - "pipeline", "job", "unpause", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - "--job", *firstJob.Name, - }) - if unpauseErr != nil { - t.Errorf("cmd cy pp job unpause failed for pipeline '%s', out: %s, err: %s", *firstPipeline.Name, unpauseOut, unpauseErr) - } - }) - }) - - t.Run("PipelineClearTaskCacheOk", func(t *testing.T) { - t.Skip() - _, clearErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "pipeline", "clear-task-cache", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - "--job", *firstJob.Name, - }) - if clearErr != nil { - t.Errorf("pipeline clear-task-cache should not err: %s", clearErr) - } - }) - - var triggeredBuild *models.Build - // Builds - t.Run("CreateBuildOk", func(t *testing.T) { - triggerOut, triggerErr := executeCommand([]string{ - "--output", "json", - "pipeline", "build", "create", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - "--job", *firstJob.Name, - }) - if triggerErr != nil { - t.Errorf("cmd cy pp build create failed for job '%s' in pipeline '%s', out: %s, err: %s", *firstJob.Name, *firstPipeline.Name, triggerOut, triggerErr) - } - - err := json.Unmarshal([]byte(triggerOut), &triggeredBuild) - if err != nil { - t.Errorf("cmd output is not a models.Build, out: %s\nerr: %s", triggerOut, triggerErr) - } - - buildIDStr := strconv.Itoa(int(*triggeredBuild.ID)) - if err != nil { - t.Errorf("invalid build id in:\n%v\n%s", triggeredBuild, err) - } - - t.Run("GetBuildOk", func(t *testing.T) { - getOut, getErr := executeCommand([]string{ - "--output", "json", - "pipeline", "build", "get", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - "--job", *firstJob.Name, - "--build-id", buildIDStr, - }) - if getErr != nil { - t.Errorf("cmd cy pp build get failed for job '%s' in pipeline '%s', out: %s, err: %s", *firstJob.Name, *firstPipeline.Name, getOut, getErr) - } - }) - - t.Run("ListBuildOk", func(t *testing.T) { - listOut, listErr := executeCommand([]string{ - "--output", "json", - "pipeline", "build", "list", - "--project", *firstPipeline.Project.Canonical, - "--env", *firstPipeline.Environment.Canonical, - "--component", *firstPipeline.Component.Canonical, - "--pipeline", *firstPipeline.Name, - "--job", *firstJob.Name, - }) - if listErr != nil { - t.Errorf("cmd cy pp build list failed for job '%s' in pipeline '%s', out: %s, err: %s", *firstJob.Name, *firstPipeline.Name, listOut, listErr) - } - }) - }) - }) -} diff --git a/e2e/plugin_setup_test.go b/e2e/plugin_setup_test.go deleted file mode 100644 index 2322e8c8b..000000000 --- a/e2e/plugin_setup_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package e2e_test - -import ( - "fmt" - "math/rand" - "os" - "os/exec" - "sync" - "testing" -) - -const ( - helloWorldSource = "cycloid/plugin-hello-world:latest" - // baseLocalImage is the base path in the host-reachable registry. - baseLocalImage = "localhost:5000/plugin-hello-world" - // baseAPIImage is the base path as seen from inside the docker network. - // Must match the registry URL configured in the plugin-registry service. - baseAPIImage = "docker-registry:5000/plugin-hello-world" -) - -var imageOnce sync.Once - -// ensureHelloWorldImage ensures the plugin-hello-world source image is pulled once. -// Unique tags are pushed on demand by uniqueHelloWorldVersion. -func ensureHelloWorldImage(t *testing.T) { - t.Helper() - imageOnce.Do(func() { - run := func(name string, args ...string) { - cmd := exec.Command(name, args...) - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - t.Fatalf("command %q %v failed: %v", name, args, err) - } - } - run("docker", "pull", helloWorldSource) - run("docker", "login", "localhost:5000", "-u", "cycloid", "-p", "cycloid123") - }) -} - -// uniqueHelloWorldVersion generates a unique semver-compatible image tag, pushes it -// to the local registry, and returns the docker-registry:5000 URL for use with the API. -// The plugin-registry enforces a global unique constraint on version URLs, so each -// call to CreatePluginVersion must use a different image tag. -func uniqueHelloWorldVersion(t *testing.T) string { - t.Helper() - ensureHelloWorldImage(t) - - tag := fmt.Sprintf("1.0.%d", rand.Intn(999999)) - local := fmt.Sprintf("%s:%s", baseLocalImage, tag) - api := fmt.Sprintf("%s:%s", baseAPIImage, tag) - - run := func(name string, args ...string) { - t.Helper() - cmd := exec.Command(name, args...) - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - t.Fatalf("uniqueHelloWorldVersion: %q %v failed: %v", name, args, err) - } - } - - run("docker", "tag", helloWorldSource, local) - run("docker", "push", local) - return api -} diff --git a/e2e/plugins_test.go b/e2e/plugins_test.go deleted file mode 100644 index 5676834f1..000000000 --- a/e2e/plugins_test.go +++ /dev/null @@ -1,586 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "os" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// pluginsEnabled reports whether the plugin e2e suite should run. -func pluginsEnabled() bool { - return os.Getenv("CY_TEST_E2E_PLUGINS") == "1" -} - -// pollPluginRunning polls GetPlugin until Status == "running" or timeout. -// Returns true if "running" was reached, false on timeout (plugin-manager may lack -// a container runtime in the compose test environment). -func pollPluginRunning(t *testing.T, org string, installID uint32) bool { - t.Helper() - deadline := time.Now().Add(90 * time.Second) - for time.Now().Before(deadline) { - install, _, err := config.Middleware.GetPlugin(org, installID) - if err == nil && install != nil && install.Status != nil && *install.Status == "running" { - return true - } - if err == nil && install != nil && install.Status != nil && *install.Status == "failed" { - t.Logf("plugin install %d entered failed state (plugin-manager may lack container runtime)", installID) - return false - } - time.Sleep(3 * time.Second) - } - t.Logf("plugin install %d did not reach running state within 90s (plugin-manager may lack container runtime)", installID) - return false -} - -func TestPluginManagers(t *testing.T) { - if !pluginsEnabled() { - t.Skip("set CY_TEST_E2E_PLUGINS=1 to run plugin e2e tests") - } - - org := config.Org - - t.Run("List", func(t *testing.T) { - out, err := executeCommand([]string{"plugin", "manager", "list", "--output", "json"}) - require.NoError(t, err, "plugin manager list failed: %s", out) - var managers []map[string]any - require.NoError(t, json.Unmarshal([]byte(out), &managers), "output not valid JSON") - }) - - t.Run("AcceptTestPluginManager", func(t *testing.T) { - mgr, err := config.AcceptPluginManager(t) - require.NoError(t, err, "failed to accept test-plugin-manager") - require.NotNil(t, mgr) - // API returns "invite_accepted" once accepted. - assert.Contains(t, []string{"accepted", "invite_accepted"}, *mgr.InviteStatus) - }) - - t.Run("GetAfterAccept", func(t *testing.T) { - managers, _, err := config.Middleware.ListPluginManagers(org) - require.NoError(t, err) - var found bool - for _, m := range managers { - if m.Name != nil && *m.Name == "test-plugin-manager" { - found = true - assert.Contains(t, []string{"accepted", "invite_accepted"}, *m.InviteStatus) - break - } - } - assert.True(t, found, "test-plugin-manager not found after accept") - }) -} - -func TestPluginRegistries(t *testing.T) { - if !pluginsEnabled() { - t.Skip("set CY_TEST_E2E_PLUGINS=1 to run plugin e2e tests") - } - - name := randomCanonical("e2e-registry") - // Use a unique offline URL per test run to avoid the API's one-URL-per-registry constraint. - regURL := fmt.Sprintf("http://test-reg-%s:9999", name) - - t.Run("Create", func(t *testing.T) { - out, err := executeCommand([]string{ - "plugin", "registry", "create", - "--name", name, - "--url", regURL, - "--output", "json", - }) - require.NoError(t, err, "create failed: %s", out) - var reg map[string]any - require.NoError(t, json.Unmarshal([]byte(out), ®)) - assert.Equal(t, name, reg["name"]) - }) - - defer t.Run("Cleanup", func(t *testing.T) { - _, err := executeCommand([]string{"plugin", "registry", "delete", name}) - assert.NoError(t, err, "cleanup delete failed") - }) - - t.Run("List", func(t *testing.T) { - out, err := executeCommand([]string{"plugin", "registry", "list", "--output", "json"}) - require.NoError(t, err) - names, err := JSONListExtractFields(out, "name", "", "") - require.NoError(t, err) - assert.Contains(t, names, name) - }) - - t.Run("Get", func(t *testing.T) { - out, err := executeCommand([]string{"plugin", "registry", "get", name, "--output", "json"}) - require.NoError(t, err, "get failed: %s", out) - var reg map[string]any - require.NoError(t, json.Unmarshal([]byte(out), ®)) - assert.Equal(t, name, reg["name"]) - }) - - t.Run("UpdateName", func(t *testing.T) { - renamed := name + "-r" - out, err := executeCommand([]string{ - "plugin", "registry", "update", name, - "--name", renamed, - "--output", "json", - }) - require.NoError(t, err, "update failed: %s", out) - var reg map[string]any - require.NoError(t, json.Unmarshal([]byte(out), ®)) - assert.Equal(t, renamed, reg["name"]) - // Rename back so subsequent subtests can find by original name. - _, err = executeCommand([]string{ - "plugin", "registry", "update", renamed, - "--name", name, - }) - require.NoError(t, err) - }) - - t.Run("CreateIdempotentWithUpdate", func(t *testing.T) { - out, err := executeCommand([]string{ - "plugin", "registry", "create", - "--name", name, - "--url", regURL, - "--update", - "--output", "json", - }) - require.NoError(t, err, "create --update failed: %s", out) - var reg map[string]any - require.NoError(t, json.Unmarshal([]byte(out), ®)) - assert.Equal(t, name, reg["name"]) - }) - - t.Run("CreateDuplicateFails", func(t *testing.T) { - _, err := executeCommand([]string{ - "plugin", "registry", "create", - "--name", name, - "--url", regURL, - }) - assert.Error(t, err, "expected error creating duplicate registry without --update") - }) -} - -func TestRegistryPlugins(t *testing.T) { - if !pluginsEnabled() { - t.Skip("set CY_TEST_E2E_PLUGINS=1 to run plugin e2e tests") - } - - regURL := "http://plugin-registry:4000" - reg, err := config.NewTestPluginRegistry(t, randomCanonical("e2e-reg-pl"), regURL) - require.NoError(t, err) - regID := *reg.ID - regName := *reg.Name - - pluginName := randomCanonical("e2e-plugin") - - t.Run("Create", func(t *testing.T) { - out, err := executeCommand([]string{ - "plugin", "registry", "plugin", "create", - regName, - "--name", pluginName, - "--output", "json", - }) - require.NoError(t, err, "create plugin failed: %s", out) - var p map[string]any - require.NoError(t, json.Unmarshal([]byte(out), &p)) - assert.Equal(t, pluginName, p["name"]) - }) - - defer t.Run("CleanupPlugin", func(t *testing.T) { - _, _ = executeCommand([]string{ - "plugin", "registry", "plugin", "delete", - regName, - pluginName, - }) - }) - - t.Run("List", func(t *testing.T) { - out, err := executeCommand([]string{ - "plugin", "registry", "plugin", "list", - regName, - "--output", "json", - }) - require.NoError(t, err) - names, err := JSONListExtractFields(out, "name", "", "") - require.NoError(t, err) - assert.Contains(t, names, pluginName) - }) - - t.Run("Get", func(t *testing.T) { - out, err := executeCommand([]string{ - "plugin", "registry", "plugin", "get", - pluginName, - "--registry", regName, - "--output", "json", - }) - require.NoError(t, err, "get plugin failed: %s", out) - var p map[string]any - require.NoError(t, json.Unmarshal([]byte(out), &p)) - assert.Equal(t, pluginName, p["name"]) - }) - - t.Run("Update", func(t *testing.T) { - renamed := pluginName + "-r" - out, err := executeCommand([]string{ - "plugin", "registry", "plugin", "update", - regName, - pluginName, - "--name", renamed, - "--output", "json", - }) - require.NoError(t, err, "update plugin failed: %s", out) - var p map[string]any - require.NoError(t, json.Unmarshal([]byte(out), &p)) - assert.Equal(t, renamed, p["name"]) - // Rename back. - _, err = executeCommand([]string{ - "plugin", "registry", "plugin", "update", - regName, - renamed, - "--name", pluginName, - }) - require.NoError(t, err) - }) - - _ = regID -} - -func TestPluginVersions(t *testing.T) { - if !pluginsEnabled() { - t.Skip("set CY_TEST_E2E_PLUGINS=1 to run plugin e2e tests") - } - - ensureHelloWorldImage(t) - - regURL := "http://plugin-registry:4000" - reg, err := config.NewTestPluginRegistry(t, randomCanonical("e2e-reg-ver"), regURL) - require.NoError(t, err) - regName := *reg.Name - - plugin, err := config.NewTestPluginInRegistry(t, *reg.ID, randomCanonical("e2e-plver")) - require.NoError(t, err) - pluginID := *plugin.ID - pluginName := *plugin.Name - - t.Run("Publish", func(t *testing.T) { - out, err := executeCommand([]string{ - "plugin", "registry", "plugin", "version", "publish", - "--registry", regName, - "--plugin", pluginName, - "--docker-image", uniqueHelloWorldVersion(t), - "--output", "json", - }) - require.NoError(t, err, "publish failed: %s", out) - var v map[string]any - require.NoError(t, json.Unmarshal([]byte(out), &v)) - assert.NotEmpty(t, v["id"]) - }) - - versions, _, err := config.Middleware.ListPluginVersions(config.Org, *reg.ID, pluginID) - require.NoError(t, err) - require.NotEmpty(t, versions, "no versions after publish") - versionID := *versions[0].ID - - t.Run("List", func(t *testing.T) { - out, err := executeCommand([]string{ - "plugin", "registry", "plugin", "version", "list", - "--registry", regName, - "--plugin", pluginName, - "--output", "json", - }) - require.NoError(t, err) - var vs []map[string]any - require.NoError(t, json.Unmarshal([]byte(out), &vs)) - assert.NotEmpty(t, vs) - }) - - t.Run("Get", func(t *testing.T) { - out, err := executeCommand([]string{ - "plugin", "registry", "plugin", "version", "get", - fmt.Sprint(versionID), - "--registry", regName, - "--plugin", pluginName, - "--output", "json", - }) - require.NoError(t, err, "get version failed: %s", out) - var v map[string]any - require.NoError(t, json.Unmarshal([]byte(out), &v)) - assert.NotEmpty(t, v["id"]) - }) - - t.Run("Logs", func(t *testing.T) { - // Version logs endpoint should succeed even when empty. - out, err := executeCommand([]string{ - "plugin", "registry", "plugin", "version", "logs", - fmt.Sprint(versionID), - "--registry", regName, - "--plugin", pluginName, - "--output", "json", - }) - require.NoError(t, err, "version logs failed: %s", out) - }) - - defer t.Run("Delete", func(t *testing.T) { - _, err := executeCommand([]string{ - "plugin", "registry", "plugin", "version", "delete", - fmt.Sprint(versionID), - "--registry", regName, - "--plugin", pluginName, - }) - assert.NoError(t, err) - }) -} - -func TestPluginInstallLifecycle(t *testing.T) { - if !pluginsEnabled() { - t.Skip("set CY_TEST_E2E_PLUGINS=1 to run plugin e2e tests") - } - - ensureHelloWorldImage(t) - - org := config.Org - - // Ensure test-plugin-manager is accepted. - _, err := config.AcceptPluginManager(t) - require.NoError(t, err, "failed to accept test-plugin-manager") - - regURL := "http://plugin-registry:4000" - reg, err := config.NewTestPluginRegistry(t, randomCanonical("e2e-reg-inst"), regURL) - require.NoError(t, err) - regName := *reg.Name - - plugin, err := config.NewTestPluginInRegistry(t, *reg.ID, randomCanonical("e2e-plinst")) - require.NoError(t, err) - pluginName := *plugin.Name - - version, err := config.NewTestPluginVersion(t, *reg.ID, *plugin.ID, uniqueHelloWorldVersion(t)) - require.NoError(t, err) - versionID := *version.ID - - var installID uint32 - - t.Run("Install", func(t *testing.T) { - _, err := executeCommand([]string{ - "plugin", "registry", "plugin", "version", "install", - fmt.Sprint(versionID), - "--registry", regName, - "--plugin", pluginName, - }) - require.NoError(t, err, "install failed") - - // Resolve the install ID from the plugin list. - installs, _, err := config.Middleware.ListPlugins(org) - require.NoError(t, err) - for _, p := range installs { - if p.Name != nil && *p.Name == pluginName && p.Install != nil { - installID = *p.Install.ID - break - } - } - require.NotZero(t, installID, "install record not found after install") - }) - - var pluginRunning bool - t.Run("PollRunning", func(t *testing.T) { - if installID == 0 { - t.Skip("install step did not complete") - } - pluginRunning = pollPluginRunning(t, org, installID) - if !pluginRunning { - t.Skip("plugin did not reach running state (plugin-manager may lack container runtime)") - } - }) - - t.Run("Get", func(t *testing.T) { - if installID == 0 { - t.Skip("install step did not complete") - } - out, err := executeCommand([]string{ - "plugin", "get", fmt.Sprint(installID), - "--output", "json", - }) - require.NoError(t, err, "plugin get failed: %s", out) - var install map[string]any - require.NoError(t, json.Unmarshal([]byte(out), &install)) - assert.NotNil(t, install["id"], "install record should have an id") - }) - - t.Run("List", func(t *testing.T) { - out, err := executeCommand([]string{"plugin", "list", "--output", "json"}) - require.NoError(t, err) - var installs []map[string]any - require.NoError(t, json.Unmarshal([]byte(out), &installs)) - assert.NotEmpty(t, installs) - }) - - t.Run("RetryIdempotent", func(t *testing.T) { - // A second install with --retry should not fail with 409. - _, err := executeCommand([]string{ - "plugin", "registry", "plugin", "version", "install", - fmt.Sprint(versionID), - "--registry", regName, - "--plugin", pluginName, - "--retry", - }) - require.NoError(t, err, "install --retry on already-installed version should succeed") - }) - - defer t.Run("Uninstall", func(t *testing.T) { - if installID == 0 { - return - } - _, err := executeCommand([]string{"plugin", "uninstall", fmt.Sprint(installID)}) - assert.NoError(t, err, "uninstall failed") - }) -} - -func TestPluginWidgets(t *testing.T) { - if !pluginsEnabled() { - t.Skip("set CY_TEST_E2E_PLUGINS=1 to run plugin e2e tests") - } - - ensureHelloWorldImage(t) - - org := config.Org - - // Ensure test-plugin-manager is accepted. - _, err := config.AcceptPluginManager(t) - require.NoError(t, err, "failed to accept test-plugin-manager") - - regURL := "http://plugin-registry:4000" - reg, err := config.NewTestPluginRegistry(t, randomCanonical("e2e-reg-wgt"), regURL) - require.NoError(t, err) - regName := *reg.Name - - plugin, err := config.NewTestPluginInRegistry(t, *reg.ID, randomCanonical("e2e-plwgt")) - require.NoError(t, err) - pluginName := *plugin.Name - - version, err := config.NewTestPluginVersion(t, *reg.ID, *plugin.ID, uniqueHelloWorldVersion(t)) - require.NoError(t, err) - versionID := *version.ID - - // Install and wait for running. - _, err = executeCommand([]string{ - "plugin", "registry", "plugin", "version", "install", - fmt.Sprint(versionID), - "--registry", regName, - "--plugin", pluginName, - }) - require.NoError(t, err) - - installs, _, err := config.Middleware.ListPlugins(org) - require.NoError(t, err) - var installID uint32 - for _, p := range installs { - if p.Name != nil && *p.Name == pluginName && p.Install != nil { - installID = *p.Install.ID - break - } - } - require.NotZero(t, installID) - - defer t.Run("CleanupInstall", func(t *testing.T) { - _, _ = config.Middleware.DeletePlugin(org, installID) - }) - - running := pollPluginRunning(t, org, installID) - - t.Run("ListWidgets", func(t *testing.T) { - if !running { - t.Skip("plugin not running — skipping widget test (plugin-manager may lack container runtime)") - } - out, err := executeCommand([]string{ - "plugin", "widget", "list", - "--placement", "sideMenuPage", - "--output", "json", - }) - require.NoError(t, err, "widget list failed: %s", out) - var widgets []map[string]any - require.NoError(t, json.Unmarshal([]byte(out), &widgets)) - assert.NotEmpty(t, widgets, "expected at least one widget after install") - }) - - t.Run("IframeServedContent", func(t *testing.T) { - if !running { - t.Skip("plugin not running — skipping iframe test (plugin-manager may lack container runtime)") - } - // Resolve the widget URL from the plugin widget list and verify it - // serves HTML containing "Hello World". - widgets, _, err := config.Middleware.ListPluginWidgets(org, "sideMenuPage") - require.NoError(t, err) - require.NotEmpty(t, widgets, "no widgets found for sideMenuPage placement") - - // Find the iframe widget belonging to our install. - var iframeURL string - for _, w := range widgets { - if w.Type == nil || *w.Type != "iframe" { - continue - } - // Widget field is a map with a "url" key. - wmap, ok := w.Widget.(map[string]any) - if !ok { - continue - } - rawURL, ok := wmap["url"].(string) - if !ok { - continue - } - iframeURL = rawURL - break - } - require.NotEmpty(t, iframeURL, "no iframe widget URL found") - - // plugin-manager is reachable on localhost:4000 (compose port mapping). - hostURL := strings.ReplaceAll(iframeURL, "plugin-manager:4000", "localhost:4000") - - resp, err := http.Get(hostURL) //nolint:noctx - require.NoError(t, err, "GET iframe URL failed: %s", hostURL) - defer resp.Body.Close() - - assert.Equal(t, http.StatusOK, resp.StatusCode) - - body, err := io.ReadAll(resp.Body) - require.NoError(t, err) - assert.Contains(t, strings.ToLower(string(body)), "hello world", - "iframe URL %s did not return Hello World content", hostURL) - }) -} - -func TestPluginCommandsErrorPaths(t *testing.T) { - if !pluginsEnabled() { - t.Skip("set CY_TEST_E2E_PLUGINS=1 to run plugin e2e tests") - } - - t.Run("WatchIntervalTooShort", func(t *testing.T) { - _, err := executeCommand([]string{ - "plugin", "logs", "999", - "--watch-interval", "100ms", - }) - assert.Error(t, err, "expected error for --watch-interval below 500ms") - assert.Contains(t, err.Error(), "500ms") - }) - - t.Run("RegistryCreateMissingURL", func(t *testing.T) { - _, err := executeCommand([]string{ - "plugin", "registry", "create", - "--name", "missing-url-test", - }) - assert.Error(t, err, "expected error when --url is absent") - }) - - t.Run("InstallRetryOnNonExistent", func(t *testing.T) { - // Should fail cleanly, not panic. - _, err := executeCommand([]string{ - "plugin", "registry", "plugin", "version", "install", - "--registry", "nonexistent-registry-e2e", - "--plugin", "nonexistent-plugin-e2e", - "99999", - "--retry", - }) - assert.Error(t, err) - }) -} diff --git a/e2e/projects_test.go b/e2e/projects_test.go deleted file mode 100644 index 354108898..000000000 --- a/e2e/projects_test.go +++ /dev/null @@ -1,323 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "os" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" -) - -func TestProjects(t *testing.T) { - - os.Setenv("CY_API_URL", config.APIUrl) - os.Setenv("CY_API_KEY", config.APIKey) - os.Setenv("CY_ORG", config.Org) - - var ( - projectName = "Test E2E project" - project = randomCanonical("test-e2e-project") - description = "Testing project" - owner = "" - color = "demo" - icon = "public" - ) - - t.Run("Create", func(t *testing.T) { - args := []string{ - "project", "create", - "--project", project, - "--name", projectName, - "--description", description, - "--owner", owner, - "--icon", icon, - "--color", color, - } - _, err := executeCommand(args) - if err != nil { - t.Errorf("failed to create project '%s': %v", project, err) - } - }) - - t.Run("CreateWithNameOnlyAndUpdate", func(t *testing.T) { - var ( - nameOnly = "Project Name " + randomCanonical("e2e") - canonical = middleware.ToCanonical(nameOnly) - updatedDesc = "Updated inferred project description" - newIcon = cyargs.PickRandomIcon(nil) - newColor = cyargs.PickRandomColor(nil) - ) - - createArgs := []string{ - "--output", "json", - "project", "create", - "--name", nameOnly, - "--description", description, - "--owner", owner, - "--icon", icon, - "--color", color, - } - createOut, err := executeCommand(createArgs) - if err != nil { - t.Errorf("failed to create project with name-only '%s': %v", nameOnly, err) - } - - defer t.Run("DeleteNameOnlyProject", func(t *testing.T) { - args := []string{ - "project", "delete", - "--project", canonical, - } - _, err := executeCommand(args) - if err != nil { - t.Errorf("failed to delete project '%s': %v", canonical, err) - } - }) - - var createdProject models.Project - err = json.Unmarshal([]byte(createOut), &createdProject) - if err != nil { - t.Errorf("failed to parse create output for inferred project: %v\noutput: %s", err, createOut) - } - assert.Equal(t, nameOnly, *createdProject.Name) - assert.Equal(t, canonical, *createdProject.Canonical) - - updateArgs := []string{ - "--output", "json", - "project", "create", - "--name", nameOnly, - "--description", updatedDesc, - "--owner", owner, - "--icon", newIcon, - "--color", newColor, - "--update", - } - updateOut, err := executeCommand(updateArgs) - if err != nil { - t.Errorf("failed to create --update project with name-only '%s': %v", nameOnly, err) - } - - var updatedProject models.Project - err = json.Unmarshal([]byte(updateOut), &updatedProject) - if err != nil { - t.Errorf("failed to parse update output for inferred project: %v\noutput: %s", err, updateOut) - } - assert.Equal(t, canonical, *updatedProject.Canonical) - assert.Equal(t, nameOnly, *updatedProject.Name) - assert.Equal(t, updatedDesc, updatedProject.Description) - assert.Equal(t, newColor, *updatedProject.Color) - assert.Equal(t, newIcon, *updatedProject.Icon) - }) - - defer t.Run("Delete", func(t *testing.T) { - args := []string{ - "project", "delete", - "--project", project, - } - _, err := executeCommand(args) - if err != nil { - t.Errorf("failed to delete project '%s': %v", project, err) - } - }) - - t.Run("CreateWithUpdateExisting", func(t *testing.T) { - var ( - createUpdateName = "helloUpdate" - newIcon = cyargs.PickRandomIcon(nil) - newColor = cyargs.PickRandomColor(nil) - ) - args := []string{ - "-o", "json", - "project", "create", - "--project", project, - "--name", createUpdateName, - "--description", description, - "--owner", owner, - "--icon", newIcon, - "--color", newColor, - "--update", - } - out, err := executeCommand(args) - if err != nil { - t.Errorf("failed to create project '%s': %v", project, err) - } - - var projectResult models.Project - err = json.Unmarshal([]byte(out), &projectResult) - if err != nil { - t.Errorf("failed to parse json output from the CLI on create --update: %v\noutput: %s", err, out) - } - - assert.Equal(t, createUpdateName, *projectResult.Name) - assert.Equal(t, newColor, *projectResult.Color) - assert.Equal(t, newIcon, *projectResult.Icon) - }) - - t.Run("CreateWithUpdateNew", func(t *testing.T) { - var newProject = randomCanonical("e2e-new") - args := []string{ - "-o", "json", - "project", "create", - "--project", newProject, - "--description", description, - "--owner", owner, - "--icon", icon, - "--color", color, - "--update", - } - _, err := executeCommand(args) - if err != nil { - t.Errorf("failed to create project '%s': %v", newProject, err) - } - - defer t.Run("DeleteCreateUpdate", func(t *testing.T) { - args := []string{ - "project", "delete", - "--project", newProject, - } - _, err := executeCommand(args) - if err != nil { - t.Errorf("failed to delete project '%s': %v", newProject, err) - } - }) - }) - - t.Run("Update", func(t *testing.T) { - var updateDesc = "NewDesc" - args := []string{ - "project", "update", - "--output", "json", - "--project", project, - "--name", projectName, - "--description", updateDesc, - "--owner", owner, - "--icon", icon, - "--color", color, - } - jsonOut, err := executeCommand(args) - if err != nil { - t.Errorf("failed to update project '%s': %v", project, err) - } - - var projectResult models.Project - err = json.Unmarshal([]byte(jsonOut), &projectResult) - if err != nil { - t.Errorf("failed to parse json output from the CLI on update: %v\noutput: %s", err, jsonOut) - } - - assert.Equal(t, updateDesc, projectResult.Description) - }) - - t.Run("ListEnv", func(t *testing.T) { - args := []string{ - "--output", "json", - "project", "list-env", - "--project", project, - } - out, err := executeCommand(args) - if err != nil { - t.Errorf("failed to list project environments for '%s': %v", project, err) - } - - var envList []*models.Environment - if jsonErr := json.Unmarshal([]byte(out), &envList); jsonErr != nil { - t.Errorf("failed to parse json output of list-env: %v\noutput: %s", jsonErr, out) - } - }) - - // Positional-arg tests — verify the new interface works alongside deprecated --project flag - - t.Run("GetWithPositionalArg", func(t *testing.T) { - args := []string{ - "--output", "json", - "project", "get", - project, // positional, no --project flag - } - out, err := executeCommand(args) - if err != nil { - t.Errorf("failed to get project '%s' via positional arg: %v", project, err) - } - - var got models.Project - if jsonErr := json.Unmarshal([]byte(out), &got); jsonErr != nil { - t.Errorf("failed to parse get output: %v\noutput: %s", jsonErr, out) - } - assert.Equal(t, project, *got.Canonical) - }) - - t.Run("DeleteWithPositionalArg", func(t *testing.T) { - // Create a dedicated project to delete via positional arg - tmpProject := randomCanonical("e2e-del-pos") - _, createErr := executeCommand([]string{ - "--output", "json", - "project", "create", - "--project", tmpProject, - "--name", tmpProject, - "--icon", icon, - "--color", color, - }) - if createErr != nil { - t.Errorf("setup: failed to create project '%s': %v", tmpProject, createErr) - } - - _, deleteErr := executeCommand([]string{ - "--output", "json", - "project", "delete", - tmpProject, // positional, no --project flag - }) - assert.NoError(t, deleteErr, "delete via positional arg should succeed") - }) - - t.Run("DeleteDefaultTableOutput", func(t *testing.T) { - // Verify delete uses table mode by default and shows the deleted canonical. - tmpProject := randomCanonical("e2e-del-tbl") - _, createErr := executeCommand([]string{ - "project", "create", - "--project", tmpProject, - "--name", tmpProject, - "--icon", icon, - "--color", color, - }) - if createErr != nil { - t.Fatalf("setup: failed to create project '%s': %v", tmpProject, createErr) - } - - out, deleteErr := executeCommand([]string{ - "project", "delete", - tmpProject, - }) - assert.NoError(t, deleteErr, "delete should succeed") - assert.Contains(t, out, tmpProject, "default table output should contain the deleted canonical") - assert.NotContains(t, out, "[", "default output should not be JSON array") - }) - - t.Run("DeleteMultiplePositionalArgs", func(t *testing.T) { - // Verify deleting multiple projects at once outputs a table with all canonicals. - proj1 := randomCanonical("e2e-del-m1") - proj2 := randomCanonical("e2e-del-m2") - for _, p := range []string{proj1, proj2} { - _, createErr := executeCommand([]string{ - "project", "create", - "--project", p, - "--name", p, - "--icon", icon, - "--color", color, - }) - if createErr != nil { - t.Fatalf("setup: failed to create project '%s': %v", p, createErr) - } - } - - out, deleteErr := executeCommand([]string{ - "project", "delete", - proj1, proj2, - }) - assert.NoError(t, deleteErr, "bulk delete should succeed") - assert.Contains(t, out, proj1, "output should contain first deleted canonical") - assert.Contains(t, out, proj2, "output should contain second deleted canonical") - assert.NotContains(t, out, "[", "default output should not be JSON array") - }) -} diff --git a/e2e/roles_test.go b/e2e/roles_test.go deleted file mode 100644 index 7563ca04b..000000000 --- a/e2e/roles_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package e2e_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestRoles(t *testing.T) { - t.Run("SuccessRolesList", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "roles", - "list", - }) - - require.Nil(t, cmdErr) - assert.Contains(t, cmdOut, "canonical\": \"organization-member") - }) - - t.Run("SuccessRolesCreate", func(t *testing.T) { - ruleFile, err := WriteTempFile(`[ - {"action": "organization:update", "effect": "allow", "resources": []}, - {"action": "organization:list", "effect": "allow", "resources": []} - ]`) - assert.NoError(t, err, "test setup failed to write temp file", ruleFile) - - roleCan := randomCanonical("role") - cmd := []string{ - "--output", "json", - "--org", config.Org, - "roles", - "create", - "--name", "Team leader", - "--role", roleCan, - "--description", "big boss", - "--rule-json", `{"action": "organization:delete", "effect": "allow", "resources": []}`, - "--rule-json", `{"action": "organization:create", "effect": "allow", "resources": []}`, - "--rule-file", ruleFile, - } - cmdOut, cmdErr := executeCommand(cmd) - - require.Nil(t, cmdErr) - assert.Contains(t, cmdOut, roleCan) - - defer t.Run("SuccessRoleDelete", func(t *testing.T) { - _, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "roles", - "delete", - roleCan, - }) - require.Nil(t, cmdErr) - }) - }) - - t.Run("SuccessRolesGet", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "roles", - "get", - "organization-member", - }) - - require.Nil(t, cmdErr) - assert.Contains(t, cmdOut, "canonical\": \"organization-member") - }) - - t.Run("SuccessRolesUpsertIdempotent", func(t *testing.T) { - roleCan := randomCanonical("role") - rule := `{"action": "organization:list", "effect": "allow", "resources": []}` - base := []string{"--output", "json", "--org", config.Org, "roles"} - - createCmd := append(base, "create", "--role", roleCan, "--name", "Upsert Role", "--description", "v1", "--rule-json", rule) - _, err := executeCommand(createCmd) - require.Nil(t, err) - - t.Cleanup(func() { - _, delErr := executeCommand(append(base, "delete", roleCan)) - require.Nil(t, delErr) - }) - - _, err = executeCommand(append(base, "create", "--update", "--role", roleCan, "--name", "Upsert Role", "--description", "v1", "--rule-json", rule)) - require.Nil(t, err, "create --update should succeed idempotently") - - _, err = executeCommand(append(base, "update", "--role", roleCan, "--name", "Upsert Role v2", "--description", "v2", "--rule-json", rule)) - require.Nil(t, err, "roles update should succeed") - - getOut, err := executeCommand(append(base, "get", roleCan)) - require.Nil(t, err) - assert.Contains(t, getOut, "Upsert Role v2") - assert.Contains(t, getOut, roleCan) - }) -} diff --git a/e2e/stacks_test.go b/e2e/stacks_test.go deleted file mode 100644 index 00bed0b37..000000000 --- a/e2e/stacks_test.go +++ /dev/null @@ -1,439 +0,0 @@ -package e2e_test - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" - "os" - "testing" - - "github.com/matryer/is" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/internal/custommodels" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -func TestStacks(t *testing.T) { - t.Run("SuccessStacksListJSON", func(t *testing.T) { - is := is.New(t) - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "stacks", - "list", - }) - - is.NoErr(cmdErr) - var stackList []*models.ServiceCatalog - err := json.Unmarshal([]byte(cmdOut), &stackList) - is.NoErr(err) - is.True(len(stackList) >= 1) // We should have at least one stack in our test org - }) - - var testStackRef = config.Org + ":stack-e2e-stackforms" - var testStackCanonical = "stack-e2e-stackforms" - - t.Run("SuccessStackCreateDuplicateWithoutUpdateErrors", func(t *testing.T) { - is := is.New(t) - catalogRepo := ptr.Value(config.CatalogRepo.Canonical) - is.True(catalogRepo != "") - - // Required flags; blueprint-ref is not used when the stack canonical already exists (CLI short-circuits). - _, dupErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "stack", "create", - "--name", "E2E existing stack", - "--stack", testStackCanonical, - "--catalog-repository", catalogRepo, - "--blueprint-ref", testStackRef, - "--use-case", "default", - }) - require.Error(t, dupErr, "create without --update must fail when stack canonical already exists") - }) - - t.Run("SuccessStackCreateWithUpdateIdempotent", func(t *testing.T) { - is := is.New(t) - catalogRepo := ptr.Value(config.CatalogRepo.Canonical) - is.True(catalogRepo != "") - - cmdOut2, cmdErr2 := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "stack", "create", - "--update", - "--name", "E2E existing stack", - "--stack", testStackCanonical, - "--catalog-repository", catalogRepo, - "--blueprint-ref", testStackRef, - "--use-case", "default", - }) - require.NoError(t, cmdErr2) - - var outStack models.ServiceCatalog - err := json.Unmarshal([]byte(cmdOut2), &outStack) - require.NoError(t, err) - require.NotNil(t, outStack.Canonical) - assert.Equal(t, testStackCanonical, *outStack.Canonical) - require.NotNil(t, outStack.Ref) - assert.Equal(t, testStackRef, *outStack.Ref) - }) - - t.Run("SuccessStacksGet", func(t *testing.T) { - is := is.New(t) - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "stacks", - "get", - "--stack-ref", testStackRef, - }) - is.NoErr(cmdErr) - var outStack *models.ServiceCatalog - err := json.Unmarshal([]byte(cmdOut), &outStack) - is.NoErr(err) - }) - - t.Run("SuccessStacksUpdateVisibilty", func(t *testing.T) { - is := is.New(t) - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "stack", - "update", - "--stack-ref", testStackRef, - "--visibility", "shared", - }) - is.NoErr(cmdErr) - - var updatedStack *models.ServiceCatalog - err := json.Unmarshal([]byte(cmdOut), &updatedStack) - is.NoErr(err) - is.Equal(*updatedStack.Visibility, "shared") - }) - - t.Run("SuccessAddStackMaintainer", func(t *testing.T) { - var teamCanonical = "test-team" - body := map[string]any{ - "canonical": teamCanonical, - "name": teamCanonical, - "roles_canonical": []string{ - "default-project-viewer", - }, - } - jsonBody, err := json.Marshal(body) - if err != nil { - t.Errorf("[preparation]: json serialization shouldn't fail: %s", err.Error()) - } - - // team management is not implemented on the CLI, so making the call ourselves - request, err := http.NewRequest("POST", fmt.Sprintf("%s/organizations/%s/teams", config.APIUrl, config.Org), bytes.NewBuffer(jsonBody)) - if err != nil { - t.Errorf("[preparation]: request creationg shoudn't fail: %s", err.Error()) - } - - request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", config.APIKey)) - request.Header.Add("Content-Type", "application/vnd.cycloid.io.v1+json") - - client := &http.Client{} - _, err = client.Do(request) - if err != nil { - t.Errorf("[Preparation]: request to create teams shouldn't fail: %s", err.Error()) - } - - // At this point we should have a team, I assume CR and stacks are present too - is := is.New(t) - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "stack", "update", - "--stack-ref", testStackRef, - "--team", teamCanonical, - }) - is.NoErr(cmdErr) - var updatedStack *models.ServiceCatalog - err = json.Unmarshal([]byte(cmdOut), &updatedStack) - is.NoErr(err) - is.Equal(*updatedStack.Team.Canonical, teamCanonical) // New team canonical must match - }) - - t.Run("SuccessRemoveMaintainer", func(t *testing.T) { - is := is.New(t) - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "stack", "update", - "--stack-ref", testStackRef, - "--team", "", // setting the flag with empty string should remove the maintainer - }) - is.NoErr(cmdErr) // This command must not fail - var updatedStack *models.ServiceCatalog - err := json.Unmarshal([]byte(cmdOut), &updatedStack) - is.NoErr(err) // We should be able to deserialize a valid model - is.Equal(updatedStack.Team, nil) // Team should be unset - }) - - t.Run("InvalidMaintainerShouldError", func(t *testing.T) { - is := is.New(t) - _, cmdErr := executeCommand([]string{ - "--output", "json", - "stack", "update", - "--stack-ref", testStackRef, - "--team", "invalidteam", - }) - is.True(cmdErr != nil) // CLI should output an error if we try to update a stack with a team that doesn't exists - }) - t.Run("SuccessStacksGetConfig", func(t *testing.T) { - is := is.New(t) - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "--project", *config.Project.Canonical, - "--env", *config.Environment.Canonical, - "--component", *config.Component.Canonical, - "stack", "get-config", - "--use-case", "default", - }) - is.NoErr(cmdErr) // get-config should not fail - - // Output should be valid JSON - var out interface{} - err := json.Unmarshal([]byte(cmdOut), &out) - is.NoErr(err) // output should be deserializable JSON - }) - - t.Run("SuccessStacksValidateForm", func(t *testing.T) { - is := is.New(t) - var TestForms = []byte(`--- -version: "4" -shared: -- &anchor2 - name: "hello" - key: "toto3" - widget: "simple_text" - type: "string" -use_cases: -- name: use_cases - sections: - - name: "hello" - groups: - - name: "toto" - technlogies: ["tutu"] - vars: - - &anchor1 - name: "hello" - key: "toto" - widget: "simple_text" - type: "string" - - <<: *anchor1 - key: "toto1" - - *anchor2 - - <<: *anchor2 - key: "toto4" -`) - testForms, err := os.CreateTemp("", "test-stackforms.yml") - if err != nil { - t.Errorf("setup failed: error while writing test forms at '%s'", testForms.Name()) - } - testFormsPath := testForms.Name() - WriteFile(testFormsPath, TestForms) - defer os.Remove(testFormsPath) - - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "stacks", - "forms", "validate", - testFormsPath, - }) - is.NoErr(cmdErr) - is.Equal(cmdOut, "") - }) - - t.Run("SuccessStacksListWithBlueprintFlag", func(t *testing.T) { - is := is.New(t) - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "stacks", - "list", - "--blueprint", - }) - is.NoErr(cmdErr) // cmd should not fail - - var blueprints []*custommodels.Blueprint - err := json.Unmarshal([]byte(cmdOut), &blueprints) - is.NoErr(err) // json output should be deserializable - }) - - t.Run("SuccessCreateStackFromBlueprint", func(t *testing.T) { - t.Skip("Skipping due to missing way to cleanup stack afterwards") - }) - - // Completion tests - t.Run("SuccessCompleteStackVersionCommitHash", func(t *testing.T) { - is := is.New(t) - // Test completion for component create with stack-ref - cmdOut, cmdErr := executeCommand([]string{ - "__complete", - "component", "create", - "--org", config.Org, - "--stack-ref", testStackRef, - "--stack-commit-hash", "", - }) - is.NoErr(cmdErr) - // The output should contain commit hashes - // Format: commitHash\tDescription\n:4\nCompletion ended with directive: ShellCompDirectiveNoFileComp - is.True(len(cmdOut) > 0) // Should have some output - is.True(!bytes.Contains([]byte(cmdOut), []byte("_activeHelp"))) // Should not have error help - is.True(bytes.Contains([]byte(cmdOut), []byte(":4"))) // Should have NoFileComp directive (4) - }) - - t.Run("SuccessCompleteStackVersionCommitHashWithPartialInput", func(t *testing.T) { - is := is.New(t) - // First, get a valid commit hash from the stack versions - cmdOut, cmdErr := executeCommand([]string{ - "__complete", - "component", "create", - "--org", config.Org, - "--stack-ref", testStackRef, - "--stack-commit-hash", "", - }) - is.NoErr(cmdErr) - - // Parse the first commit hash (before the tab character) - lines := bytes.Split([]byte(cmdOut), []byte("\n")) - if len(lines) > 0 && len(lines[0]) > 3 { - // Take first 3 characters as partial input - partial := string(lines[0][:3]) - - // Test completion with partial input - cmdOut2, cmdErr2 := executeCommand([]string{ - "__complete", - "component", "create", - "--org", config.Org, - "--stack-ref", testStackRef, - "--stack-commit-hash", partial, - }) - is.NoErr(cmdErr2) - is.True(len(cmdOut2) > 0) // Should have some output - is.True(!bytes.Contains([]byte(cmdOut2), []byte("_activeHelp"))) // Should not have error help - is.True(bytes.Contains([]byte(cmdOut2), []byte(partial))) // Should contain the partial string - } - }) - - t.Run("FailCompleteStackVersionCommitHashNoStackRef", func(t *testing.T) { - is := is.New(t) - // Test completion without stack-ref should provide helpful error - cmdOut, cmdErr := executeCommand([]string{ - "__complete", - "component", "create", - "--org", config.Org, - "--stack-commit-hash", "", - }) - // The command itself doesn't error, but completion should show active help - is.NoErr(cmdErr) - is.True(bytes.Contains([]byte(cmdOut), []byte("_activeHelp"))) // Should have error help - is.True(bytes.Contains([]byte(cmdOut), []byte("missing stack-ref"))) // Should mention missing stack-ref - }) - - t.Run("SuccessCompleteStackVersionCommitHashForUpdate", func(t *testing.T) { - is := is.New(t) - // For component update, if we provide stack-ref it should work - cmdOut, cmdErr := executeCommand([]string{ - "__complete", - "component", "update", - "--org", config.Org, - "--stack-ref", testStackRef, - "--stack-commit-hash", "", - }) - is.NoErr(cmdErr) - is.True(len(cmdOut) > 0) // Should have some output - is.True(!bytes.Contains([]byte(cmdOut), []byte("_activeHelp"))) // Should not have error help - is.True(bytes.Contains([]byte(cmdOut), []byte(":4"))) // Should have NoFileComp directive - }) - - // Stack version tag completion tests - t.Run("SuccessCompleteStackVersionTag", func(t *testing.T) { - is := is.New(t) - // Test completion for component create with stack-ref - cmdOut, cmdErr := executeCommand([]string{ - "__complete", - "component", "create", - "--org", config.Org, - "--stack-ref", testStackRef, - "--stack-tag", "", - }) - is.NoErr(cmdErr) - // The output should contain version tags - is.True(len(cmdOut) > 0) // Should have some output - is.True(!bytes.Contains([]byte(cmdOut), []byte("_activeHelp"))) // Should not have error help - is.True(bytes.Contains([]byte(cmdOut), []byte(":4"))) // Should have NoFileComp directive (4) - }) - - t.Run("SuccessCompleteStackVersionTagWithPartialInput", func(t *testing.T) { - is := is.New(t) - // First, get a valid version tag from the stack versions - cmdOut, cmdErr := executeCommand([]string{ - "__complete", - "component", "create", - "--org", config.Org, - "--stack-ref", testStackRef, - "--stack-tag", "", - }) - is.NoErr(cmdErr) - - // Parse the first version tag (before the tab character) - lines := bytes.Split([]byte(cmdOut), []byte("\n")) - if len(lines) > 0 && len(lines[0]) > 0 { - // Take first character as partial input - parts := bytes.Split(lines[0], []byte("\t")) - if len(parts) > 0 && len(parts[0]) > 0 { - partial := string(parts[0][:1]) - - // Test completion with partial input - cmdOut2, cmdErr2 := executeCommand([]string{ - "__complete", - "component", "create", - "--org", config.Org, - "--stack-ref", testStackRef, - "--stack-tag", partial, - }) - is.NoErr(cmdErr2) - is.True(len(cmdOut2) > 0) // Should have some output - is.True(!bytes.Contains([]byte(cmdOut2), []byte("_activeHelp"))) // Should not have error help - } - } - }) - - t.Run("FailCompleteStackVersionTagNoStackRef", func(t *testing.T) { - is := is.New(t) - // Test completion without stack-ref should provide helpful error - cmdOut, cmdErr := executeCommand([]string{ - "__complete", - "component", "create", - "--org", config.Org, - "--stack-tag", "", - }) - // The command itself doesn't error, but completion should show active help - is.NoErr(cmdErr) - is.True(bytes.Contains([]byte(cmdOut), []byte("_activeHelp"))) // Should have error help - is.True(bytes.Contains([]byte(cmdOut), []byte("missing stack-ref"))) // Should mention missing stack-ref - }) - - t.Run("SuccessCompleteStackVersionTagForUpdate", func(t *testing.T) { - is := is.New(t) - // For component update, if we provide stack-ref it should work - cmdOut, cmdErr := executeCommand([]string{ - "__complete", - "component", "update", - "--org", config.Org, - "--stack-ref", testStackRef, - "--stack-tag", "", - }) - is.NoErr(cmdErr) - is.True(len(cmdOut) > 0) // Should have some output - is.True(!bytes.Contains([]byte(cmdOut), []byte("_activeHelp"))) // Should not have error help - is.True(bytes.Contains([]byte(cmdOut), []byte(":4"))) // Should have NoFileComp directive - }) -} diff --git a/e2e/teams_test.go b/e2e/teams_test.go deleted file mode 100644 index d6f8345da..000000000 --- a/e2e/teams_test.go +++ /dev/null @@ -1,160 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "slices" - "testing" - - "github.com/sanity-io/litter" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -func TestTeams(t *testing.T) { - teamCan := randomCanonical("team") - t.Run("SuccessTeamCreate", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "team", "create", - "--name", teamCan, - "--role", "organization-admin", - }) - require.NoError(t, cmdErr, "cmd should succeed") - - defer t.Run("SuccessTeamDelete", func(t *testing.T) { - _, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "team", "delete", teamCan, - }) - require.NoError(t, cmdErr, "cmd delete should succeed") - }) - - var outTeam models.Team - err := json.Unmarshal([]byte(cmdOut), &outTeam) - assert.NoError(t, err, "unmarshal output should work") - assert.NotNil(t, outTeam, "team should not be empty") - assert.Equal(t, teamCan, ptr.Value(outTeam.Canonical)) - - t.Run("SuccessTeamList", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "team", "list", - }) - require.NoError(t, cmdErr, "cmd should succeed") - - var outTeams []*models.Team - err := json.Unmarshal([]byte(cmdOut), &outTeams) - assert.NoError(t, err, "unmarshal output should work") - index := slices.IndexFunc(outTeams, func(t *models.Team) bool { - return ptr.Value(t.Canonical) == teamCan - }) - assert.NotEqual(t, -1, index, "we should find our team index in the out array") - assert.Equal(t, teamCan, ptr.Value(outTeams[index].Canonical)) - }) - - t.Run("SuccessTeamUpdate", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "team", "update", - "--name", "newName", - "--team", teamCan, - "--role", "organization-admin", - }) - require.NoError(t, cmdErr, "cmd should succeed") - var outTeam models.Team - err := json.Unmarshal([]byte(cmdOut), &outTeam) - assert.NoError(t, err, "unmarshal output should work") - assert.NotNil(t, outTeam, "team should not be empty") - assert.Equal(t, teamCan, ptr.Value(outTeam.Canonical)) - assert.Equal(t, "newName", ptr.Value(outTeam.Name)) - }) - - t.Run("SuccessTeamGet", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "team", "get", teamCan, - }) - require.NoError(t, cmdErr, "cmd should succeed") - - var outTeam models.Team - err := json.Unmarshal([]byte(cmdOut), &outTeam) - assert.NoError(t, err, "unmarshal output should work") - assert.Equal(t, teamCan, ptr.Value(outTeam.Canonical)) - }) - - t.Run("SuccessTeamMemberAssign", func(t *testing.T) { - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "team", "member", "assign", "admin@cycloid.io", - "--team", teamCan, - }) - require.NoError(t, cmdErr, "cmd should succeed") - defer t.Run("SuccessTeamMemberUnAssign", func(t *testing.T) { - _, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "team", "member", "unassign", "admin@cycloid.io", - "--team", teamCan, - }) - require.NoError(t, cmdErr, "cmd should succeed") - }) - - var outMember []models.MemberTeam - litter.Dump(cmdOut) - err := json.Unmarshal([]byte(cmdOut), &outMember) - assert.NoError(t, err, "unmarshal output should work") - assert.NotNil(t, outMember, "we should have a member") - assert.Len(t, outMember, 1, "There should be one member in the team") - assert.Equal(t, "admin@cycloid.io", ptr.Value(outMember[0].Email).String()) - }) - }) - - t.Run("SuccessTeamCreateUpdateWithNameOnly", func(t *testing.T) { - displayName := "Upsert Team " + randomCanonical("team") - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "team", "create", - "--name", displayName, - "--role", "organization-admin", - }) - require.NoError(t, cmdErr, "first create should succeed") - - var first models.Team - require.NoError(t, json.Unmarshal([]byte(cmdOut), &first)) - canonical := ptr.Value(first.Canonical) - require.NotEmpty(t, canonical) - - defer func() { - _, err := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "team", "delete", canonical, - }) - require.NoError(t, err, "cleanup delete should succeed") - }() - - cmdOut2, cmdErr2 := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "team", "create", - "--update", - "--name", displayName, - "--role", "organization-admin", - }) - require.NoError(t, cmdErr2, "create --update with name only should find team by inferred canonical") - - var second models.Team - require.NoError(t, json.Unmarshal([]byte(cmdOut2), &second)) - assert.Equal(t, canonical, ptr.Value(second.Canonical), "upsert should target the same team") - }) -} diff --git a/e2e/terracost_test.go b/e2e/terracost_test.go deleted file mode 100644 index faf8601e4..000000000 --- a/e2e/terracost_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func TestTerracost(t *testing.T) { - t.Run("SuccessTerracostEstimate", func(t *testing.T) { - tmpDir := t.TempDir() - planPath := filepath.Join(tmpDir, "test-plan.json") - WriteFile(planPath, TestTerraformPlanSample) - - cmdOut, cmdErr := executeCommand([]string{ - "--output", "json", - "--org", config.Org, - "terracost", - "estimate", - "--plan-path", planPath, - }) - - require.Nil(t, cmdErr, "terracost estimate should not fail, out: %s", cmdOut) - - // Output should deserialize to a cost estimation result - var result models.CostEstimationResult - err := json.Unmarshal([]byte(cmdOut), &result) - assert.Nil(t, err, "output should deserialize to models.CostEstimationResult, out: %s", cmdOut) - }) -} diff --git a/e2e/uri_test.go b/e2e/uri_test.go deleted file mode 100644 index 3c6382b7a..000000000 --- a/e2e/uri_test.go +++ /dev/null @@ -1,260 +0,0 @@ -package e2e_test - -import ( - "encoding/json" - "fmt" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "go.yaml.in/yaml/v4" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -func TestGetCmd(t *testing.T) { - var baseURL = fmt.Sprintf("cy://org/%s", config.Org) - testCases := []struct { - name string - args []string - expect func(t *testing.T, actual string) - }{ - { - "getSSHKeyOk", - []string{"uri", "get", baseURL + "/cred/local-git?key=.raw.ssh_key"}, - func(t *testing.T, actual string) { - assert.Equal(t, strings.Join([]string{ - "-----BEGIN OPENSSH PRIVATE KEY-----", - "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW", - "QyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+AAAAJjCF9jzwhfY", - "8wAAAAtzc2gtZWQyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+A", - "AAAEC0ryBZ1uJQ2drmjsO+WpsC2E/5SWheJD/r8+Q4LghWxfw72aGSXkICIPQ0t5Byg9/V", - "25gciZCVOM5dwI6AeYL4AAAAE2N5Y2xvaWRAZXhhbXBsZS5jb20BAg==", - "-----END OPENSSH PRIVATE KEY-----", - }, "\n"), actual, "ssh key must match") - }, - }, - { - "getSSHKeyLPadOK", - []string{"uri", "get", baseURL + "/cred/local-git?key=.raw.ssh_key&indent=4"}, - func(t *testing.T, actual string) { - assert.Equal(t, strings.Join([]string{ - " -----BEGIN OPENSSH PRIVATE KEY-----", - " b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW", - " QyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+AAAAJjCF9jzwhfY", - " 8wAAAAtzc2gtZWQyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+A", - " AAAEC0ryBZ1uJQ2drmjsO+WpsC2E/5SWheJD/r8+Q4LghWxfw72aGSXkICIPQ0t5Byg9/V", - " 25gciZCVOM5dwI6AeYL4AAAAE2N5Y2xvaWRAZXhhbXBsZS5jb20BAg==", - " -----END OPENSSH PRIVATE KEY-----", - }, "\n"), actual, "ssh key must be indented") - }, - }, - { - "getSSHKeyNLPadOK", - []string{"uri", "get", baseURL + "/cred/local-git?key=.raw.ssh_key&nindent=4"}, - func(t *testing.T, actual string) { - assert.Equal(t, strings.Join([]string{ - "", - " -----BEGIN OPENSSH PRIVATE KEY-----", - " b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW", - " QyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+AAAAJjCF9jzwhfY", - " 8wAAAAtzc2gtZWQyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+A", - " AAAEC0ryBZ1uJQ2drmjsO+WpsC2E/5SWheJD/r8+Q4LghWxfw72aGSXkICIPQ0t5Byg9/V", - " 25gciZCVOM5dwI6AeYL4AAAAE2N5Y2xvaWRAZXhhbXBsZS5jb20BAg==", - " -----END OPENSSH PRIVATE KEY-----", - }, "\n"), actual, "ssh key must be indented after newline") - }, - }, - { - "getJSONListOK", - []string{"uri", "get", baseURL + "/projects"}, - func(t *testing.T, actual string) { - var projects []*models.Project - err := json.Unmarshal([]byte(actual), &projects) - assert.NoError(t, err, "failed to parse JSON response:", actual) - }, - }, - { - "testYAMLOutput", - []string{"uri", "get", baseURL + "/projects?yaml"}, - func(t *testing.T, actual string) { - var projects []*models.Project - err := yaml.Unmarshal([]byte(actual), &projects) - assert.NoError(t, err, "failed to parse YAML response:", actual) - }, - }, - } - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - cmdOut, cmdErr := executeCommand(testCase.args) - if cmdErr != nil { - t.Errorf("failed to get from urls: %v: %s", testCase.args, cmdErr) - } - - testCase.expect(t, cmdOut) - }) - } -} - -func TestE2e(t *testing.T) { - var baseURL = fmt.Sprintf("cy://org/%s", config.Org) - t.Run("TestInterpolateStdinOk", func(t *testing.T) { - stdin := strings.Join([]string{ - "ssh: | " + baseURL + "/cred/local-git?key=.raw.ssh_key&nindent=2", - "json: '" + baseURL + "/cred/local-git?key=.raw&json'", - }, "\n") - args := []string{"uri", "interpolate"} - cmdOut, cmdErr, err := executeCommandStdin(stdin, args) - assert.NoError(t, err, "cmd should not fail") - assert.Empty(t, cmdErr, "stderr should be empty") - assert.Equal(t, "ssh: | \n -----BEGIN OPENSSH PRIVATE KEY-----\n b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\n QyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+AAAAJjCF9jzwhfY\n 8wAAAAtzc2gtZWQyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+A\n AAAEC0ryBZ1uJQ2drmjsO+WpsC2E/5SWheJD/r8+Q4LghWxfw72aGSXkICIPQ0t5Byg9/V\n 25gciZCVOM5dwI6AeYL4AAAAE2N5Y2xvaWRAZXhhbXBsZS5jb20BAg==\n -----END OPENSSH PRIVATE KEY-----\njson: '{\n \"ssh_key\": \"-----BEGIN OPENSSH PRIVATE KEY-----\\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\\nQyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+AAAAJjCF9jzwhfY\\n8wAAAAtzc2gtZWQyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+A\\nAAAEC0ryBZ1uJQ2drmjsO+WpsC2E/5SWheJD/r8+Q4LghWxfw72aGSXkICIPQ0t5Byg9/V\\n25gciZCVOM5dwI6AeYL4AAAAE2N5Y2xvaWRAZXhhbXBsZS5jb20BAg==\\n-----END OPENSSH PRIVATE KEY-----\"\n}'\n", cmdOut, "the output should match expectation") - }) -} - -func TestInterpolateCmd(t *testing.T) { - sampleContent := fmt.Sprintf("ssh_key: cy://organizations/%s/credentials/%s?key=.canonical", config.Org, config.ConfigRepo.CredentialCanonical) - sampleExpect := fmt.Sprintf("ssh_key: %s\n", config.ConfigRepo.CredentialCanonical) - - t.Run("InPlaceInterpolationOk", func(t *testing.T) { - tempDir := t.TempDir() - sampleFilePath := tempDir + "/sample.yml" - err := os.WriteFile(sampleFilePath, []byte(sampleContent), 0666) - if err != nil { - t.Logf("test setup failed, cannot write sample file at path %q: %v", tempDir, err) - t.FailNow() - } - - args := []string{ - "uri", "interpolate", "--in-place", sampleFilePath, - } - cmdOut, cmdErr := executeCommand(args) - assert.NoError(t, cmdErr, "the cmd should not fail") - assert.Empty(t, cmdOut, "valid in-place interpolation returns nothing") - fileContent, err := os.ReadFile(sampleFilePath) - assert.NoError(t, err, "we should be able to read the file after interpolation") - assert.Equal(t, sampleExpect, string(fileContent)) - }) - - t.Run("RecurseInterpolationOk", func(t *testing.T) { - // setup - tempDir := t.TempDir() - nestedDir := tempDir + "/nested" - ignoreDir := tempDir + "/ignore-me" - sampleFilePath := tempDir + "/sample.yml" - defaultDotGitDir := tempDir + "/.git" - nestedSampleFilePath := nestedDir + "/nested.yml" - ignoreSampleFilePath := ignoreDir + "/ignored.yml" - dotGitFile := defaultDotGitDir + "/somegitfile" - - for _, dir := range []string{tempDir, nestedDir, ignoreDir, defaultDotGitDir} { - err := os.MkdirAll(dir, 0777) - if err != nil { - t.Logf("test setup failed, create nested dir %q: %v", dir, err) - t.FailNow() - } - } - - for _, file := range []string{sampleFilePath, nestedSampleFilePath, ignoreSampleFilePath, dotGitFile} { - err := os.WriteFile(file, []byte(sampleContent), 0666) - if err != nil { - t.Logf("test setup failed, cannot write sample file at path %q: %v", file, err) - t.FailNow() - } - } - // end setup - - args := []string{ - "uri", "interpolate", "--in-place", "--recurse", tempDir, "--ignore", "ignore-me*", "--ignore", ".git", - } - cmdOut, cmdErr := executeCommand(args) - assert.NoError(t, cmdErr, "the cmd", args, "should not fail") - assert.Empty(t, cmdOut, "valid in-place interpolation returns nothing") - - // check top level - fileContent, err := os.ReadFile(sampleFilePath) - assert.NoError(t, err, "we should be able to read the file after interpolation") - assert.Equal(t, sampleExpect, string(fileContent), "this file must be interpolated") - - // check nested - fileContent, err = os.ReadFile(nestedSampleFilePath) - assert.NoError(t, err, "we should be able to read the nested file after interpolation") - assert.Equal(t, sampleExpect, string(fileContent), "this file must be interpolated") - - // check ignore - fileContent, err = os.ReadFile(ignoreSampleFilePath) - assert.NoError(t, err, "we should be able to read the ignored file after interpolation") - assert.Equal(t, sampleContent, string(fileContent), "this file must not be interpolated") - - // check default ignore - t.Run("defaultDotGitIgnoreOk", func(t *testing.T) { - fileContent, err = os.ReadFile(dotGitFile) - assert.NoError(t, err, "we should be able to read the ignored file after interpolation") - assert.Equal(t, sampleContent, string(fileContent), ".git file must not be interpolated") - }) - - t.Run("StdoutRecuseInterpolationOk", func(t *testing.T) { - args := []string{ - "uri", "interpolate", "--recurse", tempDir, - } - cmdOut, cmdErr := executeCommand(args) - assert.NoError(t, cmdErr, "the cmd should not fail") - assert.Equal(t, "ssh_key: local-git\nssh_key: local-git\nssh_key: local-git\n", cmdOut, "we should get both file content") - }) - }) - - t.Run("StdoutInterpolationOk", func(t *testing.T) { - args := []string{ - "uri", "interpolate", - } - cmdOut, cmdErr, err := executeCommandStdin(sampleContent, args) - assert.NoError(t, err, "cmd should not err") - assert.Empty(t, cmdErr, "cmd should not output on stderr if no err") - assert.Equal(t, sampleExpect, cmdOut, "output should match interpolation") - }) - - t.Run("StdinNoExtraNewlineOrSpaces", func(t *testing.T) { - args := []string{ - "uri", "interpolate", - } - cmdOut, cmdErr, err := executeCommandStdin(" \n \n", args) - assert.NoError(t, err, "cmd should not err") - assert.Empty(t, cmdErr, "cmd should not output on stderr if no err") - assert.Equal(t, "\n", cmdOut, "there should be no more than one newline and no spaces") - }) - - t.Run("FileNoExtraNewlineOrSpaces", func(t *testing.T) { - tempDir := t.TempDir() - tempFile := filepath.Join(tempDir, "testfile") - err := os.WriteFile(tempFile, []byte(" \n \n"), 0640) - if err != nil { - t.Logf("failed to setup test, failed to write to file %q: %v", tempFile, err) - t.FailNow() - } - - args := []string{"uri", "interpolate", tempFile} - cmdOut, cmdErr := executeCommand(args) - assert.NoError(t, cmdErr, "cmdErr should be nil") - assert.Equal(t, "\n", cmdOut, "output should be stripped of extra space and end with a newline.") - }) - - t.Run("FileInPlaceNoExtraNewlineOrSpaces", func(t *testing.T) { - tempDir := t.TempDir() - tempFile := filepath.Join(tempDir, "testfile") - err := os.WriteFile(tempFile, []byte(" \n \n"), 0640) - if err != nil { - t.Logf("failed to setup test, failed to write to file %q: %v", tempFile, err) - t.FailNow() - } - - args := []string{"uri", "interpolate", "--in-place", tempFile} - cmdOut, cmdErr := executeCommand(args) - assert.NoError(t, cmdErr, "cmdErr should be nil") - assert.Equal(t, "", cmdOut, "When using --in-place, output should be empty") - - fileContent, err := os.ReadFile(tempFile) - assert.NoError(t, err, "failed to read test file %q: %w", tempFile, err) - assert.Equal(t, "\n", string(fileContent), "the file should not have trailling space and end with a newline") - }) -} diff --git a/flake.lock b/flake.lock deleted file mode 100644 index 24c7a383e..000000000 --- a/flake.lock +++ /dev/null @@ -1,61 +0,0 @@ -{ - "nodes": { - "flake-utils": { - "inputs": { - "systems": "systems" - }, - "locked": { - "lastModified": 1731533236, - "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", - "owner": "numtide", - "repo": "flake-utils", - "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", - "type": "github" - }, - "original": { - "owner": "numtide", - "repo": "flake-utils", - "type": "github" - } - }, - "nixpkgs": { - "locked": { - "lastModified": 1767313136, - "narHash": "sha256-16KkgfdYqjaeRGBaYsNrhPRRENs0qzkQVUooNHtoy2w=", - "owner": "NixOs", - "repo": "nixpkgs", - "rev": "ac62194c3917d5f474c1a844b6fd6da2db95077d", - "type": "github" - }, - "original": { - "owner": "NixOs", - "ref": "nixos-25.05", - "repo": "nixpkgs", - "type": "github" - } - }, - "root": { - "inputs": { - "flake-utils": "flake-utils", - "nixpkgs": "nixpkgs" - } - }, - "systems": { - "locked": { - "lastModified": 1681028828, - "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", - "owner": "nix-systems", - "repo": "default", - "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", - "type": "github" - }, - "original": { - "owner": "nix-systems", - "repo": "default", - "type": "github" - } - } - }, - "root": "root", - "version": 7 -} diff --git a/flake.nix b/flake.nix deleted file mode 100644 index e94381883..000000000 --- a/flake.nix +++ /dev/null @@ -1,37 +0,0 @@ -{ - description = "A basic dev shell for nix/nixos users"; - - inputs = { - nixpkgs = { url = "github:NixOs/nixpkgs/nixos-25.05"; }; - flake-utils = { url = "github:numtide/flake-utils"; }; - }; - - outputs = inputs@{ self, nixpkgs, flake-utils }: - flake-utils.lib.eachDefaultSystem (system: - let - pkgs = import nixpkgs { inherit system; }; - lib = pkgs.lib; - swaggerPython = (pkgs.python312.withPackages (p: with p; [ - pyyaml - ])); - in - { - devShells.default = pkgs.mkShell { - buildInputs = [ swaggerPython ] - ++ (with pkgs; [ - # You packages here - gnumake - libgcc - - go_1_25 - go-swagger - # gci - # golangci-lint - # golangci-lint-langserver - awscli - docker - pre-commit - ]); - }; - }); -} diff --git a/go.mod b/go.mod index 87aa30695..9dfa22b95 100644 --- a/go.mod +++ b/go.mod @@ -1,92 +1,3 @@ module github.com/cycloidio/cycloid-cli go 1.25 - -require ( - dario.cat/mergo v1.0.2 - github.com/adrg/xdg v0.5.3 - github.com/charmbracelet/lipgloss v1.1.0 - github.com/go-openapi/errors v0.22.1 - github.com/go-openapi/runtime v0.28.0 - github.com/go-openapi/strfmt v0.23.0 - github.com/go-openapi/swag v0.23.1 - github.com/go-openapi/validate v0.24.0 - github.com/itchyny/gojq v0.12.17 - github.com/matryer/is v1.4.1 - github.com/pkg/errors v0.9.1 - github.com/sanity-io/litter v1.5.8 - github.com/spf13/cobra v1.10.1 - github.com/spf13/pflag v1.0.9 - github.com/spf13/viper v1.20.1 - github.com/stretchr/testify v1.10.0 - go.yaml.in/yaml/v4 v4.0.0-rc.2 - golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 - golang.org/x/term v0.33.0 - gopkg.in/yaml.v3 v3.0.1 -) - -require ( - github.com/Masterminds/goutils v1.1.1 // indirect - github.com/Masterminds/semver/v3 v3.2.1 // indirect - github.com/Masterminds/sprig/v3 v3.2.3 // indirect - github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect - github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect - github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect - github.com/charmbracelet/x/ansi v0.8.0 // indirect - github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect - github.com/charmbracelet/x/term v0.2.1 // indirect - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/fsnotify/fsnotify v1.9.0 // indirect - github.com/go-openapi/analysis v0.23.0 // indirect - github.com/go-openapi/inflect v0.21.0 // indirect - github.com/go-openapi/jsonpointer v0.21.1 // indirect - github.com/go-openapi/jsonreference v0.21.0 // indirect - github.com/go-openapi/loads v0.22.0 // indirect - github.com/go-openapi/spec v0.21.0 // indirect - github.com/go-swagger/go-swagger v0.31.0 // indirect - github.com/go-viper/mapstructure/v2 v2.2.1 // indirect - github.com/google/go-cmp v0.7.0 // indirect - github.com/google/uuid v1.6.0 // indirect - github.com/gorilla/handlers v1.5.2 // indirect - github.com/huandu/xstrings v1.4.0 // indirect - github.com/imdario/mergo v0.3.16 // indirect - github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/itchyny/timefmt-go v0.1.6 // indirect - github.com/jessevdk/go-flags v1.5.0 // indirect - github.com/josharian/intern v1.0.0 // indirect - github.com/kr/pretty v0.3.1 // indirect - github.com/kr/text v0.2.0 // indirect - github.com/lucasb-eyer/go-colorful v1.2.0 // indirect - github.com/mailru/easyjson v0.9.0 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect - github.com/mattn/go-runewidth v0.0.16 // indirect - github.com/mitchellh/copystructure v1.2.0 // indirect - github.com/mitchellh/mapstructure v1.5.0 // indirect - github.com/mitchellh/reflectwalk v1.0.2 // indirect - github.com/muesli/termenv v0.16.0 // indirect - github.com/oklog/ulid v1.3.1 // indirect - github.com/pelletier/go-toml/v2 v2.2.4 // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/rivo/uniseg v0.4.7 // indirect - github.com/rogpeppe/go-internal v1.13.1 // indirect - github.com/sagikazarmark/locafero v0.9.0 // indirect - github.com/shopspring/decimal v1.3.1 // indirect - github.com/sourcegraph/conc v0.3.0 // indirect - github.com/spf13/afero v1.14.0 // indirect - github.com/spf13/cast v1.8.0 // indirect - github.com/subosito/gotenv v1.6.0 // indirect - github.com/toqueteos/webbrowser v1.2.0 // indirect - github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect - go.mongodb.org/mongo-driver v1.17.3 // indirect - go.uber.org/multierr v1.11.0 // indirect - golang.org/x/crypto v0.32.0 // indirect - golang.org/x/mod v0.18.0 // indirect - golang.org/x/sync v0.14.0 // indirect - golang.org/x/sys v0.34.0 // indirect - golang.org/x/text v0.25.0 // indirect - golang.org/x/tools v0.22.0 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect -) - -tool github.com/go-swagger/go-swagger/cmd/swagger diff --git a/go.sum b/go.sum deleted file mode 100644 index 5751606f5..000000000 --- a/go.sum +++ /dev/null @@ -1,226 +0,0 @@ -dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= -dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= -github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= -github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= -github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= -github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0= -github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= -github.com/Masterminds/sprig/v3 v3.2.3 h1:eL2fZNezLomi0uOLqjQoN6BfsDD+fyLtgbJMAj9n6YA= -github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBaRMhvYXJNkGuM= -github.com/adrg/xdg v0.5.3 h1:xRnxJXne7+oWDatRhR1JLnvuccuIeCoBu2rtuLqQB78= -github.com/adrg/xdg v0.5.3/go.mod h1:nlTsY+NNiCBGCK2tpm09vRqfVzrc2fLmXGpBLF0zlTQ= -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= -github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= -github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= -github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= -github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= -github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= -github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= -github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= -github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q= -github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8= -github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= -github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a h1:G99klV19u0QnhiizODirwVksQB91TJKV/UaTnACcG30= -github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= -github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= -github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= -github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/davecgh/go-spew v0.0.0-20161028175848-04cdfd42973b/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= -github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= -github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= -github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= -github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= -github.com/go-openapi/analysis v0.23.0 h1:aGday7OWupfMs+LbmLZG4k0MYXIANxcuBTYUC03zFCU= -github.com/go-openapi/analysis v0.23.0/go.mod h1:9mz9ZWaSlV8TvjQHLl2mUW2PbZtemkE8yA5v22ohupo= -github.com/go-openapi/errors v0.22.1 h1:kslMRRnK7NCb/CvR1q1VWuEQCEIsBGn5GgKD9e+HYhU= -github.com/go-openapi/errors v0.22.1/go.mod h1:+n/5UdIqdVnLIJ6Q9Se8HNGUXYaY6CN8ImWzfi/Gzp0= -github.com/go-openapi/inflect v0.21.0 h1:FoBjBTQEcbg2cJUWX6uwL9OyIW8eqc9k4KhN4lfbeYk= -github.com/go-openapi/inflect v0.21.0/go.mod h1:INezMuUu7SJQc2AyR3WO0DqqYUJSj8Kb4hBd7WtjlAw= -github.com/go-openapi/jsonpointer v0.21.1 h1:whnzv/pNXtK2FbX/W9yJfRmE2gsmkfahjMKB0fZvcic= -github.com/go-openapi/jsonpointer v0.21.1/go.mod h1:50I1STOfbY1ycR8jGz8DaMeLCdXiI6aDteEdRNNzpdk= -github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ= -github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4= -github.com/go-openapi/loads v0.22.0 h1:ECPGd4jX1U6NApCGG1We+uEozOAvXvJSF4nnwHZ8Aco= -github.com/go-openapi/loads v0.22.0/go.mod h1:yLsaTCS92mnSAZX5WWoxszLj0u+Ojl+Zs5Stn1oF+rs= -github.com/go-openapi/runtime v0.28.0 h1:gpPPmWSNGo214l6n8hzdXYhPuJcGtziTOgUpvsFWGIQ= -github.com/go-openapi/runtime v0.28.0/go.mod h1:QN7OzcS+XuYmkQLw05akXk0jRH/eZ3kb18+1KwW9gyc= -github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY= -github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk= -github.com/go-openapi/strfmt v0.23.0 h1:nlUS6BCqcnAk0pyhi9Y+kdDVZdZMHfEKQiS4HaMgO/c= -github.com/go-openapi/strfmt v0.23.0/go.mod h1:NrtIpfKtWIygRkKVsxh7XQMDQW5HKQl6S5ik2elW+K4= -github.com/go-openapi/swag v0.23.1 h1:lpsStH0n2ittzTnbaSloVZLuB5+fvSY/+hnagBjSNZU= -github.com/go-openapi/swag v0.23.1/go.mod h1:STZs8TbRvEQQKUA+JZNAm3EWlgaOBGpyFDqQnDHMef0= -github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58= -github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ= -github.com/go-swagger/go-swagger v0.31.0 h1:H8eOYQnY2u7vNKWDNykv2xJP3pBhRG/R+SOCAmKrLlc= -github.com/go-swagger/go-swagger v0.31.0/go.mod h1:WSigRRWEig8zV6t6Sm8Y+EmUjlzA/HoaZJ5edupq7po= -github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss= -github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= -github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= -github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE= -github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w= -github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= -github.com/huandu/xstrings v1.4.0 h1:D17IlohoQq4UcpqD7fDk80P7l+lwAmlFaBHgOipl2FU= -github.com/huandu/xstrings v1.4.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= -github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= -github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= -github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= -github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= -github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/itchyny/gojq v0.12.17 h1:8av8eGduDb5+rvEdaOO+zQUjA04MS0m3Ps8HiD+fceg= -github.com/itchyny/gojq v0.12.17/go.mod h1:WBrEMkgAfAGO1LUcGOckBl5O726KPp+OlkKug0I/FEY= -github.com/itchyny/timefmt-go v0.1.6 h1:ia3s54iciXDdzWzwaVKXZPbiXzxxnv1SPGFfM/myJ5Q= -github.com/itchyny/timefmt-go v0.1.6/go.mod h1:RRDZYC5s9ErkjQvTvvU7keJjxUYzIISJGxm9/mAERQg= -github.com/jessevdk/go-flags v1.5.0 h1:1jKYvbxEjfUl0fmqTCOfonvskHHXMjBySTLW4y9LFvc= -github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= -github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= -github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4= -github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= -github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ= -github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= -github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= -github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= -github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= -github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= -github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= -github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= -github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= -github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= -github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= -github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= -github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= -github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= -github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= -github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= -github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= -github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sagikazarmark/locafero v0.9.0 h1:GbgQGNtTrEmddYDSAH9QLRyfAHY12md+8YFTqyMTC9k= -github.com/sagikazarmark/locafero v0.9.0/go.mod h1:UBUyz37V+EdMS3hDF3QWIiVr/2dPrx49OMO0Bn0hJqk= -github.com/sanity-io/litter v1.5.8 h1:uM/2lKrWdGbRXDrIq08Lh9XtVYoeGtcQxk9rtQ7+rYg= -github.com/sanity-io/litter v1.5.8/go.mod h1:9gzJgR2i4ZpjZHsKvUXIRQVk7P+yM3e+jAF7bU2UI5U= -github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= -github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= -github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= -github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA= -github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo= -github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cast v1.8.0 h1:gEN9K4b8Xws4EX0+a0reLmhq8moKn7ntRlQYgjPeCDk= -github.com/spf13/cast v1.8.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= -github.com/spf13/cobra v1.10.1 h1:lJeBwCfmrnXthfAupyUTzJ/J4Nc1RsHC/mSRU2dll/s= -github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0= -github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= -github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= -github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v0.0.0-20161117074351-18a02ba4a312/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= -github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= -github.com/toqueteos/webbrowser v1.2.0 h1:tVP/gpK69Fx+qMJKsLE7TD8LuGWPnEV71wBN9rrstGQ= -github.com/toqueteos/webbrowser v1.2.0/go.mod h1:XWoZq4cyp9WeUeak7w7LXRUQf1F1ATJMir8RTqb4ayM= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -go.mongodb.org/mongo-driver v1.17.3 h1:TQyXhnsWfWtgAhMtOgtYHMTkZIfBTpMTsMnd9ZBeHxQ= -go.mongodb.org/mongo-driver v1.17.3/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= -go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= -go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s= -go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= -golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= -golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= -golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 h1:LfspQV/FYTatPTr/3HzIcmiUFH7PGP+OQ6mgDYo3yuQ= -golang.org/x/exp v0.0.0-20240222234643-814bf88cf225/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0= -golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ= -golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= -golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= -golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg= -golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4= -golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.22.0 h1:gqSGLZqv+AI9lIQzniJ0nZDRG5GBPsSi+DRNHWNz6yA= -golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/buildwatch/events.go b/internal/buildwatch/events.go deleted file mode 100644 index cb5c51080..000000000 --- a/internal/buildwatch/events.go +++ /dev/null @@ -1,46 +0,0 @@ -// JSON shapes for Concourse-style build event payloads (SSE data lines). -package buildwatch - -import "encoding/json" - -type eventEnvelope struct { - Event string `json:"event"` - Version string `json:"version"` - EventID string `json:"event_id"` - Data json.RawMessage `json:"data"` -} - -type eventOrigin struct { - ID string `json:"id"` - Source string `json:"source"` -} - -type eventDataStatus struct { - Status string `json:"status"` - Time int64 `json:"time"` -} - -type eventDataLog struct { - Time int64 `json:"time"` - Origin eventOrigin `json:"origin"` - Payload string `json:"payload"` -} - -type eventDataTask struct { - Time int64 `json:"time"` - Origin eventOrigin `json:"origin"` - ExitStatus int `json:"exit_status"` -} - -type eventDataFinish struct { - Time int64 `json:"time"` - Origin eventOrigin `json:"origin"` - Succeeded *bool `json:"succeeded"` - Name string `json:"name"` -} - -type eventDataFinishGet struct { - Time int64 `json:"time"` - Origin eventOrigin `json:"origin"` - ExitStatus int `json:"exit_status"` -} diff --git a/internal/buildwatch/format.go b/internal/buildwatch/format.go deleted file mode 100644 index b75baac53..000000000 --- a/internal/buildwatch/format.go +++ /dev/null @@ -1,235 +0,0 @@ -// Human-readable formatting for pipeline build watch SSE events (cy pipeline build trigger --watch). -// Rollback: docs/pipeline-build-watch-output.md (quick disable in build_trigger.go or remove this package). -package buildwatch - -import ( - "encoding/json" - "fmt" - "io" - "regexp" - "strings" -) - -type lineFormat int - -const ( - lineFormatHuman lineFormat = iota - lineFormatRaw -) - -type consumeOpts struct { - format lineFormat - verbose bool - theme StreamTheme - stripLogANSI bool -} - -var ansiEscapeSeq = regexp.MustCompile(`\x1b\[[0-9;]*m`) - -func stripANSISequences(s string) string { - return ansiEscapeSeq.ReplaceAllString(s, "") -} - -func shortOriginID(id string) string { - if i := strings.Index(id, "/"); i >= 0 { - return id[:i] - } - return id -} - -func writeString(w io.Writer, s string) error { - if sw, ok := w.(io.StringWriter); ok { - _, err := sw.WriteString(s) - return err - } - _, err := w.Write([]byte(s)) - return err -} - -func formatAndWriteBuildEvent(w io.Writer, payload string, opts consumeOpts) error { - if opts.format == lineFormatRaw { - if err := writeString(w, payload); err != nil { - return err - } - if !strings.HasSuffix(payload, "\n") { - return writeString(w, "\n") - } - return nil - } - - out, ok := formatHumanBuildEvent(payload, opts) - if !ok { - return nil - } - return writeString(w, out) -} - -func formatHumanBuildEvent(payload string, opts consumeOpts) (string, bool) { - var env eventEnvelope - if err := json.Unmarshal([]byte(payload), &env); err != nil { - return payload + "\n", true - } - - t := opts.theme - - switch env.Event { - case "status": - var d eventDataStatus - if err := json.Unmarshal(env.Data, &d); err != nil { - return "", false - } - msg := fmt.Sprintf("status: %s", d.Status) - return paintBuildLine(msg, t), true - - case "log": - var d eventDataLog - if err := json.Unmarshal(env.Data, &d); err != nil { - return "", false - } - text := d.Payload - if opts.stripLogANSI { - text = stripANSISequences(text) - } - out := paintLogLines(d.Origin.Source, text, t) - if out == "" { - return "", false - } - return out, true - - case "initialize-task": - if !opts.verbose { - return "", false - } - var d eventDataTask - if err := json.Unmarshal(env.Data, &d); err != nil { - return "", false - } - id := shortOriginID(d.Origin.ID) - return paintTaskLine(fmt.Sprintf("%s: initialize", id), t), true - - case "start-task": - var d eventDataTask - if err := json.Unmarshal(env.Data, &d); err != nil { - return "", false - } - id := shortOriginID(d.Origin.ID) - msg := fmt.Sprintf("%s: started", id) - if opts.verbose { - msg = fmt.Sprintf("%s: start-task", id) - } - return paintTaskLine(msg, t), true - - case "finish-task": - var d eventDataTask - if err := json.Unmarshal(env.Data, &d); err != nil { - return "", false - } - id := shortOriginID(d.Origin.ID) - msg := fmt.Sprintf("%s: finished (exit %d)", id, d.ExitStatus) - return paintTaskLine(msg, t), true - - case "initialize-check", "start", "image-check", "image-get", "initialize-get", "start-get", "selected-worker": - if !opts.verbose { - return "", false - } - return paintResourceLine(env.Event, compactJSONData(env.Data), t), true - - case "finish": - var d eventDataFinish - if err := json.Unmarshal(env.Data, &d); err != nil { - return "", false - } - if !opts.verbose { - if d.Succeeded == nil || *d.Succeeded { - return "", false - } - } - detail := shortOriginID(d.Origin.ID) - if d.Name != "" { - detail = fmt.Sprintf("%s check %q", detail, d.Name) - } - if d.Succeeded != nil { - detail = fmt.Sprintf("%s succeeded=%v", detail, *d.Succeeded) - } - return paintResourceLine(env.Event, detail, t), true - - case "finish-get": - var d eventDataFinishGet - if err := json.Unmarshal(env.Data, &d); err != nil { - return "", false - } - if !opts.verbose && d.ExitStatus == 0 { - return "", false - } - id := shortOriginID(d.Origin.ID) - return paintResourceLine(env.Event, fmt.Sprintf("%s exit=%d", id, d.ExitStatus), t), true - - default: - if !opts.verbose { - return "", false - } - return paintResourceLine(env.Event, compactJSONData(env.Data), t), true - } -} - -func compactJSONData(raw json.RawMessage) string { - s := strings.TrimSpace(string(raw)) - if len(s) > 120 { - return s[:117] + "..." - } - return s -} - -func paintBuildLine(msg string, t StreamTheme) string { - if t.Reset == "" { - return fmt.Sprintf("[build] %s\n", msg) - } - return fmt.Sprintf("%s[build]%s %s%s%s\n", t.BuildLabel, t.Reset, t.BuildText, msg, t.Reset) -} - -func paintTaskLine(msg string, t StreamTheme) string { - if t.Reset == "" { - return fmt.Sprintf("[task] %s\n", msg) - } - return fmt.Sprintf("%s[task]%s %s%s%s\n", t.TaskLabel, t.Reset, t.TaskText, msg, t.Reset) -} - -func paintResourceLine(event, detail string, t StreamTheme) string { - if t.Reset == "" { - return fmt.Sprintf("[res] %s %s\n", event, detail) - } - line := fmt.Sprintf("%s[res]%s %s%s:%s %s%s\n", - t.ResourceLabel, t.Reset, t.Dim, event, t.Reset, detail, t.Reset) - return line -} - -func paintLogLines(source, payload string, t StreamTheme) string { - label := "stdout" - prefixColor := t.LogStdoutPrefix - if source == "stderr" { - label = "stderr" - prefixColor = t.LogStderrPrefix - } - - if strings.TrimSpace(payload) == "" { - return "" - } - - lines := strings.Split(strings.TrimRight(payload, "\r\n"), "\n") - var b strings.Builder - for _, line := range lines { - if strings.TrimSpace(line) == "" { - b.WriteByte('\n') - continue - } - if t.Reset == "" { - fmt.Fprintf(&b, "[%s] %s\n", label, line) - continue - } - fmt.Fprintf(&b, "%s[%s]%s %s\n", prefixColor, label, t.Reset, line) - } - if b.Len() == 0 { - return "" - } - return b.String() -} diff --git a/internal/buildwatch/stream.go b/internal/buildwatch/stream.go deleted file mode 100644 index de3b99dae..000000000 --- a/internal/buildwatch/stream.go +++ /dev/null @@ -1,113 +0,0 @@ -package buildwatch - -import ( - "context" - "io" - "strings" - "time" -) - -const defaultIdleTimeout = 3 * time.Second - -// StreamLogs fetches the event log for a specific build. -// -// Dump mode (options.Watch == false): opens the SSE stream once, formats events, -// and returns when the stream closes (completed build) or after a period of -// inactivity (in-progress build — prints whatever has been logged so far). -// -// Watch mode (options.Watch == true): delegates to Watch with ReadOnly: true — -// reconnects on disconnect, polls build status, and exits cleanly when the build -// finishes or on Ctrl+C (exit 130, no abort). -func StreamLogs( - ctx context.Context, - m Client, - org, project, env, component, pipeline, job, buildID string, - options Options, -) error { - if options.Watch { - return Watch(ctx, m, org, project, env, component, pipeline, job, buildID, Options{ - LogWriter: options.LogWriter, - PollInterval: options.PollInterval, - ReconnectDelay: options.ReconnectDelay, - Output: options.Output, - Verbose: options.Verbose, - Theme: options.Theme, - StripLogANSI: options.StripLogANSI, - StatusWriter: options.StatusWriter, - DisableInterruptHandler: options.DisableInterruptHandler, - ReadOnly: true, - }) - } - - // Dump mode: open SSE stream once and consume events until the stream closes - // or idles out (for in-progress builds). - stream, _, err := m.OpenBuildEventsStream(ctx, org, project, env, component, pipeline, buildID, "") - if err != nil { - return err - } - wrapped := newIdleCloseRC(stream, defaultIdleTimeout) - defer wrapped.Close() - - writer := options.LogWriter - if writer == nil { - writer = io.Discard - } - - lineFmt := lineFormatHuman - if options.Output == OutputRaw { - lineFmt = lineFormatRaw - } - evtOpts := consumeOpts{ - format: lineFmt, - verbose: options.Verbose, - theme: options.Theme, - stripLogANSI: options.StripLogANSI, - } - - _, err = consumeBuildEvents(ctx, wrapped, writer, "", evtOpts) - // Ignore errors caused by the idle-timeout close (closed reader / net error). - // Those are expected and mean we've caught up with the current build state. - if err != nil && !isClosedErr(err) { - return err - } - return nil -} - -// idleCloseRC wraps an io.ReadCloser and closes it automatically after a period -// of inactivity. Each successful Read call resets the idle timer. -// This is used in dump mode to stop reading from in-progress SSE streams. -type idleCloseRC struct { - rc io.ReadCloser - timeout time.Duration - timer *time.Timer -} - -func newIdleCloseRC(rc io.ReadCloser, timeout time.Duration) *idleCloseRC { - icr := &idleCloseRC{rc: rc, timeout: timeout} - icr.timer = time.AfterFunc(timeout, func() { _ = rc.Close() }) - return icr -} - -func (r *idleCloseRC) Read(p []byte) (int, error) { - n, err := r.rc.Read(p) - if n > 0 { - r.timer.Reset(r.timeout) - } - return n, err -} - -func (r *idleCloseRC) Close() error { - r.timer.Stop() - return r.rc.Close() -} - -// isClosedErr reports whether the error is a result of a closed connection, -// which is the expected outcome when idleCloseRC fires its timer. -func isClosedErr(err error) bool { - if err == nil { - return false - } - s := err.Error() - // Match common "use of closed network connection" and pipe errors. - return strings.Contains(s, "closed") || strings.Contains(s, "EOF") || strings.Contains(s, "broken pipe") -} diff --git a/internal/buildwatch/stream_test.go b/internal/buildwatch/stream_test.go deleted file mode 100644 index c61ed6d27..000000000 --- a/internal/buildwatch/stream_test.go +++ /dev/null @@ -1,92 +0,0 @@ -package buildwatch - -import ( - "bytes" - "context" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// TestStreamLogsDumpCompletedBuild verifies that StreamLogs (dump mode) consumes -// all events from a completed build and returns nil when the stream closes naturally. -func TestStreamLogsDumpCompletedBuild(t *testing.T) { - body := "id:1\ndata:{\"event\":\"status\",\"data\":{\"status\":\"started\",\"time\":1}}\n\n" + - "id:2\ndata:{\"event\":\"status\",\"data\":{\"status\":\"succeeded\",\"time\":2}}\n\n" - - client := &fakeClient{ - statuses: []string{"succeeded"}, - streamBodies: []string{body}, - } - - var out bytes.Buffer - err := StreamLogs( - context.Background(), - client, - "org", "proj", "env", "comp", "pipeline", "job", "42", - Options{ - LogWriter: &out, - DisableInterruptHandler: true, - }, - ) - require.NoError(t, err) - // The stream had two events; human output should mention build status lines. - assert.Contains(t, out.String(), "[build]") -} - -// TestStreamLogsDumpIdleTimeout verifies that StreamLogs (dump mode) returns -// after the idle timeout fires, without blocking indefinitely on an open stream. -func TestStreamLogsDumpIdleTimeout(t *testing.T) { - // An empty stream body will block in a real connection, but our fakeClient - // returns a closed reader immediately. This tests the normal "no events" path. - client := &fakeClient{ - statuses: []string{"started"}, - streamBodies: []string{""}, - } - - var out bytes.Buffer - start := time.Now() - err := StreamLogs( - context.Background(), - client, - "org", "proj", "env", "comp", "pipeline", "job", "42", - Options{ - LogWriter: &out, - DisableInterruptHandler: true, - }, - ) - elapsed := time.Since(start) - require.NoError(t, err) - // Should complete quickly (stream closed immediately by fake client). - assert.Less(t, elapsed, 5*time.Second) -} - -// TestStreamLogsWatchDelegatesToWatch verifies that StreamLogs in watch mode -// behaves like Watch (returns error codes for failed builds, etc.). -func TestStreamLogsWatchDelegatesToWatch(t *testing.T) { - client := &fakeClient{ - statuses: []string{"started", "failed"}, - streamBodies: []string{""}, - } - - var out bytes.Buffer - err := StreamLogs( - context.Background(), - client, - "org", "proj", "env", "comp", "pipeline", "job", "42", - Options{ - Watch: true, - LogWriter: &out, - PollInterval: 10 * time.Millisecond, - DisableInterruptHandler: true, - }, - ) - // Watch mode should return ExitError for a failed build. - var exitErr *ExitError - require.ErrorAs(t, err, &exitErr) - assert.Equal(t, exitCodeFailed, exitErr.ExitCode()) - // AbortBuild should NOT be called in read-only watch mode. - assert.Equal(t, 0, client.abortCalls) -} diff --git a/internal/buildwatch/theme.go b/internal/buildwatch/theme.go deleted file mode 100644 index d8748f325..000000000 --- a/internal/buildwatch/theme.go +++ /dev/null @@ -1,35 +0,0 @@ -// ANSI theme for human watch output only. Not related to cyargs project --color. -// See docs/pipeline-build-watch-output.md to disable or remove the whole watch formatting layer. -package buildwatch - -// StreamTheme groups ANSI SGR sequences for --watch human output. -// Change DefaultStreamTheme to adjust the look; keep Reset for correct TTY behavior. -type StreamTheme struct { - Reset string - - BuildLabel string - BuildText string - - TaskLabel string - TaskText string - - LogStdoutPrefix string - LogStderrPrefix string - - ResourceLabel string - - Dim string -} - -// DefaultStreamTheme is used when stdout is a TTY and output mode is human. -var DefaultStreamTheme = StreamTheme{ - Reset: "\033[0m", - BuildLabel: "\033[1;35m", - BuildText: "\033[35m", - TaskLabel: "\033[1;36m", - TaskText: "\033[36m", - LogStdoutPrefix: "\033[32m", - LogStderrPrefix: "\033[33m", - ResourceLabel: "\033[90m", - Dim: "\033[2m", -} diff --git a/internal/buildwatch/watch.go b/internal/buildwatch/watch.go deleted file mode 100644 index 8233618f0..000000000 --- a/internal/buildwatch/watch.go +++ /dev/null @@ -1,398 +0,0 @@ -// Package buildwatch implements pipeline build watch: SSE event streaming and polling until the build finishes. -// Used by cmd/cycloid/pipelines (build trigger --watch). See docs/pipeline-build-watch-output.md. -package buildwatch - -import ( - "bufio" - "context" - "errors" - "fmt" - "io" - "net/http" - "os" - "os/signal" - "strings" - "sync/atomic" - "time" - - "golang.org/x/term" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -const ( - exitCodeAborted = 2 - exitCodeFailed = 3 - exitCodeTimeout = 4 - exitCodeInterrupted = 130 // second Ctrl+C: stop watching (128 + SIGINT) - - defaultPollInterval = 3 * time.Second - defaultReconnect = time.Second -) - -// OutputMode selects how SSE data lines are written when watching a build. -type OutputMode int - -const ( - // OutputHuman prints parsed, filtered lines ([build], [task], logs, etc.). - OutputHuman OutputMode = iota - // OutputRaw writes each SSE data payload as NDJSON (for --output json). - OutputRaw -) - -// Client is the minimal middleware surface required for watch (implemented by middleware.Middleware). -type Client interface { - GetBuild(org, project, env, component, pipeline, job, buildID string) (*models.Build, *http.Response, error) - AbortBuild(org, project, env, component, pipeline, job, buildID string) (*http.Response, error) - OpenBuildEventsStream(ctx context.Context, org, project, env, component, pipeline, buildID, lastEventID string) (io.ReadCloser, *http.Response, error) -} - -// ExitError is returned when the build ends in aborted, failed, or timed-out states (non-zero CLI exit). -type ExitError struct { - code int - message string -} - -func (e *ExitError) Error() string { - return e.message -} - -// ExitCode implements CLI exit code handling in main. -func (e *ExitError) ExitCode() int { - return e.code -} - -// Options configures Watch. -type Options struct { - Timeout time.Duration - CancelOnTimeout bool - LogWriter io.Writer - PollInterval time.Duration - ReconnectDelay time.Duration - - // OutputHuman vs OutputRaw; see docs/pipeline-build-watch-output.md. - Output OutputMode - // Verbose human output (all event types), e.g. when CLI verbosity is debug. - Verbose bool - // Theme for human output; empty for no ANSI. - Theme StreamTheme - // Strip ANSI inside log payloads when not a TTY. - StripLogANSI bool - // StatusWriter receives short interrupt hints (first/second Ctrl+C). Often cmd.ErrOrStderr(). - StatusWriter io.Writer - // DisableInterruptHandler skips OS signal handling (tests). - DisableInterruptHandler bool - // ReadOnly disables AbortBuild on first Ctrl+C. First interrupt immediately exits (code 130). - // Use this when streaming logs of an existing build without intending to control it. - ReadOnly bool - // Watch enables tailing mode in StreamLogs: reconnects on disconnect and polls for completion. - // When false, StreamLogs dumps available events and returns after an idle timeout. - Watch bool -} - -// IsTerminalWriter reports whether w is an *os.File open on a terminal. -func IsTerminalWriter(w io.Writer) bool { - f, ok := w.(*os.File) - if !ok { - return false - } - return term.IsTerminal(int(f.Fd())) -} - -// Watch polls build status until completion while streaming build events to LogWriter. -func Watch( - ctx context.Context, - m Client, - org, project, env, component, pipeline, job, buildID string, - options Options, -) error { - if options.PollInterval <= 0 { - options.PollInterval = defaultPollInterval - } - if options.ReconnectDelay <= 0 { - options.ReconnectDelay = defaultReconnect - } - if options.LogWriter == nil { - options.LogWriter = io.Discard - } - - watchCtx, cancel := context.WithCancel(ctx) - defer cancel() - - var userStop atomic.Bool - - if !options.DisableInterruptHandler { - sigCh := make(chan os.Signal, 8) - signal.Notify(sigCh, os.Interrupt) - go func() { - defer signal.Stop(sigCh) - interrupts := 0 - for { - select { - case <-watchCtx.Done(): - return - case <-sigCh: - interrupts++ - if options.ReadOnly { - // Read-only watch: first Ctrl+C exits immediately without aborting. - userStop.Store(true) - cancel() - return - } - if interrupts == 1 { - _, err := m.AbortBuild(org, project, env, component, pipeline, job, buildID) - if options.StatusWriter != nil { - if err != nil { - fmt.Fprintf(options.StatusWriter, "warning: build abort request failed: %v\n", err) - } - fmt.Fprintln(options.StatusWriter, "Interrupt: press Ctrl+C again to stop watching immediately") - } - } else { - userStop.Store(true) - cancel() - return - } - } - } - }() - } - - lineFmt := lineFormatHuman - if options.Output == OutputRaw { - lineFmt = lineFormatRaw - } - evtOpts := consumeOpts{ - format: lineFmt, - verbose: options.Verbose, - theme: options.Theme, - stripLogANSI: options.StripLogANSI, - } - - streamErrCh := make(chan error, 1) - go func() { - streamErrCh <- streamEventsWithReconnect(watchCtx, m, options, evtOpts, org, project, env, component, pipeline, buildID) - }() - - waitErr := waitForCompletion( - watchCtx, - m, - org, project, env, component, pipeline, job, buildID, - options.Timeout, - options.CancelOnTimeout, - options.PollInterval, - ) - - cancel() - - streamErr := <-streamErrCh - if waitErr != nil { - if errors.Is(waitErr, context.Canceled) && userStop.Load() { - return &ExitError{ - code: exitCodeInterrupted, - message: "watch interrupted", - } - } - return waitErr - } - if streamErr != nil && !errors.Is(streamErr, context.Canceled) { - return streamErr - } - - return nil -} - -func waitForCompletion( - ctx context.Context, - m Client, - org, project, env, component, pipeline, job, buildID string, - timeout time.Duration, - cancelOnTimeout bool, - pollInterval time.Duration, -) error { - start := time.Now() - - for { - if timeout > 0 && time.Since(start) >= timeout { - if cancelOnTimeout { - if _, err := m.AbortBuild(org, project, env, component, pipeline, job, buildID); err != nil { - return fmt.Errorf("timed out waiting for build completion and failed to abort build: %w", err) - } - } - - return &ExitError{ - code: exitCodeTimeout, - message: fmt.Sprintf("build timed out after %s", timeout), - } - } - - build, _, err := m.GetBuild(org, project, env, component, pipeline, job, buildID) - if err != nil { - return fmt.Errorf("failed to get build status: %w", err) - } - if build == nil || build.Status == nil { - return errors.New("build status is empty") - } - - status := strings.ToLower(strings.TrimSpace(*build.Status)) - switch status { - case "succeeded": - return nil - case "aborted": - return &ExitError{ - code: exitCodeAborted, - message: "build was aborted", - } - case "failed", "errored": - return &ExitError{ - code: exitCodeFailed, - message: "build failed", - } - case "pending", "started": - default: - return fmt.Errorf("unknown build status %q", status) - } - - select { - case <-ctx.Done(): - return ctx.Err() - case <-time.After(pollInterval): - } - } -} - -func streamEventsWithReconnect( - ctx context.Context, - m Client, - opts Options, - evtOpts consumeOpts, - org, project, env, component, pipeline, buildID string, -) error { - lastEventID := "" - reconnectDelay := opts.ReconnectDelay - if reconnectDelay <= 0 { - reconnectDelay = defaultReconnect - } - writer := opts.LogWriter - if writer == nil { - writer = io.Discard - } - - for { - select { - case <-ctx.Done(): - return nil - default: - } - - stream, _, err := m.OpenBuildEventsStream(ctx, org, project, env, component, pipeline, buildID, lastEventID) - if err != nil { - if errors.Is(ctx.Err(), context.Canceled) { - return nil - } - if err := sleepWithContext(ctx, reconnectDelay); err != nil { - return nil - } - continue - } - - nextEventID, err := consumeBuildEvents(ctx, stream, writer, lastEventID, evtOpts) - closeErr := stream.Close() - if nextEventID != "" { - lastEventID = nextEventID - } - - if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, context.Canceled) { - if sleepErr := sleepWithContext(ctx, reconnectDelay); sleepErr != nil { - return nil - } - continue - } - if closeErr != nil && !errors.Is(closeErr, context.Canceled) { - if sleepErr := sleepWithContext(ctx, reconnectDelay); sleepErr != nil { - return nil - } - continue - } - - if err := sleepWithContext(ctx, reconnectDelay); err != nil { - return nil - } - } -} - -func consumeBuildEvents(ctx context.Context, stream io.Reader, writer io.Writer, lastEventID string, evtOpts consumeOpts) (string, error) { - scanner := bufio.NewScanner(stream) - scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) - - eventID := "" - dataLines := make([]string, 0, 4) - currentLastEventID := lastEventID - - flushEvent := func() error { - if len(dataLines) == 0 { - return nil - } - - payload := strings.Join(dataLines, "\n") - if err := formatAndWriteBuildEvent(writer, payload, evtOpts); err != nil { - return err - } - - if eventID != "" { - currentLastEventID = eventID - } - - eventID = "" - dataLines = dataLines[:0] - return nil - } - - for scanner.Scan() { - select { - case <-ctx.Done(): - return currentLastEventID, ctx.Err() - default: - } - - line := scanner.Text() - if line == "" { - if err := flushEvent(); err != nil { - return currentLastEventID, err - } - continue - } - - if strings.HasPrefix(line, ":") { - continue - } - if strings.HasPrefix(line, "id:") { - eventID = strings.TrimSpace(strings.TrimPrefix(line, "id:")) - continue - } - if strings.HasPrefix(line, "data:") { - data := strings.TrimPrefix(strings.TrimPrefix(line, "data:"), " ") - dataLines = append(dataLines, data) - } - } - - if err := scanner.Err(); err != nil { - return currentLastEventID, err - } - if err := flushEvent(); err != nil { - return currentLastEventID, err - } - - return currentLastEventID, nil -} - -func sleepWithContext(ctx context.Context, delay time.Duration) error { - timer := time.NewTimer(delay) - defer timer.Stop() - - select { - case <-ctx.Done(): - return ctx.Err() - case <-timer.C: - return nil - } -} diff --git a/internal/buildwatch/watch_test.go b/internal/buildwatch/watch_test.go deleted file mode 100644 index 2dce600a7..000000000 --- a/internal/buildwatch/watch_test.go +++ /dev/null @@ -1,300 +0,0 @@ -package buildwatch - -import ( - "context" - "errors" - "io" - "net/http" - "strings" - "sync" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -type fakeClient struct { - mu sync.Mutex - - statuses []string - getBuildCalls int - getBuildErr error - - abortCalls int - abortErr error - - streamBodies []string - openErr error - openCalls int -} - -func (f *fakeClient) GetBuild(_, _, _, _, _, _, _ string) (*models.Build, *http.Response, error) { - f.mu.Lock() - defer f.mu.Unlock() - - if f.getBuildErr != nil { - return nil, nil, f.getBuildErr - } - if len(f.statuses) == 0 { - return nil, nil, errors.New("no status configured") - } - - idx := f.getBuildCalls - if idx >= len(f.statuses) { - idx = len(f.statuses) - 1 - } - f.getBuildCalls++ - - status := f.statuses[idx] - return &models.Build{Status: &status}, nil, nil -} - -func (f *fakeClient) AbortBuild(_, _, _, _, _, _, _ string) (*http.Response, error) { - f.mu.Lock() - defer f.mu.Unlock() - f.abortCalls++ - return nil, f.abortErr -} - -func (f *fakeClient) OpenBuildEventsStream(_ context.Context, _, _, _, _, _, _, _ string) (io.ReadCloser, *http.Response, error) { - f.mu.Lock() - defer f.mu.Unlock() - - if f.openErr != nil { - return nil, nil, f.openErr - } - - idx := f.openCalls - if idx >= len(f.streamBodies) { - idx = len(f.streamBodies) - 1 - } - f.openCalls++ - - if len(f.streamBodies) == 0 { - return io.NopCloser(strings.NewReader("")), nil, nil - } - - return io.NopCloser(strings.NewReader(f.streamBodies[idx])), nil, nil -} - -func TestWatchSucceeded(t *testing.T) { - t.Parallel() - - client := &fakeClient{ - statuses: []string{"pending", "started", "succeeded"}, - streamBodies: []string{"data: first line\n\ndata: second line\n\n"}, - } - - var out strings.Builder - err := Watch( - context.Background(), - client, - "org", - "project", - "env", - "component", - "pipeline", - "job", - "42", - Options{ - LogWriter: &out, - PollInterval: time.Millisecond, - ReconnectDelay: 50 * time.Millisecond, - Output: OutputRaw, - DisableInterruptHandler: true, - }, - ) - require.NoError(t, err) - assert.Contains(t, out.String(), "first line") - assert.Contains(t, out.String(), "second line") -} - -func TestWatchAborted(t *testing.T) { - t.Parallel() - - client := &fakeClient{ - statuses: []string{"aborted"}, - } - - err := Watch( - context.Background(), - client, - "org", - "project", - "env", - "component", - "pipeline", - "job", - "42", - Options{ - PollInterval: time.Millisecond, - ReconnectDelay: 50 * time.Millisecond, - DisableInterruptHandler: true, - }, - ) - require.Error(t, err) - - var codedErr *ExitError - require.ErrorAs(t, err, &codedErr) - assert.Equal(t, exitCodeAborted, codedErr.ExitCode()) -} - -func TestWatchFailed(t *testing.T) { - t.Parallel() - - client := &fakeClient{ - statuses: []string{"failed"}, - } - - err := Watch( - context.Background(), - client, - "org", - "project", - "env", - "component", - "pipeline", - "job", - "42", - Options{ - PollInterval: time.Millisecond, - ReconnectDelay: 50 * time.Millisecond, - DisableInterruptHandler: true, - }, - ) - require.Error(t, err) - - var codedErr *ExitError - require.ErrorAs(t, err, &codedErr) - assert.Equal(t, exitCodeFailed, codedErr.ExitCode()) -} - -func TestWatchTimeoutWithCancel(t *testing.T) { - t.Parallel() - - client := &fakeClient{ - statuses: []string{"pending"}, - } - - err := Watch( - context.Background(), - client, - "org", - "project", - "env", - "component", - "pipeline", - "job", - "42", - Options{ - Timeout: 5 * time.Millisecond, - CancelOnTimeout: true, - PollInterval: time.Millisecond, - ReconnectDelay: 50 * time.Millisecond, - DisableInterruptHandler: true, - }, - ) - require.Error(t, err) - - var codedErr *ExitError - require.ErrorAs(t, err, &codedErr) - assert.Equal(t, exitCodeTimeout, codedErr.ExitCode()) - assert.Equal(t, 1, client.abortCalls) -} - -func TestConsumeBuildEventsTracksLastEventID(t *testing.T) { - t.Parallel() - - stream := strings.NewReader("id: 10\ndata: one\n\ndata: two\n\nid: 11\ndata: three\n\n") - var out strings.Builder - - rawOpts := consumeOpts{format: lineFormatRaw} - lastID, err := consumeBuildEvents(context.Background(), stream, &out, "", rawOpts) - require.NoError(t, err) - assert.Equal(t, "11", lastID) - assert.Equal(t, "one\ntwo\nthree\n", out.String()) -} - -func TestFormatHumanBuildEventSample(t *testing.T) { - t.Parallel() - - opts := consumeOpts{ - format: lineFormatHuman, - verbose: false, - theme: StreamTheme{}, - stripLogANSI: true, - } - - statusStarted := `{"data":{"status":"started","time":1774994819},"event":"status","version":"1.0","event_id":"0"}` - out, ok := formatHumanBuildEvent(statusStarted, opts) - require.True(t, ok) - assert.Equal(t, "[build] status: started\n", out) - - logOut := `{"data":{"time":1774994823,"origin":{"id":"69b7cd6b","source":"stdout"},"payload":"hello world\r\n"},"event":"log","version":"5.1","event_id":"16"}` - out, ok = formatHumanBuildEvent(logOut, opts) - require.True(t, ok) - assert.Contains(t, out, "[stdout]") - assert.Contains(t, out, "hello world") - - startTask := `{"data":{"time":1774994823,"origin":{"id":"69b7cd6b"}},"event":"start-task","version":"5.0","event_id":"15"}` - out, ok = formatHumanBuildEvent(startTask, opts) - require.True(t, ok) - assert.Equal(t, "[task] 69b7cd6b: started\n", out) - - finishTask := `{"data":{"time":1774994823,"exit_status":0,"origin":{"id":"69b7cd6b"}},"event":"finish-task","version":"4.0","event_id":"17"}` - out, ok = formatHumanBuildEvent(finishTask, opts) - require.True(t, ok) - assert.Equal(t, "[task] 69b7cd6b: finished (exit 0)\n", out) - - imageCheck := `{"data":{"time":1},"event":"image-check","version":"1.1","event_id":"2"}` - _, ok = formatHumanBuildEvent(imageCheck, opts) - assert.False(t, ok) - - opts.verbose = true - out, ok = formatHumanBuildEvent(imageCheck, opts) - require.True(t, ok) - assert.Contains(t, out, "[res]") - assert.Contains(t, out, "image-check") -} - -func TestFormatHumanBuildEventRawPassthroughInvalidJSON(t *testing.T) { - t.Parallel() - - opts := consumeOpts{format: lineFormatHuman, theme: StreamTheme{}} - out, ok := formatHumanBuildEvent("not-json", opts) - require.True(t, ok) - assert.Equal(t, "not-json\n", out) -} - -func TestFormatHumanBuildEventLogPreservesBlankLines(t *testing.T) { - t.Parallel() - - opts := consumeOpts{ - format: lineFormatHuman, - theme: StreamTheme{}, - stripLogANSI: true, - } - - // Blank lines within a payload are preserved as bare newlines so - // meaningful output separators (e.g. ls column groups) are not lost. - multi := `{"data":{"origin":{"source":"stdout"},"payload":"hello\n\n\nworld\n"},"event":"log","version":"1.0"}` - out, ok := formatHumanBuildEvent(multi, opts) - require.True(t, ok) - assert.Contains(t, out, "[stdout] hello") - assert.Contains(t, out, "[stdout] world") - assert.NotContains(t, out, "[stdout] \n") // blank lines must not get the [stdout] prefix - assert.Equal(t, 2, strings.Count(out, "[stdout]")) - assert.Greater(t, strings.Count(out, "\n"), 2) // blank lines are present as bare newlines - - // Fully-whitespace payloads are suppressed entirely. - emptyPayload := `{"data":{"origin":{"source":"stdout"},"payload":"\n"},"event":"log","version":"1.0"}` - _, ok = formatHumanBuildEvent(emptyPayload, opts) - assert.False(t, ok) - - onlySpaces := `{"data":{"origin":{"source":"stderr"},"payload":" \n\t\n"},"event":"log","version":"1.0"}` - _, ok = formatHumanBuildEvent(onlySpaces, opts) - assert.False(t, ok) -} diff --git a/internal/custommodels/stacks.go b/internal/custommodels/stacks.go deleted file mode 100644 index 6c5b5c4e6..000000000 --- a/internal/custommodels/stacks.go +++ /dev/null @@ -1,10 +0,0 @@ -package custommodels - -import "github.com/cycloidio/cycloid-cli/client/models" - -type Blueprint struct { - // Added use cases for blueprint make it more usable output - // for MCP server - UseCases *[]string `json:"use_cases"` - models.ServiceCatalog -} diff --git a/internal/cyargs/api_key.go b/internal/cyargs/api_key.go deleted file mode 100644 index 99d7e2b7c..000000000 --- a/internal/cyargs/api_key.go +++ /dev/null @@ -1,101 +0,0 @@ -package cyargs - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func AddAPIKeyDescriptionFlag(cmd *cobra.Command) string { - flagName := "description" - cmd.Flags().StringP(flagName, "d", "", "set the description of the apikey") - return flagName -} - -func GetAPIKeyDescription(cmd *cobra.Command) (string, error) { - description, err := cmd.Flags().GetString("description") - if err != nil { - return "", err - } - - return description, nil -} - -func AddAPIKeyNameFlag(cmd *cobra.Command) string { - flagName := "name" - cmd.Flags().StringP(flagName, "n", "", "set the name of the apikey, will default to canonical if unset.") - return flagName -} - -func GetAPIKeyName(cmd *cobra.Command) (string, error) { - name, err := cmd.Flags().GetString("name") - if err != nil { - return "", err - } - - return name, nil -} - -func AddAPIKeyCanonicalFlag(cmd *cobra.Command) string { - flagName := "canonical" - cmd.Flags().String(flagName, "", "set the canonical of the API key, if unset, will use the sanitized name.") - _ = cmd.RegisterFlagCompletionFunc(flagName, CompleteAPIKeyCanonical) - return flagName -} - -func CompleteAPIKeyCanonical(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org parameter for completion"), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - APIKeys, _, err := m.ListAPIKeys(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list API Keys: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var APIKeysComp = make([]cobra.Completion, len(APIKeys)) - for index, apiKey := range APIKeys { - if apiKey.Canonical != nil && strings.HasPrefix(*apiKey.Canonical, toComplete) { - APIKeysComp[index] = cobra.CompletionWithDesc(*apiKey.Canonical, fmt.Sprintf("%s from %s: %s", *apiKey.Name, *apiKey.Owner.Username, apiKey.Description)) - } - } - - return APIKeysComp, cobra.ShellCompDirectiveNoFileComp -} - -func GetAPIKeyCanonical(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("canonical") -} - -func AddAPIKeyRulesFlag(cmd *cobra.Command) string { - flagName := "rules" - cmd.Flags().String(flagName, "", `Set the permissions of the api, must be a JSON array of rules formatted like: '[{"action": "organization:**", "effect": "allow", "resources": []}]'.\nSee API Docs https://docs.cycloid.io/api/#tag/Organization-API-keys/operation/createAPIKey`) - cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - if toComplete == "" { - return []cobra.Completion{ - cobra.CompletionWithDesc(`[{"action":"organization:**","effect":"allow","resources":[]}]`, "Admin permissions"), - }, cobra.ShellCompDirectiveNoFileComp - } - - return []string{}, cobra.ShellCompDirectiveNoFileComp - }) - return flagName -} - -func GetAPIKeyRules(cmd *cobra.Command) (string, error) { - rules, err := cmd.Flags().GetString("rules") - if err != nil { - return "", err - } - - return rules, nil -} diff --git a/internal/cyargs/bootstrap.go b/internal/cyargs/bootstrap.go deleted file mode 100644 index a72be18ec..000000000 --- a/internal/cyargs/bootstrap.go +++ /dev/null @@ -1,70 +0,0 @@ -package cyargs - -import ( - "fmt" - "io" - "strings" - - "github.com/spf13/cobra" -) - -func AddBootstrapUserFlags(cmd *cobra.Command) { - cmd.Flags().String("username", "", "admin username for the first user") - cmd.Flags().String("full-name", "", "full name for the first user") - cmd.Flags().String("email", "", "email for the first user") - cmd.Flags().String("password", "", "password for the first user") - cmd.Flags().Bool("password-stdin", false, "read the password from stdin") - - _ = cmd.MarkFlagRequired("username") - _ = cmd.MarkFlagRequired("full-name") - _ = cmd.MarkFlagRequired("email") - - cmd.MarkFlagsMutuallyExclusive("password", "password-stdin") -} - -func AddBootstrapAPIKeyCanonicalFlag(cmd *cobra.Command) string { - flagName := "api-key-canonical" - cmd.Flags().String(flagName, "", "optional canonical for an admin API key and matching credential") - return flagName -} - -func GetBootstrapPassword(cmd *cobra.Command) (string, error) { - fromStdin, err := cmd.Flags().GetBool("password-stdin") - if err != nil { - return "", err - } - password, err := cmd.Flags().GetString("password") - if err != nil { - return "", err - } - - if fromStdin && password != "" { - return "", fmt.Errorf("only one of --password and --password-stdin may be set") - } - if fromStdin { - content, err := io.ReadAll(cmd.InOrStdin()) - if err != nil { - return "", fmt.Errorf("failed to read password from stdin: %w", err) - } - password = strings.TrimSpace(string(content)) - if password == "" { - return "", fmt.Errorf("stdin looks empty, please provide a password") - } - return password, nil - } - if password == "" { - return "", fmt.Errorf("password is required: pass --password or --password-stdin") - } - return password, nil -} - -func GetBootstrapAPIKeyCanonical(cmd *cobra.Command) (*string, error) { - canonical, err := cmd.Flags().GetString("api-key-canonical") - if err != nil { - return nil, err - } - if canonical == "" { - return nil, nil - } - return &canonical, nil -} diff --git a/internal/cyargs/cloud_accounts.go b/internal/cyargs/cloud_accounts.go deleted file mode 100644 index 55d4f84d2..000000000 --- a/internal/cyargs/cloud_accounts.go +++ /dev/null @@ -1,84 +0,0 @@ -package cyargs - -import ( - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -// CloudAccountFlag is the canonical flag name for cloud-account targeting, -// exposed so callers can build cobra Args validators without hardcoding strings. -const CloudAccountFlag = "cloud-account" - -func AddCloudAccountFlag(cmd *cobra.Command) string { - cmd.Flags().StringP(CloudAccountFlag, "a", "", "cloud account canonical") - _ = cmd.RegisterFlagCompletionFunc(CloudAccountFlag, CompleteCloudAccountCanonical) - return CloudAccountFlag -} - -func GetCloudAccount(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(CloudAccountFlag) -} - -func AddExistingCredentialFlag(cmd *cobra.Command) string { - flagName := "credential" - cmd.Flags().String(flagName, "", "canonical of an existing credential to wrap") - _ = cmd.RegisterFlagCompletionFunc(flagName, CompleteCredentialCanonical) - return flagName -} - -func GetExistingCredential(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("credential") -} - -func AddNewCredentialTypeFlag(cmd *cobra.Command) string { - flagName := "new-credential" - cmd.Flags().String(flagName, "", "create a new credential inline (ssh|aws|azure|azure_storage|gcp|custom|basic_auth|elasticsearch|swift)") - return flagName -} - -func GetNewCredentialType(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("new-credential") -} - -func AddEnvironmentTypeCanonicalFlag(cmd *cobra.Command) string { - flagName := "environment-type" - cmd.Flags().String(flagName, "", "environment type canonical") - _ = cmd.RegisterFlagCompletionFunc(flagName, CompleteEnvironmentType) - return flagName -} - -func GetEnvironmentTypeCanonical(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("environment-type") -} - -func CompleteCloudAccount(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org parameter for completion"), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - accounts, _, err := m.ListCloudAccounts(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list cloud accounts: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, 0, len(accounts)) - for _, account := range accounts { - if account.Canonical != nil && strings.HasPrefix(*account.Canonical, toComplete) { - name := "" - if account.Name != nil { - name = *account.Name - } - completions = append(completions, cobra.CompletionWithDesc(*account.Canonical, name)) - } - } - return completions, cobra.ShellCompDirectiveNoFileComp -} diff --git a/internal/cyargs/common.go b/internal/cyargs/common.go deleted file mode 100644 index f62b57629..000000000 --- a/internal/cyargs/common.go +++ /dev/null @@ -1,492 +0,0 @@ -package cyargs - -import ( - "errors" - "fmt" - "math/rand/v2" - "strings" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -var ( - v = viper.GetViper() - DefaultIcon = "" - DefaultColor = "" - ValidIcons = []string{ - "folder_open", - "mdi-cube-outline", - "public", - "extension", - "science", - "bug_report", - "bolt", - "call_merge", - "commit", - "mdi-source-branch", - "traffic", - "mdi-clipboard-check-outline", - "mdi-progress-clock", - "visibility", - "vpn_key", - "lightbulb", - "favorite", - "star", - "auto_awesome", - "mdi-controller-classic", - "precision_manufacturing", - "tour", - "podcasts", - "inventory", - "save", - "security", - "mdi-lifebuoy", - "mdi-ab-testing", - "mdi-api", - "mdi-console", - "mdi-database", - "mdi-vpn", - "mdi-server", - "mdi-server-security", - "mdi-network-outline", - "mdi-lan", - "mdi-nas", - "mdi-ansible", - "mdi-aws", - "mdi-microsoft-azure", - "mdi-google-cloud", - "mdi-kubernetes", - "mdi-terraform", - } - ValidColors = []string{ - "dev", - "prod", - "demo", - "success", - "default", - "error", - "staging", - "preprod", - } -) - -func AddCyContext(cmd *cobra.Command) { - AddProjectFlag(cmd) - AddEnvFlag(cmd) - AddComponentFlag(cmd) -} - -func GetCyContext(cmd *cobra.Command) (org, project, env, component string, err error) { - org, err = GetOrg(cmd) - if err != nil { - return "", "", "", "", err - } - - project, err = GetProject(cmd) - if err != nil { - return org, "", "", "", err - } - - env, err = GetEnv(cmd) - if err != nil { - return org, project, "", "", err - } - - component, err = GetComponent(cmd) - if err != nil { - return org, project, env, "", err - } - - return org, project, env, component, nil -} - -func AddNameFlag(cmd *cobra.Command) string { - flagName := "name" - cmd.Flags().StringP(flagName, "n", "", "set a human friendly name.") - return flagName -} - -func GetName(cmd *cobra.Command) (string, error) { - name, err := cmd.Flags().GetString("name") - if err != nil { - return "", err - } - - return name, nil -} - -func AddProjectFlag(cmd *cobra.Command) { - cmd.Flags().StringP("project", "p", "", "the project canonical, can also be set with the CY_PROJECT env var") - v.BindPFlag("project", cmd.Flags().Lookup("project")) - _ = cmd.RegisterFlagCompletionFunc("project", CompleteProject) -} - -func CompleteProject(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org parameter for completion"), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - projects, _, err := m.ListProjects(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to fetch project list for completion in org '"+org+"': "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var canonicals = make([]cobra.Completion, len(projects)) - for index, project := range projects { - if project.Canonical != nil && strings.HasPrefix(*project.Canonical, toComplete) { - canonicals[index] = cobra.CompletionWithDesc(*project.Canonical, *project.Name) - } - } - - return canonicals, cobra.ShellCompDirectiveNoFileComp -} - -func GetProject(cmd *cobra.Command) (string, error) { - project, err := GetProjectOrEmpty(cmd) - if err != nil { - return "", err - } - if project == "" { - return "", errors.New("project is not set, use --project flag or CY_PROJECT env var") - } - - return project, nil -} - -func GetProjectOrEmpty(cmd *cobra.Command) (string, error) { - project, _ := cmd.Flags().GetString("project") - if project != "" { - return project, nil - } - - project = v.GetString("project") - return project, nil -} - -func AddEnvFlag(cmd *cobra.Command) { - cmd.Flags().StringP("env", "e", "", "the env canonical, can also be set with the CY_ENV env var") - v.BindPFlag("env", cmd.Flags().Lookup("env")) - - cmd.RegisterFlagCompletionFunc("env", func(cmd *cobra.Command, args []cobra.Completion, toComplete string) ([]string, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "completion failed: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - project, err := GetProject(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to fetch project list for completion in org '"+org+"': "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - envs, _, err := m.ListProjectEnvs(org, project) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list env from org '"+org+"' in project '"+project+"' for completion: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var canonicals = make([]cobra.Completion, len(envs)) - for index, env := range envs { - if env.Canonical != nil && strings.HasPrefix(*env.Canonical, toComplete) { - canonicals[index] = cobra.CompletionWithDesc(*env.Canonical, env.Name) - } - } - - return canonicals, cobra.ShellCompDirectiveNoFileComp - }) -} - -func GetEnv(cmd *cobra.Command) (string, error) { - env, err := GetEnvOrEmpty(cmd) - if err != nil { - return "", err - } - if env == "" { - return "", errors.New("env is not set, use --env flag or CY_ENV env var") - } - - return env, nil -} - -func GetEnvOrEmpty(cmd *cobra.Command) (string, error) { - env, _ := cmd.Flags().GetString("env") - if env != "" { - return env, nil - } - - env = v.GetString("env") - return env, nil -} - -func AddComponentFlag(cmd *cobra.Command) { - cmd.Flags().StringP("component", "c", "", "the component canonical, can also be set with the CY_COMPONENT env var") - v.BindPFlag("component", cmd.Flags().Lookup("component")) - cmd.RegisterFlagCompletionFunc("component", func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "completion failed: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - project, err := GetProject(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "completion failed: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - env, err := GetEnv(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "completion failed: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - components, _, err := m.ListComponents(org, project, env) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list components for completion in org '"+org+"' with project '"+project+"' and env '"+env+"': "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var canonicals = make([]string, len(components)) - for index, component := range components { - if component.Canonical != nil && strings.HasPrefix(*component.Canonical, toComplete) { - canonicals[index] = cobra.CompletionWithDesc(*component.Canonical, *component.Name) - } - } - - return canonicals, cobra.ShellCompDirectiveNoFileComp - }) -} - -func GetComponent(cmd *cobra.Command) (string, error) { - component, _ := cmd.Flags().GetString("component") - if component != "" { - return component, nil - } - - component = v.GetString("component") - if component == "" { - return "", errors.New("component is not set, use --component flag or CY_COMPONENT component var") - } - - return component, nil -} - -func AddColorFlag(cmd *cobra.Command) string { - flagName := "color" - cmd.Flags().String(flagName, DefaultColor, "set the color.") - cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []cobra.Completion, toComplete string) ([]string, cobra.ShellCompDirective) { - var completions []cobra.Completion - for _, color := range ValidColors { - if strings.HasPrefix(color, toComplete) { - completions = append(completions, color) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp - }) - return flagName -} - -func GetColor(cmd *cobra.Command) (string, error) { - color, err := cmd.Flags().GetString("color") - if err != nil { - return "", nil - } - - return color, nil -} - -// PickRandomColor will select a random color, if you -// fill env != nil it will try to infer the color based -// on the env name with our convention. -// This is define in the FE here: -// https://github.com/cycloidio/youdeploy-frontend-web/blob/develop/src/utils/config/icons.js -func PickRandomColor(env *string) string { - if env != nil { - switch *env { - case "prod", "prd": - return "prod" - case "staging", "stg": - return "staging" - case "preprod", "pp", "pre-prd": - return "preprod" - case "test", "testing", "dev", "developpement": - return "dev" - case "demo", "integration", "intg": - return "demo" - default: - return "success" - } - } - - randomIndex := rand.IntN(len(ValidColors)) - return ValidColors[randomIndex] -} - -func AddIconFlag(cmd *cobra.Command) { - cmd.Flags().String("icon", DefaultIcon, "set the icon.") - err := cmd.RegisterFlagCompletionFunc("icon", func(cmd *cobra.Command, args []cobra.Completion, toComplete string) ([]string, cobra.ShellCompDirective) { - var completions []cobra.Completion - for _, icon := range ValidIcons { - if strings.HasPrefix(icon, toComplete) { - completions = append(completions, icon) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp - }) - if err != nil { - panic(err) - } -} - -func GetIcon(cmd *cobra.Command) (string, error) { - icon, err := cmd.Flags().GetString("icon") - if err != nil { - return "", nil - } - - return icon, nil -} - -// PickRandomIcon will select a random icon, if you -// fill env != nil it will try to infer the icon based -// on the env name with our convention. -// This is define in the FE here: -// https://github.com/cycloidio/youdeploy-frontend-web/blob/develop/src/utils/config/icons.js -func PickRandomIcon(env *string) string { - if env != nil { - switch *env { - case "prod", "prd": - return "public" - case "staging", "stg": - return "science" - case "preprod", "pp", "pre-prd": - return "traffic" - case "test", "testing", "dev", "developpement": - return "commit" - case "demo", "integration", "intg": - return "auto_awesome" - default: - return "extension" - } - } - - randomIndex := rand.IntN(len(ValidIcons)) - return ValidIcons[randomIndex] -} - -func AddOwnerFlag(cmd *cobra.Command) string { - flagName := "owner" - cmd.Flags().String(flagName, "", "canonical of a user to set as owner, will be the user attached to the current api key if empty.") - cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "completion failed: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - members, _, err := m.ListMembers(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "cannot list org members for owner completion: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var owners = make([]cobra.Completion, len(members)) - for index, member := range members { - if strings.HasPrefix(member.Username, toComplete) { - owners[index] = cobra.CompletionWithDesc( - member.Username, - fmt.Sprintf("(%s)", member.Email.String()), - ) - } - } - - return owners, cobra.ShellCompDirectiveNoFileComp - }) - - return flagName -} - -func GetOwner(cmd *cobra.Command) (string, error) { - owner, err := cmd.Flags().GetString("owner") - if err != nil { - return "", nil - } - - return owner, nil -} - -func AddDescriptionFlag(cmd *cobra.Command) { - cmd.Flags().String("description", "", "a human friendly description for your peers") -} - -func GetDescription(cmd *cobra.Command) (string, error) { - description, err := cmd.Flags().GetString("description") - if err != nil { - return "", nil - } - - return description, nil -} - -func AddDeleteFlags(cmd *cobra.Command) { - cmd.Flags().Bool("force", false, "shorthand for --skip-hooks --ignore-config-files-err") - cmd.Flags().Bool("skip-hooks", false, "skip component on_delete hooks (sets skip_hooks=true)") - cmd.Flags().Bool("ignore-config-files-err", false, "ignore possible errors on config repository update (sets ignore_config_files_err=true)") -} - -func GetDeleteFlags(cmd *cobra.Command) (force, skipHooks, ignoreConfigFilesErr bool, err error) { - if force, err = cmd.Flags().GetBool("force"); err != nil { - return - } - if skipHooks, err = cmd.Flags().GetBool("skip-hooks"); err != nil { - return - } - ignoreConfigFilesErr, err = cmd.Flags().GetBool("ignore-config-files-err") - return -} - -func GetOrg(cmd *cobra.Command) (string, error) { - org := v.GetString("org") - if org == "" { - return "", fmt.Errorf("org is not set, use --org flag or CY_ORG env var, current value: %q", org) - } - - return org, nil -} - -// RequireArgsOrFlag returns a cobra.PositionalArgs validator that accepts positional -// arguments OR falls back gracefully when the named flag is provided instead. -// This enables backward compatibility when a flag is deprecated in favor of positional args. -func RequireArgsOrFlag(flagName string) cobra.PositionalArgs { - return func(cmd *cobra.Command, args []string) error { - if len(args) > 0 { - return nil - } - if f := cmd.Flags().Lookup(flagName); f != nil && f.Value.String() != "" { - return nil - } - return fmt.Errorf("requires at least 1 arg(s) or --%s flag, only received 0", flagName) - } -} diff --git a/internal/cyargs/common_test.go b/internal/cyargs/common_test.go deleted file mode 100644 index 7373f9c66..000000000 --- a/internal/cyargs/common_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package cyargs_test - -import ( - "os" - "strings" - "testing" - - "github.com/sanity-io/litter" - "github.com/spf13/cobra" - "github.com/spf13/viper" - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/internal/cyargs" -) - -var ( - org = "myOrg" - project = "myProject" - env = "myEnv" - component = "myComponent" - v = viper.GetViper() -) - -func parseArgFunc(t *testing.T, cmd *cobra.Command, args []string) { - t.Logf("Input args: %v", args) - t.Logf("cmd persistent flags: %s", litter.Sdump(cmd.PersistentFlags())) - if !cmd.HasPersistentFlags() { - t.Fatal("cmd does not have the org persistent flag") - } - - err := cmd.ParseFlags(args) - if err != nil { - t.Errorf("Failed to parse flags '%v' with cmd: %v", args, err) - } - - orgArg, projectArg, envArg, componentArg, err := cyargs.GetCyContext(cmd) - if err != nil { - t.Fatal("failed to parse args for cy context:", err) - } - - assert.Equal(t, org, orgArg) - assert.Equal(t, project, projectArg) - assert.Equal(t, env, envArg) - assert.Equal(t, component, componentArg) -} - -func TestCyContext(t *testing.T) { - // This test does not work as intended, remove or fix later - t.Skip() - - // Add the same viper setup that our root cmd - v.SetEnvPrefix("CY") - v.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) - v.AutomaticEnv() - - // Add the org flag that is normally declared in the root org - cmd := cobra.Command{} - cmd.PersistentFlags().String("org", "", "Specify the org to use. override CY_ORG env var. Required for all Org scoped endpoint.") - v.BindPFlag("org", cmd.PersistentFlags().Lookup("org")) - cyargs.AddCyContext(&cmd) - - t.Run("WithFullFlag", func(t *testing.T) { - parseArgFunc(t, &cmd, []string{ - "--org", org, - "--project", project, - "--env", env, - "--component", component, - }, - ) - }) - - t.Run("WithShortFlag", func(t *testing.T) { - parseArgFunc(t, &cmd, []string{ - "--org", org, - "-p", project, - "-e", env, - "-c", component, - }, - ) - }) - - t.Run("WithEnvVar", func(t *testing.T) { - os.Setenv("CY_ORG", org) - os.Setenv("CY_PROJECT", project) - os.Setenv("CY_ENV", env) - os.Setenv("CY_COMPONENT", component) - parseArgFunc(t, &cmd, []string{}) - }) -} diff --git a/internal/cyargs/component.go b/internal/cyargs/component.go deleted file mode 100644 index e91017a75..000000000 --- a/internal/cyargs/component.go +++ /dev/null @@ -1,119 +0,0 @@ -package cyargs - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func AddComponentDescriptionFlag(cmd *cobra.Command) { - cmd.Flags().StringP("description", "d", "", "set the description of the component") -} - -func GetComponentDescription(cmd *cobra.Command) (*string, error) { - description, err := cmd.Flags().GetString("description") - if err != nil { - return nil, err - } - - return &description, nil -} - -func AddCloudProviderFlag(cmd *cobra.Command) string { - flagName := "cloud-provider" - cmd.Flags().String(flagName, "", "set the cloud provider of the component") - return flagName -} - -func GetCloudProvider(cmd *cobra.Command) (*string, error) { - cloudProvider, err := cmd.Flags().GetString("cloud-provider") - if err != nil { - return nil, err - } - - return &cloudProvider, nil -} - -func AddComponentStackRefFlag(cmd *cobra.Command) string { - flagName := "stack-ref" - cmd.Flags().StringP(flagName, "s", "", "set the stack ref of the component in format org:stack-canonical") - cmd.MarkFlagRequired(flagName) - cmd.RegisterFlagCompletionFunc(flagName, CompleteStackRef) - return flagName -} - -func GetComponentStackRef(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("stack-ref") -} - -// AddUseCaseFlag will add the use-case flag with completion and return the flag name -func AddUseCaseFlag(cmd *cobra.Command) string { - flagName := "use-case" - cmd.Flags().StringP(flagName, "u", "", "set the use-case of the component") - cmd.RegisterFlagCompletionFunc(flagName, CompleteUseCase) - return flagName -} - -func CompleteUseCase(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org for completion: "+err.Error()), cobra.ShellCompDirectiveError - } - - var stackRef string - stackRef, _ = GetStackRef(cmd) - if stackRef == "" { // Check for blueprint ref in case of cy stack create - stackRef, err = GetBlueprintRef(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing stack-ref or blueprint ref for completion: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - } - - // Try to get the stack version flags - tag, branch, hash, err := GetStackVersionFlags(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to read stack version flags: "+err.Error()), cobra.ShellCompDirectiveError - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - // Try to get the stack use cases using the provided flags - // If none are provided yet, this will use default version - stackUseCases, _, err := m.ListStackUseCases(org, stackRef, tag, branch, hash) - if err != nil { - // During completion, the version flags might not be set yet - // Return a helpful message to guide the user - return cobra.AppendActiveHelp( - nil, - fmt.Sprintf("Cannot detect version for stack %q: %s. Check and refresh your catalog repository.", stackRef, err.Error()), - ), - cobra.ShellCompDirectiveNoFileComp - } - - var useCases []string - for _, useCase := range stackUseCases { - if strings.HasPrefix(*useCase.UseCase, toComplete) { - desc := *useCase.Name - if useCase.Description != "" { - desc = desc + " - " + useCase.Description - } - useCases = append(useCases, cobra.CompletionWithDesc(*useCase.UseCase, desc)) - } - } - - return useCases, cobra.ShellCompDirectiveNoFileComp -} - -func GetUseCase(cmd *cobra.Command) (string, error) { - useCase, err := cmd.Flags().GetString("use-case") - if err != nil { - return "", err - } - - return useCase, nil -} diff --git a/internal/cyargs/config_catalog_repositories.go b/internal/cyargs/config_catalog_repositories.go deleted file mode 100644 index 0ec5353e7..000000000 --- a/internal/cyargs/config_catalog_repositories.go +++ /dev/null @@ -1,152 +0,0 @@ -package cyargs - -import ( - "fmt" - "slices" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func AddCatalogRepositoryFlag(cmd *cobra.Command) string { - flagName := "catalog-repository" - cmd.Flags().String(flagName, "", "canonical of a catalog repository") - cmd.RegisterFlagCompletionFunc("catalog-repository", CompleteCatalogRepository) - return flagName -} - -// AddCatalogRepoCanonicalFlag registers optional --canonical on catalog-repo create (identity for upsert). -func AddCatalogRepoCanonicalFlag(cmd *cobra.Command) string { - const flagName = "canonical" - cmd.Flags().String(flagName, "", "catalog repository canonical; if omitted, derived from --name") - _ = cmd.RegisterFlagCompletionFunc(flagName, CompleteCatalogRepository) - return flagName -} - -// GetCatalogRepoCanonical returns the optional catalog repository canonical from create (empty if unset). -func GetCatalogRepoCanonical(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("canonical") -} - -// GetConfigRepoCanonical returns the optional config repository canonical (empty if unset). -func GetConfigRepoCanonical(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("canonical") -} - -func GetCatalogRepository(cmd *cobra.Command) (string, error) { - catalogRepository, err := cmd.Flags().GetString("catalog-repository") - if err != nil { - return "", err - } - return catalogRepository, err -} - -func CompleteCatalogRepository(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "completion failed: "+err.Error()), cobra.ShellCompDirectiveError - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - stacks, _, err := m.ListCatalogRepositories(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list catalog repositories for completion in org '"+org+"': "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var catalogRepositories = make([]cobra.Completion, len(stacks)) - for index, catalogRepository := range stacks { - if catalogRepository.Canonical != nil { - catalogRepositories[index] = cobra.CompletionWithDesc(*catalogRepository.Canonical, *catalogRepository.Name+" - branch: "+catalogRepository.Branch) - } - } - - return catalogRepositories, cobra.ShellCompDirectiveNoFileComp -} - -func AddConfigRepositoryFlag(cmd *cobra.Command) string { - flagName := "config-repository" - cmd.Flags().String(flagName, "", "canonical of a config repository, if empty will use the default one in the current org.") - cmd.RegisterFlagCompletionFunc(flagName, CompleteConfigRepository) - return flagName -} - -// AddConfigRepoCanonicalFlag registers --canonical for config-repository get/delete/update commands. -func AddConfigRepoCanonicalFlag(cmd *cobra.Command) string { - const flagName = "canonical" - cmd.Flags().String(flagName, "", "config repository canonical") - _ = cmd.RegisterFlagCompletionFunc(flagName, CompleteConfigRepository) - return flagName -} - -func CompleteConfigRepository(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "completion failed: "+err.Error()), cobra.ShellCompDirectiveError - } - - stacks, _, err := m.ListConfigRepositories(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list config repositories for completion in org '"+org+"': "+err.Error()), cobra.ShellCompDirectiveError - } - - var configRepositories = make([]cobra.Completion, len(stacks)) - for index, configRepository := range stacks { - if configRepository.Canonical != nil { - configRepositories[index] = cobra.CompletionWithDesc(*configRepository.Canonical, *configRepository.Name+" - branch: "+configRepository.Branch) - } - } - - return configRepositories, cobra.ShellCompDirectiveNoFileComp -} - -// GetConfigRepository return the config repository flag, if empty, will try to return -// the current org default config repository -func GetConfigRepository(cmd *cobra.Command) (string, error) { - configRepository, err := cmd.Flags().GetString("config-repository") - if err != nil { - return "", err - } - - return configRepository, err -} - -func GetDefaultConfigRepository(cmd *cobra.Command) (string, error) { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := GetOrg(cmd) - if err != nil { - return "", fmt.Errorf("failed to get default config repository, missing org argument: %w", err) - } - - configRepository, _ := GetConfigRepository(cmd) - if configRepository != "" { - return configRepository, nil - } - - // TODO: This behavior will be pushed to backend - // track issue: https://linear.app/cycloid/issue/BE-807/make-the-createproject-route-use-the-default-catalog-if - catalogRepos, _, err := m.ListConfigRepositories(org) - if err != nil { - return "", fmt.Errorf("failed to get the default config repository: %w", err) - } - - index := slices.IndexFunc(catalogRepos, func(c *models.ConfigRepository) bool { - return *c.Default - }) - if index == -1 { - docURL := "https://docs.cycloid.io/reference/config-and-catalog-repository/" - return "", fmt.Errorf("error: seems like your org %q does not have a default config repository, please add one using this doc: %q", org, docURL) - } - - return *catalogRepos[index].Canonical, nil -} diff --git a/internal/cyargs/credentials.go b/internal/cyargs/credentials.go deleted file mode 100644 index acacb5c9d..000000000 --- a/internal/cyargs/credentials.go +++ /dev/null @@ -1,350 +0,0 @@ -package cyargs - -import ( - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func AddCredentialDescriptionPersistentFlag(cmd *cobra.Command) string { - flagName := "description" - cmd.PersistentFlags().StringP(flagName, "d", "", "add an helpful description to your credential.") - return flagName -} - -func AddCredentialDescriptionFlag(cmd *cobra.Command) string { - flagName := "description" - cmd.Flags().StringP(flagName, "d", "", "add an helpful description to your credential.") - return flagName -} - -func GetCredentialDescription(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("description") -} - -func AddCredentialCanonicalPersistentFlag(cmd *cobra.Command) string { - flagName := "canonical" - cmd.PersistentFlags().StringP(flagName, "c", "", "the canonical of your credential") - cmd.RegisterFlagCompletionFunc(flagName, CompleteCredentialCanonical) - return flagName -} - -func AddCredentialCanonicalFlag(cmd *cobra.Command) string { - flagName := "canonical" - cmd.Flags().StringP(flagName, "c", "", "the canonical of your credential") - cmd.RegisterFlagCompletionFunc(flagName, CompleteCredentialCanonical) - return flagName -} - -func CompleteCredentialCanonical(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return []string{}, cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - creds, _, err := m.ListCredentials(org, "") - if err != nil { - return cobra.AppendActiveHelp(nil, "completion failed: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var completions = make([]cobra.Completion, len(creds)) - for index, cred := range creds { - if cred.Canonical != nil && strings.HasPrefix(*cred.Canonical, toComplete) { - completions[index] = cobra.CompletionWithDesc(*cred.Canonical, *cred.Name+": "+cred.Description) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func GetCredentialCanonical(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("canonical") -} - -func AddCredentialPathPersistentFlag(cmd *cobra.Command) string { - flagName := "path" - cmd.PersistentFlags().StringP(flagName, "p", "", "the path of your credential") - cmd.RegisterFlagCompletionFunc(flagName, CompleteCredentialPath) - return flagName -} - -func AddCredentialPathFlag(cmd *cobra.Command) string { - flagName := "path" - cmd.Flags().StringP(flagName, "p", "", "the path of your credential") - cmd.RegisterFlagCompletionFunc(flagName, CompleteCredentialPath) - return flagName -} - -func CompleteCredentialPath(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return []string{}, cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - creds, _, err := m.ListCredentials(org, "") - if err != nil { - return cobra.AppendActiveHelp(nil, "completion failed: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var completions = make([]cobra.Completion, len(creds)) - for index, cred := range creds { - if cred.Path != nil && strings.HasPrefix(*cred.Path, toComplete) { - completions[index] = cobra.CompletionWithDesc(*cred.Path, *cred.Name+": "+cred.Description) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func GetCredentialPath(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("path") -} - -func AddCredentialNamePersistentFlag(cmd *cobra.Command) string { - flagName := "name" - cmd.PersistentFlags().StringP(flagName, "n", "", "the name of your credential") - cmd.RegisterFlagCompletionFunc(flagName, CompleteCredentialName) - return flagName -} - -func AddCredentialNameFlag(cmd *cobra.Command) string { - flagName := "name" - cmd.Flags().StringP(flagName, "n", "", "the name of your credential") - cmd.RegisterFlagCompletionFunc(flagName, CompleteCredentialName) - return flagName -} - -func CompleteCredentialName(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return []string{}, cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - creds, _, err := m.ListCredentials(org, "") - if err != nil { - return cobra.AppendActiveHelp(nil, "completion failed: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var completions = make([]cobra.Completion, len(creds)) - for index, cred := range creds { - if cred.Name != nil && strings.HasPrefix(*cred.Name, toComplete) { - completions[index] = cobra.CompletionWithDesc(*cred.Name, *cred.Canonical+": "+cred.Description) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func GetCredentialName(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("name") -} - -func AddCredentialCaCertFlag(cmd *cobra.Command) string { - flagName := "ca-cert" - cmd.Flags().String(flagName, "", "ca-cert") - return flagName -} - -func GetCredentialCaCert(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("ca-cert") -} - -func AddCredentialAuthURLFlag(cmd *cobra.Command) string { - flagName := "auth-url" - cmd.Flags().String(flagName, "", "auth-url") - return flagName -} - -func GetCredentialAuthURL(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("auth-url") -} - -func AddCredentialDomainIDFlag(cmd *cobra.Command) string { - flagName := "domain-id" - cmd.Flags().String(flagName, "", "domain-id") - return flagName -} - -func GetCredentialDomainID(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("domain-id") -} - -func AddCredentialAccountNameFlag(cmd *cobra.Command) string { - flagName := "account-name" - cmd.Flags().String(flagName, "", "account-name") - return flagName -} - -func GetCredentialAccountName(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("account-name") -} - -func AddCredentialClientIDFlag(cmd *cobra.Command) string { - flagName := "client-id" - cmd.Flags().String(flagName, "", "client-id") - return flagName -} - -func GetCredentialClientID(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("client-id") -} - -func AddCredentialClientSecretFlag(cmd *cobra.Command) string { - flagName := "client-secret" - cmd.Flags().String(flagName, "", "client-secret") - return flagName -} - -func GetCredentialClientSecret(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("client-secret") -} - -func AddCredentialSubscriptionIDFlag(cmd *cobra.Command) string { - flagName := "subscription-id" - cmd.Flags().String(flagName, "", "subscription-id") - return flagName -} - -func GetCredentialSubscriptionID(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("subscription-id") -} - -func AddCredentialTenantIDFlag(cmd *cobra.Command) string { - flagName := "tenant-id" - cmd.Flags().String(flagName, "", "tenant-id") - return flagName -} - -func GetCredentialTenantID(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("tenant-id") -} - -func AddCredentialAccessKeyFlag(cmd *cobra.Command) string { - flagName := "access-key" - cmd.Flags().String(flagName, "", "access-key") - return flagName -} - -func GetCredentialAccessKey(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("access-key") -} - -func AddCredentialSecretKeyFlag(cmd *cobra.Command) string { - flagName := "secret-key" - cmd.Flags().String(flagName, "", "secret-key") - return flagName -} - -func GetCredentialSecretKey(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("secret-key") -} - -func AddCredentialFieldFlag(cmd *cobra.Command) string { - flagName := "field" - cmd.Flags().StringToString(flagName, nil, "key=value") - return flagName -} - -func GetCredentialField(cmd *cobra.Command) (map[string]string, error) { - return cmd.Flags().GetStringToString("field") -} - -func AddCredentialFieldFileFlag(cmd *cobra.Command) string { - flagName := "field-file" - cmd.Flags().StringToString(flagName, nil, "key=/file/path") - return flagName -} - -func GetCredentialFieldFile(cmd *cobra.Command) (map[string]string, error) { - return cmd.Flags().GetStringToString("field-file") -} - -func AddCredentialTypeFlag(cmd *cobra.Command) string { - flagName := "type" - cmd.Flags().String(flagName, "", "type") - cmd.RegisterFlagCompletionFunc("type", CompleteCredentialType) - - return flagName -} - -func CompleteCredentialType(_ *cobra.Command, _ []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - credTypes := []cobra.Completion{ - "ssh", - "basic_auth", - "custom", - "aws", - "azure", - "azure_storage", - "gcp", - "elasticsearch", - "swift", - } - - var comps = make([]cobra.Completion, len(credTypes)) - for index, credType := range credTypes { - if strings.HasPrefix(credType, toComplete) { - comps[index] = credType - } - } - - return comps, cobra.ShellCompDirectiveNoFileComp -} - -func GetCredentialType(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("type") -} - -func AddCredentialUsernameFlag(cmd *cobra.Command) string { - flagName := "username" - cmd.Flags().String(flagName, "", "username") - return flagName -} - -func GetCredentialUsername(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("username") -} - -func AddCredentialPasswordFlag(cmd *cobra.Command) string { - flagName := "password" - cmd.Flags().String(flagName, "", "password") - return flagName -} - -func GetCredentialPassword(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("password") -} - -func AddCredentialSSHKeyFlag(cmd *cobra.Command) string { - flagName := "ssh-key" - cmd.Flags().String(flagName, "", "ssh key path") - return flagName -} - -func GetCredentialSSHKey(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("ssh-key") -} - -func AddCredentialJSONKeyFlag(cmd *cobra.Command) string { - flagName := "json-key" - cmd.Flags().String(flagName, "", "json key path") - return flagName -} - -func GetCredentialJSONKey(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("json-key") -} diff --git a/internal/cyargs/environment_types.go b/internal/cyargs/environment_types.go deleted file mode 100644 index 33fa9092c..000000000 --- a/internal/cyargs/environment_types.go +++ /dev/null @@ -1,48 +0,0 @@ -package cyargs - -import ( - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func AddEnvironmentTypeNameFlag(cmd *cobra.Command) string { - flagName := "environment-type-name" - cmd.Flags().String(flagName, "", "display name of the environment type") - return flagName -} - -func GetEnvironmentTypeName(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("environment-type-name") -} - -func CompleteEnvironmentTypeCanonical(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org parameter for completion"), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - types, _, err := m.ListEnvironmentTypes(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list environment types: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, 0, len(types)) - for _, envType := range types { - if envType.Canonical != nil && strings.HasPrefix(*envType.Canonical, toComplete) { - name := "" - if envType.Name != nil { - name = *envType.Name - } - completions = append(completions, cobra.CompletionWithDesc(*envType.Canonical, name)) - } - } - return completions, cobra.ShellCompDirectiveNoFileComp -} diff --git a/internal/cyargs/environments.go b/internal/cyargs/environments.go deleted file mode 100644 index 8dc765e20..000000000 --- a/internal/cyargs/environments.go +++ /dev/null @@ -1,169 +0,0 @@ -package cyargs - -import ( - "fmt" - "os" - "strings" - - "github.com/spf13/cobra" - "gopkg.in/yaml.v3" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -func AddEnvironmentTypeFlag(cmd *cobra.Command) string { - flagName := "type" - cmd.Flags().String(flagName, "", "environment type canonical (e.g. production, staging, development)") - _ = cmd.RegisterFlagCompletionFunc(flagName, CompleteEnvironmentType) - return flagName -} - -func GetEnvironmentType(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("type") -} - -func CompleteEnvironmentType(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org parameter for completion"), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - types, _, err := m.ListEnvironmentTypes(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list environment types: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, 0, len(types)) - for _, envType := range types { - if envType.Canonical != nil && strings.HasPrefix(*envType.Canonical, toComplete) { - name := "" - if envType.Name != nil { - name = *envType.Name - } - completions = append(completions, cobra.CompletionWithDesc(*envType.Canonical, name)) - } - } - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func AddCloudAccountCanonicalsFlag(cmd *cobra.Command) string { - flagName := "cloud-account" - cmd.Flags().StringArray(flagName, nil, "cloud account canonical to link (repeatable); pass \"\" to unlink all") - _ = cmd.RegisterFlagCompletionFunc(flagName, CompleteCloudAccountCanonical) - return flagName -} - -func GetCloudAccountCanonicals(cmd *cobra.Command) ([]string, error) { - return cmd.Flags().GetStringArray("cloud-account") -} - -func CompleteCloudAccountCanonical(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org parameter for completion"), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - accounts, _, err := m.ListCloudAccounts(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list cloud accounts: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, 0, len(accounts)) - for _, account := range accounts { - if account.Canonical != nil && strings.HasPrefix(*account.Canonical, toComplete) { - name := "" - if account.Name != nil { - name = *account.Name - } - completions = append(completions, cobra.CompletionWithDesc(*account.Canonical, name)) - } - } - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func AddEnvironmentVariablesFlag(cmd *cobra.Command) string { - flagName := "variable" - cmd.Flags().StringArray(flagName, nil, "environment variable as KEY=VALUE (repeatable)") - return flagName -} - -func AddEnvironmentVariablesFileFlag(cmd *cobra.Command) string { - flagName := "variables-file" - cmd.Flags().StringArray(flagName, nil, "path to a YAML file containing environment variables") - cmd.MarkFlagFilename(flagName, "yaml", "yml") - return flagName -} - -func GetEnvironmentVariables(cmd *cobra.Command) ([]*models.EnvironmentVariableItem, error) { - var items []*models.EnvironmentVariableItem - - files, err := cmd.Flags().GetStringArray("variables-file") - if err != nil { - return nil, err - } - for _, file := range files { - fileItems, err := parseEnvironmentVariablesFile(file) - if err != nil { - return nil, err - } - items = append(items, fileItems...) - } - - variables, err := cmd.Flags().GetStringArray("variable") - if err != nil { - return nil, err - } - for _, variable := range variables { - item, err := parseEnvironmentVariablePair(variable) - if err != nil { - return nil, err - } - items = append(items, item) - } - - return items, nil -} - -func parseEnvironmentVariablesFile(path string) ([]*models.EnvironmentVariableItem, error) { - content, err := os.ReadFile(path) - if err != nil { - return nil, fmt.Errorf("failed to read variables file %q: %w", path, err) - } - - var items []*models.EnvironmentVariableItem - if err := yaml.Unmarshal(content, &items); err != nil { - return nil, fmt.Errorf("failed to parse variables file %q: %w", path, err) - } - return items, nil -} - -func parseEnvironmentVariablePair(pair string) (*models.EnvironmentVariableItem, error) { - key, value, ok := strings.Cut(pair, "=") - if !ok || key == "" { - return nil, fmt.Errorf("invalid variable %q, expected KEY=VALUE", pair) - } - return &models.EnvironmentVariableItem{ - Key: ptr.Ptr(key), - Type: ptr.Ptr(models.EnvironmentVariableItemTypeString), - Value: value, - }, nil -} - -func AddEnvironmentOwnerFlag(cmd *cobra.Command) string { - return AddOwnerFlag(cmd) -} - -func GetEnvironmentOwner(cmd *cobra.Command) (string, error) { - return GetOwner(cmd) -} diff --git a/internal/cyargs/file.go b/internal/cyargs/file.go deleted file mode 100644 index 7e4d7b2db..000000000 --- a/internal/cyargs/file.go +++ /dev/null @@ -1,79 +0,0 @@ -package cyargs - -import ( - "fmt" - "os" - "strings" - - "github.com/spf13/cobra" -) - -func AddFSRecurseFlag(cmd *cobra.Command) string { - flagName := "recurse" - cmd.Flags().BoolP(flagName, "r", false, "will walk directories recursively if set") - return flagName -} - -func GetFSRecurseFlag(cmd *cobra.Command) (bool, error) { - return cmd.Flags().GetBool("recurse") -} - -func AddFSIgnoreFlag(cmd *cobra.Command) string { - flagName := "ignore" - cmd.Flags().StringArray( - flagName, []string{".git"}, - strings.Join([]string{ - "add glob pattern to ignore when using --recurse argument", - "can be specified multiple time", - }, "\n"), - ) - return flagName -} - -func GetFSIgnoreFlag(cmd *cobra.Command) ([]string, error) { - return cmd.Flags().GetStringArray("ignore") -} - -func ValidateFSArguments(cmd *cobra.Command, args []string) error { - recurse, _ := GetFSRecurseFlag(cmd) - for _, path := range args { - file, err := os.Stat(path) - if err != nil { - return fmt.Errorf("no file was found at path %q: %w", path, err) - } - - if file.IsDir() && !recurse { - return fmt.Errorf("path %q is a directory, add --recurse argument for walking directories", path) - } - } - - return nil -} - -// ValidFileArgs return an error if a file argument is invalid -// will validate the use of --recurse -func ValidFileArgs() cobra.PositionalArgs { - return ValidateFSArguments -} - -func AddInPlaceFlag(cmd *cobra.Command) string { - flagName := "in-place" - cmd.Flags().BoolP(flagName, "i", false, "inject values directly in the file in-place") - return flagName -} - -func GetInPlaceFlag(cmd *cobra.Command) (bool, error) { - return cmd.Flags().GetBool("in-place") -} - -func AddOutputDirectoryFlag(cmd *cobra.Command) string { - flagName := "directory" - cmd.Flags().StringP(flagName, "d", "", "add an output directory path") - cmd.MarkFlagDirname(flagName) - cmd.MarkFlagsMutuallyExclusive("in-place") - return flagName -} - -func GetOutputDirectoryFlag(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("directory") -} diff --git a/internal/cyargs/flags.go b/internal/cyargs/flags.go deleted file mode 100644 index 79f6b7614..000000000 --- a/internal/cyargs/flags.go +++ /dev/null @@ -1,27 +0,0 @@ -package cyargs - -import "github.com/spf13/cobra" - -// UpdateFlag is the canonical name for the upsert flag used by create/update commands. -const UpdateFlag = "update" - -// IsSet reports whether the user explicitly set a flag on the command. -func IsSet(cmd *cobra.Command, name string) bool { - return cmd.Flags().Changed(name) -} - -// AddUpdateFlag registers the boolean upsert flag and returns its name so -// callers can MarkFlag* without hardcoding the literal. -func AddUpdateFlag(cmd *cobra.Command, usage string) string { - if usage == "" { - usage = "update the resource if it already exists" - } - cmd.Flags().Bool(UpdateFlag, false, usage) - return UpdateFlag -} - -// GetUpdate returns the value of the upsert flag (false when not set). -func GetUpdate(cmd *cobra.Command) bool { - v, _ := cmd.Flags().GetBool(UpdateFlag) - return v -} diff --git a/internal/cyargs/global_flags.go b/internal/cyargs/global_flags.go deleted file mode 100644 index eb1c6be3d..000000000 --- a/internal/cyargs/global_flags.go +++ /dev/null @@ -1,39 +0,0 @@ -package cyargs - -import ( - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cycloidio/cycloid-cli/config" -) - -// GetOutput resolves the effective output format using this priority order: -// 1. --jq flag (sugar for jq=) -// 2. --output / -o flag (if explicitly set by the user on the CLI) -// 3. CY_OUTPUT environment variable (via viper AutomaticEnv) -// 4. Output field in the config file (~/.config/cycloid-cli/config.yaml) -// 5. "table" (built-in default) -func GetOutput(cmd *cobra.Command) (string, error) { - // 1. --jq takes precedence - if jqExpr, err := cmd.Flags().GetString("jq"); err == nil && jqExpr != "" { - return "jq=" + jqExpr, nil - } - - // 2. --output / -o explicitly set on CLI - if cmd.Flags().Changed("output") { - return cmd.Flags().GetString("output") - } - - // 3. CY_OUTPUT env var (viper AutomaticEnv maps CY_OUTPUT → "output") - if envOutput := viper.GetString("output"); envOutput != "" { - return envOutput, nil - } - - // 4. Config file - if conf, err := config.Read(); err == nil && conf.Output != "" { - return conf.Output, nil - } - - // 5. Default - return "table", nil -} diff --git a/internal/cyargs/licence.go b/internal/cyargs/licence.go deleted file mode 100644 index 8b34084af..000000000 --- a/internal/cyargs/licence.go +++ /dev/null @@ -1,95 +0,0 @@ -package cyargs - -import ( - "fmt" - "io" - "os" - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" -) - -func AddLicenceKeyFlag(cmd *cobra.Command) string { - flagName := "key" - cmd.Flags().String(flagName, "", "licence key value") - return flagName -} - -func AddLicenceKeyFileFlag(cmd *cobra.Command) string { - flagName := "key-file" - cmd.Flags().String(flagName, "", "path to a file containing the licence key") - cmd.RegisterFlagCompletionFunc(flagName, completeFilePath) - return flagName -} - -func AddLicenceFlag(cmd *cobra.Command) string { - flagName := "licence" - cmd.Flags().String(flagName, "", "licence key value") - return flagName -} - -func AddLicenceFileFlag(cmd *cobra.Command) string { - flagName := "licence-file" - cmd.Flags().String(flagName, "", "path to a file containing the licence key") - cmd.RegisterFlagCompletionFunc(flagName, completeFilePath) - return flagName -} - -func GetLicenceKey(cmd *cobra.Command) (string, error) { - return readSecretValue(cmd, "key", "key-file") -} - -func GetLicence(cmd *cobra.Command) (string, error) { - return readSecretValue(cmd, "licence", "licence-file") -} - -func readSecretValue(cmd *cobra.Command, valueFlag, fileFlag string) (string, error) { - value, err := cmd.Flags().GetString(valueFlag) - if err != nil { - return "", err - } - file, err := cmd.Flags().GetString(fileFlag) - if err != nil { - return "", err - } - - if value != "" && file != "" { - return "", fmt.Errorf("only one of --%s and --%s may be set", valueFlag, fileFlag) - } - if value != "" { - return strings.TrimSpace(value), nil - } - if file != "" { - content, err := os.ReadFile(file) - if err != nil { - return "", fmt.Errorf("failed to read licence from %q: %w", file, err) - } - key := strings.TrimSpace(string(content)) - if key == "" { - return "", fmt.Errorf("licence file %q is empty", file) - } - return key, nil - } - if common.DetectStdinInput() { - content, err := io.ReadAll(cmd.InOrStdin()) - if err != nil { - return "", fmt.Errorf("failed to read licence from stdin: %w", err) - } - key := strings.TrimSpace(string(content)) - if key == "" { - return "", fmt.Errorf("stdin looks empty, please provide a licence key") - } - return key, nil - } - - return "", fmt.Errorf( - "licence key required: pass --%s, --%s, or pipe the key via stdin", - valueFlag, fileFlag, - ) -} - -func completeFilePath(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - return nil, cobra.ShellCompDirectiveFilterFileExt -} diff --git a/internal/cyargs/members.go b/internal/cyargs/members.go deleted file mode 100644 index 58e03b81d..000000000 --- a/internal/cyargs/members.go +++ /dev/null @@ -1,110 +0,0 @@ -package cyargs - -import ( - "fmt" - "strconv" - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -// AddMemberIDFlag registers --id for member get/delete/update commands. -func AddMemberIDFlag(cmd *cobra.Command) string { - const flagName = "id" - cmd.Flags().Uint32(flagName, 0, "member id") - cmd.RegisterFlagCompletionFunc(flagName, CompleteMemberID) - return flagName -} - -func GetMemberID(cmd *cobra.Command) (uint32, error) { - return cmd.Flags().GetUint32("id") -} - -// AddMemberEmailFlag registers --email for member invite commands. -func AddMemberEmailFlag(cmd *cobra.Command) string { - const flagName = "email" - cmd.Flags().String(flagName, "", "member email address") - cmd.RegisterFlagCompletionFunc(flagName, CompleteMemberEmail) - return flagName -} - -func GetMemberEmail(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("email") -} - -// AddMemberRoleFlag registers --role for member invite/update commands. -// Completion lists available role canonicals. -func AddMemberRoleFlag(cmd *cobra.Command) string { - const flagName = "role" - cmd.Flags().String(flagName, "", "role canonical to assign to the member") - cmd.RegisterFlagCompletionFunc(flagName, CompleteRoleCanonical) - return flagName -} - -func GetMemberRole(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("role") -} - -func CompleteMemberID(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org for completion: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - members, _, err := m.ListMembers(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list members for completion: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, 0, len(members)) - for _, member := range members { - if member.ID == nil { - continue - } - idStr := strconv.Itoa(int(*member.ID)) - if strings.HasPrefix(idStr, toComplete) || toComplete == "" { - completions = append(completions, cobra.CompletionWithDesc(idStr, - fmt.Sprintf("(%s)", member.Email.String()), - )) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func CompleteMemberEmail(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org for completion: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - members, _, err := m.ListMembers(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list members for completion: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, 0, len(members)) - for _, member := range members { - emailStr := member.Email.String() - if strings.HasPrefix(emailStr, toComplete) || toComplete == "" { - completions = append(completions, cobra.CompletionWithDesc(emailStr, - fmt.Sprintf("(%s)", member.Username), - )) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} diff --git a/internal/cyargs/oidc.go b/internal/cyargs/oidc.go deleted file mode 100644 index 3ebf238da..000000000 --- a/internal/cyargs/oidc.go +++ /dev/null @@ -1,264 +0,0 @@ -package cyargs - -import ( - "os" - - "github.com/spf13/cobra" -) - -// OIDC flag names. Exported so commands can test cmd.Flags().Changed(...) for -// read-merge-write semantics on the full-replace settings endpoint. -const ( - OIDCGroupNameFlagName = "group-name" - OIDCMappingIDFlagName = "mapping-id" - OIDCManagedFlagName = "oidc-managed" - OIDCNoMatchPolicyFlagName = "no-match-policy" - OIDCDefaultRoleFlagName = "default-role" -) - -// AddOIDCGroupNameFlag registers --group-name for OIDC group mapping commands. -func AddOIDCGroupNameFlag(cmd *cobra.Command) string { - cmd.Flags().String(OIDCGroupNameFlagName, "", "OIDC group claim value to map") - return OIDCGroupNameFlagName -} - -// GetOIDCGroupName reads the --group-name flag. -func GetOIDCGroupName(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(OIDCGroupNameFlagName) -} - -// AddOIDCMappingIDFlag registers --mapping-id for OIDC group mapping delete. -func AddOIDCMappingIDFlag(cmd *cobra.Command) string { - cmd.Flags().Uint32(OIDCMappingIDFlagName, 0, "OIDC group mapping ID") - return OIDCMappingIDFlagName -} - -// GetOIDCMappingID reads the --mapping-id flag. -func GetOIDCMappingID(cmd *cobra.Command) (uint32, error) { - return cmd.Flags().GetUint32(OIDCMappingIDFlagName) -} - -// AddOIDCManagedFlag registers --oidc-managed for OIDC settings commands. -func AddOIDCManagedFlag(cmd *cobra.Command) string { - cmd.Flags().Bool(OIDCManagedFlagName, false, "make OIDC the authoritative source for org membership") - return OIDCManagedFlagName -} - -// GetOIDCManaged reads the --oidc-managed flag. -func GetOIDCManaged(cmd *cobra.Command) (bool, error) { - return cmd.Flags().GetBool(OIDCManagedFlagName) -} - -// AddOIDCNoMatchPolicyFlag registers --no-match-policy with fixed completions. -func AddOIDCNoMatchPolicyFlag(cmd *cobra.Command) string { - cmd.Flags().String(OIDCNoMatchPolicyFlagName, "", "action for members whose OIDC groups match no team (keep_membership|eject)") - _ = cmd.RegisterFlagCompletionFunc(OIDCNoMatchPolicyFlagName, - cobra.FixedCompletions( - []string{"keep_membership", "eject"}, - cobra.ShellCompDirectiveNoFileComp, - ), - ) - return OIDCNoMatchPolicyFlagName -} - -// GetOIDCNoMatchPolicy reads the --no-match-policy flag. -func GetOIDCNoMatchPolicy(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(OIDCNoMatchPolicyFlagName) -} - -// AddOIDCDefaultRoleFlag registers --default-role for OIDC settings. -// This is distinct from the per-member --role flag (AddMemberRoleFlag / AddRoleCanonicalFlag) -// because it configures the org-level default role granted to OIDC-provisioned members, and -// is only used on the settings subcommand. -func AddOIDCDefaultRoleFlag(cmd *cobra.Command) string { - cmd.Flags().String(OIDCDefaultRoleFlagName, "", "role canonical granted by default to OIDC-provisioned members (empty clears it)") - _ = cmd.RegisterFlagCompletionFunc(OIDCDefaultRoleFlagName, CompleteRoleCanonical) - return OIDCDefaultRoleFlagName -} - -// GetOIDCDefaultRole reads the --default-role flag. -func GetOIDCDefaultRole(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(OIDCDefaultRoleFlagName) -} - -// OIDC integration flag names. Exported so commands can test -// cmd.Flags().Changed() for read-merge-write semantics. -const ( - OIDCIssuerFlagName = "issuer" - OIDCClientIDFlagName = "client-id" - OIDCClientSecretFlagName = "client-secret" - OIDCDisplayNameFlagName = "display-name" - OIDCIconFlagName = "icon" - OIDCDiscoveryURLFlagName = "discovery-url" - OIDCGroupsClaimNameFlagName = "groups-claim-name" - OIDCSessionTTLSecondsFlagName = "session-ttl-seconds" - OIDCClientSecretJwtFlagName = "client-secret-jwt" - OIDCUseCaCertFlagName = "use-ca-cert" - OIDCCaCertFlagName = "ca-cert" - OIDCSkipTLSVerifyFlagName = "skip-tls-verify" - OIDCAllowInsecureDiscoveryFlagName = "allow-insecure-discovery" - OIDCEnabledFlagName = "enabled" - OIDCAdoptManualMembersFlagName = "adopt-manual-members" -) - -// AddOIDCIssuerFlag registers --issuer for OIDC integration commands. -func AddOIDCIssuerFlag(cmd *cobra.Command) { - cmd.Flags().String(OIDCIssuerFlagName, "", "OIDC issuer URL") -} - -// GetOIDCIssuer reads the --issuer flag. -func GetOIDCIssuer(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(OIDCIssuerFlagName) -} - -// AddOIDCClientIDFlag registers --client-id for OIDC integration commands. -func AddOIDCClientIDFlag(cmd *cobra.Command) { - cmd.Flags().String(OIDCClientIDFlagName, "", "OIDC client ID") -} - -// GetOIDCClientID reads the --client-id flag. -func GetOIDCClientID(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(OIDCClientIDFlagName) -} - -// AddOIDCClientSecretFlag registers --client-secret for OIDC integration commands. -// The secret can also be supplied via the CY_OIDC_CLIENT_SECRET environment variable. -func AddOIDCClientSecretFlag(cmd *cobra.Command) { - cmd.Flags().String(OIDCClientSecretFlagName, "", "OIDC client secret (also read from CY_OIDC_CLIENT_SECRET env var)") -} - -// GetOIDCClientSecret returns the OIDC client secret: flag value if the flag was -// explicitly set, otherwise the CY_OIDC_CLIENT_SECRET environment variable. -// An empty string means "no secret supplied" — the backend then preserves the -// stored secret unchanged. -func GetOIDCClientSecret(cmd *cobra.Command) (string, error) { - if cmd.Flags().Changed(OIDCClientSecretFlagName) { - return cmd.Flags().GetString(OIDCClientSecretFlagName) - } - return os.Getenv("CY_OIDC_CLIENT_SECRET"), nil -} - -// AddOIDCDisplayNameFlag registers --display-name for OIDC integration commands. -func AddOIDCDisplayNameFlag(cmd *cobra.Command) { - cmd.Flags().String(OIDCDisplayNameFlagName, "", "Display name shown on the OIDC login button") -} - -// GetOIDCDisplayName reads the --display-name flag. -func GetOIDCDisplayName(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(OIDCDisplayNameFlagName) -} - -// AddOIDCIconFlag registers --icon for OIDC integration commands. -func AddOIDCIconFlag(cmd *cobra.Command) { - cmd.Flags().String(OIDCIconFlagName, "", "Icon URL for the OIDC login button") -} - -// GetOIDCIcon reads the --icon flag. -func GetOIDCIcon(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(OIDCIconFlagName) -} - -// AddOIDCDiscoveryURLFlag registers --discovery-url for OIDC integration commands. -func AddOIDCDiscoveryURLFlag(cmd *cobra.Command) { - cmd.Flags().String(OIDCDiscoveryURLFlagName, "", "OIDC discovery (well-known) URL (overrides issuer-derived URL when set)") -} - -// GetOIDCDiscoveryURL reads the --discovery-url flag. -func GetOIDCDiscoveryURL(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(OIDCDiscoveryURLFlagName) -} - -// AddOIDCGroupsClaimNameFlag registers --groups-claim-name for OIDC integration commands. -func AddOIDCGroupsClaimNameFlag(cmd *cobra.Command) { - cmd.Flags().String(OIDCGroupsClaimNameFlagName, "", "JWT claim name that carries the user's group memberships") -} - -// GetOIDCGroupsClaimName reads the --groups-claim-name flag. -func GetOIDCGroupsClaimName(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(OIDCGroupsClaimNameFlagName) -} - -// AddOIDCSessionTTLSecondsFlag registers --session-ttl-seconds for OIDC integration commands. -func AddOIDCSessionTTLSecondsFlag(cmd *cobra.Command) { - cmd.Flags().Int64(OIDCSessionTTLSecondsFlagName, 0, "OIDC session lifetime in seconds (0 uses provider default)") -} - -// GetOIDCSessionTTLSeconds reads the --session-ttl-seconds flag. -func GetOIDCSessionTTLSeconds(cmd *cobra.Command) (int64, error) { - return cmd.Flags().GetInt64(OIDCSessionTTLSecondsFlagName) -} - -// AddOIDCClientSecretJwtFlag registers --client-secret-jwt for OIDC integration commands. -func AddOIDCClientSecretJwtFlag(cmd *cobra.Command) { - cmd.Flags().Bool(OIDCClientSecretJwtFlagName, false, "Use client_secret_jwt authentication method") -} - -// GetOIDCClientSecretJwt reads the --client-secret-jwt flag. -func GetOIDCClientSecretJwt(cmd *cobra.Command) (bool, error) { - return cmd.Flags().GetBool(OIDCClientSecretJwtFlagName) -} - -// AddOIDCUseCaCertFlag registers --use-ca-cert for OIDC integration commands. -func AddOIDCUseCaCertFlag(cmd *cobra.Command) { - cmd.Flags().Bool(OIDCUseCaCertFlagName, false, "Validate the OIDC provider's TLS certificate against the configured CA cert") -} - -// GetOIDCUseCaCert reads the --use-ca-cert flag. -func GetOIDCUseCaCert(cmd *cobra.Command) (bool, error) { - return cmd.Flags().GetBool(OIDCUseCaCertFlagName) -} - -// AddOIDCCaCertFlag registers --ca-cert for OIDC integration commands. -// The CA cert can also be supplied via the CY_OIDC_CA_CERT environment variable. -func AddOIDCCaCertFlag(cmd *cobra.Command) { - cmd.Flags().String(OIDCCaCertFlagName, "", "PEM-encoded CA certificate for the OIDC provider (also read from CY_OIDC_CA_CERT env var)") -} - -// GetOIDCCaCert returns the CA certificate PEM: flag value if explicitly set, -// otherwise the CY_OIDC_CA_CERT environment variable. -func GetOIDCCaCert(cmd *cobra.Command) (string, error) { - if cmd.Flags().Changed(OIDCCaCertFlagName) { - return cmd.Flags().GetString(OIDCCaCertFlagName) - } - return os.Getenv("CY_OIDC_CA_CERT"), nil -} - -// AddOIDCSkipTLSVerifyFlag registers --skip-tls-verify for OIDC integration commands. -func AddOIDCSkipTLSVerifyFlag(cmd *cobra.Command) { - cmd.Flags().Bool(OIDCSkipTLSVerifyFlagName, false, "Skip TLS certificate verification for the OIDC provider (insecure)") -} - -// GetOIDCSkipTLSVerify reads the --skip-tls-verify flag. -func GetOIDCSkipTLSVerify(cmd *cobra.Command) (bool, error) { - return cmd.Flags().GetBool(OIDCSkipTLSVerifyFlagName) -} - -// AddOIDCAllowInsecureDiscoveryFlag registers --allow-insecure-discovery for OIDC integration commands. -func AddOIDCAllowInsecureDiscoveryFlag(cmd *cobra.Command) { - cmd.Flags().Bool(OIDCAllowInsecureDiscoveryFlagName, false, "Allow fetching the OIDC discovery document over HTTP (insecure)") -} - -// GetOIDCAllowInsecureDiscovery reads the --allow-insecure-discovery flag. -func GetOIDCAllowInsecureDiscovery(cmd *cobra.Command) (bool, error) { - return cmd.Flags().GetBool(OIDCAllowInsecureDiscoveryFlagName) -} - -// AddOIDCEnabledFlag registers --enabled for OIDC integration commands. -func AddOIDCEnabledFlag(cmd *cobra.Command) { - cmd.Flags().Bool(OIDCEnabledFlagName, false, "Enable or disable the OIDC SSO integration (use --enabled=false to disable)") -} - -// GetOIDCEnabled reads the --enabled flag. -func GetOIDCEnabled(cmd *cobra.Command) (bool, error) { - return cmd.Flags().GetBool(OIDCEnabledFlagName) -} - -// AddOIDCAdoptManualMembersFlag registers --adopt-manual-members for OIDC integration commands. -func AddOIDCAdoptManualMembersFlag(cmd *cobra.Command) { - cmd.Flags().Bool(OIDCAdoptManualMembersFlagName, false, "Adopt manually-invited members on OIDC login (flips their source to 'oidc' so group mapping manages them)") -} - -// GetOIDCAdoptManualMembers reads the --adopt-manual-members flag. -func GetOIDCAdoptManualMembers(cmd *cobra.Command) (bool, error) { - return cmd.Flags().GetBool(OIDCAdoptManualMembersFlagName) -} diff --git a/internal/cyargs/organizations.go b/internal/cyargs/organizations.go deleted file mode 100644 index 89fe3b70a..000000000 --- a/internal/cyargs/organizations.go +++ /dev/null @@ -1,190 +0,0 @@ -package cyargs - -import ( - "encoding/json" - "fmt" - "io" - "os" - "strings" - - "github.com/spf13/cobra" - "go.yaml.in/yaml/v4" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -func AddOrgNameFlag(cmd *cobra.Command) string { - flagName := "name" - cmd.Flags().StringP(flagName, "n", "", "the organization's name") - return flagName -} - -func GetOrgName(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("name") -} - -func CompleteOrg(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := GetOrg(cmd) - if err != nil { - return []string{}, cobra.ShellCompDirectiveNoFileComp - } - - orgs, _, err := m.ListOrganizationChildrens(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list orgs for completion: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, len(orgs)) - for index, org := range orgs { - if org.Canonical != nil && strings.HasPrefix(*org.Canonical, toComplete) { - completions[index] = cobra.CompletionWithDesc(*org.Canonical, *org.Name) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func AddOrgChildOfFlag(cmd *cobra.Command) string { - flagName := "parent-canonical" - cmd.Flags().StringP(flagName, "p", "", "the parent organization canonical") - cmd.RegisterFlagCompletionFunc(flagName, CompleteOrg) - return flagName -} - -func GetOrgParentCanonical(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("parent-canonical") -} - -func AddRoleCanonicalFlag(cmd *cobra.Command) string { - flagName := "role" - cmd.Flags().StringP(flagName, "r", "", "the role canonical") - cmd.RegisterFlagCompletionFunc(flagName, CompleteRoleCanonical) - return flagName -} - -func GetRoleCanonical(cmd *cobra.Command) (string, error) { - roleFlag, err := cmd.Flags().GetString("role") - if err != nil { - return "", err - } - if roleFlag != "" { - return roleFlag, nil - } - - // TODO: remove next release - // Support for the old flag, deprecated - can, err := cmd.Flags().GetString("canonical") - if err != nil { - return "", err - } - - return can, nil -} - -func CompleteRoleCanonical(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list role, missing org for completion "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - roles, _, err := m.ListRoles(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list roles, "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, len(roles)) - for i, role := range roles { - completions[i] = *role.Canonical - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func AddRoleNameFlag(cmd *cobra.Command) string { - flagName := "name" - cmd.Flags().String(flagName, "", "The name of the role") - return flagName -} - -func AddRoleRulesJSONFlag(cmd *cobra.Command) string { - flagName := "rule-json" - cmd.Flags().StringArrayP(flagName, "j", []string{}, - `a JSON string representing a list of rules, spec: {"action": "string", "effect": "string", "resources": ["string"]}`, - ) - return flagName -} - -func AddRoleRulesFilesFlag(cmd *cobra.Command) string { - flagName := "rule-file" - cmd.Flags().StringArrayP(flagName, "f", []string{}, - `path to a YAML or JSON file (use "-" to read from stdin) containing a list of rules, spec: '[{"action": "string", "effect": "string", "resources": ["strings"]}]'`, - ) - cmd.MarkFlagFilename(flagName, "json", "yaml") - return flagName -} - -func GetRoleName(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("name") -} - -func GetRoleRulesJSON(cmd *cobra.Command) ([]*models.NewRule, error) { - rulesJSON, err := cmd.Flags().GetStringArray("rule-json") - if err != nil { - return nil, err - } - - var rules = make([]*models.NewRule, len(rulesJSON)) - for i, ruleJSON := range rulesJSON { - var rule models.NewRule - err := json.Unmarshal([]byte(ruleJSON), &rule) - if err != nil { - return nil, fmt.Errorf("failed to parse JSON: %s, as rule: %w", ruleJSON, err) - } - - rules[i] = &rule - } - - return rules, nil -} - -func GetRoleRulesFiles(cmd *cobra.Command) ([]*models.NewRule, error) { - rulesFiles, err := cmd.Flags().GetStringArray("rule-file") - if err != nil { - return nil, err - } - - var rules = []*models.NewRule{} - for _, ruleFile := range rulesFiles { - var content []byte - if ruleFile == "-" && common.DetectStdinInput() { - ruleFile = "stdin" - content, err = io.ReadAll(cmd.InOrStdin()) - if err != nil { - return nil, fmt.Errorf("failed to read rule from stdin %q: %w", ruleFile, err) - } - } else { - content, err = os.ReadFile(ruleFile) - if err != nil { - return nil, fmt.Errorf("failed to read rule file %q: %w", ruleFile, err) - } - } - - var fileRules []*models.NewRule - err = yaml.Unmarshal(content, &fileRules) - if err != nil { - return nil, fmt.Errorf("failed to decode file content from %q: %w", ruleFile, err) - } - - rules = append(rules, fileRules...) - } - - return rules, nil -} diff --git a/internal/cyargs/pipelines_jobs_build.go b/internal/cyargs/pipelines_jobs_build.go deleted file mode 100644 index f8dbc5d9f..000000000 --- a/internal/cyargs/pipelines_jobs_build.go +++ /dev/null @@ -1,258 +0,0 @@ -package cyargs - -import ( - "fmt" - "slices" - "strconv" - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -var ( - validPipelineStatuses = []string{ - "aborted", - "errored", - "failed", - "paused", - "pending", - "started", - "succeeded", - } -) - -func AddPipelineStatuses(cmd *cobra.Command) string { - flagName := "statuses" - cmd.Flags().StringSliceP( - flagName, "S", validPipelineStatuses, - fmt.Sprintf("filter per status for pipelines. valid options are [%s]", strings.Join(validPipelineStatuses, ", ")), - ) - - cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []cobra.Completion, toComplete string) ([]string, cobra.ShellCompDirective) { - var completions []cobra.Completion - for _, status := range validPipelineStatuses { - if strings.HasPrefix(status, toComplete) { - completions = append(completions, status) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp - }) - return flagName -} - -func GetPipelineStatuses(cmd *cobra.Command) ([]string, error) { - statuses, err := cmd.Flags().GetStringSlice("statuses") - if err != nil { - return []string{}, err - } - - return statuses, nil -} - -func AddPipeline(cmd *cobra.Command) string { - flagName := "pipeline" - cmd.Flags().StringP(flagName, "P", "", "the name of a pipeline") - cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []cobra.Completion, toComplete string) ([]string, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org parameter for completion"), - cobra.ShellCompDirectiveNoFileComp - } - - project, _ := GetProject(cmd) - env, _ := GetEnv(cmd) - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - pipelines, _, err := m.GetEnvPipelines(org, project, env) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to fetch pipeline list for completion in org '"+org+"': "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var names = make([]cobra.Completion, len(pipelines)) - for index, pipeline := range pipelines { - if pipeline.Name != nil && strings.HasPrefix(*pipeline.Name, toComplete) { - names[index] = cobra.CompletionWithDesc(*pipeline.Name, - strings.Join([]string{*pipeline.Project.Name, pipeline.Environment.Name, *pipeline.Component.Name}, " > "), - ) - } - } - - return names, cobra.ShellCompDirectiveNoFileComp - }) - - return flagName -} - -func GetPipeline(cmd *cobra.Command) (string, error) { - pipeline, err := cmd.Flags().GetString("pipeline") - if pipeline != "" && err != nil { - return pipeline, nil - } - - // If pipeline not set, try to get it from the component - org, project, environment, component, err := GetCyContext(cmd) - if err != nil { - return "", fmt.Errorf("missing context to infer pipeline, set --pipeline flag or fill org/project/env/component: %w", err) - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - pipelines, _, err := m.GetEnvPipelines(org, project, environment) - if err != nil { - return "", fmt.Errorf("failed to infer pipeline from context: %w", err) - } - - index := slices.IndexFunc(pipelines, func(p *models.Pipeline) bool { - return *p.Component.Canonical == component - }) - - if index == -1 { - return "", fmt.Errorf("pipeline for component %q in project %q and environment %q is not found, please fill --pipeline argument: %w", component, project, environment, err) - } - - return *pipelines[index].Name, nil -} - -func AddPipelineConfig(cmd *cobra.Command) string { - flagName := "pipeline-config" - cmd.Flags().StringP(flagName, "C", "pipeline.yml", "path to the pipeline config file.") - cmd.MarkFlagFilename("pipeline-config", "yml", "yaml") - return flagName -} - -func GetPipelineConfig(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("pipeline-config") -} - -func AddPipelineVars(cmd *cobra.Command) string { - flagName := "pipeline-vars" - cmd.Flags().StringP(flagName, "V", "variables.sample.yml", "path to the pipeline variable file.") - cmd.MarkFlagFilename("pipeline-vars", "yml", "yaml") - return flagName -} - -func GetPipelineVars(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("pipeline-vars") -} - -func AddPipelineJob(cmd *cobra.Command) string { - flagName := "job" - cmd.Flags().StringP(flagName, "j", "", "job canonical.") - cmd.RegisterFlagCompletionFunc("job", func(cmd *cobra.Command, args []cobra.Completion, toComplete string) ([]string, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org parameter for completion"), - cobra.ShellCompDirectiveNoFileComp - } - - project, _ := GetProject(cmd) - env, _ := GetEnv(cmd) - component, _ := GetEnv(cmd) - pipeline, _ := GetPipeline(cmd) - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - jobs, _, err := m.GetJobs(org, project, env, component, pipeline) - if err != nil { - return cobra.AppendActiveHelp(nil, fmt.Sprintf( - "failed to fetch job list for completion with context org: %s, project: %s, env: %s, component: %s, pipeline: %s, err: %s", - org, project, env, component, pipeline, err, - )), - cobra.ShellCompDirectiveNoFileComp - } - - jobNames := make([]cobra.Completion, len(jobs)) - for index, job := range jobs { - if job.Name != nil && strings.HasPrefix(*job.Name, toComplete) { - jobNames[index] = cobra.CompletionWithDesc(*job.Name, strconv.Itoa(int(*job.ID))) - } - } - - return jobNames, cobra.ShellCompDirectiveNoFileComp - }) - - return flagName -} - -func GetPipelineJob(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("job") -} - -func AddPipelineStep(cmd *cobra.Command) string { - flagName := "step" - cmd.Flags().StringP(flagName, "s", "", "step canonical.") - return flagName -} - -func GetPipelineStep(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("step") -} - -func AddPipelineBuildID(cmd *cobra.Command) string { - flagName := "build-id" - cmd.Flags().StringP(flagName, "b", "", "the concourse build id") - cmd.RegisterFlagCompletionFunc( - flagName, - func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org parameter for completion"), - cobra.ShellCompDirectiveNoFileComp - } - - project, _ := GetProject(cmd) - env, _ := GetEnv(cmd) - component, _ := GetEnv(cmd) - pipeline, _ := GetPipeline(cmd) - job, _ := GetPipelineJob(cmd) - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - builds, _, err := m.GetBuilds(org, project, env, component, pipeline, job) - if err != nil { - return cobra.AppendActiveHelp(nil, fmt.Sprintf( - "failed to fetch job list for completion with context org: %s, project: %s, env: %s, component: %s, pipeline: %s, job: %s err: %s", - org, project, env, component, pipeline, job, err, - )), cobra.ShellCompDirectiveNoFileComp - } - - buildIDs := make([]cobra.Completion, len(builds)) - for index, build := range builds { - if build.ID != nil { - buildStr := strconv.Itoa(int(*build.ID)) - if strings.HasPrefix(buildStr, toComplete) { - var buildName string - if build.Name != nil { - buildName = *build.Name - } - - buildIDs[index] = cobra.CompletionWithDesc( - buildStr, - fmt.Sprintf( - "%s from %s started at %s.", - buildName, build.JobName, common.UnixTimestampToLocalTime(&build.StartTime), - ), - ) - } - } - } - - return buildIDs, cobra.ShellCompDirectiveNoFileComp - }, - ) - - return flagName -} - -func GetPipelineBuildID(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("build-id") -} diff --git a/internal/cyargs/plugins.go b/internal/cyargs/plugins.go deleted file mode 100644 index 7412d8301..000000000 --- a/internal/cyargs/plugins.go +++ /dev/null @@ -1,491 +0,0 @@ -package cyargs - -import ( - "encoding/json" - "fmt" - "os" - "strconv" - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" -) - -// --------------------------------------------------------------------------- -// Registry context flag (--registry, used by plugin and version subcommands) -// --------------------------------------------------------------------------- - -// AddRegistryFlag registers a --registry flag and returns the flag name for use -// with MarkFlagRequired. -func AddRegistryFlag(cmd *cobra.Command) string { - cmd.Flags().String("registry", "", "plugin registry name, ID, or URL") - return "registry" -} - -// GetRegistry reads the --registry flag value. -func GetRegistry(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("registry") -} - -// --------------------------------------------------------------------------- -// Plugin context flag (--plugin, used by version subcommands) -// --------------------------------------------------------------------------- - -// AddPluginFlag registers a --plugin flag and returns the flag name for use -// with MarkFlagRequired. -func AddPluginFlag(cmd *cobra.Command) string { - cmd.Flags().String("plugin", "", "plugin name or ID within the registry") - return "plugin" -} - -// GetPlugin reads the --plugin flag value. -func GetPlugin(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("plugin") -} - -// --------------------------------------------------------------------------- -// URL flag (registry add, manager create, version publish) -// --------------------------------------------------------------------------- - -// AddURLFlag registers a --url flag with the given usage description. -func AddURLFlag(cmd *cobra.Command, usage string) { - cmd.Flags().String("url", "", usage) -} - -// GetURL returns the value of the --url flag. -func GetURL(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("url") -} - -// --------------------------------------------------------------------------- -// Plugin version ID flag (for install / upgrade) -// --------------------------------------------------------------------------- - -// AddPluginVersionIDFlag registers an optional --version-id uint32 flag. -func AddPluginVersionIDFlag(cmd *cobra.Command) { - cmd.Flags().Uint32("version-id", 0, "ID of the target plugin version") -} - -// GetPluginVersionID reads the --version-id flag. -// Returns nil if the flag was not set (zero value means unset). -func GetPluginVersionID(cmd *cobra.Command) (*uint32, error) { - v, err := cmd.Flags().GetUint32("version-id") - if err != nil { - return nil, err - } - if v == 0 { - return nil, nil - } - return &v, nil -} - -// --------------------------------------------------------------------------- -// Docker image flag (for version publish) -// --------------------------------------------------------------------------- - -// AddDockerImageFlag registers a --docker-image string flag. -func AddDockerImageFlag(cmd *cobra.Command) { - cmd.Flags().String("docker-image", "", "Docker image reference for the plugin version (e.g. registry:5000/org/plugin:tag)") -} - -// GetDockerImage returns the value of the --docker-image flag. -func GetDockerImage(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("docker-image") -} - -// --------------------------------------------------------------------------- -// Plugin config flags (for install / upgrade) -// --------------------------------------------------------------------------- - -// AddPluginConfigFlags registers --config key=val and --config-file path.json. -func AddPluginConfigFlags(cmd *cobra.Command) { - cmd.Flags().StringToString("config", nil, "plugin configuration as key=value pairs. Can be specified multiple times.") - cmd.Flags().StringP("config-file", "f", "", "path to a JSON file containing plugin configuration (map of string to string)") - cmd.MarkFlagFilename("config-file", "json") -} - -// GetPluginConfig reads and merges plugin configuration from --config-file (base) -// and --config key=val overrides. -func GetPluginConfig(cmd *cobra.Command) (map[string]string, error) { - result := make(map[string]string) - - filename, err := cmd.Flags().GetString("config-file") - if err != nil { - return nil, err - } - if filename != "" { - data, err := os.ReadFile(filename) - if err != nil { - return nil, fmt.Errorf("reading --config-file %q: %w", filename, err) - } - if err := json.Unmarshal(data, &result); err != nil { - return nil, fmt.Errorf("parsing --config-file %q as JSON object: %w", filename, err) - } - } - - kvPairs, err := cmd.Flags().GetStringToString("config") - if err != nil { - return nil, err - } - for k, v := range kvPairs { - result[k] = v - } - - return result, nil -} - -// --------------------------------------------------------------------------- -// Plugin install ID resolution + completion -// --------------------------------------------------------------------------- - -// CompletePluginInstallID offers both numeric-ID and name-based completions. -// The shell inserts the selected value; RunE resolves names to IDs via ResolvePluginInstallID. -func CompletePluginInstallID(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - m := middleware.NewMiddleware(common.NewAPI()) - plugins, _, err := m.ListPlugins(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list plugins: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, 0, len(plugins)*2) - for _, p := range plugins { - if p.Install == nil || p.Install.ID == nil { - continue - } - idStr := strconv.Itoa(int(*p.Install.ID)) - status := "" - if p.Install.Status != nil { - status = *p.Install.Status - } - name := idStr - if p.Name != nil { - name = *p.Name - } - completions = append(completions, - cobra.CompletionWithDesc(idStr, fmt.Sprintf("%s (%s)", name, status)), - cobra.CompletionWithDesc(name, fmt.Sprintf("id:%s (%s)", idStr, status)), - ) - } - return completions, cobra.ShellCompDirectiveNoFileComp -} - -// ResolvePluginInstallID resolves a numeric ID string or name to a uint32 plugin install ID. -// The install ID lives at Plugin.Install.ID (not Plugin.ID which is the registry plugin ID). -func ResolvePluginInstallID(org, nameOrID string, m middleware.Middleware) (uint32, error) { - if id, err := strconv.ParseUint(nameOrID, 10, 32); err == nil { - return uint32(id), nil - } - plugins, _, err := m.ListPlugins(org) - if err != nil { - return 0, fmt.Errorf("listing plugins to resolve %q: %w", nameOrID, err) - } - var matches []uint32 - for _, p := range plugins { - if p.Install == nil || p.Install.ID == nil { - continue - } - if p.Name != nil && *p.Name == nameOrID { - matches = append(matches, *p.Install.ID) - } - } - return resolveUnique("plugin install", nameOrID, matches) -} - -// --------------------------------------------------------------------------- -// Plugin manager ID resolution + completion -// --------------------------------------------------------------------------- - -// CompletePluginManagerID offers both ID and name completions for plugin managers. -func CompletePluginManagerID(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - m := middleware.NewMiddleware(common.NewAPI()) - managers, _, err := m.ListPluginManagers(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list plugin managers: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, 0, len(managers)*2) - for _, pm := range managers { - if pm.ID == nil || pm.Name == nil || pm.Status == nil { - continue - } - idStr := strconv.Itoa(int(*pm.ID)) - name := *pm.Name - status := *pm.Status - completions = append(completions, - cobra.CompletionWithDesc(idStr, fmt.Sprintf("%s (%s)", name, status)), - cobra.CompletionWithDesc(name, fmt.Sprintf("id:%s (%s)", idStr, status)), - ) - } - return completions, cobra.ShellCompDirectiveNoFileComp -} - -// ResolvePluginManagerID resolves a numeric ID, name, or URL to a plugin manager ID. -func ResolvePluginManagerID(org, nameOrID string, m middleware.Middleware) (uint32, error) { - if id, err := strconv.ParseUint(nameOrID, 10, 32); err == nil { - return uint32(id), nil - } - managers, _, err := m.ListPluginManagers(org) - if err != nil { - return 0, fmt.Errorf("listing plugin managers to resolve %q: %w", nameOrID, err) - } - var matches []uint32 - for _, pm := range managers { - if pm.ID == nil { - continue - } - if (pm.Name != nil && *pm.Name == nameOrID) || - (pm.URL != nil && pm.URL.String() == nameOrID) { - matches = append(matches, *pm.ID) - } - } - return resolveUnique("plugin manager", nameOrID, matches) -} - -// --------------------------------------------------------------------------- -// Plugin registry ID resolution + completion -// --------------------------------------------------------------------------- - -// CompletePluginRegistryID offers ID, name, and URL completions for plugin registries. -func CompletePluginRegistryID(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - m := middleware.NewMiddleware(common.NewAPI()) - registries, _, err := m.ListPluginRegistries(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list plugin registries: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, 0, len(registries)*3) - for _, r := range registries { - if r.ID == nil || r.Name == nil || r.Status == nil { - continue - } - idStr := strconv.Itoa(int(*r.ID)) - name := *r.Name - status := *r.Status - urlStr := "" - if r.URL != nil { - urlStr = r.URL.String() - } - completions = append(completions, - cobra.CompletionWithDesc(idStr, fmt.Sprintf("%s (%s)", name, status)), - cobra.CompletionWithDesc(name, fmt.Sprintf("id:%s (%s)", idStr, status)), - ) - if urlStr != "" { - completions = append(completions, - cobra.CompletionWithDesc(urlStr, fmt.Sprintf("%s id:%s (%s)", name, idStr, status)), - ) - } - } - return completions, cobra.ShellCompDirectiveNoFileComp -} - -// ResolvePluginRegistryID resolves a numeric ID, name, or URL to a plugin registry ID. -// URL matching is tried when the value starts with "http". -func ResolvePluginRegistryID(org, nameOrID string, m middleware.Middleware) (uint32, error) { - if id, err := strconv.ParseUint(nameOrID, 10, 32); err == nil { - return uint32(id), nil - } - registries, _, err := m.ListPluginRegistries(org) - if err != nil { - return 0, fmt.Errorf("listing plugin registries to resolve %q: %w", nameOrID, err) - } - isURL := strings.HasPrefix(nameOrID, "http") - var matches []uint32 - for _, r := range registries { - if r.ID == nil { - continue - } - if isURL { - if r.URL != nil && r.URL.String() == nameOrID { - matches = append(matches, *r.ID) - } - } else { - if r.Name != nil && *r.Name == nameOrID { - matches = append(matches, *r.ID) - } - } - } - return resolveUnique("plugin registry", nameOrID, matches) -} - -// CompletePluginIDFromRegistryFlag completes plugin names/IDs by reading the registry -// from the --registry flag rather than positional args. -func CompletePluginIDFromRegistryFlag(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - registryStr, _ := cmd.Flags().GetString("registry") - if registryStr == "" { - return cobra.AppendActiveHelp(nil, "provide --registry first"), cobra.ShellCompDirectiveNoFileComp - } - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - m := middleware.NewMiddleware(common.NewAPI()) - registryID, err := ResolvePluginRegistryID(org, registryStr, m) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to resolve registry: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - plugins, _, err := m.ListRegistryPlugins(org, registryID) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list plugins: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - completions := make([]cobra.Completion, 0, len(plugins)*2) - for _, p := range plugins { - if p.ID == nil || p.Name == nil { - continue - } - idStr := strconv.Itoa(int(*p.ID)) - completions = append(completions, - cobra.CompletionWithDesc(idStr, *p.Name), - cobra.CompletionWithDesc(*p.Name, "id:"+idStr), - ) - } - return completions, cobra.ShellCompDirectiveNoFileComp -} - -// CompletePluginVersionID completes version IDs by reading registry and plugin from flags. -func CompletePluginVersionID(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - registryStr, _ := cmd.Flags().GetString("registry") - pluginStr, _ := cmd.Flags().GetString("plugin") - if registryStr == "" || pluginStr == "" { - return cobra.AppendActiveHelp(nil, "provide --registry and --plugin first"), cobra.ShellCompDirectiveNoFileComp - } - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - m := middleware.NewMiddleware(common.NewAPI()) - registryID, err := ResolvePluginRegistryID(org, registryStr, m) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to resolve registry: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - pluginID, err := ResolveRegistryPluginID(org, registryID, pluginStr, m) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to resolve plugin: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - versions, _, err := m.ListPluginVersions(org, registryID, pluginID) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list versions: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - completions := make([]cobra.Completion, 0, len(versions)) - for _, v := range versions { - if v.ID == nil { - continue - } - idStr := strconv.Itoa(int(*v.ID)) - desc := "" - if v.Status != nil { - desc = *v.Status - } - completions = append(completions, cobra.CompletionWithDesc(idStr, desc)) - } - return completions, cobra.ShellCompDirectiveNoFileComp -} - -// CompleteRegistryPluginID offers ID and name completions for plugins within a registry. -// The registry must already be resolved from args[0]. -func CompleteRegistryPluginID(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - if len(args) < 1 { - return cobra.AppendActiveHelp(nil, "registry ID or name required first"), cobra.ShellCompDirectiveNoFileComp - } - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - m := middleware.NewMiddleware(common.NewAPI()) - registryID, err := ResolvePluginRegistryID(org, args[0], m) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to resolve registry: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - plugins, _, err := m.ListRegistryPlugins(org, registryID) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list registry plugins: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, 0, len(plugins)*2) - for _, p := range plugins { - if p.ID == nil || p.Name == nil { - continue - } - idStr := strconv.Itoa(int(*p.ID)) - name := *p.Name - completions = append(completions, - cobra.CompletionWithDesc(idStr, name), - cobra.CompletionWithDesc(name, "id:"+idStr), - ) - } - return completions, cobra.ShellCompDirectiveNoFileComp -} - -// ResolveRegistryPluginID resolves a numeric ID or name to a plugin ID within a registry. -func ResolveRegistryPluginID(org string, registryID uint32, nameOrID string, m middleware.Middleware) (uint32, error) { - if id, err := strconv.ParseUint(nameOrID, 10, 32); err == nil { - return uint32(id), nil - } - plugins, _, err := m.ListRegistryPlugins(org, registryID) - if err != nil { - return 0, fmt.Errorf("listing registry plugins to resolve %q: %w", nameOrID, err) - } - var matches []uint32 - for _, p := range plugins { - if p.ID == nil { - continue - } - if p.Name != nil && *p.Name == nameOrID { - matches = append(matches, *p.ID) - } - } - return resolveUnique("registry plugin", nameOrID, matches) -} - -// --------------------------------------------------------------------------- -// Internal helpers -// --------------------------------------------------------------------------- - -// noMatchPrefix is the sentinel prefix used by resolveUnique for not-found errors. -const noMatchPrefix = "no " - -// resolveUnique returns the single ID from matches, or a descriptive error. -// Not-found errors are detectable via IsNoMatchError. -func resolveUnique(kind, nameOrID string, matches []uint32) (uint32, error) { - switch len(matches) { - case 0: - return 0, fmt.Errorf(noMatchPrefix+"%s found matching %q; use a numeric ID or check spelling", kind, nameOrID) - case 1: - return matches[0], nil - default: - ids := make([]string, len(matches)) - for i, id := range matches { - ids[i] = strconv.Itoa(int(id)) - } - return 0, fmt.Errorf( - "%q matches %d %ss (IDs: %s); use a numeric ID to disambiguate", - nameOrID, len(matches), kind, strings.Join(ids, ", "), - ) - } -} - -// IsNoMatchError reports whether err is a "not found" error from resolveUnique. -func IsNoMatchError(err error) bool { - if err == nil { - return false - } - return strings.HasPrefix(err.Error(), noMatchPrefix) -} diff --git a/internal/cyargs/repositories.go b/internal/cyargs/repositories.go deleted file mode 100644 index 769ebc958..000000000 --- a/internal/cyargs/repositories.go +++ /dev/null @@ -1,51 +0,0 @@ -package cyargs - -import ( - "github.com/spf13/cobra" -) - -// AddRepoBranchFlag registers --branch for catalog/config repository commands. -func AddRepoBranchFlag(cmd *cobra.Command) string { - const flagName = "branch" - cmd.Flags().String(flagName, "", "git branch") - return flagName -} - -func GetRepoBranch(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("branch") -} - -// AddRepoURLFlag registers --url for catalog/config repository commands. -func AddRepoURLFlag(cmd *cobra.Command) string { - const flagName = "url" - cmd.Flags().String(flagName, "", "git url") - return flagName -} - -func GetRepoURL(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("url") -} - -// AddRepoCredFlag registers --cred for catalog/config repository commands. -// Completion lists credential canonicals. -func AddRepoCredFlag(cmd *cobra.Command) string { - const flagName = "cred" - cmd.Flags().String(flagName, "", "credential canonical used to access the repository") - cmd.RegisterFlagCompletionFunc(flagName, CompleteCredentialCanonical) - return flagName -} - -func GetRepoCred(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("cred") -} - -// AddRepoDefaultFlag registers --default for config repository commands. -func AddRepoDefaultFlag(cmd *cobra.Command) string { - const flagName = "default" - cmd.Flags().Bool(flagName, false, "set as default config repository for the org") - return flagName -} - -func GetRepoDefault(cmd *cobra.Command) (bool, error) { - return cmd.Flags().GetBool("default") -} diff --git a/internal/cyargs/stackforms_input.go b/internal/cyargs/stackforms_input.go deleted file mode 100644 index 297aa9102..000000000 --- a/internal/cyargs/stackforms_input.go +++ /dev/null @@ -1,287 +0,0 @@ -package cyargs - -import ( - "encoding/json" - "fmt" - "io" - "log" - "os" - "slices" - "strconv" - "strings" - - "dario.cat/mergo" - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" -) - -var ( - StackformsEnvVarName = "CY_STACKFORMS_VARS" -) - -func AddStackFormsInputFlags(cmd *cobra.Command) { - cmd.Flags().StringArrayP("json-file", "f", []string{}, "path to a JSON file containing Stackform input. Can be '-' to read from stdin. This flag can be set multiple times.") - cmd.MarkFlagFilename("json-file", "json") - cmd.Flags().StringArrayP("json-vars", "j", []string{}, "JSON string containing Stackform input. This flag can be set multiple times. Can also be set using "+StackformsEnvVarName+" env var") - cmd.Flags().StringToStringP("var", "V", nil, `specify a StackForms variable using a section.group.key=value notation. The value will be parsed to try to validate the type. To force a string, add double quotes " to the value`) -} - -// GetStackformsVars wrap the flag parsing and the merge of the variables -// set by the user. The caller must provide the defaults values as he only knows -// if it must be fetched from a stack or a current component. -func GetStackformsVars(cmd *cobra.Command, defaults models.FormVariables) (models.FormVariables, error) { - if defaults == nil { - defaults = make(models.FormVariables) - } - - varFiles, err := cmd.Flags().GetStringArray("json-file") - if err != nil { - return nil, err - } - - // We need to check for the '-' filename at this stage to be able to - // dump stdin from cmd.InOrStdin() in a temp file. - index := slices.Index(varFiles, "-") - if index != -1 { - if !common.DetectStdinInput() { - return nil, fmt.Errorf("stdin looks empty, please fill stdin when using '-' argument") - } - - tempFile, err := os.CreateTemp("", "cy-stdin-*") - if err != nil { - return nil, fmt.Errorf("failed to write temp file for stdin: %w", err) - } - defer func() { - closeErr := tempFile.Close() - rmErr := os.Remove(tempFile.Name()) - if closeErr != nil || rmErr != nil { - log.Fatalf("failed to purge temp file with stdin content: %s: %s", closeErr, rmErr) - } - }() - - stdin, err := io.ReadAll(cmd.InOrStdin()) - if err != nil { - return nil, fmt.Errorf("failed to read from stdin: %w", err) - } - - _, err = tempFile.Write(stdin) - if err != nil { - return nil, fmt.Errorf("failed to write stdin to temp file: %w", err) - } - - varFiles[index] = tempFile.Name() - } - - varJSON, err := cmd.Flags().GetStringArray("json-vars") - if err != nil { - return nil, err - } - - jsonFromEnv, ok := os.LookupEnv(StackformsEnvVarName) - var varsFromEnv = make(models.FormVariables) - if ok { - decoder := json.NewDecoder(strings.NewReader(jsonFromEnv)) - err := decoder.Decode(&varsFromEnv) - if err != nil { - return nil, fmt.Errorf("invalid JSON variables in %q env var: %w", StackformsEnvVarName, err) - } - } - - varField, err := cmd.Flags().GetStringToString("var") - if err != nil { - return nil, err - } - - output, err := MergeStackformsVars(defaults, varsFromEnv, varFiles, varJSON, varField) - if err != nil { - return nil, err - } - - if output == nil { - return nil, errors.New("invalid user input: stackforms vars must not be empty.") - } - - return output, nil -} - -// MergeStackformsVars will parse and merge all variables inputs in the following order of -// precedence: -// file < jsonString < keyValueField -func MergeStackformsVars(defaults models.FormVariables, envVars models.FormVariables, jsonFiles, jsonStrings []string, keyValueField map[string]string) (models.FormVariables, error) { - if defaults == nil { - defaults = make(models.FormVariables) - } - - err := mergo.Merge(&defaults, envVars, mergo.WithOverride) - if err != nil { - return nil, fmt.Errorf("failed to merge JSON from env var: %w", err) - } - - jsonFileVars, err := MergeJSONFileVars(jsonFiles) - if err != nil { - return nil, err - } - - err = mergo.Merge(&defaults, jsonFileVars, mergo.WithOverride) - if err != nil { - return nil, fmt.Errorf("failed to merge JSON vars files: %w", err) - } - - jsonVars, err := MergeJSONVars(jsonStrings) - if err != nil { - return nil, err - } - - err = mergo.Merge(&defaults, jsonVars, mergo.WithOverride) - if err != nil { - return nil, fmt.Errorf("failed to merge JSON Vars: %w", err) - } - - for k, v := range keyValueField { - err = UpdateFormVar(k, v, defaults) - if err != nil { - return nil, fmt.Errorf("failed to update vars %q with field %q: %w", k, v, err) - } - } - - return defaults, nil -} - -// MergeJSONFileVars will read and merge the Stackforms vars from the `json-file` arg -func MergeJSONFileVars(jsonFiles []string) (models.FormVariables, error) { - var output = make(models.FormVariables) - - for _, filename := range jsonFiles { - var decoder *json.Decoder - reader, err := os.Open(filename) - if err != nil { - return nil, fmt.Errorf("failed to open var file at path %q: %w", filename, err) - } - defer reader.Close() - - decoder = json.NewDecoder(reader) - - for { - var extractedVars = make(models.FormVariables) - err := decoder.Decode(&extractedVars) - if err == io.EOF { - break - } - if err != nil { - return nil, fmt.Errorf("failed to read StackForms variables from %q: %w", filename, err) - } - - if err := mergo.Merge(&output, extractedVars, mergo.WithOverride); err != nil { - return nil, fmt.Errorf("failed to merge variables from %q: %w", filename, err) - } - } - } - - return output, nil -} - -// MergeJSONVars expect an array of valid JSON string as stackforms input and return a models.FormVariables -func MergeJSONVars(jsonVars []string) (models.FormVariables, error) { - var output = make(models.FormVariables) - for _, jsonString := range jsonVars { - if jsonString == "" { - continue - } - - var extractedVars = make(models.FormVariables) - - err := json.Unmarshal([]byte(jsonString), &extractedVars) - if err != nil { - return nil, fmt.Errorf("failed to parse json-var input as valid Stackform JSON %q: %w", jsonString, err) - } - - if err := mergo.Merge(&output, extractedVars, mergo.WithOverride); err != nil { - return nil, fmt.Errorf("failed to merge input vars from json-var input %q: %w", extractedVars, err) - } - } - - return output, nil -} - -// UpdateFormVar will take a Stackform variable ref in the format section.group.var -// and update its value. The value is passed as string but can be any valid 'JSON' type. -func UpdateFormVar(field string, value string, vars models.FormVariables) error { - keys := strings.Split(field, ".") - if len(keys) != 3 { - return errors.New("key=val update failed, you can only update a value using `section.group.var=value` syntax") - } - - var section, group, key = keys[0], keys[1], keys[2] - - if vars == nil { - vars = models.FormVariables{section: {group: {key: nil}}} - } - - if vars[section] == nil { - vars[section] = map[string]map[string]any{ - group: {key: nil}, - } - } - - if vars[section][group] == nil { - vars[section][group] = map[string]any{ - key: nil, - } - } - - // Try to detect JSON first - // we strip value for space and newline in begin/end of the string - trimmedValue := strings.TrimSpace(value) - // We check if we have a valid JSON array or object by looking up first and last char. - if strings.HasPrefix(trimmedValue, "[") && strings.HasSuffix(trimmedValue, "]") || strings.HasPrefix(trimmedValue, "{") && strings.HasSuffix(trimmedValue, "}") { - var data any - err := json.Unmarshal([]byte(trimmedValue), &data) - if err != nil { - return errors.Wrapf(err, "invalid JSON value in key=val update with value %q", trimmedValue) - } - - vars[section][group][key] = data - return nil - } - - // We will prioritize the use of quotes to explicitly define strings values - // This allow users to circumvent issues in case of strings that could be parsed - // as other types - // Note: cobra seems to already trim trailling double quotes. - if strings.HasPrefix(trimmedValue, `"`) { - vars[section][group][key] = trimmedValue[1:] - return nil - } else if strings.HasPrefix(trimmedValue, "'") && strings.HasSuffix(trimmedValue, "'") { - vars[section][group][key] = trimmedValue[1 : len(trimmedValue)-1] // single quote won't be trimmed by cobra - return nil - } - - // Detect standard types - // numbers, we do all as float since JSON doesn't care - // Important! We parse number firsts, since 1 and 0 are considered bools by strconv.ParseBool - float, err := strconv.ParseFloat(value, 64) - if err == nil { - vars[section][group][key] = float - return nil - } - - // bools - boolean, err := strconv.ParseBool(value) - if err == nil { - vars[section][group][key] = boolean - return nil - } - - // null - if strings.ToLower(value) == "null" { - vars[section][group][key] = nil - return nil - } - - // if all type conversion failed, consider the value as string - vars[section][group][key] = value - return nil -} diff --git a/internal/cyargs/stackforms_input_test.go b/internal/cyargs/stackforms_input_test.go deleted file mode 100644 index 0c3511fb6..000000000 --- a/internal/cyargs/stackforms_input_test.go +++ /dev/null @@ -1,215 +0,0 @@ -package cyargs_test - -import ( - "encoding/json" - "os" - "testing" - - "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/internal/cyargs" -) - -func TestGetStackformsVars(t *testing.T) { - // vars - anyArray := []any{"string", 1, 1.1, true, []string{"hello"}, map[string]string{"hello": "world"}} - anyMap := map[string]any{ - "string": "string", - "int": 1, - "float": 1.1, - "bool": true, - "array": anyArray, - "map": map[string]any{ - "hello": "world", - }, - } - expected := models.FormVariables{ - "section": { - "group": { - "string": "string", - "int": 1, - "float": 1.1, - "bool": true, - "array": anyArray, - "map": anyMap, - }, - }, - } - expectedJSON, err := json.Marshal(expected) - if err != nil { - t.Errorf("failed setup for test, failed to encode expected value '%v' to json: %s", expected, err) - } - - t.Run("VarsStdin", func(t *testing.T) { - cmd := &cobra.Command{} - cyargs.AddStackFormsInputFlags(cmd) - - tempFile, err := os.CreateTemp("", "json-test") - if err != nil { - t.Errorf("failed to setup test, cannot create temp file: %s", err) - } - defer os.Remove(tempFile.Name()) - - _, err = tempFile.Write(expectedJSON) - if err != nil { - t.Errorf("failed to setup test, cannot write to test file %s: %s", tempFile.Name(), err) - } - - _, err = tempFile.Seek(0, 0) - if err != nil { - t.Errorf("failed to setup test, cannot change offset in file reader: %s", err) - } - - oldStdin := os.Stdin - defer func() { os.Stdin = oldStdin }() - - os.Stdin = tempFile - - cmd.ParseFlags([]string{ - "--json-file", "-", - }) - - var defaults = make(models.FormVariables) - output, err := cyargs.GetStackformsVars(cmd, defaults) - if err != nil { - t.Errorf("stackform var parsing failed: %s", err) - } - - gotJSON, err := json.Marshal(output) - if err != nil { - t.Errorf("failed to serialize json output '%v': %s", &output, err) - } - assert.Equal(t, string(expectedJSON), string(gotJSON), "should be equal") - }) - - t.Run("EmptyDefaultsEmptyVars", func(t *testing.T) { - cmd := &cobra.Command{} - cyargs.AddStackFormsInputFlags(cmd) - - var defaults = make(models.FormVariables) - output, err := cyargs.GetStackformsVars(cmd, defaults) - if err != nil { - t.Errorf("Empty default should work: %s", err) - } - - assert.Equal(t, defaults, output, "should be empty") - }) - - t.Run("EnvVar", func(t *testing.T) { - cmd := &cobra.Command{} - cyargs.AddStackFormsInputFlags(cmd) - - os.Setenv(cyargs.StackformsEnvVarName, string(expectedJSON)) - defer os.Unsetenv(cyargs.StackformsEnvVarName) - var defaults = make(models.FormVariables) - output, err := cyargs.GetStackformsVars(cmd, defaults) - if err != nil { - t.Errorf("Empty default should work: %s", err) - } - - gotJSON, err := json.Marshal(output) - if err != nil { - t.Errorf("failed to serialize json output '%v': %s", &output, err) - } - assert.Equal(t, expectedJSON, gotJSON, "should be equal") - }) - - t.Run("VarsJSON", func(t *testing.T) { - cmd := &cobra.Command{} - cyargs.AddStackFormsInputFlags(cmd) - - cmd.ParseFlags([]string{ - "--json-vars", string(expectedJSON), - }) - - var defaults = make(models.FormVariables) - output, err := cyargs.GetStackformsVars(cmd, defaults) - if err != nil { - t.Errorf("Empty default should work: %s", err) - } - - gotJSON, err := json.Marshal(output) - if err != nil { - t.Errorf("failed to serialize json output '%v': %s", &output, err) - } - assert.Equal(t, string(expectedJSON), string(gotJSON), "should be equal") - }) - - t.Run("VarsFile", func(t *testing.T) { - cmd := &cobra.Command{} - cyargs.AddStackFormsInputFlags(cmd) - - tempFile, err := os.CreateTemp("", "json-test") - if err != nil { - t.Errorf("failed to setup test, cannot create temp file: %s", err) - } - defer os.Remove(tempFile.Name()) - - _, err = tempFile.Write(expectedJSON) - if err != nil { - t.Errorf("failed to setup test, cannot write to test file %s: %s", tempFile.Name(), err) - } - - cmd.ParseFlags([]string{ - "--json-file", tempFile.Name(), - }) - - var defaults = make(models.FormVariables) - output, err := cyargs.GetStackformsVars(cmd, defaults) - if err != nil { - t.Errorf("Empty default should work: %s", err) - } - - gotJSON, err := json.Marshal(output) - if err != nil { - t.Errorf("failed to serialize json output '%v': %s", &output, err) - } - assert.Equal(t, string(expectedJSON), string(gotJSON), "should be equal") - }) - - t.Run("VarFlag", func(t *testing.T) { - cmd := &cobra.Command{} - cyargs.AddStackFormsInputFlags(cmd) - - cmd.ParseFlags([]string{ - "--var", `types.string.double_quote="1"`, - "--var", `types.string.single_quote='1'`, - "--var", `types.float.no_quote=1`, - "--var", `types.boolean.no_quote=true`, - "--var", `types.array.no_quote=["string", "hello_there"]`, - "--var", `types.map.no_quote={"string": "hello_there"}`, - }) - - var defaults = make(models.FormVariables) - parsedVars, err := cyargs.GetStackformsVars(cmd, defaults) - if err != nil { - t.Errorf("Empty default should work: %s", err) - } - - value, ok := parsedVars["types"]["string"]["double_quote"].(string) - assert.True(t, ok, "type cast to string should be okay") - assert.Equal(t, "1", value, "the output should be a string 1 with no quotes") - - value, ok = parsedVars["types"]["string"]["single_quote"].(string) - assert.True(t, ok, "type cast to string should be okay") - assert.Equal(t, "1", value, "the output should be a string 1 with no quotes") - - valueFloat, ok := parsedVars["types"]["float"]["no_quote"].(float64) - assert.True(t, ok, "type cast to float should be okay") - assert.Equal(t, 1.0, valueFloat, "the output should be a float") - - valueBool, ok := parsedVars["types"]["boolean"]["no_quote"].(bool) - assert.True(t, ok, "type cast to boolean should be okay") - assert.Equal(t, true, valueBool, "the output should be a bool") - - valueArray, ok := parsedVars["types"]["array"]["no_quote"] - assert.True(t, ok, "type cast to array should be okay") - assert.Equal(t, []any{"string", "hello_there"}, valueArray, "the output should be a array") - - valueMap, ok := parsedVars["types"]["map"]["no_quote"] - assert.True(t, ok, "type cast to map should be okay") - assert.Equal(t, map[string]any{"string": "hello_there"}, valueMap, "the output should be a map") - }) -} diff --git a/internal/cyargs/stacks.go b/internal/cyargs/stacks.go deleted file mode 100644 index 54579c295..000000000 --- a/internal/cyargs/stacks.go +++ /dev/null @@ -1,484 +0,0 @@ -package cyargs - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -func ValidateForms(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - return []cobra.Completion{"yml", "yaml"}, cobra.ShellCompDirectiveFilterFileExt -} - -func AddStackRefFlag(cmd *cobra.Command) string { - flagName := "stack-ref" - cmd.Flags().StringP(flagName, "s", "", "referential of the stack, format 'org:canonical'") - cmd.RegisterFlagCompletionFunc(flagName, CompleteStackRef) - return flagName -} - -func CompleteStackRef(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "completion failed: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - stacks, _, err := m.ListStacks(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list stacks in org '"+org+"': "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var stackRefs = make([]string, len(stacks)) - for index, stack := range stacks { - if stack.Ref != nil && strings.HasPrefix(*stack.Ref, toComplete) { - desc := *stack.Name - if stack.Description != "" { - desc = desc + " - " + stack.Description - } - stackRefs[index] = cobra.CompletionWithDesc(*stack.Ref, desc) - } - } - - return stackRefs, cobra.ShellCompDirectiveNoFileComp -} - -func GetStackRef(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("stack-ref") -} - -func AddVisibilityFlag(cmd *cobra.Command) string { - flagName := "visibility" - cmd.Flags().StringP(flagName, "V", "", "set the visibility of a stack") - cmd.RegisterFlagCompletionFunc(flagName, CompleteVisibility) - return flagName -} - -func GetVisibility(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("visibility") -} - -func CompleteVisibility(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - return []cobra.Completion{ - "hidden", - "shared", - "local", - }, cobra.ShellCompDirectiveNoFileComp -} - -// Blueprint-related functions -func AddBlueprintRefFlag(cmd *cobra.Command) string { - flagName := "blueprint-ref" - cmd.Flags().StringP(flagName, "", "", "Blueprint reference to use") - cmd.RegisterFlagCompletionFunc(flagName, CompleteBlueprint) - return flagName -} - -func CompleteBlueprint(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "completion failed: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - blueprints, _, err := m.ListBlueprints(org) - if err != nil { - return cobra.AppendActiveHelp(nil, "failed to list stacks in org '"+org+"': "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var completions = make([]cobra.Completion, len(blueprints)) - for index, blueprint := range blueprints { - if blueprint.Ref != nil && strings.HasPrefix(*blueprint.Ref, toComplete) { - completions[index] = cobra.CompletionWithDesc(*blueprint.Ref, *blueprint.Name+" - "+blueprint.Description) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func GetBlueprintRef(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("blueprint-ref") -} - -func AddStackNameFlag(cmd *cobra.Command) string { - flagName := "name" - cmd.Flags().StringP(flagName, "n", "", "name of the stack") - return flagName -} - -func AddStackFlag(cmd *cobra.Command) string { - flagStack := "stack" - cmd.Flags().StringP(flagStack, "s", "", "canonical of the stack") - return flagStack -} - -func GetStack(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString("stack") -} - -// AddStackVersionFlags adds flags for specifying stack versions. -// The primary flag is --stack-version, which accepts a bare name (resolved via API) -// or a typed prefix: tag:, branch:, sha:. -// Legacy flags --stack-tag, --stack-branch, --stack-commit-hash are kept for -// backward compatibility but are deprecated and will be removed in a future major release. -func AddStackVersionFlags(cmd *cobra.Command) { - cmd.Flags().String("stack-version", "", "stack version (tag, branch, or commit hash). "+ - "Use type prefixes to avoid ambiguity: tag:, branch:, sha:") - cmd.RegisterFlagCompletionFunc("stack-version", CompleteStackVersionUnified) - - // Legacy flags — kept for backward compatibility. - cmd.Flags().String("stack-tag", "", "the stack version tag to use (e.g., v1.0.0)") - cmd.Flags().String("stack-branch", "", "the stack version branch to use (e.g., main)") - cmd.Flags().String("stack-commit-hash", "", "the stack version commit hash to use") - - //nolint:errcheck - cmd.Flags().MarkDeprecated("stack-tag", "use --stack-version=tag: instead (will be removed in a future major release)") - //nolint:errcheck - cmd.Flags().MarkDeprecated("stack-branch", "use --stack-version=branch: instead (will be removed in a future major release)") - //nolint:errcheck - cmd.Flags().MarkDeprecated("stack-commit-hash", "use --stack-version=sha: instead (will be removed in a future major release)") - - cmd.RegisterFlagCompletionFunc("stack-tag", CompleteStackVersionTag) - cmd.RegisterFlagCompletionFunc("stack-branch", CompleteStackVersionBranch) - cmd.RegisterFlagCompletionFunc("stack-commit-hash", CompleteCatalogRepoCommitHash) - - // Mutual exclusion: --stack-version vs each legacy flag - cmd.MarkFlagsMutuallyExclusive("stack-version", "stack-tag") - cmd.MarkFlagsMutuallyExclusive("stack-version", "stack-branch") - cmd.MarkFlagsMutuallyExclusive("stack-version", "stack-commit-hash") - // Legacy flags remain mutually exclusive with each other - cmd.MarkFlagsMutuallyExclusive("stack-tag", "stack-branch", "stack-commit-hash") -} - -// GetStackVersionFlags reads the legacy stack version flags from the command. -// Prefer ResolveStackVersionArg for new code. -func GetStackVersionFlags(cmd *cobra.Command) (tag, branch, hash string, err error) { - tag, err = cmd.Flags().GetString("stack-tag") - if err != nil { - return "", "", "", err - } - - branch, err = cmd.Flags().GetString("stack-branch") - if err != nil { - return "", "", "", err - } - - hash, err = cmd.Flags().GetString("stack-commit-hash") - if err != nil { - return "", "", "", err - } - - return tag, branch, hash, nil -} - -// ResolveStackVersionArg resolves the --stack-version flag (or legacy flags) to -// the (tag, branch, hash) triple expected by middleware methods. -// -// Resolution order: -// 1. Legacy flags (--stack-tag / --stack-branch / --stack-commit-hash) — returned as-is. -// 2. --stack-version is empty — returns ("", "", "", nil); callers should preserve the current version. -// 3. --stack-version has a type prefix (tag: / branch: / sha: / commit:) — parsed client-side, no API call. -// 4. Bare value — calls m.ListStackVersions to resolve; requires a non-empty stackRef. -// Precedence: tag > branch > commit-hash-prefix (min 7 chars). -// Collision (same name matches both tag and branch) → error with disambiguation hint. -func ResolveStackVersionArg(cmd *cobra.Command, m middleware.Middleware, org, stackRef string) (tag, branch, hash string, err error) { - // Legacy flags take priority; Cobra already emits the deprecation notice. - tag, branch, hash, err = GetStackVersionFlags(cmd) - if err != nil || tag != "" || branch != "" || hash != "" { - return - } - - v, err := cmd.Flags().GetString("stack-version") - if err != nil { - return "", "", "", err - } - if v == "" { - return "", "", "", nil - } - - // Typed prefix form — no API call needed. - typeHint, value, hasPrefix := strings.Cut(v, ":") - if hasPrefix { - switch strings.ToLower(typeHint) { - case "tag": - return value, "", "", nil - case "branch": - return "", value, "", nil - case "sha", "commit": - return "", "", value, nil - } - // Unknown prefix: fall through and attempt bare resolution on the full value. - } - - // Bare form requires the stack ref to query available versions. - if stackRef == "" { - return "", "", "", fmt.Errorf( - "cannot auto-detect version type for %q without a stack reference; "+ - "use --stack-version=tag:, --stack-version=branch:, or --stack-version=sha:", v) - } - - versions, _, err := m.ListStackVersions(org, stackRef) - if err != nil { - return "", "", "", fmt.Errorf("failed to resolve --stack-version=%q: %w", v, err) - } - - var matchTag, matchBranch, matchCommit string - for _, ver := range versions { - name := ptr.Value(ver.Name) - if name == v { - if ptr.Value(ver.Type) == "tag" { - matchTag = name - } else { - matchBranch = name - } - } - if commitHash := ptr.Value(ver.CommitHash); commitHash != "" && len(v) >= 7 && strings.HasPrefix(commitHash, v) { - matchCommit = commitHash - } - } - - switch { - case matchTag != "" && matchBranch != "": - return "", "", "", fmt.Errorf( - "ambiguous version %q (matches both a tag and a branch); "+ - "use --stack-version=tag:%s or --stack-version=branch:%s", v, v, v) - case matchTag != "": - return matchTag, "", "", nil - case matchBranch != "": - return "", matchBranch, "", nil - case matchCommit != "": - return "", "", matchCommit, nil - default: - return "", "", "", fmt.Errorf("version %q not found in stack %q", v, stackRef) - } -} - -// CompleteStackVersionUnified provides prefix-aware completion for --stack-version. -// -// - No prefix typed (e.g. "v1"): lists all versions with type in description. -// - "tag:": lists only tags, formatted as "tag:". -// - "branch:": lists only branches, formatted as "branch:". -// - "sha:": lists only commit hashes (short), formatted as "sha:". -func CompleteStackVersionUnified(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org for completion: "+err.Error()), cobra.ShellCompDirectiveError - } - - stackRef := resolveStackRefForCompletion(cmd, org) - if stackRef == "" { - return cobra.AppendActiveHelp(nil, "missing stack-ref for completion: please provide --stack-ref flag"), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - versions, _, err := m.ListStackVersions(org, stackRef) - if err != nil { - return cobra.AppendActiveHelp(nil, "cannot find versions for stack: "+stackRef+", err: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - typeHint, valuePrefix, hasPrefix := strings.Cut(toComplete, ":") - - var completions []cobra.Completion - for _, ver := range versions { - if ver.Name == nil || ver.Type == nil { - continue - } - name := *ver.Name - vType := *ver.Type - - if hasPrefix { - switch strings.ToLower(typeHint) { - case "tag": - if vType == "tag" && strings.HasPrefix(name, valuePrefix) { - completions = append(completions, cobra.CompletionWithDesc("tag:"+name, versionDesc(ver))) - } - case "branch": - if vType == "branch" && strings.HasPrefix(name, valuePrefix) { - completions = append(completions, cobra.CompletionWithDesc("branch:"+name, versionDesc(ver))) - } - case "sha", "commit": - if ver.CommitHash != nil { - h := shortHash(*ver.CommitHash) - if strings.HasPrefix(h, valuePrefix) { - completions = append(completions, cobra.CompletionWithDesc("sha:"+h, versionDesc(ver))) - } - } - } - } else { - if strings.HasPrefix(name, toComplete) { - completions = append(completions, cobra.CompletionWithDesc(name, "("+vType+") "+versionDesc(ver))) - } - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -// resolveStackRefForCompletion tries to determine the stack ref for completion functions. -// It checks --stack-ref first, then falls back to fetching it from the existing component. -func resolveStackRefForCompletion(cmd *cobra.Command, org string) string { - stackRef, _ := GetStackRef(cmd) - if stackRef != "" { - return stackRef - } - - project, errProj := GetProject(cmd) - env, errEnv := GetEnv(cmd) - component, errComp := GetComponent(cmd) - if errProj != nil || errEnv != nil || errComp != nil { - return "" - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - currentComponent, _, errGet := m.GetComponent(org, project, env, component) - if errGet == nil && currentComponent.ServiceCatalog != nil && currentComponent.ServiceCatalog.Ref != nil { - return *currentComponent.ServiceCatalog.Ref - } - return "" -} - -func versionDesc(ver *middleware.StackVersion) string { - desc := "" - if ver.CommitHash != nil { - desc = shortHash(*ver.CommitHash) - } - if ptr.Value(ver.IsLatest) { - if desc != "" { - desc += " " - } - desc += "[latest]" - } - return desc -} - -func shortHash(h string) string { - if len(h) > 8 { - return h[:8] - } - return h -} - -// CompleteCatalogRepoCommitHash provides completion for the --stack-commit-hash flag. -func CompleteCatalogRepoCommitHash(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org for completion: "+err.Error()), cobra.ShellCompDirectiveError - } - - stackRef := resolveStackRefForCompletion(cmd, org) - if stackRef == "" { - return cobra.AppendActiveHelp(nil, "missing stack-ref for completion: please provide --stack-ref flag"), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - versions, _, err := m.ListStackVersions(org, stackRef) - if err != nil { - return cobra.AppendActiveHelp(nil, "cannot find versions for stack: "+stackRef+", err: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var commitHashes []string - for _, version := range versions { - if version.CommitHash != nil && strings.HasPrefix(*version.CommitHash, toComplete) { - desc := ptr.Value(version.Name) - if t := ptr.Value(version.Type); t != "" { - if desc != "" { - desc = desc + " (" + t + ")" - } else { - desc = t - } - } - if ptr.Value(version.IsLatest) { - desc = desc + " [latest]" - } - commitHashes = append(commitHashes, cobra.CompletionWithDesc(*version.CommitHash, desc)) - } - } - - return commitHashes, cobra.ShellCompDirectiveNoFileComp -} - -// CompleteStackVersionTag provides completion for the --stack-tag flag. -func CompleteStackVersionTag(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org for completion: "+err.Error()), cobra.ShellCompDirectiveError - } - - stackRef := resolveStackRefForCompletion(cmd, org) - if stackRef == "" { - return cobra.AppendActiveHelp(nil, "missing stack-ref for completion: please provide --stack-ref flag"), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - versions, _, err := m.ListStackVersions(org, stackRef) - if err != nil { - return cobra.AppendActiveHelp(nil, "cannot find versions for stack: "+stackRef+", err: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var tags []string - for _, version := range versions { - if ptr.Value(version.Type) == "tag" && version.Name != nil && strings.HasPrefix(*version.Name, toComplete) { - tags = append(tags, cobra.CompletionWithDesc(*version.Name, versionDesc(version))) - } - } - - return tags, cobra.ShellCompDirectiveNoFileComp -} - -// CompleteStackVersionBranch provides completion for the --stack-branch flag. -func CompleteStackVersionBranch(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org for completion: "+err.Error()), cobra.ShellCompDirectiveError - } - - stackRef := resolveStackRefForCompletion(cmd, org) - if stackRef == "" { - return cobra.AppendActiveHelp(nil, "missing stack-ref for completion: please provide --stack-ref flag"), - cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - versions, _, err := m.ListStackVersions(org, stackRef) - if err != nil { - return cobra.AppendActiveHelp(nil, "cannot find versions for stack: "+stackRef+", err: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - var branches []string - for _, version := range versions { - if ptr.Value(version.Type) == "branch" && version.Name != nil && strings.HasPrefix(*version.Name, toComplete) { - branches = append(branches, cobra.CompletionWithDesc(*version.Name, versionDesc(version))) - } - } - - return branches, cobra.ShellCompDirectiveNoFileComp -} diff --git a/internal/cyargs/stacks_test.go b/internal/cyargs/stacks_test.go deleted file mode 100644 index 09cdae514..000000000 --- a/internal/cyargs/stacks_test.go +++ /dev/null @@ -1,183 +0,0 @@ -package cyargs_test - -import ( - "net/http" - "testing" - - "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -// stubMiddleware implements only ListStackVersions; all other methods panic. -type stubMiddleware struct { - middleware.Middleware - versions []*middleware.StackVersion - err error -} - -func (s *stubMiddleware) ListStackVersions(org, ref string, _ ...middleware.LHSFilter) ([]*middleware.StackVersion, *http.Response, error) { - return s.versions, nil, s.err -} - -func newCmd() *cobra.Command { - cmd := &cobra.Command{} - cyargs.AddStackVersionFlags(cmd) - return cmd -} - -func makeVersion(name, vType, commitHash string, isLatest bool) *middleware.StackVersion { - return &middleware.StackVersion{ - Name: ptr.Ptr(name), - Type: ptr.Ptr(vType), - CommitHash: ptr.Ptr(commitHash), - IsLatest: ptr.Ptr(isLatest), - } -} - -func TestResolveStackVersionArg(t *testing.T) { - tagVersion := makeVersion("v1.0.0", "tag", "aabbccdd1234567", true) - branchVersion := makeVersion("main", "branch", "deadbeef1234567", false) - ambigTag := makeVersion("release", "tag", "1111111111111111", false) - ambigBranch := makeVersion("release", "branch", "2222222222222222", false) - - canned := []*middleware.StackVersion{tagVersion, branchVersion, ambigTag, ambigBranch} - - m := &stubMiddleware{versions: canned} - const org = "myorg" - const stackRef = "myorg:mystack" - - cases := []struct { - name string - args []string - wantTag string - wantBranch string - wantHash string - wantErr string - }{ - { - name: "empty returns empty triple", - args: nil, - wantTag: "", wantBranch: "", wantHash: "", - }, - { - name: "tag prefix resolved client-side", - args: []string{"--stack-version", "tag:v1.0.0"}, - wantTag: "v1.0.0", - }, - { - name: "branch prefix resolved client-side", - args: []string{"--stack-version", "branch:main"}, - wantBranch: "main", - }, - { - name: "sha prefix resolved client-side", - args: []string{"--stack-version", "sha:deadbeef"}, - wantHash: "deadbeef", - }, - { - name: "commit prefix alias resolved client-side", - args: []string{"--stack-version", "commit:deadbeef"}, - wantHash: "deadbeef", - }, - { - name: "bare value resolves to tag (tag wins over branch)", - args: []string{"--stack-version", "v1.0.0"}, - wantTag: "v1.0.0", - }, - { - name: "bare value resolves to branch when no tag matches", - args: []string{"--stack-version", "main"}, - wantBranch: "main", - }, - { - name: "bare short hash resolves to commit", - args: []string{"--stack-version", "aabbccd"}, - wantHash: "aabbccdd1234567", - }, - { - name: "collision between tag and branch errors with hint", - args: []string{"--stack-version", "release"}, - wantErr: "ambiguous version", - }, - { - name: "unknown bare value returns not-found error", - args: []string{"--stack-version", "nonexistent"}, - wantErr: "not found", - }, - { - name: "short hash under 7 chars is not matched as commit", - args: []string{"--stack-version", "aabbcc"}, - wantErr: "not found", - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - cmd := newCmd() - if tc.args != nil { - require.NoError(t, cmd.ParseFlags(tc.args)) - } - - tag, branch, hash, err := cyargs.ResolveStackVersionArg(cmd, m, org, stackRef) - - if tc.wantErr != "" { - require.Error(t, err) - assert.Contains(t, err.Error(), tc.wantErr) - return - } - - require.NoError(t, err) - assert.Equal(t, tc.wantTag, tag) - assert.Equal(t, tc.wantBranch, branch) - assert.Equal(t, tc.wantHash, hash) - }) - } - - t.Run("legacy --stack-tag bypasses resolution", func(t *testing.T) { - noCallMiddleware := &stubMiddleware{} // panics if ListStackVersions called - cmd := newCmd() - require.NoError(t, cmd.ParseFlags([]string{"--stack-tag", "v2.0.0"})) - - tag, branch, hash, err := cyargs.ResolveStackVersionArg(cmd, noCallMiddleware, org, stackRef) - require.NoError(t, err) - assert.Equal(t, "v2.0.0", tag) - assert.Empty(t, branch) - assert.Empty(t, hash) - }) - - t.Run("legacy --stack-branch bypasses resolution", func(t *testing.T) { - noCallMiddleware := &stubMiddleware{} - cmd := newCmd() - require.NoError(t, cmd.ParseFlags([]string{"--stack-branch", "dev"})) - - tag, branch, hash, err := cyargs.ResolveStackVersionArg(cmd, noCallMiddleware, org, stackRef) - require.NoError(t, err) - assert.Empty(t, tag) - assert.Equal(t, "dev", branch) - assert.Empty(t, hash) - }) - - t.Run("tag prefix with no API call (noCallMiddleware should not panic)", func(t *testing.T) { - noCallMiddleware := &stubMiddleware{} - cmd := newCmd() - require.NoError(t, cmd.ParseFlags([]string{"--stack-version", "tag:v1.0.0"})) - - tag, _, _, err := cyargs.ResolveStackVersionArg(cmd, noCallMiddleware, org, stackRef) - require.NoError(t, err) - assert.Equal(t, "v1.0.0", tag) - }) - - t.Run("bare value without stackRef returns helpful error", func(t *testing.T) { - cmd := newCmd() - require.NoError(t, cmd.ParseFlags([]string{"--stack-version", "main"})) - - _, _, _, err := cyargs.ResolveStackVersionArg(cmd, m, org, "") - require.Error(t, err) - assert.Contains(t, err.Error(), "stack reference") - }) -} diff --git a/internal/cyargs/teams.go b/internal/cyargs/teams.go deleted file mode 100644 index a7aac2fd7..000000000 --- a/internal/cyargs/teams.go +++ /dev/null @@ -1,336 +0,0 @@ -package cyargs - -import ( - "fmt" - "strconv" - "strings" - "time" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -const ( - teamFlagName = "team" - teamNameFlagName = "name" - teamOrderByFlagName = "order-by" - teamMemberIDFlagName = "member-id" - teamMemberFlagName = "member" - teamMemberEmailFlagName = "email" - teamMemberUsernameFlagName = "username" - teamCreatedAtFlagName = "created-at" - teamOwnerFlagName = "owner" - teamRolesFlagName = "role" -) - -func AddTeamFlag(cmd *cobra.Command) string { - _ = cmd.Flags().StringP(teamFlagName, "t", "", "the team canonical") - cmd.RegisterFlagCompletionFunc(teamFlagName, CompleteTeam) - return teamFlagName -} - -func CompleteTeam(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp(nil, "missing org for completion: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - name, _ := GetTeamName(cmd) - memberID, _ := GetTeamMemberID(cmd) - createdAt, _ := GetTeamCreatedAt(cmd) - orderBy, _ := GetTeamOrderBy(cmd) - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - teams, _, err := m.ListTeams(org, &name, createdAt, &memberID, orderBy) - if err != nil { - return cobra.AppendActiveHelp(nil, "Failed to list team for completion: "+err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, len(teams)) - for i, t := range teams { - if t.Canonical != nil { - completions[i] = cobra.CompletionWithDesc(*t.Canonical, ptr.Value(t.Name)) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func GetTeam(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(teamFlagName) -} - -func AddTeamNameFlag(cmd *cobra.Command) string { - cmd.Flags().StringP(teamNameFlagName, "n", "", "the name of the team") - return teamNameFlagName -} - -func GetTeamName(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(teamNameFlagName) -} - -// TeamMembersCompletionHelper is meant to be consumed by other members related -// complete functions. -func TeamMembersCompletionHelper(cmd *cobra.Command) ([]*models.MemberTeam, error) { - org, err := GetOrg(cmd) - if err != nil { - return nil, fmt.Errorf("missing org for completion: %w", err) - } - - team, err := GetTeam(cmd) - if err != nil { - return nil, fmt.Errorf("missing team canonical for completion: %w", err) - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - teams, _, err := m.ListTeamMembers(org, team) - if err != nil { - return nil, fmt.Errorf("cannot list members from team %q for completion: %w", team, err) - } - - return teams, nil -} - -func CompleteTeamMemberID(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - members, err := TeamMembersCompletionHelper(cmd) - if err != nil { - return cobra.AppendActiveHelp([]cobra.Completion{}, err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, len(members)) - for i, member := range members { - if member.ID == nil { - continue - } - - idStr := strconv.Itoa(int(*member.ID)) - if strings.HasPrefix(idStr, toComplete) || toComplete == "" { - emailStr := "" - if member.Email != nil { - emailStr = member.Email.String() - } - completions[i] = cobra.CompletionWithDesc(idStr, emailStr+": "+member.Username) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func CompleteTeamMemberUsername(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - members, err := TeamMembersCompletionHelper(cmd) - if err != nil { - return cobra.AppendActiveHelp([]cobra.Completion{}, err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, len(members)) - for i, member := range members { - username := member.Username - if strings.HasPrefix(username, toComplete) || toComplete == "" { - emailStr := "" - if member.Email != nil { - emailStr = member.Email.String() - } - completions[i] = cobra.CompletionWithDesc(username, emailStr+": "+username) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func CompleteTeamMemberEmail(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - members, err := TeamMembersCompletionHelper(cmd) - if err != nil { - return cobra.AppendActiveHelp([]cobra.Completion{}, err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, len(members)) - for i, member := range members { - emailStr := "" - if member.Email != nil { - emailStr = member.Email.String() - } - if strings.HasPrefix(emailStr, toComplete) || toComplete == "" { - completions[i] = cobra.CompletionWithDesc(emailStr, member.Username) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func CompleteTeamMemberEmailOrUsername(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - members, err := TeamMembersCompletionHelper(cmd) - if err != nil { - return cobra.AppendActiveHelp([]cobra.Completion{}, err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, len(members)) - for i, member := range members { - emailStr := "" - if member.Email != nil { - emailStr = member.Email.String() - } - username := member.Username - if strings.HasPrefix(emailStr, toComplete) || - strings.HasPrefix(username, toComplete) || - toComplete == "" { - completions[i] = cobra.CompletionWithDesc(emailStr, username) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func CompleteTeamMemberAny(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - members, err := TeamMembersCompletionHelper(cmd) - if err != nil { - return cobra.AppendActiveHelp([]cobra.Completion{}, err.Error()), - cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, len(members)) - for i, member := range members { - // Try to complete any of those team member attributes, fullname, email, id - emailStr := "" - if member.Email != nil { - emailStr = member.Email.String() - } - username := member.Username - idStr := strconv.Itoa(int(ptr.Value(member.ID))) - if strings.HasPrefix(idStr, toComplete) || toComplete == "" { - completions[i] = cobra.CompletionWithDesc(idStr, username) - continue - } - - if strings.HasPrefix(username, toComplete) || toComplete == "" { - completions[i] = cobra.CompletionWithDesc(username, username) - continue - } - - if strings.HasPrefix(emailStr, toComplete) || toComplete == "" { - completions[i] = cobra.CompletionWithDesc(emailStr, username) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func AddTeamMemberIDFlag(cmd *cobra.Command) string { - cmd.Flags().Uint32P(teamMemberIDFlagName, "i", 0, "specify a team member id") - cmd.RegisterFlagCompletionFunc(teamMemberIDFlagName, CompleteTeamMemberID) - return teamMemberIDFlagName -} - -func GetTeamMemberID(cmd *cobra.Command) (uint32, error) { - return cmd.Flags().GetUint32(teamMemberIDFlagName) -} - -func AddTeamMemberUsernameFlag(cmd *cobra.Command) string { - cmd.Flags().StringP(teamMemberFlagName, "m", "", "specify a team member by its username") - cmd.RegisterFlagCompletionFunc(teamMemberFlagName, CompleteTeamMemberUsername) - return teamMemberFlagName -} - -func GetTeamMember(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(teamMemberFlagName) -} - -func AddTeamMemberEmailFlagName(cmd *cobra.Command) string { - cmd.Flags().StringP(teamMemberEmailFlagName, "e", "", "team member email") - cmd.RegisterFlagCompletionFunc(teamMemberEmailFlagName, CompleteTeamMemberEmail) - return teamMemberEmailFlagName -} - -func GetTeamMemberUsername(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(teamMemberUsernameFlagName) -} - -func AddTeamCreatedAt(cmd *cobra.Command) string { - cmd.Flags().Time(teamCreatedAtFlagName, time.UnixMilli(0), []string{}, "filter by creation timestamp") - return teamCreatedAtFlagName -} - -func GetTeamCreatedAt(cmd *cobra.Command) (*uint64, error) { - time, err := cmd.Flags().GetTime(teamCreatedAtFlagName) - if err != nil { - return nil, err - } - return ptr.Ptr(uint64(time.UnixMilli())), nil -} - -func AddTeamOrderBy(cmd *cobra.Command) string { - cmd.Flags().String(teamOrderByFlagName, "asc", "specify the output order, asc for ascending and desc for descending") - cmd.RegisterFlagCompletionFunc(teamOrderByFlagName, cobra.FixedCompletions([]string{"asc", "desc"}, cobra.ShellCompDirectiveNoFileComp)) - return teamOrderByFlagName -} - -func GetTeamOrderBy(cmd *cobra.Command) (*middleware.TeamOrderByParam, error) { - orderByStr, err := cmd.Flags().GetString(teamOrderByFlagName) - if err != nil { - return &middleware.Ascending, err - } - - switch orderByStr { - case "desc", "descending": - return &middleware.Descending, nil - default: - return &middleware.Ascending, nil - } -} - -func AddTeamOwnerFlag(cmd *cobra.Command) string { - cmd.Flags().String(teamOwnerFlagName, "", "specify a team owner canonical") - cmd.RegisterFlagCompletionFunc(teamOwnerFlagName, CompleteTeamOwnerCanonical) - return teamOwnerFlagName -} - -func CompleteTeamOwnerCanonical(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { - org, err := GetOrg(cmd) - if err != nil { - return cobra.AppendActiveHelp([]string{}, "missing org for completion: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - api := common.NewAPI() - m := middleware.NewMiddleware(api) - - users, _, err := m.ListMembers(org) - if err != nil { - return cobra.AppendActiveHelp([]string{}, "failed to list current org members: "+err.Error()), cobra.ShellCompDirectiveNoFileComp - } - - completions := make([]cobra.Completion, len(users)) - for i, user := range users { - if strings.HasPrefix(user.Username, toComplete) { - completions[i] = cobra.CompletionWithDesc(user.Username, user.Email.String()) - } - } - - return completions, cobra.ShellCompDirectiveNoFileComp -} - -func GetTeamOwner(cmd *cobra.Command) (string, error) { - return cmd.Flags().GetString(teamOwnerFlagName) -} - -func AddTeamRolesFlag(cmd *cobra.Command) string { - cmd.Flags().StringArrayP(teamRolesFlagName, "r", []string{}, "list of role canonical to associate to the team") - cmd.RegisterFlagCompletionFunc(teamRolesFlagName, CompleteRoleCanonical) - return teamRolesFlagName -} - -func GetTeamRoles(cmd *cobra.Command) ([]string, error) { - return cmd.Flags().GetStringArray(teamRolesFlagName) -} diff --git a/internal/cyout/errors.go b/internal/cyout/errors.go deleted file mode 100644 index e5ac1223b..000000000 --- a/internal/cyout/errors.go +++ /dev/null @@ -1,130 +0,0 @@ -package cyout - -import ( - "fmt" - "io" - "strings" - - "github.com/charmbracelet/lipgloss" - "github.com/spf13/cobra" - "github.com/spf13/pflag" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// apiErrorInfo is satisfied by *middleware.APIResponseError. -// Defined locally to avoid importing cmd/cycloid/middleware from internal/. -type apiErrorInfo interface { - error - HTTPStatusCode() int - HTTPRequestMethod() string - HTTPRequestPath() string - HTTPRequestBody() []byte - HTTPResponseBody() []byte -} - -// apiErrorPayloader is optionally implemented by errors that carry a parsed payload. -type apiErrorPayloader interface { - GetPayload() *models.ErrorPayload -} - -var ( - styleHeader = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("9")) // bold red - styleDim = lipgloss.NewStyle().Foreground(lipgloss.Color("8")) // dim gray - styleEndpoint = lipgloss.NewStyle().Foreground(lipgloss.Color("11")) // yellow - styleCode = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("8")) // bold dim - styleCmdHint = lipgloss.NewStyle().Foreground(lipgloss.Color("8")).Italic(true) // dim italic -) - -// printError writes a formatted error block to cmd's stderr. -// API errors get a rich display with status, method, path, payload details, and request ID. -// Local errors get a one-line command hint showing what was invoked. -func printError(cmd *cobra.Command, err error) { - w := cmd.ErrOrStderr() - if ae, ok := err.(apiErrorInfo); ok { - printAPIError(w, ae) - return - } - printLocalError(w, cmd) -} - -func printAPIError(w io.Writer, ae apiErrorInfo) { - // Header: "API Error 422 — POST /organizations/myorg/projects" - status := ae.HTTPStatusCode() - method := ae.HTTPRequestMethod() - path := ae.HTTPRequestPath() - - header := fmt.Sprintf("%s %s %s", - styleHeader.Render(fmt.Sprintf("API Error %d", status)), - styleDim.Render("—"), - styleEndpoint.Render(method+" "+path), - ) - fmt.Fprintln(w, header) - - // Optional: sanitized request body - if body := ae.HTTPRequestBody(); len(body) > 0 { - fmt.Fprintf(w, " %s %s\n", styleDim.Render("Body:"), string(body)) - } - - // Error details from parsed payload, or raw response body as fallback - var requestID string - if pe, ok := ae.(apiErrorPayloader); ok { - if p := pe.GetPayload(); p != nil && len(p.Errors) > 0 { - for _, item := range p.Errors { - if item == nil { - continue - } - printErrorItem(w, item) - } - requestID = p.RequestID - } - } - - if requestID == "" { - // No structured payload — fall back to raw response body - raw := strings.TrimSpace(string(ae.HTTPResponseBody())) - if raw != "" { - fmt.Fprintf(w, " %s\n", raw) - } - } - - if requestID != "" { - fmt.Fprintf(w, " %s\n", styleDim.Render("Request-ID: "+requestID)) - } - - fmt.Fprintln(w) -} - -func printErrorItem(w io.Writer, item *models.ErrorDetailsItem) { - code := "" - if item.Code != nil { - code = styleCode.Render("["+*item.Code+"]") + " " - } - - msg := "" - if item.Message != nil { - msg = *item.Message - } - - fmt.Fprintf(w, " %s%s\n", code, msg) - - for _, d := range item.Details { - if d != "" { - fmt.Fprintf(w, " %s %s\n", styleDim.Render("·"), d) - } - } -} - -func printLocalError(w io.Writer, cmd *cobra.Command) { - // Build "cy project get --org myorg" hint from the command path and set flags - var parts []string - parts = append(parts, cmd.CommandPath()) - cmd.Flags().Visit(func(f *pflag.Flag) { - parts = append(parts, "--"+f.Name+"="+f.Value.String()) - }) - - hint := strings.Join(parts, " ") - if hint != "" { - fmt.Fprintln(w, styleCmdHint.Render(hint)) - } -} diff --git a/internal/cyout/errors_test.go b/internal/cyout/errors_test.go deleted file mode 100644 index 46ee004ce..000000000 --- a/internal/cyout/errors_test.go +++ /dev/null @@ -1,166 +0,0 @@ -package cyout - -import ( - "bytes" - "errors" - "testing" - - "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" - - "github.com/cycloidio/cycloid-cli/client/models" -) - -// fakeAPIError implements apiErrorInfo + apiErrorPayloader for tests. -type fakeAPIError struct { - statusCode int - method string - path string - reqBody []byte - respBody []byte - payload *models.ErrorPayload -} - -func (e *fakeAPIError) Error() string { return "fake api error" } -func (e *fakeAPIError) HTTPStatusCode() int { return e.statusCode } -func (e *fakeAPIError) HTTPRequestMethod() string { return e.method } -func (e *fakeAPIError) HTTPRequestPath() string { return e.path } -func (e *fakeAPIError) HTTPRequestBody() []byte { return e.reqBody } -func (e *fakeAPIError) HTTPResponseBody() []byte { return e.respBody } -func (e *fakeAPIError) GetPayload() *models.ErrorPayload { return e.payload } - -func ptrString(s string) *string { return &s } - -func newTestCmd() *cobra.Command { - cmd := &cobra.Command{Use: "test"} - var buf bytes.Buffer - cmd.SetErr(&buf) - return cmd -} - -func captureError(cmd *cobra.Command, err error) string { - var buf bytes.Buffer - cmd.SetErr(&buf) - printError(cmd, err) - return buf.String() -} - -func TestPrintError_LocalError(t *testing.T) { - cmd := newTestCmd() - out := captureError(cmd, errors.New("missing flag: --project")) - // Local error: only command hint (no "API Error" line), main.go handles the Error: line - assert.NotContains(t, out, "API Error") -} - -func TestPrintError_APIErrorWithPayload(t *testing.T) { - cmd := newTestCmd() - err := &fakeAPIError{ - statusCode: 422, - method: "GET", - path: "/organizations", - respBody: []byte(`{"errors":[{"code":"Invalid","message":"This endpoint cannot be used with API Key"}]}`), - payload: &models.ErrorPayload{ - Errors: []*models.ErrorDetailsItem{ - {Code: ptrString("Invalid"), Message: ptrString("This endpoint cannot be used with API Key")}, - }, - }, - } - out := captureError(cmd, err) - assert.Contains(t, out, "API Error 422") - assert.Contains(t, out, "GET") - assert.Contains(t, out, "/organizations") - assert.Contains(t, out, "Invalid") - assert.Contains(t, out, "This endpoint cannot be used with API Key") -} - -func TestPrintError_APIErrorMultipleErrors(t *testing.T) { - cmd := newTestCmd() - err := &fakeAPIError{ - statusCode: 422, - method: "POST", - path: "/organizations/myorg/projects", - payload: &models.ErrorPayload{ - Errors: []*models.ErrorDetailsItem{ - {Code: ptrString("RequiredField"), Message: ptrString("name: must not be empty")}, - {Code: ptrString("InvalidType"), Message: ptrString("color: must be a valid hex color")}, - }, - }, - } - out := captureError(cmd, err) - assert.Contains(t, out, "RequiredField") - assert.Contains(t, out, "name: must not be empty") - assert.Contains(t, out, "InvalidType") - assert.Contains(t, out, "color: must be a valid hex color") -} - -func TestPrintError_APIErrorWithDetails(t *testing.T) { - cmd := newTestCmd() - err := &fakeAPIError{ - statusCode: 422, - method: "POST", - path: "/organizations/myorg/projects", - payload: &models.ErrorPayload{ - Errors: []*models.ErrorDetailsItem{ - { - Code: ptrString("InvalidValue"), - Message: ptrString("invalid color"), - Details: []string{"accepted values are #RRGGBB hex codes"}, - }, - }, - }, - } - out := captureError(cmd, err) - assert.Contains(t, out, "invalid color") - assert.Contains(t, out, "accepted values are #RRGGBB hex codes") -} - -func TestPrintError_APIErrorWithRequestBody(t *testing.T) { - cmd := newTestCmd() - err := &fakeAPIError{ - statusCode: 422, - method: "POST", - path: "/organizations/myorg/credentials", - reqBody: []byte(`{"name":"my-cred","ssh_key":"[REDACTED]"}`), - payload: &models.ErrorPayload{ - Errors: []*models.ErrorDetailsItem{ - {Code: ptrString("InvalidField"), Message: ptrString("unsupported type")}, - }, - }, - } - out := captureError(cmd, err) - assert.Contains(t, out, "Body:") - assert.Contains(t, out, "my-cred") - assert.Contains(t, out, "[REDACTED]") -} - -func TestPrintError_APIErrorRawBodyFallback(t *testing.T) { - // No structured payload — falls back to raw response body - cmd := newTestCmd() - err := &fakeAPIError{ - statusCode: 503, - method: "GET", - path: "/health", - respBody: []byte("Service Unavailable"), - } - out := captureError(cmd, err) - assert.Contains(t, out, "API Error 503") - assert.Contains(t, out, "Service Unavailable") -} - -func TestPrintError_APIErrorWithRequestID(t *testing.T) { - cmd := newTestCmd() - err := &fakeAPIError{ - statusCode: 500, - method: "GET", - path: "/organizations", - payload: &models.ErrorPayload{ - RequestID: "550e8400-e29b-41d4-a716-446655440000", - Errors: []*models.ErrorDetailsItem{ - {Code: ptrString("InternalError"), Message: ptrString("unexpected failure")}, - }, - }, - } - out := captureError(cmd, err) - assert.Contains(t, out, "Request-ID") - assert.Contains(t, out, "550e8400-e29b-41d4-a716-446655440000") -} diff --git a/internal/cyout/print.go b/internal/cyout/print.go deleted file mode 100644 index 22c52e33f..000000000 --- a/internal/cyout/print.go +++ /dev/null @@ -1,47 +0,0 @@ -// Package cyout provides a one-liner helper to replace the 3-line -// GetOutput/GetPrinter/SmartPrint boilerplate used across all commands. -package cyout - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cycloidio/cycloid-cli/internal/cyargs" - "github.com/cycloidio/cycloid-cli/printer" - "github.com/cycloidio/cycloid-cli/printer/factory" -) - -// Print outputs obj (or err) using the command's --output flag. -// Replaces the GetOutput/GetPrinter/SmartPrint 3-liner. -func Print(cmd *cobra.Command, obj interface{}, err error, errMsg string) error { - return PrintWithOptions(cmd, obj, err, errMsg, printer.Options{}) -} - -// PrintWithOptions outputs with explicit column/identifier options for table mode. -// Commands with curated views call this to specify default columns and identifier. -// -// On error: writes a formatted error block to stderr (API errors include status, -// method, path, payload details, request ID; local errors show command context), -// then returns the wrapped error so main.go can print the final "Error:" summary line. -// -// On success: writes the object to stdout using the selected printer. -func PrintWithOptions(cmd *cobra.Command, obj interface{}, err error, errMsg string, opts printer.Options) error { - if err != nil { - printError(cmd, err) - if errMsg != "" { - return fmt.Errorf("%s: %w", errMsg, err) - } - return err - } - - output, oerr := cyargs.GetOutput(cmd) - if oerr != nil { - return oerr - } - p, perr := factory.GetPrinter(output) - if perr != nil { - return perr - } - return printer.SmartPrint(p, obj, nil, "", opts, cmd.OutOrStdout()) -} diff --git a/internal/cyout/register.go b/internal/cyout/register.go deleted file mode 100644 index f799fba54..000000000 --- a/internal/cyout/register.go +++ /dev/null @@ -1,40 +0,0 @@ -package cyout - -import ( - "reflect" - "strings" - - "github.com/spf13/cobra" -) - -const annotationFields = "cyout.fields" - -// RegisterModel stores the exported field names of model in cmd.Annotations. -// The global --output completion function reads these to offer model-aware suggestions. -// Call this in NewXCommand() for every command that outputs structured data. -func RegisterModel(cmd *cobra.Command, model interface{}) { - t := reflect.TypeOf(model) - if t.Kind() == reflect.Ptr { - t = t.Elem() - } - fields := make([]string, 0, t.NumField()) - for i := 0; i < t.NumField(); i++ { - if t.Field(i).IsExported() { - fields = append(fields, strings.ToLower(t.Field(i).Name)) - } - } - if cmd.Annotations == nil { - cmd.Annotations = map[string]string{} - } - cmd.Annotations[annotationFields] = strings.Join(fields, ",") -} - -// GetModelFields reads the field names stored by RegisterModel from a command's annotations. -// Returns nil if RegisterModel was not called for this command. -func GetModelFields(cmd *cobra.Command) []string { - raw, ok := cmd.Annotations[annotationFields] - if !ok || raw == "" { - return nil - } - return strings.Split(raw, ",") -} diff --git a/internal/ptr/ptr.go b/internal/ptr/ptr.go deleted file mode 100644 index 238b6776e..000000000 --- a/internal/ptr/ptr.go +++ /dev/null @@ -1,13 +0,0 @@ -package ptr - -// Ptr returns a pointer address of given value -func Ptr[V any](v V) *V { return &v } - -// Value returns a value of given pointer -func Value[V any](v *V) V { - if v == nil { - var noop V - return noop - } - return *v -} diff --git a/internal/testcfg/config.go b/internal/testcfg/config.go deleted file mode 100644 index f54e537b0..000000000 --- a/internal/testcfg/config.go +++ /dev/null @@ -1,384 +0,0 @@ -package testcfg - -import ( - "errors" - "fmt" - "log" - "os" - "strconv" - "strings" - "time" - - "github.com/cycloidio/cycloid-cli/client/models" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/common" - "github.com/cycloidio/cycloid-cli/cmd/cycloid/middleware" - "github.com/cycloidio/cycloid-cli/internal/ptr" -) - -type Config struct { - APIKey string - APIUrl string - Org string - // GitCredential models.Credential - ConfigRepo *models.ConfigRepository - CatalogRepo *models.ServiceCatalogSource - CatalogRepoVersionStacks *middleware.StackVersion - Middleware middleware.Middleware - // Common project to use for tests that require one - Project *models.Project - // Common environment to use for tests that require one - Environment *models.Environment - // Common component to use for tests that require one - Component *models.Component - // Slice containing all functions to exec for cleaning common test resources - cleanupFuncs []func() -} - -func NewConfig(testName string) (*Config, error) { - if len(testName) < 1 { - return nil, fmt.Errorf("testName argument must not be empty") - } - - var ( - localGitSSHKey = strings.Join([]string{ - "-----BEGIN OPENSSH PRIVATE KEY-----", - "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW", - "QyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+AAAAJjCF9jzwhfY", - "8wAAAAtzc2gtZWQyNTUxOQAAACD8O9mhkl5CAiD0NLeQcoPf1duYHImQlTjOXcCOgHmC+A", - "AAAEC0ryBZ1uJQ2drmjsO+WpsC2E/5SWheJD/r8+Q4LghWxfw72aGSXkICIPQ0t5Byg9/V", - "25gciZCVOM5dwI6AeYL4AAAAE2N5Y2xvaWRAZXhhbXBsZS5jb20BAg==", - "-----END OPENSSH PRIVATE KEY-----", - }, "\n") - localGitCredential = "local-git" - dockerIPAM = EnvDefault("DOCKER_IPAM", "192.168.10") - configRepoName = "cli-test-config" - configRepository = "cli-test-config" - configRepoURL = fmt.Sprintf("git@%s.7:/git-server/repos/backend-test-config-repo.git", dockerIPAM) - configRepoBranch = "master" - isDefault = true - gitCred = "github" - catalogRepo = "cli-test-stacks" - catalogRepoName = "CLI test catalog" - catalogRepoURL = "https://github.com/cycloidio/cycloid-cli-test-catalog.git" - catalogRepoBranch = "stacks" - defaultStackCanonical = "stack-e2e-stackforms" - defaultStackUseCase = "default" - ) - - var config = &Config{} - config.ConfigRepo = &models.ConfigRepository{ - Name: &configRepoName, - Canonical: &configRepository, - URL: &configRepoURL, - Branch: configRepoBranch, - CredentialCanonical: gitCred, - Default: &isDefault, - } - config.CatalogRepo = &models.ServiceCatalogSource{ - Name: &catalogRepoName, - Canonical: &catalogRepo, - URL: &catalogRepoURL, - Branch: catalogRepoBranch, - CredentialCanonical: gitCred, - } - - provisionAPI, _ := strconv.ParseBool(EnvDefault("CY_TEST_PROVISION_API", "1")) - config.APIUrl = EnvDefault("CY_TEST_API_URL", "http://"+dockerIPAM+".10:3001") - config.Org = EnvDefault("CY_TEST_ROOT_ORG", "cycloid") - licence, ok := os.LookupEnv("API_LICENCE_KEY") - if !ok && provisionAPI { - return config, fmt.Errorf("licence required for provisionning, set it with API_LICENCE_KEY") - } - - // If we provision the api, we will try to login first - if !provisionAPI { - apiKey, ok := os.LookupEnv("CY_TEST_API_KEY") - if !ok { - return config, fmt.Errorf("api key not set in CY_TEST_API_KEY env var") - } - config.APIKey = apiKey - } - - api := common.NewAPI( - common.WithURL(config.APIUrl), - common.WithInsecure(true), - common.WithToken(config.APIKey), - ) - m := middleware.NewMiddleware(api) - config.Middleware = m - - var ( - username = "administrator" - fullName = "administrator" - email = "admin@cycloid.io" - password = "cycloidadmin" - apiKeyCanonical = "admin-" + testName - ) - - if provisionAPI { - // try to login, is successful, console is initialized - init, _, err := m.InitFirstOrg(config.Org, username, fullName, email, password, licence, &apiKeyCanonical) - if err != nil { - return nil, fmt.Errorf("failed to init console: %w", err) - } - - config.APIKey = *init.APIKey - api.Config.Token = *init.APIKey - - // Write the API for the User, we'll look up a better way later - root, err := FindRepoRoot() - if err != nil { - return nil, err - } - - apiKeyEnvFile := strings.Join([]string{ - "CY_API_KEY=" + config.APIKey, - "CY_API_URL=" + config.APIUrl, - "CY_ORG=" + config.Org, - }, "\n") - err = os.WriteFile(root+"/.api_key", []byte(apiKeyEnvFile), 0666) - if err != nil { - return nil, err - } - } - - _, _, err := m.CreateCredential(config.Org, localGitCredential, "ssh", - &models.CredentialRaw{SSHKey: localGitSSHKey}, "", localGitCredential, "", - ) - var apiErr *middleware.APIResponseError - if errors.As(err, &apiErr) { - if apiErr.StatusCode != 409 { - return config, fmt.Errorf("failed to init config repo credential: %w", err) - } - } - - currentConfigRepo, _, err := m.CreateConfigRepository(config.Org, - *config.ConfigRepo.Canonical, *config.ConfigRepo.Canonical, *config.ConfigRepo.URL, - config.ConfigRepo.Branch, localGitCredential, *config.ConfigRepo.Default, - ) - if errors.As(err, &apiErr) { - var getErr error - currentConfigRepo, _, getErr = m.GetConfigRepository(config.Org, configRepository) - if apiErr.StatusCode != 409 || getErr != nil { - return config, fmt.Errorf("failed to setup config repo: %w%w", err, getErr) - } - } - - config.ConfigRepo = currentConfigRepo - - _, _, err = m.CreateCatalogRepository(config.Org, *config.CatalogRepo.Canonical, - *config.CatalogRepo.URL, config.CatalogRepo.Branch, "", "local", "", - ) - if errors.As(err, &apiErr) { - if apiErr.StatusCode != 409 { - return config, fmt.Errorf("failed to setup catalog repo: %w", err) - } - } - - _, _, err = m.RefreshCatalogRepository(config.Org, *config.CatalogRepo.Canonical) - if err != nil { - return config, fmt.Errorf("failed to refresh catalog repo: %w", err) - } - - stackRef := config.Org + ":" + defaultStackCanonical - stackVersions, _, err := m.ListStackVersions(config.Org, stackRef) - if err != nil { - return config, fmt.Errorf("failed to list stack versions: %w", err) - } - - for _, v := range stackVersions { - if ptr.Value(v.Name) == catalogRepoBranch { - config.CatalogRepoVersionStacks = v - break - } - } - if config.CatalogRepoVersionStacks == nil { - return config, fmt.Errorf("failed to find latest catalog repo version after refresh") - } - - project, err := config.NewTestProject("common") - if err != nil { - return config, err - } - config.Project = project - - environment, err := config.NewTestEnv("common", *project.Canonical) - if err != nil { - return config, err - } - config.Environment = environment - - component, err := config.NewTestComponent( - *project.Canonical, *environment.Canonical, "common", stackRef, defaultStackUseCase, "", "", ptr.Value(config.CatalogRepoVersionStacks.CommitHash), nil, - ) - if err != nil { - return config, err - } - config.Component = component - - stackConfig, _, err := m.GetComponentStackConfig(config.Org, *project.Canonical, *environment.Canonical, *component.Canonical, defaultStackUseCase, "", "", ptr.Value(config.CatalogRepoVersionStacks.CommitHash)) - if err != nil { - return config, err - } - - vars, err := common.FormUseCaseToFormVars(stackConfig, defaultStackUseCase) - if err != nil { - return config, err - } - common.UpdateMapField("types.tests.string", RandomCanonical("common"), vars) - - return config, nil -} - -// NewTestProject will create a project with a random canonical derived from identifier -// and return the project, the function to defer for its deletion and error. -// The func will always be returned so even if err != nil, defer the func. -func (config *Config) NewTestProject(identifier string) (*models.Project, error) { - var ( - project = RandomCanonical(identifier) - description = "Testing project " + identifier - configRepository = *config.ConfigRepo.Canonical - owner = "" - team = "" - color = "default" - icon = "inventory" - ) - - m := config.Middleware - - out, _, err := m.CreateProject(config.Org, project, project, description, configRepository, owner, team, color, icon) - if err != nil { - return nil, fmt.Errorf("failed to setup test project: %w", err) - } - - config.AppendCleanup(func() { - _, err := m.DeleteProject(config.Org, project, middleware.DeleteOptions{}) - if err != nil { - log.Fatalf("cannot cleanup projet %q for test %q: %v", project, identifier, err) - return - } - }) - - return out, nil -} - -// setupTestProject will create an env with a random canonical derived from identifier -// and return the env, the function to defer for its deletion and error. -// The func will always be returned so even if err != nil, defer the func. -func (config *Config) NewTestEnv(identifier, project string) (*models.Environment, error) { - var ( - env = RandomCanonical(identifier) - envType = "production" - ) - - m := config.Middleware - - body := &models.NewEnvironment{ - Canonical: env, - Name: ptr.Ptr(env), - Type: ptr.Ptr(envType), - } - out, _, err := m.CreateOrgEnv(config.Org, body) - if err != nil { - return nil, fmt.Errorf("failed to setup test environment: %w", err) - } - - if project != "" { - if _, err := m.LinkEnvToProject(config.Org, project, env); err != nil { - return nil, fmt.Errorf("failed to link test environment to project: %w", err) - } - } - - config.AppendCleanup(func() { - if project != "" { - _, _ = m.UnlinkEnvFromProject(config.Org, project, env, middleware.DeleteOptions{}) - } - _, err := m.DeleteOrgEnv(config.Org, env) - if err != nil { - log.Fatalf("cannot cleanup env %q for test %q: %v", env, identifier, err) - return - } - }) - - return out, nil -} - -// setupTestProject will create an component with a random canonical derived from identifier -// and return the component, the function to defer for its deletion and error. -// The func will always be returned so even if err != nil, defer the func. -func (config *Config) NewTestComponent(project, env, identifier, stackRef, useCase, versionTag, versionBranch, versionCommitHash string, inputs models.FormVariables) (*models.Component, error) { - m := config.Middleware - component := RandomCanonical(identifier) - - // Workaround for BE-1344: RefreshCatalogRepository is async — the DB is updated - // immediately but the backend git fetch may not be complete when we try to create a - // component. On a 404 GitObject error, trigger another refresh and retry. - const maxAttempts = 5 - var outComponent *models.Component - var err error - for attempt := range maxAttempts { - if attempt > 0 { - time.Sleep(5 * time.Second) - // Nudge backend to complete git fetch before retrying - _, _, _ = m.RefreshCatalogRepository(config.Org, *config.CatalogRepo.Canonical) - } - outComponent, _, err = m.CreateOrUpdateComponent(config.Org, project, env, - component, "", component, stackRef, versionTag, versionBranch, - versionCommitHash, useCase, "", inputs) - if err == nil { - break - } - var apiErr *middleware.APIResponseError - if !errors.As(err, &apiErr) || apiErr.StatusCode != 404 || - !strings.Contains(err.Error(), "GitObject") { - return nil, err // non-transient error, fail immediately - } - log.Printf("NewTestComponent: attempt %d/%d: transient GitObject error (BE-1344), retrying: %v", - attempt+1, maxAttempts, err) - } - if err != nil { - return nil, err - } - - config.AppendCleanup(func() { - if _, err := m.DeleteComponent(config.Org, project, env, component, middleware.DeleteOptions{}); err != nil { - log.Printf("failed to cleanup component for test %q: %v", identifier, err) - } - }) - - return outComponent, nil -} - -func (config *Config) AppendCleanup(f ...func()) { - config.cleanupFuncs = append(config.cleanupFuncs, f...) -} - -func (config *Config) Cleanup() { - if config == nil { - return - } - - for _, f := range config.cleanupFuncs { - defer f() - } -} - -// NewTestChildOrg is a helper function that create a suborg for a -// specific test and return a function to defer() for its deletion. -func (config *Config) NewTestChildOrg(parent, child string) (func(), error) { - m := config.Middleware - deferFunc := func() { - _, err := m.DeleteOrganization(child) - if err != nil { - log.Fatalf("Failed to delete org %q: %v", child, err) - return - } - } - - _, _, err := m.CreateOrganizationChild(parent, child, nil) - if err != nil { - return deferFunc, fmt.Errorf("failed to create child org %q: %v", child, err) - } - - return deferFunc, nil -} diff --git a/internal/testcfg/helpers.go b/internal/testcfg/helpers.go deleted file mode 100644 index 027e69bfb..000000000 --- a/internal/testcfg/helpers.go +++ /dev/null @@ -1,45 +0,0 @@ -package testcfg - -import ( - "fmt" - "math/rand" - "os" - "path/filepath" - "strings" -) - -func RandomCanonical(baseName string) string { - var size = 4 - var letterRunes = []rune("abcdefghijklmnopqrstuvwxyz") - - b := make([]rune, size) - for i := range b { - b[i] = letterRunes[rand.Intn(len(letterRunes))] - } - return strings.ToLower(baseName) + "-" + string(b) -} - -func EnvDefault(envVar, defaultValue string) string { - if value, ok := os.LookupEnv(envVar); ok { - return value - } - - return defaultValue -} - -func FindRepoRoot() (string, error) { - path := ".git" - for i := 0; true; i++ { - if pwd, err := os.Getwd(); pwd == "/" || err != nil { - return "", fmt.Errorf("failed to find project root we reached /") - } - - testPath := strings.Repeat("../", i) + path - _, err := os.Stat(testPath) - if err == nil { - return filepath.Join(filepath.Dir(testPath)), nil - } - } - - return "", fmt.Errorf("failed for some reason") -} diff --git a/internal/utils/utils.go b/internal/utils/utils.go deleted file mode 100644 index 14668efef..000000000 --- a/internal/utils/utils.go +++ /dev/null @@ -1,32 +0,0 @@ -package utils - -// Coalesce will return the first non-empty value -func Coalesce[T any](values ...*T) *T { - for _, v := range values { - if v != nil { - return v - } - } - - return nil -} - -func CoalesceNonZero[T comparable](values ...T) T { - var zero T - for _, v := range values { - if v != zero { - return v - } - } - return zero -} - -func CoalesceNonZeroPtr[T comparable](values ...T) *T { - var zero T - for _, v := range values { - if v != zero { - return &v - } - } - return nil -} diff --git a/internal/version/info.go b/internal/version/info.go deleted file mode 100644 index e262a06a4..000000000 --- a/internal/version/info.go +++ /dev/null @@ -1,15 +0,0 @@ -package version - -import ( - "runtime" -) - -// Build information. Populated at build-time. -var ( - Version string - Revision string - Branch string - BuildOrigin string - BuildDate string - GoVersion = runtime.Version() -) diff --git a/interpolator/docs.go b/interpolator/docs.go deleted file mode 100644 index d7991eaf1..000000000 --- a/interpolator/docs.go +++ /dev/null @@ -1,39 +0,0 @@ -package interpolator - -import ( - "strings" - - "github.com/cycloidio/cycloid-cli/interpolator/formatters" - "github.com/cycloidio/cycloid-cli/interpolator/transformers" -) - -const URIDoc = `An URI resource path is defined as follows: - - cy://[?=&] - -Where: - - Any valid path from our API as defined in our api docs: https://docs.cycloid.io/api/ - - - Urlencoded parameters, they can be either an API parameter, or a formatting parameter. - formatting parameters allow you to format the output of the API. - - By default the output will be JSON for objects and array and a string for any simple value. - -