diff --git a/python/connector/connector_register.go b/python/connector/connector_register.go index 15d73f7f8..8ae86c4b2 100755 --- a/python/connector/connector_register.go +++ b/python/connector/connector_register.go @@ -64,6 +64,8 @@ import ( cloudbuild_alpha_connector "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudbuild/alpha_connector" + cloudbuildv2_alpha_connector "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudbuildv2/alpha_connector" + clouddeploy_connector "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/clouddeploy/connector" clouddeploy_beta_connector "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/clouddeploy/beta_connector" @@ -339,6 +341,8 @@ func InitializeServer(grpcServer *grpc.Server) *connectorpb.InitializeResponse { cloudbuild_alpha_connector.RegisterServers(grpcServer) + cloudbuildv2_alpha_connector.RegisterServers(grpcServer) + clouddeploy_connector.RegisterServers(grpcServer) clouddeploy_beta_connector.RegisterServers(grpcServer) diff --git a/python/proto/BUILD b/python/proto/BUILD index 673b0a3eb..6d145dd62 100644 --- a/python/proto/BUILD +++ b/python/proto/BUILD @@ -30,4 +30,4 @@ go_proto_library( load("//:connector_rules.bzl", "python_protos") -python_protos(packages = ["ud/graphite/mmv2/connector","apikeys","apikeys/beta","apikeys/alpha","apigee","apigee/beta","apigee/alpha","assuredworkloads","assuredworkloads/beta","assuredworkloads/alpha","billingbudgets","billingbudgets/beta","billingbudgets/alpha","bigquery","bigquery/beta","bigquery/alpha","bigqueryreservation","bigqueryreservation/beta","bigqueryreservation/alpha","binaryauthorization","binaryauthorization/beta","binaryauthorization/alpha","cloudbuild","cloudbuild/beta","cloudbuild/alpha","clouddeploy","clouddeploy/beta","clouddeploy/alpha","cloudfunctions","cloudfunctions/beta","cloudfunctions/alpha","cloudidentity","cloudidentity/beta","cloudidentity/alpha","cloudkms","cloudkms/beta","cloudkms/alpha","cloudresourcemanager","cloudresourcemanager/beta","cloudresourcemanager/alpha","cloudscheduler","cloudscheduler/beta","cloudscheduler/alpha","compute","compute/beta","compute/alpha","configcontroller/alpha","containeranalysis","containeranalysis/beta","containeranalysis/alpha","containeraws","containeraws/beta","containeraws/alpha","containerazure","containerazure/beta","containerazure/alpha","datafusion/alpha","datafusion/beta","dataplex","dataplex/beta","dataplex/alpha","dataproc","dataproc/beta","dataproc/alpha","dlp","dlp/beta","dlp/alpha","eventarc","eventarc/beta","eventarc/alpha","filestore","filestore/beta","filestore/alpha","firebase/alpha","firebase/beta","firebaserules","firebaserules/beta","firebaserules/alpha","gameservices","gameservices/beta","gameservices/alpha","gkehub/alpha","gkehub/beta","iam","iam/beta","iam/alpha","iap","iap/beta","iap/alpha","identitytoolkit","identitytoolkit/beta","identitytoolkit/alpha","logging","logging/beta","logging/alpha","monitoring","monitoring/beta","monitoring/alpha","networkconnectivity","networkconnectivity/beta","networkconnectivity/alpha","networksecurity/alpha","networksecurity/beta","networkservices/alpha","networkservices/beta","orgpolicy","orgpolicy/beta","orgpolicy/alpha","osconfig","osconfig/beta","osconfig/alpha","pubsub","pubsub/beta","pubsub/alpha","run/alpha","servicemanagement","servicemanagement/beta","servicemanagement/alpha","storage","storage/beta","storage/alpha","privateca","privateca/beta","privateca/alpha","vertexai","vertexai/beta","vertexai/alpha","vmware/alpha","vpcaccess","vpcaccess/beta","vpcaccess/alpha","recaptchaenterprise","recaptchaenterprise/beta","recaptchaenterprise/alpha"]) +python_protos(packages = ["ud/graphite/mmv2/connector","apikeys","apikeys/beta","apikeys/alpha","apigee","apigee/beta","apigee/alpha","assuredworkloads","assuredworkloads/beta","assuredworkloads/alpha","billingbudgets","billingbudgets/beta","billingbudgets/alpha","bigquery","bigquery/beta","bigquery/alpha","bigqueryreservation","bigqueryreservation/beta","bigqueryreservation/alpha","binaryauthorization","binaryauthorization/beta","binaryauthorization/alpha","cloudbuild","cloudbuild/beta","cloudbuild/alpha","cloudbuildv2/alpha","clouddeploy","clouddeploy/beta","clouddeploy/alpha","cloudfunctions","cloudfunctions/beta","cloudfunctions/alpha","cloudidentity","cloudidentity/beta","cloudidentity/alpha","cloudkms","cloudkms/beta","cloudkms/alpha","cloudresourcemanager","cloudresourcemanager/beta","cloudresourcemanager/alpha","cloudscheduler","cloudscheduler/beta","cloudscheduler/alpha","compute","compute/beta","compute/alpha","configcontroller/alpha","containeranalysis","containeranalysis/beta","containeranalysis/alpha","containeraws","containeraws/beta","containeraws/alpha","containerazure","containerazure/beta","containerazure/alpha","datafusion/alpha","datafusion/beta","dataplex","dataplex/beta","dataplex/alpha","dataproc","dataproc/beta","dataproc/alpha","dlp","dlp/beta","dlp/alpha","eventarc","eventarc/beta","eventarc/alpha","filestore","filestore/beta","filestore/alpha","firebase/alpha","firebase/beta","firebaserules","firebaserules/beta","firebaserules/alpha","gameservices","gameservices/beta","gameservices/alpha","gkehub/alpha","gkehub/beta","iam","iam/beta","iam/alpha","iap","iap/beta","iap/alpha","identitytoolkit","identitytoolkit/beta","identitytoolkit/alpha","logging","logging/beta","logging/alpha","monitoring","monitoring/beta","monitoring/alpha","networkconnectivity","networkconnectivity/beta","networkconnectivity/alpha","networksecurity/alpha","networksecurity/beta","networkservices/alpha","networkservices/beta","orgpolicy","orgpolicy/beta","orgpolicy/alpha","osconfig","osconfig/beta","osconfig/alpha","pubsub","pubsub/beta","pubsub/alpha","run/alpha","servicemanagement","servicemanagement/beta","servicemanagement/alpha","storage","storage/beta","storage/alpha","privateca","privateca/beta","privateca/alpha","vertexai","vertexai/beta","vertexai/alpha","vmware/alpha","vpcaccess","vpcaccess/beta","vpcaccess/alpha","recaptchaenterprise","recaptchaenterprise/beta","recaptchaenterprise/alpha"]) diff --git a/python/proto/cloudbuildv2/alpha/BUILD b/python/proto/cloudbuildv2/alpha/BUILD new file mode 100755 index 000000000..360c509a3 --- /dev/null +++ b/python/proto/cloudbuildv2/alpha/BUILD @@ -0,0 +1,16 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +load("//:connector_rules.bzl", "proto_package") +proto_package(name="cloudbuildv2/alpha", resources=["connection","repository"]) diff --git a/python/proto/cloudbuildv2/alpha/connection.proto b/python/proto/cloudbuildv2/alpha/connection.proto new file mode 100755 index 000000000..e58ab1e3a --- /dev/null +++ b/python/proto/cloudbuildv2/alpha/connection.proto @@ -0,0 +1,112 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +syntax = "proto3"; +// All generated protos should be opaque, with "xxx_hidden_" prepended to their field names. + + +package dcl; + +import "proto/connector/sdk.proto"; +import "proto/empty.proto"; + + +enum Cloudbuildv2AlphaConnectionInstallationStateStageEnum { + Cloudbuildv2AlphaConnectionInstallationStateStageEnumNO_VALUE_DO_NOT_USE = 0; + Cloudbuildv2AlphaConnectionInstallationStateStageEnumSTAGE_UNSPECIFIED = 1; + Cloudbuildv2AlphaConnectionInstallationStateStageEnumPENDING_CREATE_APP = 2; + Cloudbuildv2AlphaConnectionInstallationStateStageEnumPENDING_USER_OAUTH = 3; + Cloudbuildv2AlphaConnectionInstallationStateStageEnumPENDING_INSTALL_APP = 4; + Cloudbuildv2AlphaConnectionInstallationStateStageEnumCOMPLETE = 5; +} + +message Cloudbuildv2AlphaConnection { + string name = 1; + string create_time = 2; + string update_time = 3; + Cloudbuildv2AlphaConnectionGithubConfig github_config = 4; + Cloudbuildv2AlphaConnectionGithubEnterpriseConfig github_enterprise_config = 5; + Cloudbuildv2AlphaConnectionInstallationState installation_state = 6; + bool disabled = 7; + bool reconciling = 8; + map annotations = 9; + string etag = 10; + string project = 11; + string location = 12; +} + +message Cloudbuildv2AlphaConnectionGithubConfig { + Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential authorizer_credential = 1; + int64 app_installation_id = 2; +} + +message Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential { + string oauth_token_secret_version = 1; + string username = 2; +} + +message Cloudbuildv2AlphaConnectionGithubEnterpriseConfig { + string host_uri = 1; + int64 app_id = 2; + string app_slug = 3; + string private_key_secret_version = 4; + string webhook_secret_secret_version = 5; + string oauth_secret_secret_version = 6; + string oauth_client_id_secret_version = 7; + Cloudbuildv2AlphaConnectionGithubEnterpriseConfigAuthorizerCredential authorizer_credential = 8; + int64 app_installation_id = 9; + Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig service_directory_config = 10; + string ssl_ca = 11; +} + +message Cloudbuildv2AlphaConnectionGithubEnterpriseConfigAuthorizerCredential { + string oauth_token_secret_version = 1; + string username = 2; +} + +message Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig { + string service = 1; +} + +message Cloudbuildv2AlphaConnectionInstallationState { + Cloudbuildv2AlphaConnectionInstallationStateStageEnum stage = 1; + string message = 2; + string action_uri = 3; +} + +message ApplyCloudbuildv2AlphaConnectionRequest { + Cloudbuildv2AlphaConnection resource = 1; + repeated LifecycleDirective lifecycle_directives = 2; + string service_account_file = 3; +} + +message DeleteCloudbuildv2AlphaConnectionRequest { + string service_account_file = 1; + Cloudbuildv2AlphaConnection resource = 2; +} + +message ListCloudbuildv2AlphaConnectionRequest { + string service_account_file = 1; + string Project = 2; + string Location = 3; +} + +message ListCloudbuildv2AlphaConnectionResponse { + repeated Cloudbuildv2AlphaConnection items = 1; +} + +service Cloudbuildv2AlphaConnectionService { + rpc ApplyCloudbuildv2AlphaConnection(ApplyCloudbuildv2AlphaConnectionRequest) returns (Cloudbuildv2AlphaConnection); + rpc DeleteCloudbuildv2AlphaConnection(DeleteCloudbuildv2AlphaConnectionRequest) returns (google.protobuf.Empty); + rpc ListCloudbuildv2AlphaConnection(ListCloudbuildv2AlphaConnectionRequest) returns (ListCloudbuildv2AlphaConnectionResponse); +} diff --git a/python/proto/cloudbuildv2/alpha/repository.proto b/python/proto/cloudbuildv2/alpha/repository.proto new file mode 100755 index 000000000..711e18698 --- /dev/null +++ b/python/proto/cloudbuildv2/alpha/repository.proto @@ -0,0 +1,62 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +syntax = "proto3"; +// All generated protos should be opaque, with "xxx_hidden_" prepended to their field names. + + +package dcl; + +import "proto/connector/sdk.proto"; +import "proto/empty.proto"; + + +message Cloudbuildv2AlphaRepository { + string name = 1; + string remote_uri = 2; + string create_time = 3; + string update_time = 4; + map annotations = 5; + string etag = 6; + string project = 7; + string location = 8; + string connection = 9; +} + +message ApplyCloudbuildv2AlphaRepositoryRequest { + Cloudbuildv2AlphaRepository resource = 1; + repeated LifecycleDirective lifecycle_directives = 2; + string service_account_file = 3; +} + +message DeleteCloudbuildv2AlphaRepositoryRequest { + string service_account_file = 1; + Cloudbuildv2AlphaRepository resource = 2; +} + +message ListCloudbuildv2AlphaRepositoryRequest { + string service_account_file = 1; + string Project = 2; + string Location = 3; + string Connection = 4; +} + +message ListCloudbuildv2AlphaRepositoryResponse { + repeated Cloudbuildv2AlphaRepository items = 1; +} + +service Cloudbuildv2AlphaRepositoryService { + rpc ApplyCloudbuildv2AlphaRepository(ApplyCloudbuildv2AlphaRepositoryRequest) returns (Cloudbuildv2AlphaRepository); + rpc DeleteCloudbuildv2AlphaRepository(DeleteCloudbuildv2AlphaRepositoryRequest) returns (google.protobuf.Empty); + rpc ListCloudbuildv2AlphaRepository(ListCloudbuildv2AlphaRepositoryRequest) returns (ListCloudbuildv2AlphaRepositoryResponse); +} diff --git a/python/services/cloudbuildv2/alpha/BUILD b/python/services/cloudbuildv2/alpha/BUILD new file mode 100755 index 000000000..449c28ec3 --- /dev/null +++ b/python/services/cloudbuildv2/alpha/BUILD @@ -0,0 +1,16 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +load("//:connector_rules.bzl", "connector") +connector(name="cloudbuildv2/alpha", resources=["connection","repository"]) diff --git a/python/services/cloudbuildv2/alpha/connection.py b/python/services/cloudbuildv2/alpha/connection.py new file mode 100755 index 000000000..484a96d75 --- /dev/null +++ b/python/services/cloudbuildv2/alpha/connection.py @@ -0,0 +1,574 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from connector import channel +from google3.cloud.graphite.mmv2.services.google.cloudbuildv2 import connection_pb2 +from google3.cloud.graphite.mmv2.services.google.cloudbuildv2 import connection_pb2_grpc + +from typing import List + + +class Connection(object): + def __init__( + self, + name: str = None, + create_time: str = None, + update_time: str = None, + github_config: dict = None, + github_enterprise_config: dict = None, + installation_state: dict = None, + disabled: bool = None, + reconciling: bool = None, + annotations: dict = None, + etag: str = None, + project: str = None, + location: str = None, + service_account_file: str = "", + ): + + channel.initialize() + self.name = name + self.github_config = github_config + self.github_enterprise_config = github_enterprise_config + self.disabled = disabled + self.annotations = annotations + self.project = project + self.location = location + self.service_account_file = service_account_file + + def apply(self): + stub = connection_pb2_grpc.Cloudbuildv2AlphaConnectionServiceStub( + channel.Channel() + ) + request = connection_pb2.ApplyCloudbuildv2AlphaConnectionRequest() + if Primitive.to_proto(self.name): + request.resource.name = Primitive.to_proto(self.name) + + if ConnectionGithubConfig.to_proto(self.github_config): + request.resource.github_config.CopyFrom( + ConnectionGithubConfig.to_proto(self.github_config) + ) + else: + request.resource.ClearField("github_config") + if ConnectionGithubEnterpriseConfig.to_proto(self.github_enterprise_config): + request.resource.github_enterprise_config.CopyFrom( + ConnectionGithubEnterpriseConfig.to_proto(self.github_enterprise_config) + ) + else: + request.resource.ClearField("github_enterprise_config") + if Primitive.to_proto(self.disabled): + request.resource.disabled = Primitive.to_proto(self.disabled) + + if Primitive.to_proto(self.annotations): + request.resource.annotations = Primitive.to_proto(self.annotations) + + if Primitive.to_proto(self.project): + request.resource.project = Primitive.to_proto(self.project) + + if Primitive.to_proto(self.location): + request.resource.location = Primitive.to_proto(self.location) + + request.service_account_file = self.service_account_file + + response = stub.ApplyCloudbuildv2AlphaConnection(request) + self.name = Primitive.from_proto(response.name) + self.create_time = Primitive.from_proto(response.create_time) + self.update_time = Primitive.from_proto(response.update_time) + self.github_config = ConnectionGithubConfig.from_proto(response.github_config) + self.github_enterprise_config = ConnectionGithubEnterpriseConfig.from_proto( + response.github_enterprise_config + ) + self.installation_state = ConnectionInstallationState.from_proto( + response.installation_state + ) + self.disabled = Primitive.from_proto(response.disabled) + self.reconciling = Primitive.from_proto(response.reconciling) + self.annotations = Primitive.from_proto(response.annotations) + self.etag = Primitive.from_proto(response.etag) + self.project = Primitive.from_proto(response.project) + self.location = Primitive.from_proto(response.location) + + def delete(self): + stub = connection_pb2_grpc.Cloudbuildv2AlphaConnectionServiceStub( + channel.Channel() + ) + request = connection_pb2.DeleteCloudbuildv2AlphaConnectionRequest() + request.service_account_file = self.service_account_file + if Primitive.to_proto(self.name): + request.resource.name = Primitive.to_proto(self.name) + + if ConnectionGithubConfig.to_proto(self.github_config): + request.resource.github_config.CopyFrom( + ConnectionGithubConfig.to_proto(self.github_config) + ) + else: + request.resource.ClearField("github_config") + if ConnectionGithubEnterpriseConfig.to_proto(self.github_enterprise_config): + request.resource.github_enterprise_config.CopyFrom( + ConnectionGithubEnterpriseConfig.to_proto(self.github_enterprise_config) + ) + else: + request.resource.ClearField("github_enterprise_config") + if Primitive.to_proto(self.disabled): + request.resource.disabled = Primitive.to_proto(self.disabled) + + if Primitive.to_proto(self.annotations): + request.resource.annotations = Primitive.to_proto(self.annotations) + + if Primitive.to_proto(self.project): + request.resource.project = Primitive.to_proto(self.project) + + if Primitive.to_proto(self.location): + request.resource.location = Primitive.to_proto(self.location) + + response = stub.DeleteCloudbuildv2AlphaConnection(request) + + @classmethod + def list(self, project, location, service_account_file=""): + stub = connection_pb2_grpc.Cloudbuildv2AlphaConnectionServiceStub( + channel.Channel() + ) + request = connection_pb2.ListCloudbuildv2AlphaConnectionRequest() + request.service_account_file = service_account_file + request.Project = project + + request.Location = location + + return stub.ListCloudbuildv2AlphaConnection(request).items + + def to_proto(self): + resource = connection_pb2.Cloudbuildv2AlphaConnection() + if Primitive.to_proto(self.name): + resource.name = Primitive.to_proto(self.name) + if ConnectionGithubConfig.to_proto(self.github_config): + resource.github_config.CopyFrom( + ConnectionGithubConfig.to_proto(self.github_config) + ) + else: + resource.ClearField("github_config") + if ConnectionGithubEnterpriseConfig.to_proto(self.github_enterprise_config): + resource.github_enterprise_config.CopyFrom( + ConnectionGithubEnterpriseConfig.to_proto(self.github_enterprise_config) + ) + else: + resource.ClearField("github_enterprise_config") + if Primitive.to_proto(self.disabled): + resource.disabled = Primitive.to_proto(self.disabled) + if Primitive.to_proto(self.annotations): + resource.annotations = Primitive.to_proto(self.annotations) + if Primitive.to_proto(self.project): + resource.project = Primitive.to_proto(self.project) + if Primitive.to_proto(self.location): + resource.location = Primitive.to_proto(self.location) + return resource + + +class ConnectionGithubConfig(object): + def __init__( + self, authorizer_credential: dict = None, app_installation_id: int = None + ): + self.authorizer_credential = authorizer_credential + self.app_installation_id = app_installation_id + + @classmethod + def to_proto(self, resource): + if not resource: + return None + + res = connection_pb2.Cloudbuildv2AlphaConnectionGithubConfig() + if ConnectionGithubConfigAuthorizerCredential.to_proto( + resource.authorizer_credential + ): + res.authorizer_credential.CopyFrom( + ConnectionGithubConfigAuthorizerCredential.to_proto( + resource.authorizer_credential + ) + ) + else: + res.ClearField("authorizer_credential") + if Primitive.to_proto(resource.app_installation_id): + res.app_installation_id = Primitive.to_proto(resource.app_installation_id) + return res + + @classmethod + def from_proto(self, resource): + if not resource: + return None + + return ConnectionGithubConfig( + authorizer_credential=ConnectionGithubConfigAuthorizerCredential.from_proto( + resource.authorizer_credential + ), + app_installation_id=Primitive.from_proto(resource.app_installation_id), + ) + + +class ConnectionGithubConfigArray(object): + @classmethod + def to_proto(self, resources): + if not resources: + return resources + return [ConnectionGithubConfig.to_proto(i) for i in resources] + + @classmethod + def from_proto(self, resources): + return [ConnectionGithubConfig.from_proto(i) for i in resources] + + +class ConnectionGithubConfigAuthorizerCredential(object): + def __init__(self, oauth_token_secret_version: str = None, username: str = None): + self.oauth_token_secret_version = oauth_token_secret_version + self.username = username + + @classmethod + def to_proto(self, resource): + if not resource: + return None + + res = ( + connection_pb2.Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential() + ) + if Primitive.to_proto(resource.oauth_token_secret_version): + res.oauth_token_secret_version = Primitive.to_proto( + resource.oauth_token_secret_version + ) + if Primitive.to_proto(resource.username): + res.username = Primitive.to_proto(resource.username) + return res + + @classmethod + def from_proto(self, resource): + if not resource: + return None + + return ConnectionGithubConfigAuthorizerCredential( + oauth_token_secret_version=Primitive.from_proto( + resource.oauth_token_secret_version + ), + username=Primitive.from_proto(resource.username), + ) + + +class ConnectionGithubConfigAuthorizerCredentialArray(object): + @classmethod + def to_proto(self, resources): + if not resources: + return resources + return [ + ConnectionGithubConfigAuthorizerCredential.to_proto(i) for i in resources + ] + + @classmethod + def from_proto(self, resources): + return [ + ConnectionGithubConfigAuthorizerCredential.from_proto(i) for i in resources + ] + + +class ConnectionGithubEnterpriseConfig(object): + def __init__( + self, + host_uri: str = None, + app_id: int = None, + app_slug: str = None, + private_key_secret_version: str = None, + webhook_secret_secret_version: str = None, + oauth_secret_secret_version: str = None, + oauth_client_id_secret_version: str = None, + authorizer_credential: dict = None, + app_installation_id: int = None, + service_directory_config: dict = None, + ssl_ca: str = None, + ): + self.host_uri = host_uri + self.app_id = app_id + self.app_slug = app_slug + self.private_key_secret_version = private_key_secret_version + self.webhook_secret_secret_version = webhook_secret_secret_version + self.oauth_secret_secret_version = oauth_secret_secret_version + self.oauth_client_id_secret_version = oauth_client_id_secret_version + self.authorizer_credential = authorizer_credential + self.app_installation_id = app_installation_id + self.service_directory_config = service_directory_config + self.ssl_ca = ssl_ca + + @classmethod + def to_proto(self, resource): + if not resource: + return None + + res = connection_pb2.Cloudbuildv2AlphaConnectionGithubEnterpriseConfig() + if Primitive.to_proto(resource.host_uri): + res.host_uri = Primitive.to_proto(resource.host_uri) + if Primitive.to_proto(resource.app_id): + res.app_id = Primitive.to_proto(resource.app_id) + if Primitive.to_proto(resource.app_slug): + res.app_slug = Primitive.to_proto(resource.app_slug) + if Primitive.to_proto(resource.private_key_secret_version): + res.private_key_secret_version = Primitive.to_proto( + resource.private_key_secret_version + ) + if Primitive.to_proto(resource.webhook_secret_secret_version): + res.webhook_secret_secret_version = Primitive.to_proto( + resource.webhook_secret_secret_version + ) + if Primitive.to_proto(resource.oauth_secret_secret_version): + res.oauth_secret_secret_version = Primitive.to_proto( + resource.oauth_secret_secret_version + ) + if Primitive.to_proto(resource.oauth_client_id_secret_version): + res.oauth_client_id_secret_version = Primitive.to_proto( + resource.oauth_client_id_secret_version + ) + if ConnectionGithubEnterpriseConfigAuthorizerCredential.to_proto( + resource.authorizer_credential + ): + res.authorizer_credential.CopyFrom( + ConnectionGithubEnterpriseConfigAuthorizerCredential.to_proto( + resource.authorizer_credential + ) + ) + else: + res.ClearField("authorizer_credential") + if Primitive.to_proto(resource.app_installation_id): + res.app_installation_id = Primitive.to_proto(resource.app_installation_id) + if ConnectionGithubEnterpriseConfigServiceDirectoryConfig.to_proto( + resource.service_directory_config + ): + res.service_directory_config.CopyFrom( + ConnectionGithubEnterpriseConfigServiceDirectoryConfig.to_proto( + resource.service_directory_config + ) + ) + else: + res.ClearField("service_directory_config") + if Primitive.to_proto(resource.ssl_ca): + res.ssl_ca = Primitive.to_proto(resource.ssl_ca) + return res + + @classmethod + def from_proto(self, resource): + if not resource: + return None + + return ConnectionGithubEnterpriseConfig( + host_uri=Primitive.from_proto(resource.host_uri), + app_id=Primitive.from_proto(resource.app_id), + app_slug=Primitive.from_proto(resource.app_slug), + private_key_secret_version=Primitive.from_proto( + resource.private_key_secret_version + ), + webhook_secret_secret_version=Primitive.from_proto( + resource.webhook_secret_secret_version + ), + oauth_secret_secret_version=Primitive.from_proto( + resource.oauth_secret_secret_version + ), + oauth_client_id_secret_version=Primitive.from_proto( + resource.oauth_client_id_secret_version + ), + authorizer_credential=ConnectionGithubEnterpriseConfigAuthorizerCredential.from_proto( + resource.authorizer_credential + ), + app_installation_id=Primitive.from_proto(resource.app_installation_id), + service_directory_config=ConnectionGithubEnterpriseConfigServiceDirectoryConfig.from_proto( + resource.service_directory_config + ), + ssl_ca=Primitive.from_proto(resource.ssl_ca), + ) + + +class ConnectionGithubEnterpriseConfigArray(object): + @classmethod + def to_proto(self, resources): + if not resources: + return resources + return [ConnectionGithubEnterpriseConfig.to_proto(i) for i in resources] + + @classmethod + def from_proto(self, resources): + return [ConnectionGithubEnterpriseConfig.from_proto(i) for i in resources] + + +class ConnectionGithubEnterpriseConfigAuthorizerCredential(object): + def __init__(self, oauth_token_secret_version: str = None, username: str = None): + self.oauth_token_secret_version = oauth_token_secret_version + self.username = username + + @classmethod + def to_proto(self, resource): + if not resource: + return None + + res = ( + connection_pb2.Cloudbuildv2AlphaConnectionGithubEnterpriseConfigAuthorizerCredential() + ) + if Primitive.to_proto(resource.oauth_token_secret_version): + res.oauth_token_secret_version = Primitive.to_proto( + resource.oauth_token_secret_version + ) + if Primitive.to_proto(resource.username): + res.username = Primitive.to_proto(resource.username) + return res + + @classmethod + def from_proto(self, resource): + if not resource: + return None + + return ConnectionGithubEnterpriseConfigAuthorizerCredential( + oauth_token_secret_version=Primitive.from_proto( + resource.oauth_token_secret_version + ), + username=Primitive.from_proto(resource.username), + ) + + +class ConnectionGithubEnterpriseConfigAuthorizerCredentialArray(object): + @classmethod + def to_proto(self, resources): + if not resources: + return resources + return [ + ConnectionGithubEnterpriseConfigAuthorizerCredential.to_proto(i) + for i in resources + ] + + @classmethod + def from_proto(self, resources): + return [ + ConnectionGithubEnterpriseConfigAuthorizerCredential.from_proto(i) + for i in resources + ] + + +class ConnectionGithubEnterpriseConfigServiceDirectoryConfig(object): + def __init__(self, service: str = None): + self.service = service + + @classmethod + def to_proto(self, resource): + if not resource: + return None + + res = ( + connection_pb2.Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig() + ) + if Primitive.to_proto(resource.service): + res.service = Primitive.to_proto(resource.service) + return res + + @classmethod + def from_proto(self, resource): + if not resource: + return None + + return ConnectionGithubEnterpriseConfigServiceDirectoryConfig( + service=Primitive.from_proto(resource.service), + ) + + +class ConnectionGithubEnterpriseConfigServiceDirectoryConfigArray(object): + @classmethod + def to_proto(self, resources): + if not resources: + return resources + return [ + ConnectionGithubEnterpriseConfigServiceDirectoryConfig.to_proto(i) + for i in resources + ] + + @classmethod + def from_proto(self, resources): + return [ + ConnectionGithubEnterpriseConfigServiceDirectoryConfig.from_proto(i) + for i in resources + ] + + +class ConnectionInstallationState(object): + def __init__(self, stage: str = None, message: str = None, action_uri: str = None): + self.stage = stage + self.message = message + self.action_uri = action_uri + + @classmethod + def to_proto(self, resource): + if not resource: + return None + + res = connection_pb2.Cloudbuildv2AlphaConnectionInstallationState() + if ConnectionInstallationStateStageEnum.to_proto(resource.stage): + res.stage = ConnectionInstallationStateStageEnum.to_proto(resource.stage) + if Primitive.to_proto(resource.message): + res.message = Primitive.to_proto(resource.message) + if Primitive.to_proto(resource.action_uri): + res.action_uri = Primitive.to_proto(resource.action_uri) + return res + + @classmethod + def from_proto(self, resource): + if not resource: + return None + + return ConnectionInstallationState( + stage=ConnectionInstallationStateStageEnum.from_proto(resource.stage), + message=Primitive.from_proto(resource.message), + action_uri=Primitive.from_proto(resource.action_uri), + ) + + +class ConnectionInstallationStateArray(object): + @classmethod + def to_proto(self, resources): + if not resources: + return resources + return [ConnectionInstallationState.to_proto(i) for i in resources] + + @classmethod + def from_proto(self, resources): + return [ConnectionInstallationState.from_proto(i) for i in resources] + + +class ConnectionInstallationStateStageEnum(object): + @classmethod + def to_proto(self, resource): + if not resource: + return resource + return ( + connection_pb2.Cloudbuildv2AlphaConnectionInstallationStateStageEnum.Value( + "Cloudbuildv2AlphaConnectionInstallationStateStageEnum%s" % resource + ) + ) + + @classmethod + def from_proto(self, resource): + if not resource: + return resource + return ( + connection_pb2.Cloudbuildv2AlphaConnectionInstallationStateStageEnum.Name( + resource + )[len("Cloudbuildv2AlphaConnectionInstallationStateStageEnum") :] + ) + + +class Primitive(object): + @classmethod + def to_proto(self, s): + if not s: + return "" + return s + + @classmethod + def from_proto(self, s): + return s diff --git a/python/services/cloudbuildv2/alpha/connection_server.go b/python/services/cloudbuildv2/alpha/connection_server.go new file mode 100755 index 000000000..2963b789c --- /dev/null +++ b/python/services/cloudbuildv2/alpha/connection_server.go @@ -0,0 +1,303 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +package server + +import ( + "context" + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" + alphapb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/cloudbuildv2/alpha/cloudbuildv2_alpha_go_proto" + emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" + "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudbuildv2/alpha" +) + +// ConnectionServer implements the gRPC interface for Connection. +type ConnectionServer struct{} + +// ProtoToConnectionInstallationStateStageEnum converts a ConnectionInstallationStateStageEnum enum from its proto representation. +func ProtoToCloudbuildv2AlphaConnectionInstallationStateStageEnum(e alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum) *alpha.ConnectionInstallationStateStageEnum { + if e == 0 { + return nil + } + if n, ok := alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum_name[int32(e)]; ok { + e := alpha.ConnectionInstallationStateStageEnum(n[len("Cloudbuildv2AlphaConnectionInstallationStateStageEnum"):]) + return &e + } + return nil +} + +// ProtoToConnectionGithubConfig converts a ConnectionGithubConfig object from its proto representation. +func ProtoToCloudbuildv2AlphaConnectionGithubConfig(p *alphapb.Cloudbuildv2AlphaConnectionGithubConfig) *alpha.ConnectionGithubConfig { + if p == nil { + return nil + } + obj := &alpha.ConnectionGithubConfig{ + AuthorizerCredential: ProtoToCloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential(p.GetAuthorizerCredential()), + AppInstallationId: dcl.Int64OrNil(p.GetAppInstallationId()), + } + return obj +} + +// ProtoToConnectionGithubConfigAuthorizerCredential converts a ConnectionGithubConfigAuthorizerCredential object from its proto representation. +func ProtoToCloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential(p *alphapb.Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential) *alpha.ConnectionGithubConfigAuthorizerCredential { + if p == nil { + return nil + } + obj := &alpha.ConnectionGithubConfigAuthorizerCredential{ + OAuthTokenSecretVersion: dcl.StringOrNil(p.GetOauthTokenSecretVersion()), + Username: dcl.StringOrNil(p.GetUsername()), + } + return obj +} + +// ProtoToConnectionGithubEnterpriseConfig converts a ConnectionGithubEnterpriseConfig object from its proto representation. +func ProtoToCloudbuildv2AlphaConnectionGithubEnterpriseConfig(p *alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfig) *alpha.ConnectionGithubEnterpriseConfig { + if p == nil { + return nil + } + obj := &alpha.ConnectionGithubEnterpriseConfig{ + HostUri: dcl.StringOrNil(p.GetHostUri()), + AppId: dcl.Int64OrNil(p.GetAppId()), + AppSlug: dcl.StringOrNil(p.GetAppSlug()), + PrivateKeySecretVersion: dcl.StringOrNil(p.GetPrivateKeySecretVersion()), + WebhookSecretSecretVersion: dcl.StringOrNil(p.GetWebhookSecretSecretVersion()), + OAuthSecretSecretVersion: dcl.StringOrNil(p.GetOauthSecretSecretVersion()), + OAuthClientIdSecretVersion: dcl.StringOrNil(p.GetOauthClientIdSecretVersion()), + AuthorizerCredential: ProtoToCloudbuildv2AlphaConnectionGithubEnterpriseConfigAuthorizerCredential(p.GetAuthorizerCredential()), + AppInstallationId: dcl.Int64OrNil(p.GetAppInstallationId()), + ServiceDirectoryConfig: ProtoToCloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig(p.GetServiceDirectoryConfig()), + SslCa: dcl.StringOrNil(p.GetSslCa()), + } + return obj +} + +// ProtoToConnectionGithubEnterpriseConfigAuthorizerCredential converts a ConnectionGithubEnterpriseConfigAuthorizerCredential object from its proto representation. +func ProtoToCloudbuildv2AlphaConnectionGithubEnterpriseConfigAuthorizerCredential(p *alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfigAuthorizerCredential) *alpha.ConnectionGithubEnterpriseConfigAuthorizerCredential { + if p == nil { + return nil + } + obj := &alpha.ConnectionGithubEnterpriseConfigAuthorizerCredential{ + OAuthTokenSecretVersion: dcl.StringOrNil(p.GetOauthTokenSecretVersion()), + Username: dcl.StringOrNil(p.GetUsername()), + } + return obj +} + +// ProtoToConnectionGithubEnterpriseConfigServiceDirectoryConfig converts a ConnectionGithubEnterpriseConfigServiceDirectoryConfig object from its proto representation. +func ProtoToCloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig(p *alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig) *alpha.ConnectionGithubEnterpriseConfigServiceDirectoryConfig { + if p == nil { + return nil + } + obj := &alpha.ConnectionGithubEnterpriseConfigServiceDirectoryConfig{ + Service: dcl.StringOrNil(p.GetService()), + } + return obj +} + +// ProtoToConnectionInstallationState converts a ConnectionInstallationState object from its proto representation. +func ProtoToCloudbuildv2AlphaConnectionInstallationState(p *alphapb.Cloudbuildv2AlphaConnectionInstallationState) *alpha.ConnectionInstallationState { + if p == nil { + return nil + } + obj := &alpha.ConnectionInstallationState{ + Stage: ProtoToCloudbuildv2AlphaConnectionInstallationStateStageEnum(p.GetStage()), + Message: dcl.StringOrNil(p.GetMessage()), + ActionUri: dcl.StringOrNil(p.GetActionUri()), + } + return obj +} + +// ProtoToConnection converts a Connection resource from its proto representation. +func ProtoToConnection(p *alphapb.Cloudbuildv2AlphaConnection) *alpha.Connection { + obj := &alpha.Connection{ + Name: dcl.StringOrNil(p.GetName()), + CreateTime: dcl.StringOrNil(p.GetCreateTime()), + UpdateTime: dcl.StringOrNil(p.GetUpdateTime()), + GithubConfig: ProtoToCloudbuildv2AlphaConnectionGithubConfig(p.GetGithubConfig()), + GithubEnterpriseConfig: ProtoToCloudbuildv2AlphaConnectionGithubEnterpriseConfig(p.GetGithubEnterpriseConfig()), + InstallationState: ProtoToCloudbuildv2AlphaConnectionInstallationState(p.GetInstallationState()), + Disabled: dcl.Bool(p.GetDisabled()), + Reconciling: dcl.Bool(p.GetReconciling()), + Etag: dcl.StringOrNil(p.GetEtag()), + Project: dcl.StringOrNil(p.GetProject()), + Location: dcl.StringOrNil(p.GetLocation()), + } + return obj +} + +// ConnectionInstallationStateStageEnumToProto converts a ConnectionInstallationStateStageEnum enum to its proto representation. +func Cloudbuildv2AlphaConnectionInstallationStateStageEnumToProto(e *alpha.ConnectionInstallationStateStageEnum) alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum { + if e == nil { + return alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum(0) + } + if v, ok := alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum_value["ConnectionInstallationStateStageEnum"+string(*e)]; ok { + return alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum(v) + } + return alphapb.Cloudbuildv2AlphaConnectionInstallationStateStageEnum(0) +} + +// ConnectionGithubConfigToProto converts a ConnectionGithubConfig object to its proto representation. +func Cloudbuildv2AlphaConnectionGithubConfigToProto(o *alpha.ConnectionGithubConfig) *alphapb.Cloudbuildv2AlphaConnectionGithubConfig { + if o == nil { + return nil + } + p := &alphapb.Cloudbuildv2AlphaConnectionGithubConfig{} + p.SetAuthorizerCredential(Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredentialToProto(o.AuthorizerCredential)) + p.SetAppInstallationId(dcl.ValueOrEmptyInt64(o.AppInstallationId)) + return p +} + +// ConnectionGithubConfigAuthorizerCredentialToProto converts a ConnectionGithubConfigAuthorizerCredential object to its proto representation. +func Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredentialToProto(o *alpha.ConnectionGithubConfigAuthorizerCredential) *alphapb.Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential { + if o == nil { + return nil + } + p := &alphapb.Cloudbuildv2AlphaConnectionGithubConfigAuthorizerCredential{} + p.SetOauthTokenSecretVersion(dcl.ValueOrEmptyString(o.OAuthTokenSecretVersion)) + p.SetUsername(dcl.ValueOrEmptyString(o.Username)) + return p +} + +// ConnectionGithubEnterpriseConfigToProto converts a ConnectionGithubEnterpriseConfig object to its proto representation. +func Cloudbuildv2AlphaConnectionGithubEnterpriseConfigToProto(o *alpha.ConnectionGithubEnterpriseConfig) *alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfig { + if o == nil { + return nil + } + p := &alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfig{} + p.SetHostUri(dcl.ValueOrEmptyString(o.HostUri)) + p.SetAppId(dcl.ValueOrEmptyInt64(o.AppId)) + p.SetAppSlug(dcl.ValueOrEmptyString(o.AppSlug)) + p.SetPrivateKeySecretVersion(dcl.ValueOrEmptyString(o.PrivateKeySecretVersion)) + p.SetWebhookSecretSecretVersion(dcl.ValueOrEmptyString(o.WebhookSecretSecretVersion)) + p.SetOauthSecretSecretVersion(dcl.ValueOrEmptyString(o.OAuthSecretSecretVersion)) + p.SetOauthClientIdSecretVersion(dcl.ValueOrEmptyString(o.OAuthClientIdSecretVersion)) + p.SetAuthorizerCredential(Cloudbuildv2AlphaConnectionGithubEnterpriseConfigAuthorizerCredentialToProto(o.AuthorizerCredential)) + p.SetAppInstallationId(dcl.ValueOrEmptyInt64(o.AppInstallationId)) + p.SetServiceDirectoryConfig(Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfigToProto(o.ServiceDirectoryConfig)) + p.SetSslCa(dcl.ValueOrEmptyString(o.SslCa)) + return p +} + +// ConnectionGithubEnterpriseConfigAuthorizerCredentialToProto converts a ConnectionGithubEnterpriseConfigAuthorizerCredential object to its proto representation. +func Cloudbuildv2AlphaConnectionGithubEnterpriseConfigAuthorizerCredentialToProto(o *alpha.ConnectionGithubEnterpriseConfigAuthorizerCredential) *alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfigAuthorizerCredential { + if o == nil { + return nil + } + p := &alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfigAuthorizerCredential{} + p.SetOauthTokenSecretVersion(dcl.ValueOrEmptyString(o.OAuthTokenSecretVersion)) + p.SetUsername(dcl.ValueOrEmptyString(o.Username)) + return p +} + +// ConnectionGithubEnterpriseConfigServiceDirectoryConfigToProto converts a ConnectionGithubEnterpriseConfigServiceDirectoryConfig object to its proto representation. +func Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfigToProto(o *alpha.ConnectionGithubEnterpriseConfigServiceDirectoryConfig) *alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig { + if o == nil { + return nil + } + p := &alphapb.Cloudbuildv2AlphaConnectionGithubEnterpriseConfigServiceDirectoryConfig{} + p.SetService(dcl.ValueOrEmptyString(o.Service)) + return p +} + +// ConnectionInstallationStateToProto converts a ConnectionInstallationState object to its proto representation. +func Cloudbuildv2AlphaConnectionInstallationStateToProto(o *alpha.ConnectionInstallationState) *alphapb.Cloudbuildv2AlphaConnectionInstallationState { + if o == nil { + return nil + } + p := &alphapb.Cloudbuildv2AlphaConnectionInstallationState{} + p.SetStage(Cloudbuildv2AlphaConnectionInstallationStateStageEnumToProto(o.Stage)) + p.SetMessage(dcl.ValueOrEmptyString(o.Message)) + p.SetActionUri(dcl.ValueOrEmptyString(o.ActionUri)) + return p +} + +// ConnectionToProto converts a Connection resource to its proto representation. +func ConnectionToProto(resource *alpha.Connection) *alphapb.Cloudbuildv2AlphaConnection { + p := &alphapb.Cloudbuildv2AlphaConnection{} + p.SetName(dcl.ValueOrEmptyString(resource.Name)) + p.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime)) + p.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime)) + p.SetGithubConfig(Cloudbuildv2AlphaConnectionGithubConfigToProto(resource.GithubConfig)) + p.SetGithubEnterpriseConfig(Cloudbuildv2AlphaConnectionGithubEnterpriseConfigToProto(resource.GithubEnterpriseConfig)) + p.SetInstallationState(Cloudbuildv2AlphaConnectionInstallationStateToProto(resource.InstallationState)) + p.SetDisabled(dcl.ValueOrEmptyBool(resource.Disabled)) + p.SetReconciling(dcl.ValueOrEmptyBool(resource.Reconciling)) + p.SetEtag(dcl.ValueOrEmptyString(resource.Etag)) + p.SetProject(dcl.ValueOrEmptyString(resource.Project)) + p.SetLocation(dcl.ValueOrEmptyString(resource.Location)) + mAnnotations := make(map[string]string, len(resource.Annotations)) + for k, r := range resource.Annotations { + mAnnotations[k] = r + } + p.SetAnnotations(mAnnotations) + + return p +} + +// applyConnection handles the gRPC request by passing it to the underlying Connection Apply() method. +func (s *ConnectionServer) applyConnection(ctx context.Context, c *alpha.Client, request *alphapb.ApplyCloudbuildv2AlphaConnectionRequest) (*alphapb.Cloudbuildv2AlphaConnection, error) { + p := ProtoToConnection(request.GetResource()) + res, err := c.ApplyConnection(ctx, p) + if err != nil { + return nil, err + } + r := ConnectionToProto(res) + return r, nil +} + +// applyCloudbuildv2AlphaConnection handles the gRPC request by passing it to the underlying Connection Apply() method. +func (s *ConnectionServer) ApplyCloudbuildv2AlphaConnection(ctx context.Context, request *alphapb.ApplyCloudbuildv2AlphaConnectionRequest) (*alphapb.Cloudbuildv2AlphaConnection, error) { + cl, err := createConfigConnection(ctx, request.GetServiceAccountFile()) + if err != nil { + return nil, err + } + return s.applyConnection(ctx, cl, request) +} + +// DeleteConnection handles the gRPC request by passing it to the underlying Connection Delete() method. +func (s *ConnectionServer) DeleteCloudbuildv2AlphaConnection(ctx context.Context, request *alphapb.DeleteCloudbuildv2AlphaConnectionRequest) (*emptypb.Empty, error) { + + cl, err := createConfigConnection(ctx, request.GetServiceAccountFile()) + if err != nil { + return nil, err + } + return &emptypb.Empty{}, cl.DeleteConnection(ctx, ProtoToConnection(request.GetResource())) + +} + +// ListCloudbuildv2AlphaConnection handles the gRPC request by passing it to the underlying ConnectionList() method. +func (s *ConnectionServer) ListCloudbuildv2AlphaConnection(ctx context.Context, request *alphapb.ListCloudbuildv2AlphaConnectionRequest) (*alphapb.ListCloudbuildv2AlphaConnectionResponse, error) { + cl, err := createConfigConnection(ctx, request.GetServiceAccountFile()) + if err != nil { + return nil, err + } + + resources, err := cl.ListConnection(ctx, request.GetProject(), request.GetLocation()) + if err != nil { + return nil, err + } + var protos []*alphapb.Cloudbuildv2AlphaConnection + for _, r := range resources.Items { + rp := ConnectionToProto(r) + protos = append(protos, rp) + } + p := &alphapb.ListCloudbuildv2AlphaConnectionResponse{} + p.SetItems(protos) + return p, nil +} + +func createConfigConnection(ctx context.Context, service_account_file string) (*alpha.Client, error) { + + conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) + return alpha.NewClient(conf), nil +} diff --git a/python/services/cloudbuildv2/alpha/register.go b/python/services/cloudbuildv2/alpha/register.go new file mode 100755 index 000000000..a2b1b68dc --- /dev/null +++ b/python/services/cloudbuildv2/alpha/register.go @@ -0,0 +1,25 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +package server + +import ( + "google.golang.org/grpc" + sdkgrpc "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/cloudbuildv2/alpha/cloudbuildv2_alpha_go_proto" +) + +// RegisterServers registers each resource with the gRPC server. +func RegisterServers(s *grpc.Server) { + sdkgrpc.RegisterCloudbuildv2AlphaConnectionServiceServer(s, &ConnectionServer{}) + sdkgrpc.RegisterCloudbuildv2AlphaRepositoryServiceServer(s, &RepositoryServer{}) +} diff --git a/python/services/cloudbuildv2/alpha/repository.py b/python/services/cloudbuildv2/alpha/repository.py new file mode 100755 index 000000000..3582ea55a --- /dev/null +++ b/python/services/cloudbuildv2/alpha/repository.py @@ -0,0 +1,148 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from connector import channel +from google3.cloud.graphite.mmv2.services.google.cloudbuildv2 import repository_pb2 +from google3.cloud.graphite.mmv2.services.google.cloudbuildv2 import repository_pb2_grpc + +from typing import List + + +class Repository(object): + def __init__( + self, + name: str = None, + remote_uri: str = None, + create_time: str = None, + update_time: str = None, + annotations: dict = None, + etag: str = None, + project: str = None, + location: str = None, + connection: str = None, + service_account_file: str = "", + ): + + channel.initialize() + self.name = name + self.remote_uri = remote_uri + self.annotations = annotations + self.project = project + self.location = location + self.connection = connection + self.service_account_file = service_account_file + + def apply(self): + stub = repository_pb2_grpc.Cloudbuildv2AlphaRepositoryServiceStub( + channel.Channel() + ) + request = repository_pb2.ApplyCloudbuildv2AlphaRepositoryRequest() + if Primitive.to_proto(self.name): + request.resource.name = Primitive.to_proto(self.name) + + if Primitive.to_proto(self.remote_uri): + request.resource.remote_uri = Primitive.to_proto(self.remote_uri) + + if Primitive.to_proto(self.annotations): + request.resource.annotations = Primitive.to_proto(self.annotations) + + if Primitive.to_proto(self.project): + request.resource.project = Primitive.to_proto(self.project) + + if Primitive.to_proto(self.location): + request.resource.location = Primitive.to_proto(self.location) + + if Primitive.to_proto(self.connection): + request.resource.connection = Primitive.to_proto(self.connection) + + request.service_account_file = self.service_account_file + + response = stub.ApplyCloudbuildv2AlphaRepository(request) + self.name = Primitive.from_proto(response.name) + self.remote_uri = Primitive.from_proto(response.remote_uri) + self.create_time = Primitive.from_proto(response.create_time) + self.update_time = Primitive.from_proto(response.update_time) + self.annotations = Primitive.from_proto(response.annotations) + self.etag = Primitive.from_proto(response.etag) + self.project = Primitive.from_proto(response.project) + self.location = Primitive.from_proto(response.location) + self.connection = Primitive.from_proto(response.connection) + + def delete(self): + stub = repository_pb2_grpc.Cloudbuildv2AlphaRepositoryServiceStub( + channel.Channel() + ) + request = repository_pb2.DeleteCloudbuildv2AlphaRepositoryRequest() + request.service_account_file = self.service_account_file + if Primitive.to_proto(self.name): + request.resource.name = Primitive.to_proto(self.name) + + if Primitive.to_proto(self.remote_uri): + request.resource.remote_uri = Primitive.to_proto(self.remote_uri) + + if Primitive.to_proto(self.annotations): + request.resource.annotations = Primitive.to_proto(self.annotations) + + if Primitive.to_proto(self.project): + request.resource.project = Primitive.to_proto(self.project) + + if Primitive.to_proto(self.location): + request.resource.location = Primitive.to_proto(self.location) + + if Primitive.to_proto(self.connection): + request.resource.connection = Primitive.to_proto(self.connection) + + response = stub.DeleteCloudbuildv2AlphaRepository(request) + + @classmethod + def list(self, project, location, connection, service_account_file=""): + stub = repository_pb2_grpc.Cloudbuildv2AlphaRepositoryServiceStub( + channel.Channel() + ) + request = repository_pb2.ListCloudbuildv2AlphaRepositoryRequest() + request.service_account_file = service_account_file + request.Project = project + + request.Location = location + + request.Connection = connection + + return stub.ListCloudbuildv2AlphaRepository(request).items + + def to_proto(self): + resource = repository_pb2.Cloudbuildv2AlphaRepository() + if Primitive.to_proto(self.name): + resource.name = Primitive.to_proto(self.name) + if Primitive.to_proto(self.remote_uri): + resource.remote_uri = Primitive.to_proto(self.remote_uri) + if Primitive.to_proto(self.annotations): + resource.annotations = Primitive.to_proto(self.annotations) + if Primitive.to_proto(self.project): + resource.project = Primitive.to_proto(self.project) + if Primitive.to_proto(self.location): + resource.location = Primitive.to_proto(self.location) + if Primitive.to_proto(self.connection): + resource.connection = Primitive.to_proto(self.connection) + return resource + + +class Primitive(object): + @classmethod + def to_proto(self, s): + if not s: + return "" + return s + + @classmethod + def from_proto(self, s): + return s diff --git a/python/services/cloudbuildv2/alpha/repository_server.go b/python/services/cloudbuildv2/alpha/repository_server.go new file mode 100755 index 000000000..3476f7e08 --- /dev/null +++ b/python/services/cloudbuildv2/alpha/repository_server.go @@ -0,0 +1,118 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +package server + +import ( + "context" + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" + alphapb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/cloudbuildv2/alpha/cloudbuildv2_alpha_go_proto" + emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" + "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudbuildv2/alpha" +) + +// RepositoryServer implements the gRPC interface for Repository. +type RepositoryServer struct{} + +// ProtoToRepository converts a Repository resource from its proto representation. +func ProtoToRepository(p *alphapb.Cloudbuildv2AlphaRepository) *alpha.Repository { + obj := &alpha.Repository{ + Name: dcl.StringOrNil(p.GetName()), + RemoteUri: dcl.StringOrNil(p.GetRemoteUri()), + CreateTime: dcl.StringOrNil(p.GetCreateTime()), + UpdateTime: dcl.StringOrNil(p.GetUpdateTime()), + Etag: dcl.StringOrNil(p.GetEtag()), + Project: dcl.StringOrNil(p.GetProject()), + Location: dcl.StringOrNil(p.GetLocation()), + Connection: dcl.StringOrNil(p.GetConnection()), + } + return obj +} + +// RepositoryToProto converts a Repository resource to its proto representation. +func RepositoryToProto(resource *alpha.Repository) *alphapb.Cloudbuildv2AlphaRepository { + p := &alphapb.Cloudbuildv2AlphaRepository{} + p.SetName(dcl.ValueOrEmptyString(resource.Name)) + p.SetRemoteUri(dcl.ValueOrEmptyString(resource.RemoteUri)) + p.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime)) + p.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime)) + p.SetEtag(dcl.ValueOrEmptyString(resource.Etag)) + p.SetProject(dcl.ValueOrEmptyString(resource.Project)) + p.SetLocation(dcl.ValueOrEmptyString(resource.Location)) + p.SetConnection(dcl.ValueOrEmptyString(resource.Connection)) + mAnnotations := make(map[string]string, len(resource.Annotations)) + for k, r := range resource.Annotations { + mAnnotations[k] = r + } + p.SetAnnotations(mAnnotations) + + return p +} + +// applyRepository handles the gRPC request by passing it to the underlying Repository Apply() method. +func (s *RepositoryServer) applyRepository(ctx context.Context, c *alpha.Client, request *alphapb.ApplyCloudbuildv2AlphaRepositoryRequest) (*alphapb.Cloudbuildv2AlphaRepository, error) { + p := ProtoToRepository(request.GetResource()) + res, err := c.ApplyRepository(ctx, p) + if err != nil { + return nil, err + } + r := RepositoryToProto(res) + return r, nil +} + +// applyCloudbuildv2AlphaRepository handles the gRPC request by passing it to the underlying Repository Apply() method. +func (s *RepositoryServer) ApplyCloudbuildv2AlphaRepository(ctx context.Context, request *alphapb.ApplyCloudbuildv2AlphaRepositoryRequest) (*alphapb.Cloudbuildv2AlphaRepository, error) { + cl, err := createConfigRepository(ctx, request.GetServiceAccountFile()) + if err != nil { + return nil, err + } + return s.applyRepository(ctx, cl, request) +} + +// DeleteRepository handles the gRPC request by passing it to the underlying Repository Delete() method. +func (s *RepositoryServer) DeleteCloudbuildv2AlphaRepository(ctx context.Context, request *alphapb.DeleteCloudbuildv2AlphaRepositoryRequest) (*emptypb.Empty, error) { + + cl, err := createConfigRepository(ctx, request.GetServiceAccountFile()) + if err != nil { + return nil, err + } + return &emptypb.Empty{}, cl.DeleteRepository(ctx, ProtoToRepository(request.GetResource())) + +} + +// ListCloudbuildv2AlphaRepository handles the gRPC request by passing it to the underlying RepositoryList() method. +func (s *RepositoryServer) ListCloudbuildv2AlphaRepository(ctx context.Context, request *alphapb.ListCloudbuildv2AlphaRepositoryRequest) (*alphapb.ListCloudbuildv2AlphaRepositoryResponse, error) { + cl, err := createConfigRepository(ctx, request.GetServiceAccountFile()) + if err != nil { + return nil, err + } + + resources, err := cl.ListRepository(ctx, request.GetProject(), request.GetLocation(), request.GetConnection()) + if err != nil { + return nil, err + } + var protos []*alphapb.Cloudbuildv2AlphaRepository + for _, r := range resources.Items { + rp := RepositoryToProto(r) + protos = append(protos, rp) + } + p := &alphapb.ListCloudbuildv2AlphaRepositoryResponse{} + p.SetItems(protos) + return p, nil +} + +func createConfigRepository(ctx context.Context, service_account_file string) (*alpha.Client, error) { + + conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) + return alpha.NewClient(conf), nil +} diff --git a/services/directory.go b/services/directory.go index 2cfce9545..e5497ac7b 100755 --- a/services/directory.go +++ b/services/directory.go @@ -41,6 +41,7 @@ import ( "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudbuild" cloudbuild_alpha "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudbuild/alpha" cloudbuild_beta "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudbuild/beta" + cloudbuildv2_alpha "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudbuildv2/alpha" "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/clouddeploy" clouddeploy_alpha "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/clouddeploy/alpha" clouddeploy_beta "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/clouddeploy/beta" @@ -708,6 +709,10 @@ func Services() *Directory { d.AddResource("alpha", "binaryauthorization", "Policy", binaryauthorization_alpha.YAML_policy) d.AddResource("alpha", "cloudbuild", dcl.TitleToSnakeCase("WorkerPool"), cloudbuild_alpha.YAML_worker_pool) d.AddResource("alpha", "cloudbuild", "WorkerPool", cloudbuild_alpha.YAML_worker_pool) + d.AddResource("alpha", "cloudbuildv2", dcl.TitleToSnakeCase("Connection"), cloudbuildv2_alpha.YAML_connection) + d.AddResource("alpha", "cloudbuildv2", "Connection", cloudbuildv2_alpha.YAML_connection) + d.AddResource("alpha", "cloudbuildv2", dcl.TitleToSnakeCase("Repository"), cloudbuildv2_alpha.YAML_repository) + d.AddResource("alpha", "cloudbuildv2", "Repository", cloudbuildv2_alpha.YAML_repository) d.AddResource("alpha", "clouddeploy", dcl.TitleToSnakeCase("DeliveryPipeline"), clouddeploy_alpha.YAML_delivery_pipeline) d.AddResource("alpha", "clouddeploy", "DeliveryPipeline", clouddeploy_alpha.YAML_delivery_pipeline) d.AddResource("alpha", "clouddeploy", dcl.TitleToSnakeCase("Target"), clouddeploy_alpha.YAML_target) diff --git a/services/google/cloudbuildv2/alpha/client.go b/services/google/cloudbuildv2/alpha/client.go new file mode 100755 index 000000000..cafaa2323 --- /dev/null +++ b/services/google/cloudbuildv2/alpha/client.go @@ -0,0 +1,32 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// Package alpha defines operations in the declarative SDK. +package alpha + +import ( + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" +) + +// The Client is the base struct of all operations. This will receive the +// Get, Delete, List, and Apply operations on all resources. +type Client struct { + Config *dcl.Config +} + +// NewClient creates a client that retries all operations a few times each. +func NewClient(c *dcl.Config) *Client { + return &Client{ + Config: c, + } +} diff --git a/services/google/cloudbuildv2/alpha/connection.go b/services/google/cloudbuildv2/alpha/connection.go new file mode 100755 index 000000000..42f73a798 --- /dev/null +++ b/services/google/cloudbuildv2/alpha/connection.go @@ -0,0 +1,733 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +package alpha + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "time" + + "google.golang.org/api/googleapi" + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" +) + +type Connection struct { + Name *string `json:"name"` + CreateTime *string `json:"createTime"` + UpdateTime *string `json:"updateTime"` + GithubConfig *ConnectionGithubConfig `json:"githubConfig"` + GithubEnterpriseConfig *ConnectionGithubEnterpriseConfig `json:"githubEnterpriseConfig"` + InstallationState *ConnectionInstallationState `json:"installationState"` + Disabled *bool `json:"disabled"` + Reconciling *bool `json:"reconciling"` + Annotations map[string]string `json:"annotations"` + Etag *string `json:"etag"` + Project *string `json:"project"` + Location *string `json:"location"` +} + +func (r *Connection) String() string { + return dcl.SprintResource(r) +} + +// The enum ConnectionInstallationStateStageEnum. +type ConnectionInstallationStateStageEnum string + +// ConnectionInstallationStateStageEnumRef returns a *ConnectionInstallationStateStageEnum with the value of string s +// If the empty string is provided, nil is returned. +func ConnectionInstallationStateStageEnumRef(s string) *ConnectionInstallationStateStageEnum { + v := ConnectionInstallationStateStageEnum(s) + return &v +} + +func (v ConnectionInstallationStateStageEnum) Validate() error { + if string(v) == "" { + // Empty enum is okay. + return nil + } + for _, s := range []string{"STAGE_UNSPECIFIED", "PENDING_CREATE_APP", "PENDING_USER_OAUTH", "PENDING_INSTALL_APP", "COMPLETE"} { + if string(v) == s { + return nil + } + } + return &dcl.EnumInvalidError{ + Enum: "ConnectionInstallationStateStageEnum", + Value: string(v), + Valid: []string{}, + } +} + +type ConnectionGithubConfig struct { + empty bool `json:"-"` + AuthorizerCredential *ConnectionGithubConfigAuthorizerCredential `json:"authorizerCredential"` + AppInstallationId *int64 `json:"appInstallationId"` +} + +type jsonConnectionGithubConfig ConnectionGithubConfig + +func (r *ConnectionGithubConfig) UnmarshalJSON(data []byte) error { + var res jsonConnectionGithubConfig + if err := json.Unmarshal(data, &res); err != nil { + return err + } + + var m map[string]interface{} + json.Unmarshal(data, &m) + + if len(m) == 0 { + *r = *EmptyConnectionGithubConfig + } else { + + r.AuthorizerCredential = res.AuthorizerCredential + + r.AppInstallationId = res.AppInstallationId + + } + return nil +} + +// This object is used to assert a desired state where this ConnectionGithubConfig is +// empty. Go lacks global const objects, but this object should be treated +// as one. Modifying this object will have undesirable results. +var EmptyConnectionGithubConfig *ConnectionGithubConfig = &ConnectionGithubConfig{empty: true} + +func (r *ConnectionGithubConfig) Empty() bool { + return r.empty +} + +func (r *ConnectionGithubConfig) String() string { + return dcl.SprintResource(r) +} + +func (r *ConnectionGithubConfig) HashCode() string { + // Placeholder for a more complex hash method that handles ordering, etc + // Hash resource body for easy comparison later + hash := sha256.New().Sum([]byte(r.String())) + return fmt.Sprintf("%x", hash) +} + +type ConnectionGithubConfigAuthorizerCredential struct { + empty bool `json:"-"` + OAuthTokenSecretVersion *string `json:"oauthTokenSecretVersion"` + Username *string `json:"username"` +} + +type jsonConnectionGithubConfigAuthorizerCredential ConnectionGithubConfigAuthorizerCredential + +func (r *ConnectionGithubConfigAuthorizerCredential) UnmarshalJSON(data []byte) error { + var res jsonConnectionGithubConfigAuthorizerCredential + if err := json.Unmarshal(data, &res); err != nil { + return err + } + + var m map[string]interface{} + json.Unmarshal(data, &m) + + if len(m) == 0 { + *r = *EmptyConnectionGithubConfigAuthorizerCredential + } else { + + r.OAuthTokenSecretVersion = res.OAuthTokenSecretVersion + + r.Username = res.Username + + } + return nil +} + +// This object is used to assert a desired state where this ConnectionGithubConfigAuthorizerCredential is +// empty. Go lacks global const objects, but this object should be treated +// as one. Modifying this object will have undesirable results. +var EmptyConnectionGithubConfigAuthorizerCredential *ConnectionGithubConfigAuthorizerCredential = &ConnectionGithubConfigAuthorizerCredential{empty: true} + +func (r *ConnectionGithubConfigAuthorizerCredential) Empty() bool { + return r.empty +} + +func (r *ConnectionGithubConfigAuthorizerCredential) String() string { + return dcl.SprintResource(r) +} + +func (r *ConnectionGithubConfigAuthorizerCredential) HashCode() string { + // Placeholder for a more complex hash method that handles ordering, etc + // Hash resource body for easy comparison later + hash := sha256.New().Sum([]byte(r.String())) + return fmt.Sprintf("%x", hash) +} + +type ConnectionGithubEnterpriseConfig struct { + empty bool `json:"-"` + HostUri *string `json:"hostUri"` + AppId *int64 `json:"appId"` + AppSlug *string `json:"appSlug"` + PrivateKeySecretVersion *string `json:"privateKeySecretVersion"` + WebhookSecretSecretVersion *string `json:"webhookSecretSecretVersion"` + OAuthSecretSecretVersion *string `json:"oauthSecretSecretVersion"` + OAuthClientIdSecretVersion *string `json:"oauthClientIdSecretVersion"` + AuthorizerCredential *ConnectionGithubEnterpriseConfigAuthorizerCredential `json:"authorizerCredential"` + AppInstallationId *int64 `json:"appInstallationId"` + ServiceDirectoryConfig *ConnectionGithubEnterpriseConfigServiceDirectoryConfig `json:"serviceDirectoryConfig"` + SslCa *string `json:"sslCa"` +} + +type jsonConnectionGithubEnterpriseConfig ConnectionGithubEnterpriseConfig + +func (r *ConnectionGithubEnterpriseConfig) UnmarshalJSON(data []byte) error { + var res jsonConnectionGithubEnterpriseConfig + if err := json.Unmarshal(data, &res); err != nil { + return err + } + + var m map[string]interface{} + json.Unmarshal(data, &m) + + if len(m) == 0 { + *r = *EmptyConnectionGithubEnterpriseConfig + } else { + + r.HostUri = res.HostUri + + r.AppId = res.AppId + + r.AppSlug = res.AppSlug + + r.PrivateKeySecretVersion = res.PrivateKeySecretVersion + + r.WebhookSecretSecretVersion = res.WebhookSecretSecretVersion + + r.OAuthSecretSecretVersion = res.OAuthSecretSecretVersion + + r.OAuthClientIdSecretVersion = res.OAuthClientIdSecretVersion + + r.AuthorizerCredential = res.AuthorizerCredential + + r.AppInstallationId = res.AppInstallationId + + r.ServiceDirectoryConfig = res.ServiceDirectoryConfig + + r.SslCa = res.SslCa + + } + return nil +} + +// This object is used to assert a desired state where this ConnectionGithubEnterpriseConfig is +// empty. Go lacks global const objects, but this object should be treated +// as one. Modifying this object will have undesirable results. +var EmptyConnectionGithubEnterpriseConfig *ConnectionGithubEnterpriseConfig = &ConnectionGithubEnterpriseConfig{empty: true} + +func (r *ConnectionGithubEnterpriseConfig) Empty() bool { + return r.empty +} + +func (r *ConnectionGithubEnterpriseConfig) String() string { + return dcl.SprintResource(r) +} + +func (r *ConnectionGithubEnterpriseConfig) HashCode() string { + // Placeholder for a more complex hash method that handles ordering, etc + // Hash resource body for easy comparison later + hash := sha256.New().Sum([]byte(r.String())) + return fmt.Sprintf("%x", hash) +} + +type ConnectionGithubEnterpriseConfigAuthorizerCredential struct { + empty bool `json:"-"` + OAuthTokenSecretVersion *string `json:"oauthTokenSecretVersion"` + Username *string `json:"username"` +} + +type jsonConnectionGithubEnterpriseConfigAuthorizerCredential ConnectionGithubEnterpriseConfigAuthorizerCredential + +func (r *ConnectionGithubEnterpriseConfigAuthorizerCredential) UnmarshalJSON(data []byte) error { + var res jsonConnectionGithubEnterpriseConfigAuthorizerCredential + if err := json.Unmarshal(data, &res); err != nil { + return err + } + + var m map[string]interface{} + json.Unmarshal(data, &m) + + if len(m) == 0 { + *r = *EmptyConnectionGithubEnterpriseConfigAuthorizerCredential + } else { + + r.OAuthTokenSecretVersion = res.OAuthTokenSecretVersion + + r.Username = res.Username + + } + return nil +} + +// This object is used to assert a desired state where this ConnectionGithubEnterpriseConfigAuthorizerCredential is +// empty. Go lacks global const objects, but this object should be treated +// as one. Modifying this object will have undesirable results. +var EmptyConnectionGithubEnterpriseConfigAuthorizerCredential *ConnectionGithubEnterpriseConfigAuthorizerCredential = &ConnectionGithubEnterpriseConfigAuthorizerCredential{empty: true} + +func (r *ConnectionGithubEnterpriseConfigAuthorizerCredential) Empty() bool { + return r.empty +} + +func (r *ConnectionGithubEnterpriseConfigAuthorizerCredential) String() string { + return dcl.SprintResource(r) +} + +func (r *ConnectionGithubEnterpriseConfigAuthorizerCredential) HashCode() string { + // Placeholder for a more complex hash method that handles ordering, etc + // Hash resource body for easy comparison later + hash := sha256.New().Sum([]byte(r.String())) + return fmt.Sprintf("%x", hash) +} + +type ConnectionGithubEnterpriseConfigServiceDirectoryConfig struct { + empty bool `json:"-"` + Service *string `json:"service"` +} + +type jsonConnectionGithubEnterpriseConfigServiceDirectoryConfig ConnectionGithubEnterpriseConfigServiceDirectoryConfig + +func (r *ConnectionGithubEnterpriseConfigServiceDirectoryConfig) UnmarshalJSON(data []byte) error { + var res jsonConnectionGithubEnterpriseConfigServiceDirectoryConfig + if err := json.Unmarshal(data, &res); err != nil { + return err + } + + var m map[string]interface{} + json.Unmarshal(data, &m) + + if len(m) == 0 { + *r = *EmptyConnectionGithubEnterpriseConfigServiceDirectoryConfig + } else { + + r.Service = res.Service + + } + return nil +} + +// This object is used to assert a desired state where this ConnectionGithubEnterpriseConfigServiceDirectoryConfig is +// empty. Go lacks global const objects, but this object should be treated +// as one. Modifying this object will have undesirable results. +var EmptyConnectionGithubEnterpriseConfigServiceDirectoryConfig *ConnectionGithubEnterpriseConfigServiceDirectoryConfig = &ConnectionGithubEnterpriseConfigServiceDirectoryConfig{empty: true} + +func (r *ConnectionGithubEnterpriseConfigServiceDirectoryConfig) Empty() bool { + return r.empty +} + +func (r *ConnectionGithubEnterpriseConfigServiceDirectoryConfig) String() string { + return dcl.SprintResource(r) +} + +func (r *ConnectionGithubEnterpriseConfigServiceDirectoryConfig) HashCode() string { + // Placeholder for a more complex hash method that handles ordering, etc + // Hash resource body for easy comparison later + hash := sha256.New().Sum([]byte(r.String())) + return fmt.Sprintf("%x", hash) +} + +type ConnectionInstallationState struct { + empty bool `json:"-"` + Stage *ConnectionInstallationStateStageEnum `json:"stage"` + Message *string `json:"message"` + ActionUri *string `json:"actionUri"` +} + +type jsonConnectionInstallationState ConnectionInstallationState + +func (r *ConnectionInstallationState) UnmarshalJSON(data []byte) error { + var res jsonConnectionInstallationState + if err := json.Unmarshal(data, &res); err != nil { + return err + } + + var m map[string]interface{} + json.Unmarshal(data, &m) + + if len(m) == 0 { + *r = *EmptyConnectionInstallationState + } else { + + r.Stage = res.Stage + + r.Message = res.Message + + r.ActionUri = res.ActionUri + + } + return nil +} + +// This object is used to assert a desired state where this ConnectionInstallationState is +// empty. Go lacks global const objects, but this object should be treated +// as one. Modifying this object will have undesirable results. +var EmptyConnectionInstallationState *ConnectionInstallationState = &ConnectionInstallationState{empty: true} + +func (r *ConnectionInstallationState) Empty() bool { + return r.empty +} + +func (r *ConnectionInstallationState) String() string { + return dcl.SprintResource(r) +} + +func (r *ConnectionInstallationState) HashCode() string { + // Placeholder for a more complex hash method that handles ordering, etc + // Hash resource body for easy comparison later + hash := sha256.New().Sum([]byte(r.String())) + return fmt.Sprintf("%x", hash) +} + +// Describe returns a simple description of this resource to ensure that automated tools +// can identify it. +func (r *Connection) Describe() dcl.ServiceTypeVersion { + return dcl.ServiceTypeVersion{ + Service: "cloudbuildv2", + Type: "Connection", + Version: "alpha", + } +} + +func (r *Connection) ID() (string, error) { + if err := extractConnectionFields(r); err != nil { + return "", err + } + nr := r.urlNormalized() + params := map[string]interface{}{ + "name": dcl.ValueOrEmptyString(nr.Name), + "create_time": dcl.ValueOrEmptyString(nr.CreateTime), + "update_time": dcl.ValueOrEmptyString(nr.UpdateTime), + "github_config": dcl.ValueOrEmptyString(nr.GithubConfig), + "github_enterprise_config": dcl.ValueOrEmptyString(nr.GithubEnterpriseConfig), + "installation_state": dcl.ValueOrEmptyString(nr.InstallationState), + "disabled": dcl.ValueOrEmptyString(nr.Disabled), + "reconciling": dcl.ValueOrEmptyString(nr.Reconciling), + "annotations": dcl.ValueOrEmptyString(nr.Annotations), + "etag": dcl.ValueOrEmptyString(nr.Etag), + "project": dcl.ValueOrEmptyString(nr.Project), + "location": dcl.ValueOrEmptyString(nr.Location), + } + return dcl.Nprintf("projects/{{project}}/locations/{{location}}/connections/{{name}}", params), nil +} + +const ConnectionMaxPage = -1 + +type ConnectionList struct { + Items []*Connection + + nextToken string + + pageSize int32 + + resource *Connection +} + +func (l *ConnectionList) HasNext() bool { + return l.nextToken != "" +} + +func (l *ConnectionList) Next(ctx context.Context, c *Client) error { + ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) + defer cancel() + + if !l.HasNext() { + return fmt.Errorf("no next page") + } + items, token, err := c.listConnection(ctx, l.resource, l.nextToken, l.pageSize) + if err != nil { + return err + } + l.Items = items + l.nextToken = token + return err +} + +func (c *Client) ListConnection(ctx context.Context, project, location string) (*ConnectionList, error) { + ctx = dcl.ContextWithRequestID(ctx) + ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) + defer cancel() + + return c.ListConnectionWithMaxResults(ctx, project, location, ConnectionMaxPage) + +} + +func (c *Client) ListConnectionWithMaxResults(ctx context.Context, project, location string, pageSize int32) (*ConnectionList, error) { + ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) + defer cancel() + + // Create a resource object so that we can use proper url normalization methods. + r := &Connection{ + Project: &project, + Location: &location, + } + items, token, err := c.listConnection(ctx, r, "", pageSize) + if err != nil { + return nil, err + } + return &ConnectionList{ + Items: items, + nextToken: token, + pageSize: pageSize, + resource: r, + }, nil +} + +func (c *Client) GetConnection(ctx context.Context, r *Connection) (*Connection, error) { + ctx = dcl.ContextWithRequestID(ctx) + ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) + defer cancel() + + // This is *purposefully* supressing errors. + // This function is used with url-normalized values + not URL normalized values. + // URL Normalized values will throw unintentional errors, since those values are not of the proper parent form. + extractConnectionFields(r) + + b, err := c.getConnectionRaw(ctx, r) + if err != nil { + if dcl.IsNotFound(err) { + return nil, &googleapi.Error{ + Code: 404, + Message: err.Error(), + } + } + return nil, err + } + result, err := unmarshalConnection(b, c, r) + if err != nil { + return nil, err + } + result.Project = r.Project + result.Location = r.Location + result.Name = r.Name + + c.Config.Logger.InfoWithContextf(ctx, "Retrieved raw result state: %v", result) + c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with specified state: %v", r) + result, err = canonicalizeConnectionNewState(c, result, r) + if err != nil { + return nil, err + } + if err := postReadExtractConnectionFields(result); err != nil { + return result, err + } + c.Config.Logger.InfoWithContextf(ctx, "Created result state: %v", result) + + return result, nil +} + +func (c *Client) DeleteConnection(ctx context.Context, r *Connection) error { + ctx = dcl.ContextWithRequestID(ctx) + ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) + defer cancel() + + if r == nil { + return fmt.Errorf("Connection resource is nil") + } + c.Config.Logger.InfoWithContext(ctx, "Deleting Connection...") + deleteOp := deleteConnectionOperation{} + return deleteOp.do(ctx, r, c) +} + +// DeleteAllConnection deletes all resources that the filter functions returns true on. +func (c *Client) DeleteAllConnection(ctx context.Context, project, location string, filter func(*Connection) bool) error { + listObj, err := c.ListConnection(ctx, project, location) + if err != nil { + return err + } + + err = c.deleteAllConnection(ctx, filter, listObj.Items) + if err != nil { + return err + } + for listObj.HasNext() { + err = listObj.Next(ctx, c) + if err != nil { + return nil + } + err = c.deleteAllConnection(ctx, filter, listObj.Items) + if err != nil { + return err + } + } + return nil +} + +func (c *Client) ApplyConnection(ctx context.Context, rawDesired *Connection, opts ...dcl.ApplyOption) (*Connection, error) { + ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) + defer cancel() + + ctx = dcl.ContextWithRequestID(ctx) + var resultNewState *Connection + err := dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) { + newState, err := applyConnectionHelper(c, ctx, rawDesired, opts...) + resultNewState = newState + if err != nil { + // If the error is 409, there is conflict in resource update. + // Here we want to apply changes based on latest state. + if dcl.IsConflictError(err) { + return &dcl.RetryDetails{}, dcl.OperationNotDone{Err: err} + } + return nil, err + } + return nil, nil + }, c.Config.RetryProvider) + return resultNewState, err +} + +func applyConnectionHelper(c *Client, ctx context.Context, rawDesired *Connection, opts ...dcl.ApplyOption) (*Connection, error) { + c.Config.Logger.InfoWithContext(ctx, "Beginning ApplyConnection...") + c.Config.Logger.InfoWithContextf(ctx, "User specified desired state: %v", rawDesired) + + // 1.1: Validation of user-specified fields in desired state. + if err := rawDesired.validate(); err != nil { + return nil, err + } + + if err := extractConnectionFields(rawDesired); err != nil { + return nil, err + } + + initial, desired, fieldDiffs, err := c.connectionDiffsForRawDesired(ctx, rawDesired, opts...) + if err != nil { + return nil, fmt.Errorf("failed to create a diff: %w", err) + } + + diffs, err := convertFieldDiffsToConnectionDiffs(c.Config, fieldDiffs, opts) + if err != nil { + return nil, err + } + + // TODO(magic-modules-eng): 2.2 Feasibility check (all updates are feasible so far). + + // 2.3: Lifecycle Directive Check + var create bool + lp := dcl.FetchLifecycleParams(opts) + if initial == nil { + if dcl.HasLifecycleParam(lp, dcl.BlockCreation) { + return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Creation blocked by lifecycle params: %#v.", desired)} + } + create = true + } else if dcl.HasLifecycleParam(lp, dcl.BlockAcquire) { + return nil, dcl.ApplyInfeasibleError{ + Message: fmt.Sprintf("Resource already exists - apply blocked by lifecycle params: %#v.", initial), + } + } else { + for _, d := range diffs { + if d.RequiresRecreate { + return nil, dcl.ApplyInfeasibleError{ + Message: fmt.Sprintf("infeasible update: (%v) would require recreation", d), + } + } + if dcl.HasLifecycleParam(lp, dcl.BlockModification) { + return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Modification blocked, diff (%v) unresolvable.", d)} + } + } + } + + // 2.4 Imperative Request Planning + var ops []connectionApiOperation + if create { + ops = append(ops, &createConnectionOperation{}) + } else { + for _, d := range diffs { + ops = append(ops, d.UpdateOp) + } + } + c.Config.Logger.InfoWithContextf(ctx, "Created plan: %#v", ops) + + // 2.5 Request Actuation + for _, op := range ops { + c.Config.Logger.InfoWithContextf(ctx, "Performing operation %T %+v", op, op) + if err := op.do(ctx, desired, c); err != nil { + c.Config.Logger.InfoWithContextf(ctx, "Failed operation %T %+v: %v", op, op, err) + return nil, err + } + c.Config.Logger.InfoWithContextf(ctx, "Finished operation %T %+v", op, op) + } + return applyConnectionDiff(c, ctx, desired, rawDesired, ops, opts...) +} + +func applyConnectionDiff(c *Client, ctx context.Context, desired *Connection, rawDesired *Connection, ops []connectionApiOperation, opts ...dcl.ApplyOption) (*Connection, error) { + // 3.1, 3.2a Retrieval of raw new state & canonicalization with desired state + c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state...") + rawNew, err := c.GetConnection(ctx, desired) + if err != nil { + return nil, err + } + // Get additional values from the first response. + // These values should be merged into the newState above. + if len(ops) > 0 { + lastOp := ops[len(ops)-1] + if o, ok := lastOp.(*createConnectionOperation); ok { + if r, hasR := o.FirstResponse(); hasR { + + c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state from operation...") + + fullResp, err := unmarshalMapConnection(r, c, rawDesired) + if err != nil { + return nil, err + } + + rawNew, err = canonicalizeConnectionNewState(c, rawNew, fullResp) + if err != nil { + return nil, err + } + } + } + } + + c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with raw desired state: %v", rawDesired) + // 3.2b Canonicalization of raw new state using raw desired state + newState, err := canonicalizeConnectionNewState(c, rawNew, rawDesired) + if err != nil { + return rawNew, err + } + + c.Config.Logger.InfoWithContextf(ctx, "Created canonical new state: %v", newState) + // 3.3 Comparison of the new state and raw desired state. + // TODO(magic-modules-eng): EVENTUALLY_CONSISTENT_UPDATE + newDesired, err := canonicalizeConnectionDesiredState(rawDesired, newState) + if err != nil { + return newState, err + } + + if err := postReadExtractConnectionFields(newState); err != nil { + return newState, err + } + + // Need to ensure any transformations made here match acceptably in differ. + if err := postReadExtractConnectionFields(newDesired); err != nil { + return newState, err + } + + c.Config.Logger.InfoWithContextf(ctx, "Diffing using canonicalized desired state: %v", newDesired) + newDiffs, err := diffConnection(c, newDesired, newState) + if err != nil { + return newState, err + } + + if len(newDiffs) == 0 { + c.Config.Logger.InfoWithContext(ctx, "No diffs found. Apply was successful.") + } else { + c.Config.Logger.InfoWithContextf(ctx, "Found diffs: %v", newDiffs) + diffMessages := make([]string, len(newDiffs)) + for i, d := range newDiffs { + diffMessages[i] = fmt.Sprintf("%v", d) + } + return newState, dcl.DiffAfterApplyError{Diffs: diffMessages} + } + c.Config.Logger.InfoWithContext(ctx, "Done Apply.") + return newState, nil +} diff --git a/services/google/cloudbuildv2/alpha/connection.yaml b/services/google/cloudbuildv2/alpha/connection.yaml new file mode 100755 index 000000000..f8ec0b442 --- /dev/null +++ b/services/google/cloudbuildv2/alpha/connection.yaml @@ -0,0 +1,317 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +info: + title: Cloudbuildv2/Connection + description: The Cloudbuildv2 Connection resource + x-dcl-struct-name: Connection + x-dcl-has-iam: false +paths: + get: + description: The function used to get information about a Connection + parameters: + - name: Connection + required: true + description: A full instance of a Connection + apply: + description: The function used to apply information about a Connection + parameters: + - name: Connection + required: true + description: A full instance of a Connection + delete: + description: The function used to delete a Connection + parameters: + - name: Connection + required: true + description: A full instance of a Connection + deleteAll: + description: The function used to delete all Connection + parameters: + - name: project + required: true + schema: + type: string + - name: location + required: true + schema: + type: string + list: + description: The function used to list information about many Connection + parameters: + - name: project + required: true + schema: + type: string + - name: location + required: true + schema: + type: string +components: + schemas: + Connection: + title: Connection + x-dcl-id: projects/{{project}}/locations/{{location}}/connections/{{name}} + x-dcl-parent-container: project + x-dcl-has-create: true + x-dcl-has-iam: false + x-dcl-read-timeout: 0 + x-dcl-apply-timeout: 0 + x-dcl-delete-timeout: 0 + type: object + required: + - name + - project + - location + properties: + annotations: + type: object + additionalProperties: + type: string + x-dcl-go-name: Annotations + description: Allows clients to store small amounts of arbitrary data. + createTime: + type: string + format: date-time + x-dcl-go-name: CreateTime + readOnly: true + description: Output only. Server assigned timestamp for when the connection + was created. + x-kubernetes-immutable: true + disabled: + type: boolean + x-dcl-go-name: Disabled + description: If disabled is set to true, functionality is disabled for this + connection. Repository based API methods and webhooks processing for repositories + in this connection will be disabled. + etag: + type: string + x-dcl-go-name: Etag + readOnly: true + description: This checksum is computed by the server based on the value + of other fields, and may be sent on update and delete requests to ensure + the client has an up-to-date value before proceeding. + x-kubernetes-immutable: true + githubConfig: + type: object + x-dcl-go-name: GithubConfig + x-dcl-go-type: ConnectionGithubConfig + description: Configuration for connections to github.com. + x-dcl-conflicts: + - githubEnterpriseConfig + properties: + appInstallationId: + type: integer + format: int64 + x-dcl-go-name: AppInstallationId + description: GitHub App installation id. + authorizerCredential: + type: object + x-dcl-go-name: AuthorizerCredential + x-dcl-go-type: ConnectionGithubConfigAuthorizerCredential + description: OAuth credential of the account that authorized the Cloud + Build GitHub App. It is recommended to use a robot account instead + of a human user account. The OAuth token must be tied to the Cloud + Build GitHub App. + properties: + oauthTokenSecretVersion: + type: string + x-dcl-go-name: OAuthTokenSecretVersion + description: 'A SecretManager resource containing the OAuth token + that authorizes the Cloud Build connection. Format: `projects/*/secrets/*/versions/*`.' + x-dcl-references: + - resource: Secretmanager/SecretVersion + field: selfLink + username: + type: string + x-dcl-go-name: Username + description: The username associated to this token. + githubEnterpriseConfig: + type: object + x-dcl-go-name: GithubEnterpriseConfig + x-dcl-go-type: ConnectionGithubEnterpriseConfig + description: Configuration for connections to an instance of GitHub Enterprise. + x-dcl-conflicts: + - githubConfig + required: + - hostUri + properties: + appId: + type: integer + format: int64 + x-dcl-go-name: AppId + description: Id of the GitHub App created from the manifest. + appInstallationId: + type: integer + format: int64 + x-dcl-go-name: AppInstallationId + description: ID of the installation of the GitHub App. + appSlug: + type: string + x-dcl-go-name: AppSlug + description: The URL-friendly name of the GitHub App. + authorizerCredential: + type: object + x-dcl-go-name: AuthorizerCredential + x-dcl-go-type: ConnectionGithubEnterpriseConfigAuthorizerCredential + description: OAuth credential of the account that authorized the Cloud + Build GitHub App. It is recommended to use a robot account instead + of a human user account The OAuth token must be tied to the Cloud + Build GitHub App. + properties: + oauthTokenSecretVersion: + type: string + x-dcl-go-name: OAuthTokenSecretVersion + description: 'A SecretManager resource containing the OAuth token + that authorizes the Cloud Build connection. Format: `projects/*/secrets/*/versions/*`.' + x-dcl-references: + - resource: Secretmanager/SecretVersion + field: selfLink + username: + type: string + x-dcl-go-name: Username + description: The username associated to this token. + hostUri: + type: string + x-dcl-go-name: HostUri + description: Required. The URI of the GitHub Enterprise host this connection + is for. + oauthClientIdSecretVersion: + type: string + x-dcl-go-name: OAuthClientIdSecretVersion + description: SecretManager resource containing the OAuth client_id of + the GitHub App, formatted as `projects/*/secrets/*/versions/*`. + x-dcl-references: + - resource: Secretmanager/SecretVersion + field: selfLink + oauthSecretSecretVersion: + type: string + x-dcl-go-name: OAuthSecretSecretVersion + description: SecretManager resource containing the OAuth secret of the + GitHub App, formatted as `projects/*/secrets/*/versions/*`. + x-dcl-references: + - resource: Secretmanager/SecretVersion + field: selfLink + privateKeySecretVersion: + type: string + x-dcl-go-name: PrivateKeySecretVersion + description: SecretManager resource containing the private key of the + GitHub App, formatted as `projects/*/secrets/*/versions/*`. + x-dcl-references: + - resource: Secretmanager/SecretVersion + field: selfLink + serviceDirectoryConfig: + type: object + x-dcl-go-name: ServiceDirectoryConfig + x-dcl-go-type: ConnectionGithubEnterpriseConfigServiceDirectoryConfig + description: Configuration for using Service Directory to privately + connect to a GitHub Enterprise server. This should only be set if + the GitHub Enterprise server is hosted on-premises and not reachable + by public internet. If this field is left empty, calls to the GitHub + Enterprise server will be made over the public internet. + required: + - service + properties: + service: + type: string + x-dcl-go-name: Service + description: 'Required. The Service Directory service name. Format: + projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}.' + x-dcl-references: + - resource: Servicedirectory/Service + field: selfLink + sslCa: + type: string + x-dcl-go-name: SslCa + description: SSL certificate to use for requests to GitHub Enterprise. + webhookSecretSecretVersion: + type: string + x-dcl-go-name: WebhookSecretSecretVersion + description: SecretManager resource containing the webhook secret of + the GitHub App, formatted as `projects/*/secrets/*/versions/*`. + x-dcl-references: + - resource: Secretmanager/SecretVersion + field: selfLink + installationState: + type: object + x-dcl-go-name: InstallationState + x-dcl-go-type: ConnectionInstallationState + readOnly: true + description: Output only. Installation state of the Connection. + x-kubernetes-immutable: true + properties: + actionUri: + type: string + x-dcl-go-name: ActionUri + readOnly: true + description: Output only. Link to follow for next action. Empty string + if the installation is already complete. + x-kubernetes-immutable: true + message: + type: string + x-dcl-go-name: Message + readOnly: true + description: Output only. Message of what the user should do next to + continue the installation. Empty string if the installation is already + complete. + x-kubernetes-immutable: true + stage: + type: string + x-dcl-go-name: Stage + x-dcl-go-type: ConnectionInstallationStateStageEnum + readOnly: true + description: 'Output only. Current step of the installation process. + Possible values: STAGE_UNSPECIFIED, PENDING_CREATE_APP, PENDING_USER_OAUTH, + PENDING_INSTALL_APP, COMPLETE' + x-kubernetes-immutable: true + enum: + - STAGE_UNSPECIFIED + - PENDING_CREATE_APP + - PENDING_USER_OAUTH + - PENDING_INSTALL_APP + - COMPLETE + location: + type: string + x-dcl-go-name: Location + description: The location for the resource + x-kubernetes-immutable: true + name: + type: string + x-dcl-go-name: Name + description: Immutable. The resource name of the connection, in the format + `projects/{project}/locations/{location}/connections/{connection_id}`. + x-kubernetes-immutable: true + project: + type: string + x-dcl-go-name: Project + description: The project for the resource + x-kubernetes-immutable: true + x-dcl-references: + - resource: Cloudresourcemanager/Project + field: name + parent: true + reconciling: + type: boolean + x-dcl-go-name: Reconciling + readOnly: true + description: Output only. Set to true when the connection is being set up + or updated in the background. + x-kubernetes-immutable: true + updateTime: + type: string + format: date-time + x-dcl-go-name: UpdateTime + readOnly: true + description: Output only. Server assigned timestamp for when the connection + was updated. + x-kubernetes-immutable: true diff --git a/services/google/cloudbuildv2/alpha/connection_alpha_yaml_embed.go b/services/google/cloudbuildv2/alpha/connection_alpha_yaml_embed.go new file mode 100755 index 000000000..57978c0e8 --- /dev/null +++ b/services/google/cloudbuildv2/alpha/connection_alpha_yaml_embed.go @@ -0,0 +1,23 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// GENERATED BY gen_go_data.go +// gen_go_data -package alpha -var YAML_connection blaze-out/k8-fastbuild/genfiles/cloud/graphite/mmv2/services/google/cloudbuildv2/alpha/connection.yaml + +package alpha + +// blaze-out/k8-fastbuild/genfiles/cloud/graphite/mmv2/services/google/cloudbuildv2/alpha/connection.yaml +var YAML_connection = []byte("info:\n title: Cloudbuildv2/Connection\n description: The Cloudbuildv2 Connection resource\n x-dcl-struct-name: Connection\n x-dcl-has-iam: false\npaths:\n get:\n description: The function used to get information about a Connection\n parameters:\n - name: Connection\n required: true\n description: A full instance of a Connection\n apply:\n description: The function used to apply information about a Connection\n parameters:\n - name: Connection\n required: true\n description: A full instance of a Connection\n delete:\n description: The function used to delete a Connection\n parameters:\n - name: Connection\n required: true\n description: A full instance of a Connection\n deleteAll:\n description: The function used to delete all Connection\n parameters:\n - name: project\n required: true\n schema:\n type: string\n - name: location\n required: true\n schema:\n type: string\n list:\n description: The function used to list information about many Connection\n parameters:\n - name: project\n required: true\n schema:\n type: string\n - name: location\n required: true\n schema:\n type: string\ncomponents:\n schemas:\n Connection:\n title: Connection\n x-dcl-id: projects/{{project}}/locations/{{location}}/connections/{{name}}\n x-dcl-parent-container: project\n x-dcl-has-create: true\n x-dcl-has-iam: false\n x-dcl-read-timeout: 0\n x-dcl-apply-timeout: 0\n x-dcl-delete-timeout: 0\n type: object\n required:\n - name\n - project\n - location\n properties:\n annotations:\n type: object\n additionalProperties:\n type: string\n x-dcl-go-name: Annotations\n description: Allows clients to store small amounts of arbitrary data.\n createTime:\n type: string\n format: date-time\n x-dcl-go-name: CreateTime\n readOnly: true\n description: Output only. Server assigned timestamp for when the connection\n was created.\n x-kubernetes-immutable: true\n disabled:\n type: boolean\n x-dcl-go-name: Disabled\n description: If disabled is set to true, functionality is disabled for this\n connection. Repository based API methods and webhooks processing for repositories\n in this connection will be disabled.\n etag:\n type: string\n x-dcl-go-name: Etag\n readOnly: true\n description: This checksum is computed by the server based on the value\n of other fields, and may be sent on update and delete requests to ensure\n the client has an up-to-date value before proceeding.\n x-kubernetes-immutable: true\n githubConfig:\n type: object\n x-dcl-go-name: GithubConfig\n x-dcl-go-type: ConnectionGithubConfig\n description: Configuration for connections to github.com.\n x-dcl-conflicts:\n - githubEnterpriseConfig\n properties:\n appInstallationId:\n type: integer\n format: int64\n x-dcl-go-name: AppInstallationId\n description: GitHub App installation id.\n authorizerCredential:\n type: object\n x-dcl-go-name: AuthorizerCredential\n x-dcl-go-type: ConnectionGithubConfigAuthorizerCredential\n description: OAuth credential of the account that authorized the Cloud\n Build GitHub App. It is recommended to use a robot account instead\n of a human user account. The OAuth token must be tied to the Cloud\n Build GitHub App.\n properties:\n oauthTokenSecretVersion:\n type: string\n x-dcl-go-name: OAuthTokenSecretVersion\n description: 'A SecretManager resource containing the OAuth token\n that authorizes the Cloud Build connection. Format: `projects/*/secrets/*/versions/*`.'\n x-dcl-references:\n - resource: Secretmanager/SecretVersion\n field: selfLink\n username:\n type: string\n x-dcl-go-name: Username\n description: The username associated to this token.\n githubEnterpriseConfig:\n type: object\n x-dcl-go-name: GithubEnterpriseConfig\n x-dcl-go-type: ConnectionGithubEnterpriseConfig\n description: Configuration for connections to an instance of GitHub Enterprise.\n x-dcl-conflicts:\n - githubConfig\n required:\n - hostUri\n properties:\n appId:\n type: integer\n format: int64\n x-dcl-go-name: AppId\n description: Id of the GitHub App created from the manifest.\n appInstallationId:\n type: integer\n format: int64\n x-dcl-go-name: AppInstallationId\n description: ID of the installation of the GitHub App.\n appSlug:\n type: string\n x-dcl-go-name: AppSlug\n description: The URL-friendly name of the GitHub App.\n authorizerCredential:\n type: object\n x-dcl-go-name: AuthorizerCredential\n x-dcl-go-type: ConnectionGithubEnterpriseConfigAuthorizerCredential\n description: OAuth credential of the account that authorized the Cloud\n Build GitHub App. It is recommended to use a robot account instead\n of a human user account The OAuth token must be tied to the Cloud\n Build GitHub App.\n properties:\n oauthTokenSecretVersion:\n type: string\n x-dcl-go-name: OAuthTokenSecretVersion\n description: 'A SecretManager resource containing the OAuth token\n that authorizes the Cloud Build connection. Format: `projects/*/secrets/*/versions/*`.'\n x-dcl-references:\n - resource: Secretmanager/SecretVersion\n field: selfLink\n username:\n type: string\n x-dcl-go-name: Username\n description: The username associated to this token.\n hostUri:\n type: string\n x-dcl-go-name: HostUri\n description: Required. The URI of the GitHub Enterprise host this connection\n is for.\n oauthClientIdSecretVersion:\n type: string\n x-dcl-go-name: OAuthClientIdSecretVersion\n description: SecretManager resource containing the OAuth client_id of\n the GitHub App, formatted as `projects/*/secrets/*/versions/*`.\n x-dcl-references:\n - resource: Secretmanager/SecretVersion\n field: selfLink\n oauthSecretSecretVersion:\n type: string\n x-dcl-go-name: OAuthSecretSecretVersion\n description: SecretManager resource containing the OAuth secret of the\n GitHub App, formatted as `projects/*/secrets/*/versions/*`.\n x-dcl-references:\n - resource: Secretmanager/SecretVersion\n field: selfLink\n privateKeySecretVersion:\n type: string\n x-dcl-go-name: PrivateKeySecretVersion\n description: SecretManager resource containing the private key of the\n GitHub App, formatted as `projects/*/secrets/*/versions/*`.\n x-dcl-references:\n - resource: Secretmanager/SecretVersion\n field: selfLink\n serviceDirectoryConfig:\n type: object\n x-dcl-go-name: ServiceDirectoryConfig\n x-dcl-go-type: ConnectionGithubEnterpriseConfigServiceDirectoryConfig\n description: Configuration for using Service Directory to privately\n connect to a GitHub Enterprise server. This should only be set if\n the GitHub Enterprise server is hosted on-premises and not reachable\n by public internet. If this field is left empty, calls to the GitHub\n Enterprise server will be made over the public internet.\n required:\n - service\n properties:\n service:\n type: string\n x-dcl-go-name: Service\n description: 'Required. The Service Directory service name. Format:\n projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}.'\n x-dcl-references:\n - resource: Servicedirectory/Service\n field: selfLink\n sslCa:\n type: string\n x-dcl-go-name: SslCa\n description: SSL certificate to use for requests to GitHub Enterprise.\n webhookSecretSecretVersion:\n type: string\n x-dcl-go-name: WebhookSecretSecretVersion\n description: SecretManager resource containing the webhook secret of\n the GitHub App, formatted as `projects/*/secrets/*/versions/*`.\n x-dcl-references:\n - resource: Secretmanager/SecretVersion\n field: selfLink\n installationState:\n type: object\n x-dcl-go-name: InstallationState\n x-dcl-go-type: ConnectionInstallationState\n readOnly: true\n description: Output only. Installation state of the Connection.\n x-kubernetes-immutable: true\n properties:\n actionUri:\n type: string\n x-dcl-go-name: ActionUri\n readOnly: true\n description: Output only. Link to follow for next action. Empty string\n if the installation is already complete.\n x-kubernetes-immutable: true\n message:\n type: string\n x-dcl-go-name: Message\n readOnly: true\n description: Output only. Message of what the user should do next to\n continue the installation. Empty string if the installation is already\n complete.\n x-kubernetes-immutable: true\n stage:\n type: string\n x-dcl-go-name: Stage\n x-dcl-go-type: ConnectionInstallationStateStageEnum\n readOnly: true\n description: 'Output only. Current step of the installation process.\n Possible values: STAGE_UNSPECIFIED, PENDING_CREATE_APP, PENDING_USER_OAUTH,\n PENDING_INSTALL_APP, COMPLETE'\n x-kubernetes-immutable: true\n enum:\n - STAGE_UNSPECIFIED\n - PENDING_CREATE_APP\n - PENDING_USER_OAUTH\n - PENDING_INSTALL_APP\n - COMPLETE\n location:\n type: string\n x-dcl-go-name: Location\n description: The location for the resource\n x-kubernetes-immutable: true\n name:\n type: string\n x-dcl-go-name: Name\n description: Immutable. The resource name of the connection, in the format\n `projects/{project}/locations/{location}/connections/{connection_id}`.\n x-kubernetes-immutable: true\n project:\n type: string\n x-dcl-go-name: Project\n description: The project for the resource\n x-kubernetes-immutable: true\n x-dcl-references:\n - resource: Cloudresourcemanager/Project\n field: name\n parent: true\n reconciling:\n type: boolean\n x-dcl-go-name: Reconciling\n readOnly: true\n description: Output only. Set to true when the connection is being set up\n or updated in the background.\n x-kubernetes-immutable: true\n updateTime:\n type: string\n format: date-time\n x-dcl-go-name: UpdateTime\n readOnly: true\n description: Output only. Server assigned timestamp for when the connection\n was updated.\n x-kubernetes-immutable: true\n") + +// 12359 bytes +// MD5: dc67d92f80b70fdffc10e9d737a21b7e diff --git a/services/google/cloudbuildv2/alpha/connection_internal.go b/services/google/cloudbuildv2/alpha/connection_internal.go new file mode 100755 index 000000000..4d0c93be2 --- /dev/null +++ b/services/google/cloudbuildv2/alpha/connection_internal.go @@ -0,0 +1,2983 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +package alpha + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io/ioutil" + "strings" + + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl/operations" +) + +func (r *Connection) validate() error { + + if err := dcl.ValidateAtMostOneOfFieldsSet([]string{"GithubConfig", "GithubEnterpriseConfig"}, r.GithubConfig, r.GithubEnterpriseConfig); err != nil { + return err + } + if err := dcl.Required(r, "name"); err != nil { + return err + } + if err := dcl.RequiredParameter(r.Project, "Project"); err != nil { + return err + } + if err := dcl.RequiredParameter(r.Location, "Location"); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(r.GithubConfig) { + if err := r.GithubConfig.validate(); err != nil { + return err + } + } + if !dcl.IsEmptyValueIndirect(r.GithubEnterpriseConfig) { + if err := r.GithubEnterpriseConfig.validate(); err != nil { + return err + } + } + if !dcl.IsEmptyValueIndirect(r.InstallationState) { + if err := r.InstallationState.validate(); err != nil { + return err + } + } + return nil +} +func (r *ConnectionGithubConfig) validate() error { + if !dcl.IsEmptyValueIndirect(r.AuthorizerCredential) { + if err := r.AuthorizerCredential.validate(); err != nil { + return err + } + } + return nil +} +func (r *ConnectionGithubConfigAuthorizerCredential) validate() error { + return nil +} +func (r *ConnectionGithubEnterpriseConfig) validate() error { + if err := dcl.Required(r, "hostUri"); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(r.AuthorizerCredential) { + if err := r.AuthorizerCredential.validate(); err != nil { + return err + } + } + if !dcl.IsEmptyValueIndirect(r.ServiceDirectoryConfig) { + if err := r.ServiceDirectoryConfig.validate(); err != nil { + return err + } + } + return nil +} +func (r *ConnectionGithubEnterpriseConfigAuthorizerCredential) validate() error { + return nil +} +func (r *ConnectionGithubEnterpriseConfigServiceDirectoryConfig) validate() error { + if err := dcl.Required(r, "service"); err != nil { + return err + } + return nil +} +func (r *ConnectionInstallationState) validate() error { + return nil +} +func (r *Connection) basePath() string { + params := map[string]interface{}{} + return dcl.Nprintf("https://cloudbuild.googleapis.com/v2/", params) +} + +func (r *Connection) getURL(userBasePath string) (string, error) { + nr := r.urlNormalized() + params := map[string]interface{}{ + "project": dcl.ValueOrEmptyString(nr.Project), + "location": dcl.ValueOrEmptyString(nr.Location), + "name": dcl.ValueOrEmptyString(nr.Name), + } + return dcl.URL("projects/{{project}}/locations/{{location}}/connections/{{name}}", nr.basePath(), userBasePath, params), nil +} + +func (r *Connection) listURL(userBasePath string) (string, error) { + nr := r.urlNormalized() + params := map[string]interface{}{ + "project": dcl.ValueOrEmptyString(nr.Project), + "location": dcl.ValueOrEmptyString(nr.Location), + } + return dcl.URL("projects/{{project}}/locations/{{location}}/connections", nr.basePath(), userBasePath, params), nil + +} + +func (r *Connection) createURL(userBasePath string) (string, error) { + nr := r.urlNormalized() + params := map[string]interface{}{ + "project": dcl.ValueOrEmptyString(nr.Project), + "location": dcl.ValueOrEmptyString(nr.Location), + "name": dcl.ValueOrEmptyString(nr.Name), + } + return dcl.URL("projects/{{project}}/locations/{{location}}/connections?connectionId={{name}}", nr.basePath(), userBasePath, params), nil + +} + +func (r *Connection) deleteURL(userBasePath string) (string, error) { + nr := r.urlNormalized() + params := map[string]interface{}{ + "project": dcl.ValueOrEmptyString(nr.Project), + "location": dcl.ValueOrEmptyString(nr.Location), + "name": dcl.ValueOrEmptyString(nr.Name), + } + return dcl.URL("projects/{{project}}/locations/{{location}}/connections/{{name}}", nr.basePath(), userBasePath, params), nil +} + +// connectionApiOperation represents a mutable operation in the underlying REST +// API such as Create, Update, or Delete. +type connectionApiOperation interface { + do(context.Context, *Connection, *Client) error +} + +// newUpdateConnectionUpdateConnectionRequest creates a request for an +// Connection resource's UpdateConnection update type by filling in the update +// fields based on the intended state of the resource. +func newUpdateConnectionUpdateConnectionRequest(ctx context.Context, f *Connection, c *Client) (map[string]interface{}, error) { + req := map[string]interface{}{} + res := f + _ = res + + if v, err := expandConnectionGithubConfig(c, f.GithubConfig, res); err != nil { + return nil, fmt.Errorf("error expanding GithubConfig into githubConfig: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + req["githubConfig"] = v + } + if v, err := expandConnectionGithubEnterpriseConfig(c, f.GithubEnterpriseConfig, res); err != nil { + return nil, fmt.Errorf("error expanding GithubEnterpriseConfig into githubEnterpriseConfig: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + req["githubEnterpriseConfig"] = v + } + if v := f.Disabled; !dcl.IsEmptyValueIndirect(v) { + req["disabled"] = v + } + if v := f.Annotations; !dcl.IsEmptyValueIndirect(v) { + req["annotations"] = v + } + b, err := c.getConnectionRaw(ctx, f) + if err != nil { + return nil, err + } + var m map[string]interface{} + if err := json.Unmarshal(b, &m); err != nil { + return nil, err + } + rawEtag, err := dcl.GetMapEntry( + m, + []string{"etag"}, + ) + if err != nil { + c.Config.Logger.WarningWithContextf(ctx, "Failed to fetch from JSON Path: %v", err) + } else { + req["etag"] = rawEtag.(string) + } + req["name"] = fmt.Sprintf("projects/%s/locations/%s/connections/%s", *f.Project, *f.Location, *f.Name) + + return req, nil +} + +// marshalUpdateConnectionUpdateConnectionRequest converts the update into +// the final JSON request body. +func marshalUpdateConnectionUpdateConnectionRequest(c *Client, m map[string]interface{}) ([]byte, error) { + + return json.Marshal(m) +} + +type updateConnectionUpdateConnectionOperation struct { + // If the update operation has the REQUIRES_APPLY_OPTIONS trait, this will be populated. + // Usually it will be nil - this is to prevent us from accidentally depending on apply + // options, which should usually be unnecessary. + ApplyOptions []dcl.ApplyOption + FieldDiffs []*dcl.FieldDiff +} + +// do creates a request and sends it to the appropriate URL. In most operations, +// do will transcribe a subset of the resource into a request object and send a +// PUT request to a single URL. + +func (op *updateConnectionUpdateConnectionOperation) do(ctx context.Context, r *Connection, c *Client) error { + _, err := c.GetConnection(ctx, r) + if err != nil { + return err + } + + u, err := r.updateURL(c.Config.BasePath, "UpdateConnection") + if err != nil { + return err + } + mask := dcl.UpdateMask(op.FieldDiffs) + u, err = dcl.AddQueryParams(u, map[string]string{"updateMask": mask}) + if err != nil { + return err + } + + req, err := newUpdateConnectionUpdateConnectionRequest(ctx, r, c) + if err != nil { + return err + } + + c.Config.Logger.InfoWithContextf(ctx, "Created update: %#v", req) + body, err := marshalUpdateConnectionUpdateConnectionRequest(c, req) + if err != nil { + return err + } + resp, err := dcl.SendRequest(ctx, c.Config, "PATCH", u, bytes.NewBuffer(body), c.Config.RetryProvider) + if err != nil { + return err + } + + var o operations.StandardGCPOperation + if err := dcl.ParseResponse(resp.Response, &o); err != nil { + return err + } + err = o.Wait(context.WithValue(ctx, dcl.DoNotLogRequestsKey, true), c.Config, r.basePath(), "GET") + + if err != nil { + return err + } + + return nil +} + +func (c *Client) listConnectionRaw(ctx context.Context, r *Connection, pageToken string, pageSize int32) ([]byte, error) { + u, err := r.urlNormalized().listURL(c.Config.BasePath) + if err != nil { + return nil, err + } + + m := make(map[string]string) + if pageToken != "" { + m["pageToken"] = pageToken + } + + if pageSize != ConnectionMaxPage { + m["pageSize"] = fmt.Sprintf("%v", pageSize) + } + + u, err = dcl.AddQueryParams(u, m) + if err != nil { + return nil, err + } + resp, err := dcl.SendRequest(ctx, c.Config, "GET", u, &bytes.Buffer{}, c.Config.RetryProvider) + if err != nil { + return nil, err + } + defer resp.Response.Body.Close() + return ioutil.ReadAll(resp.Response.Body) +} + +type listConnectionOperation struct { + Connections []map[string]interface{} `json:"connections"` + Token string `json:"nextPageToken"` +} + +func (c *Client) listConnection(ctx context.Context, r *Connection, pageToken string, pageSize int32) ([]*Connection, string, error) { + b, err := c.listConnectionRaw(ctx, r, pageToken, pageSize) + if err != nil { + return nil, "", err + } + + var m listConnectionOperation + if err := json.Unmarshal(b, &m); err != nil { + return nil, "", err + } + + var l []*Connection + for _, v := range m.Connections { + res, err := unmarshalMapConnection(v, c, r) + if err != nil { + return nil, m.Token, err + } + res.Project = r.Project + res.Location = r.Location + l = append(l, res) + } + + return l, m.Token, nil +} + +func (c *Client) deleteAllConnection(ctx context.Context, f func(*Connection) bool, resources []*Connection) error { + var errors []string + for _, res := range resources { + if f(res) { + // We do not want deleteAll to fail on a deletion or else it will stop deleting other resources. + err := c.DeleteConnection(ctx, res) + if err != nil { + errors = append(errors, err.Error()) + } + } + } + if len(errors) > 0 { + return fmt.Errorf("%v", strings.Join(errors, "\n")) + } else { + return nil + } +} + +type deleteConnectionOperation struct{} + +func (op *deleteConnectionOperation) do(ctx context.Context, r *Connection, c *Client) error { + r, err := c.GetConnection(ctx, r) + if err != nil { + if dcl.IsNotFound(err) { + c.Config.Logger.InfoWithContextf(ctx, "Connection not found, returning. Original error: %v", err) + return nil + } + c.Config.Logger.WarningWithContextf(ctx, "GetConnection checking for existence. error: %v", err) + return err + } + + u, err := r.deleteURL(c.Config.BasePath) + if err != nil { + return err + } + + // Delete should never have a body + body := &bytes.Buffer{} + resp, err := dcl.SendRequest(ctx, c.Config, "DELETE", u, body, c.Config.RetryProvider) + if err != nil { + return err + } + + // wait for object to be deleted. + var o operations.StandardGCPOperation + if err := dcl.ParseResponse(resp.Response, &o); err != nil { + return err + } + if err := o.Wait(context.WithValue(ctx, dcl.DoNotLogRequestsKey, true), c.Config, r.basePath(), "GET"); err != nil { + return err + } + + // We saw a race condition where for some successful delete operation, the Get calls returned resources for a short duration. + // This is the reason we are adding retry to handle that case. + retriesRemaining := 10 + dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) { + _, err := c.GetConnection(ctx, r) + if dcl.IsNotFound(err) { + return nil, nil + } + if retriesRemaining > 0 { + retriesRemaining-- + return &dcl.RetryDetails{}, dcl.OperationNotDone{} + } + return nil, dcl.NotDeletedError{ExistingResource: r} + }, c.Config.RetryProvider) + return nil +} + +// Create operations are similar to Update operations, although they do not have +// specific request objects. The Create request object is the json encoding of +// the resource, which is modified by res.marshal to form the base request body. +type createConnectionOperation struct { + response map[string]interface{} +} + +func (op *createConnectionOperation) FirstResponse() (map[string]interface{}, bool) { + return op.response, len(op.response) > 0 +} + +func (op *createConnectionOperation) do(ctx context.Context, r *Connection, c *Client) error { + c.Config.Logger.InfoWithContextf(ctx, "Attempting to create %v", r) + u, err := r.createURL(c.Config.BasePath) + if err != nil { + return err + } + + req, err := r.marshal(c) + if err != nil { + return err + } + resp, err := dcl.SendRequest(ctx, c.Config, "POST", u, bytes.NewBuffer(req), c.Config.RetryProvider) + if err != nil { + return err + } + // wait for object to be created. + var o operations.StandardGCPOperation + if err := dcl.ParseResponse(resp.Response, &o); err != nil { + return err + } + if err := o.Wait(context.WithValue(ctx, dcl.DoNotLogRequestsKey, true), c.Config, r.basePath(), "GET"); err != nil { + c.Config.Logger.Warningf("Creation failed after waiting for operation: %v", err) + return err + } + c.Config.Logger.InfoWithContextf(ctx, "Successfully waited for operation") + op.response, _ = o.FirstResponse() + + if _, err := c.GetConnection(ctx, r); err != nil { + c.Config.Logger.WarningWithContextf(ctx, "get returned error: %v", err) + return err + } + + return nil +} + +func (c *Client) getConnectionRaw(ctx context.Context, r *Connection) ([]byte, error) { + + u, err := r.getURL(c.Config.BasePath) + if err != nil { + return nil, err + } + resp, err := dcl.SendRequest(ctx, c.Config, "GET", u, &bytes.Buffer{}, c.Config.RetryProvider) + if err != nil { + return nil, err + } + defer resp.Response.Body.Close() + b, err := ioutil.ReadAll(resp.Response.Body) + if err != nil { + return nil, err + } + + return b, nil +} + +func (c *Client) connectionDiffsForRawDesired(ctx context.Context, rawDesired *Connection, opts ...dcl.ApplyOption) (initial, desired *Connection, diffs []*dcl.FieldDiff, err error) { + c.Config.Logger.InfoWithContext(ctx, "Fetching initial state...") + // First, let us see if the user provided a state hint. If they did, we will start fetching based on that. + var fetchState *Connection + if sh := dcl.FetchStateHint(opts); sh != nil { + if r, ok := sh.(*Connection); !ok { + c.Config.Logger.WarningWithContextf(ctx, "Initial state hint was of the wrong type; expected Connection, got %T", sh) + } else { + fetchState = r + } + } + if fetchState == nil { + fetchState = rawDesired + } + + // 1.2: Retrieval of raw initial state from API + rawInitial, err := c.GetConnection(ctx, fetchState) + if rawInitial == nil { + if !dcl.IsNotFound(err) { + c.Config.Logger.WarningWithContextf(ctx, "Failed to retrieve whether a Connection resource already exists: %s", err) + return nil, nil, nil, fmt.Errorf("failed to retrieve Connection resource: %v", err) + } + c.Config.Logger.InfoWithContext(ctx, "Found that Connection resource did not exist.") + // Perform canonicalization to pick up defaults. + desired, err = canonicalizeConnectionDesiredState(rawDesired, rawInitial) + return nil, desired, nil, err + } + c.Config.Logger.InfoWithContextf(ctx, "Found initial state for Connection: %v", rawInitial) + c.Config.Logger.InfoWithContextf(ctx, "Initial desired state for Connection: %v", rawDesired) + + // The Get call applies postReadExtract and so the result may contain fields that are not part of API version. + if err := extractConnectionFields(rawInitial); err != nil { + return nil, nil, nil, err + } + + // 1.3: Canonicalize raw initial state into initial state. + initial, err = canonicalizeConnectionInitialState(rawInitial, rawDesired) + if err != nil { + return nil, nil, nil, err + } + c.Config.Logger.InfoWithContextf(ctx, "Canonicalized initial state for Connection: %v", initial) + + // 1.4: Canonicalize raw desired state into desired state. + desired, err = canonicalizeConnectionDesiredState(rawDesired, rawInitial, opts...) + if err != nil { + return nil, nil, nil, err + } + c.Config.Logger.InfoWithContextf(ctx, "Canonicalized desired state for Connection: %v", desired) + + // 2.1: Comparison of initial and desired state. + diffs, err = diffConnection(c, desired, initial, opts...) + return initial, desired, diffs, err +} + +func canonicalizeConnectionInitialState(rawInitial, rawDesired *Connection) (*Connection, error) { + // TODO(magic-modules-eng): write canonicalizer once relevant traits are added. + + if !dcl.IsZeroValue(rawInitial.GithubConfig) { + // Check if anything else is set. + if dcl.AnySet(rawInitial.GithubEnterpriseConfig) { + rawInitial.GithubConfig = EmptyConnectionGithubConfig + } + } + + if !dcl.IsZeroValue(rawInitial.GithubEnterpriseConfig) { + // Check if anything else is set. + if dcl.AnySet(rawInitial.GithubConfig) { + rawInitial.GithubEnterpriseConfig = EmptyConnectionGithubEnterpriseConfig + } + } + + return rawInitial, nil +} + +/* +* Canonicalizers +* +* These are responsible for converting either a user-specified config or a +* GCP API response to a standard format that can be used for difference checking. +* */ + +func canonicalizeConnectionDesiredState(rawDesired, rawInitial *Connection, opts ...dcl.ApplyOption) (*Connection, error) { + + if rawInitial == nil { + // Since the initial state is empty, the desired state is all we have. + // We canonicalize the remaining nested objects with nil to pick up defaults. + rawDesired.GithubConfig = canonicalizeConnectionGithubConfig(rawDesired.GithubConfig, nil, opts...) + rawDesired.GithubEnterpriseConfig = canonicalizeConnectionGithubEnterpriseConfig(rawDesired.GithubEnterpriseConfig, nil, opts...) + rawDesired.InstallationState = canonicalizeConnectionInstallationState(rawDesired.InstallationState, nil, opts...) + + return rawDesired, nil + } + + if rawDesired.GithubConfig != nil || rawInitial.GithubConfig != nil { + // Check if anything else is set. + if dcl.AnySet(rawDesired.GithubEnterpriseConfig) { + rawDesired.GithubConfig = nil + rawInitial.GithubConfig = nil + } + } + + if rawDesired.GithubEnterpriseConfig != nil || rawInitial.GithubEnterpriseConfig != nil { + // Check if anything else is set. + if dcl.AnySet(rawDesired.GithubConfig) { + rawDesired.GithubEnterpriseConfig = nil + rawInitial.GithubEnterpriseConfig = nil + } + } + + canonicalDesired := &Connection{} + if dcl.PartialSelfLinkToSelfLink(rawDesired.Name, rawInitial.Name) { + canonicalDesired.Name = rawInitial.Name + } else { + canonicalDesired.Name = rawDesired.Name + } + canonicalDesired.GithubConfig = canonicalizeConnectionGithubConfig(rawDesired.GithubConfig, rawInitial.GithubConfig, opts...) + canonicalDesired.GithubEnterpriseConfig = canonicalizeConnectionGithubEnterpriseConfig(rawDesired.GithubEnterpriseConfig, rawInitial.GithubEnterpriseConfig, opts...) + if dcl.BoolCanonicalize(rawDesired.Disabled, rawInitial.Disabled) { + canonicalDesired.Disabled = rawInitial.Disabled + } else { + canonicalDesired.Disabled = rawDesired.Disabled + } + if dcl.IsZeroValue(rawDesired.Annotations) || (dcl.IsEmptyValueIndirect(rawDesired.Annotations) && dcl.IsEmptyValueIndirect(rawInitial.Annotations)) { + // Desired and initial values are equivalent, so set canonical desired value to initial value. + canonicalDesired.Annotations = rawInitial.Annotations + } else { + canonicalDesired.Annotations = rawDesired.Annotations + } + if dcl.NameToSelfLink(rawDesired.Project, rawInitial.Project) { + canonicalDesired.Project = rawInitial.Project + } else { + canonicalDesired.Project = rawDesired.Project + } + if dcl.NameToSelfLink(rawDesired.Location, rawInitial.Location) { + canonicalDesired.Location = rawInitial.Location + } else { + canonicalDesired.Location = rawDesired.Location + } + + return canonicalDesired, nil +} + +func canonicalizeConnectionNewState(c *Client, rawNew, rawDesired *Connection) (*Connection, error) { + + if dcl.IsEmptyValueIndirect(rawNew.Name) && dcl.IsEmptyValueIndirect(rawDesired.Name) { + rawNew.Name = rawDesired.Name + } else { + if dcl.PartialSelfLinkToSelfLink(rawDesired.Name, rawNew.Name) { + rawNew.Name = rawDesired.Name + } + } + + if dcl.IsEmptyValueIndirect(rawNew.CreateTime) && dcl.IsEmptyValueIndirect(rawDesired.CreateTime) { + rawNew.CreateTime = rawDesired.CreateTime + } else { + } + + if dcl.IsEmptyValueIndirect(rawNew.UpdateTime) && dcl.IsEmptyValueIndirect(rawDesired.UpdateTime) { + rawNew.UpdateTime = rawDesired.UpdateTime + } else { + } + + if dcl.IsEmptyValueIndirect(rawNew.GithubConfig) && dcl.IsEmptyValueIndirect(rawDesired.GithubConfig) { + rawNew.GithubConfig = rawDesired.GithubConfig + } else { + rawNew.GithubConfig = canonicalizeNewConnectionGithubConfig(c, rawDesired.GithubConfig, rawNew.GithubConfig) + } + + if dcl.IsEmptyValueIndirect(rawNew.GithubEnterpriseConfig) && dcl.IsEmptyValueIndirect(rawDesired.GithubEnterpriseConfig) { + rawNew.GithubEnterpriseConfig = rawDesired.GithubEnterpriseConfig + } else { + rawNew.GithubEnterpriseConfig = canonicalizeNewConnectionGithubEnterpriseConfig(c, rawDesired.GithubEnterpriseConfig, rawNew.GithubEnterpriseConfig) + } + + if dcl.IsEmptyValueIndirect(rawNew.InstallationState) && dcl.IsEmptyValueIndirect(rawDesired.InstallationState) { + rawNew.InstallationState = rawDesired.InstallationState + } else { + rawNew.InstallationState = canonicalizeNewConnectionInstallationState(c, rawDesired.InstallationState, rawNew.InstallationState) + } + + if dcl.IsEmptyValueIndirect(rawNew.Disabled) && dcl.IsEmptyValueIndirect(rawDesired.Disabled) { + rawNew.Disabled = rawDesired.Disabled + } else { + if dcl.BoolCanonicalize(rawDesired.Disabled, rawNew.Disabled) { + rawNew.Disabled = rawDesired.Disabled + } + } + + if dcl.IsEmptyValueIndirect(rawNew.Reconciling) && dcl.IsEmptyValueIndirect(rawDesired.Reconciling) { + rawNew.Reconciling = rawDesired.Reconciling + } else { + if dcl.BoolCanonicalize(rawDesired.Reconciling, rawNew.Reconciling) { + rawNew.Reconciling = rawDesired.Reconciling + } + } + + if dcl.IsEmptyValueIndirect(rawNew.Annotations) && dcl.IsEmptyValueIndirect(rawDesired.Annotations) { + rawNew.Annotations = rawDesired.Annotations + } else { + } + + if dcl.IsEmptyValueIndirect(rawNew.Etag) && dcl.IsEmptyValueIndirect(rawDesired.Etag) { + rawNew.Etag = rawDesired.Etag + } else { + if dcl.StringCanonicalize(rawDesired.Etag, rawNew.Etag) { + rawNew.Etag = rawDesired.Etag + } + } + + rawNew.Project = rawDesired.Project + + rawNew.Location = rawDesired.Location + + return rawNew, nil +} + +func canonicalizeConnectionGithubConfig(des, initial *ConnectionGithubConfig, opts ...dcl.ApplyOption) *ConnectionGithubConfig { + if des == nil { + return initial + } + if des.empty { + return des + } + + if initial == nil { + return des + } + + cDes := &ConnectionGithubConfig{} + + cDes.AuthorizerCredential = canonicalizeConnectionGithubConfigAuthorizerCredential(des.AuthorizerCredential, initial.AuthorizerCredential, opts...) + if dcl.IsZeroValue(des.AppInstallationId) || (dcl.IsEmptyValueIndirect(des.AppInstallationId) && dcl.IsEmptyValueIndirect(initial.AppInstallationId)) { + // Desired and initial values are equivalent, so set canonical desired value to initial value. + cDes.AppInstallationId = initial.AppInstallationId + } else { + cDes.AppInstallationId = des.AppInstallationId + } + + return cDes +} + +func canonicalizeConnectionGithubConfigSlice(des, initial []ConnectionGithubConfig, opts ...dcl.ApplyOption) []ConnectionGithubConfig { + if dcl.IsEmptyValueIndirect(des) { + return initial + } + + if len(des) != len(initial) { + + items := make([]ConnectionGithubConfig, 0, len(des)) + for _, d := range des { + cd := canonicalizeConnectionGithubConfig(&d, nil, opts...) + if cd != nil { + items = append(items, *cd) + } + } + return items + } + + items := make([]ConnectionGithubConfig, 0, len(des)) + for i, d := range des { + cd := canonicalizeConnectionGithubConfig(&d, &initial[i], opts...) + if cd != nil { + items = append(items, *cd) + } + } + return items + +} + +func canonicalizeNewConnectionGithubConfig(c *Client, des, nw *ConnectionGithubConfig) *ConnectionGithubConfig { + + if des == nil { + return nw + } + + if nw == nil { + if dcl.IsEmptyValueIndirect(des) { + c.Config.Logger.Info("Found explicitly empty value for ConnectionGithubConfig while comparing non-nil desired to nil actual. Returning desired object.") + return des + } + return nil + } + + nw.AuthorizerCredential = canonicalizeNewConnectionGithubConfigAuthorizerCredential(c, des.AuthorizerCredential, nw.AuthorizerCredential) + + return nw +} + +func canonicalizeNewConnectionGithubConfigSet(c *Client, des, nw []ConnectionGithubConfig) []ConnectionGithubConfig { + if des == nil { + return nw + } + var reorderedNew []ConnectionGithubConfig + for _, d := range des { + matchedNew := -1 + for idx, n := range nw { + if diffs, _ := compareConnectionGithubConfigNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { + matchedNew = idx + break + } + } + if matchedNew != -1 { + reorderedNew = append(reorderedNew, nw[matchedNew]) + nw = append(nw[:matchedNew], nw[matchedNew+1:]...) + } + } + reorderedNew = append(reorderedNew, nw...) + + return reorderedNew +} + +func canonicalizeNewConnectionGithubConfigSlice(c *Client, des, nw []ConnectionGithubConfig) []ConnectionGithubConfig { + if des == nil { + return nw + } + + // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. + // Return the original array. + if len(des) != len(nw) { + return nw + } + + var items []ConnectionGithubConfig + for i, d := range des { + n := nw[i] + items = append(items, *canonicalizeNewConnectionGithubConfig(c, &d, &n)) + } + + return items +} + +func canonicalizeConnectionGithubConfigAuthorizerCredential(des, initial *ConnectionGithubConfigAuthorizerCredential, opts ...dcl.ApplyOption) *ConnectionGithubConfigAuthorizerCredential { + if des == nil { + return initial + } + if des.empty { + return des + } + + if initial == nil { + return des + } + + cDes := &ConnectionGithubConfigAuthorizerCredential{} + + if dcl.IsZeroValue(des.OAuthTokenSecretVersion) || (dcl.IsEmptyValueIndirect(des.OAuthTokenSecretVersion) && dcl.IsEmptyValueIndirect(initial.OAuthTokenSecretVersion)) { + // Desired and initial values are equivalent, so set canonical desired value to initial value. + cDes.OAuthTokenSecretVersion = initial.OAuthTokenSecretVersion + } else { + cDes.OAuthTokenSecretVersion = des.OAuthTokenSecretVersion + } + if dcl.StringCanonicalize(des.Username, initial.Username) || dcl.IsZeroValue(des.Username) { + cDes.Username = initial.Username + } else { + cDes.Username = des.Username + } + + return cDes +} + +func canonicalizeConnectionGithubConfigAuthorizerCredentialSlice(des, initial []ConnectionGithubConfigAuthorizerCredential, opts ...dcl.ApplyOption) []ConnectionGithubConfigAuthorizerCredential { + if dcl.IsEmptyValueIndirect(des) { + return initial + } + + if len(des) != len(initial) { + + items := make([]ConnectionGithubConfigAuthorizerCredential, 0, len(des)) + for _, d := range des { + cd := canonicalizeConnectionGithubConfigAuthorizerCredential(&d, nil, opts...) + if cd != nil { + items = append(items, *cd) + } + } + return items + } + + items := make([]ConnectionGithubConfigAuthorizerCredential, 0, len(des)) + for i, d := range des { + cd := canonicalizeConnectionGithubConfigAuthorizerCredential(&d, &initial[i], opts...) + if cd != nil { + items = append(items, *cd) + } + } + return items + +} + +func canonicalizeNewConnectionGithubConfigAuthorizerCredential(c *Client, des, nw *ConnectionGithubConfigAuthorizerCredential) *ConnectionGithubConfigAuthorizerCredential { + + if des == nil { + return nw + } + + if nw == nil { + if dcl.IsEmptyValueIndirect(des) { + c.Config.Logger.Info("Found explicitly empty value for ConnectionGithubConfigAuthorizerCredential while comparing non-nil desired to nil actual. Returning desired object.") + return des + } + return nil + } + + if dcl.StringCanonicalize(des.Username, nw.Username) { + nw.Username = des.Username + } + + return nw +} + +func canonicalizeNewConnectionGithubConfigAuthorizerCredentialSet(c *Client, des, nw []ConnectionGithubConfigAuthorizerCredential) []ConnectionGithubConfigAuthorizerCredential { + if des == nil { + return nw + } + var reorderedNew []ConnectionGithubConfigAuthorizerCredential + for _, d := range des { + matchedNew := -1 + for idx, n := range nw { + if diffs, _ := compareConnectionGithubConfigAuthorizerCredentialNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { + matchedNew = idx + break + } + } + if matchedNew != -1 { + reorderedNew = append(reorderedNew, nw[matchedNew]) + nw = append(nw[:matchedNew], nw[matchedNew+1:]...) + } + } + reorderedNew = append(reorderedNew, nw...) + + return reorderedNew +} + +func canonicalizeNewConnectionGithubConfigAuthorizerCredentialSlice(c *Client, des, nw []ConnectionGithubConfigAuthorizerCredential) []ConnectionGithubConfigAuthorizerCredential { + if des == nil { + return nw + } + + // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. + // Return the original array. + if len(des) != len(nw) { + return nw + } + + var items []ConnectionGithubConfigAuthorizerCredential + for i, d := range des { + n := nw[i] + items = append(items, *canonicalizeNewConnectionGithubConfigAuthorizerCredential(c, &d, &n)) + } + + return items +} + +func canonicalizeConnectionGithubEnterpriseConfig(des, initial *ConnectionGithubEnterpriseConfig, opts ...dcl.ApplyOption) *ConnectionGithubEnterpriseConfig { + if des == nil { + return initial + } + if des.empty { + return des + } + + if initial == nil { + return des + } + + cDes := &ConnectionGithubEnterpriseConfig{} + + if dcl.StringCanonicalize(des.HostUri, initial.HostUri) || dcl.IsZeroValue(des.HostUri) { + cDes.HostUri = initial.HostUri + } else { + cDes.HostUri = des.HostUri + } + if dcl.IsZeroValue(des.AppId) || (dcl.IsEmptyValueIndirect(des.AppId) && dcl.IsEmptyValueIndirect(initial.AppId)) { + // Desired and initial values are equivalent, so set canonical desired value to initial value. + cDes.AppId = initial.AppId + } else { + cDes.AppId = des.AppId + } + if dcl.StringCanonicalize(des.AppSlug, initial.AppSlug) || dcl.IsZeroValue(des.AppSlug) { + cDes.AppSlug = initial.AppSlug + } else { + cDes.AppSlug = des.AppSlug + } + if dcl.IsZeroValue(des.PrivateKeySecretVersion) || (dcl.IsEmptyValueIndirect(des.PrivateKeySecretVersion) && dcl.IsEmptyValueIndirect(initial.PrivateKeySecretVersion)) { + // Desired and initial values are equivalent, so set canonical desired value to initial value. + cDes.PrivateKeySecretVersion = initial.PrivateKeySecretVersion + } else { + cDes.PrivateKeySecretVersion = des.PrivateKeySecretVersion + } + if dcl.IsZeroValue(des.WebhookSecretSecretVersion) || (dcl.IsEmptyValueIndirect(des.WebhookSecretSecretVersion) && dcl.IsEmptyValueIndirect(initial.WebhookSecretSecretVersion)) { + // Desired and initial values are equivalent, so set canonical desired value to initial value. + cDes.WebhookSecretSecretVersion = initial.WebhookSecretSecretVersion + } else { + cDes.WebhookSecretSecretVersion = des.WebhookSecretSecretVersion + } + if dcl.IsZeroValue(des.OAuthSecretSecretVersion) || (dcl.IsEmptyValueIndirect(des.OAuthSecretSecretVersion) && dcl.IsEmptyValueIndirect(initial.OAuthSecretSecretVersion)) { + // Desired and initial values are equivalent, so set canonical desired value to initial value. + cDes.OAuthSecretSecretVersion = initial.OAuthSecretSecretVersion + } else { + cDes.OAuthSecretSecretVersion = des.OAuthSecretSecretVersion + } + if dcl.IsZeroValue(des.OAuthClientIdSecretVersion) || (dcl.IsEmptyValueIndirect(des.OAuthClientIdSecretVersion) && dcl.IsEmptyValueIndirect(initial.OAuthClientIdSecretVersion)) { + // Desired and initial values are equivalent, so set canonical desired value to initial value. + cDes.OAuthClientIdSecretVersion = initial.OAuthClientIdSecretVersion + } else { + cDes.OAuthClientIdSecretVersion = des.OAuthClientIdSecretVersion + } + cDes.AuthorizerCredential = canonicalizeConnectionGithubEnterpriseConfigAuthorizerCredential(des.AuthorizerCredential, initial.AuthorizerCredential, opts...) + if dcl.IsZeroValue(des.AppInstallationId) || (dcl.IsEmptyValueIndirect(des.AppInstallationId) && dcl.IsEmptyValueIndirect(initial.AppInstallationId)) { + // Desired and initial values are equivalent, so set canonical desired value to initial value. + cDes.AppInstallationId = initial.AppInstallationId + } else { + cDes.AppInstallationId = des.AppInstallationId + } + cDes.ServiceDirectoryConfig = canonicalizeConnectionGithubEnterpriseConfigServiceDirectoryConfig(des.ServiceDirectoryConfig, initial.ServiceDirectoryConfig, opts...) + if dcl.StringCanonicalize(des.SslCa, initial.SslCa) || dcl.IsZeroValue(des.SslCa) { + cDes.SslCa = initial.SslCa + } else { + cDes.SslCa = des.SslCa + } + + return cDes +} + +func canonicalizeConnectionGithubEnterpriseConfigSlice(des, initial []ConnectionGithubEnterpriseConfig, opts ...dcl.ApplyOption) []ConnectionGithubEnterpriseConfig { + if dcl.IsEmptyValueIndirect(des) { + return initial + } + + if len(des) != len(initial) { + + items := make([]ConnectionGithubEnterpriseConfig, 0, len(des)) + for _, d := range des { + cd := canonicalizeConnectionGithubEnterpriseConfig(&d, nil, opts...) + if cd != nil { + items = append(items, *cd) + } + } + return items + } + + items := make([]ConnectionGithubEnterpriseConfig, 0, len(des)) + for i, d := range des { + cd := canonicalizeConnectionGithubEnterpriseConfig(&d, &initial[i], opts...) + if cd != nil { + items = append(items, *cd) + } + } + return items + +} + +func canonicalizeNewConnectionGithubEnterpriseConfig(c *Client, des, nw *ConnectionGithubEnterpriseConfig) *ConnectionGithubEnterpriseConfig { + + if des == nil { + return nw + } + + if nw == nil { + if dcl.IsEmptyValueIndirect(des) { + c.Config.Logger.Info("Found explicitly empty value for ConnectionGithubEnterpriseConfig while comparing non-nil desired to nil actual. Returning desired object.") + return des + } + return nil + } + + if dcl.StringCanonicalize(des.HostUri, nw.HostUri) { + nw.HostUri = des.HostUri + } + if dcl.StringCanonicalize(des.AppSlug, nw.AppSlug) { + nw.AppSlug = des.AppSlug + } + nw.AuthorizerCredential = canonicalizeNewConnectionGithubEnterpriseConfigAuthorizerCredential(c, des.AuthorizerCredential, nw.AuthorizerCredential) + nw.ServiceDirectoryConfig = canonicalizeNewConnectionGithubEnterpriseConfigServiceDirectoryConfig(c, des.ServiceDirectoryConfig, nw.ServiceDirectoryConfig) + if dcl.StringCanonicalize(des.SslCa, nw.SslCa) { + nw.SslCa = des.SslCa + } + + return nw +} + +func canonicalizeNewConnectionGithubEnterpriseConfigSet(c *Client, des, nw []ConnectionGithubEnterpriseConfig) []ConnectionGithubEnterpriseConfig { + if des == nil { + return nw + } + var reorderedNew []ConnectionGithubEnterpriseConfig + for _, d := range des { + matchedNew := -1 + for idx, n := range nw { + if diffs, _ := compareConnectionGithubEnterpriseConfigNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { + matchedNew = idx + break + } + } + if matchedNew != -1 { + reorderedNew = append(reorderedNew, nw[matchedNew]) + nw = append(nw[:matchedNew], nw[matchedNew+1:]...) + } + } + reorderedNew = append(reorderedNew, nw...) + + return reorderedNew +} + +func canonicalizeNewConnectionGithubEnterpriseConfigSlice(c *Client, des, nw []ConnectionGithubEnterpriseConfig) []ConnectionGithubEnterpriseConfig { + if des == nil { + return nw + } + + // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. + // Return the original array. + if len(des) != len(nw) { + return nw + } + + var items []ConnectionGithubEnterpriseConfig + for i, d := range des { + n := nw[i] + items = append(items, *canonicalizeNewConnectionGithubEnterpriseConfig(c, &d, &n)) + } + + return items +} + +func canonicalizeConnectionGithubEnterpriseConfigAuthorizerCredential(des, initial *ConnectionGithubEnterpriseConfigAuthorizerCredential, opts ...dcl.ApplyOption) *ConnectionGithubEnterpriseConfigAuthorizerCredential { + if des == nil { + return initial + } + if des.empty { + return des + } + + if initial == nil { + return des + } + + cDes := &ConnectionGithubEnterpriseConfigAuthorizerCredential{} + + if dcl.IsZeroValue(des.OAuthTokenSecretVersion) || (dcl.IsEmptyValueIndirect(des.OAuthTokenSecretVersion) && dcl.IsEmptyValueIndirect(initial.OAuthTokenSecretVersion)) { + // Desired and initial values are equivalent, so set canonical desired value to initial value. + cDes.OAuthTokenSecretVersion = initial.OAuthTokenSecretVersion + } else { + cDes.OAuthTokenSecretVersion = des.OAuthTokenSecretVersion + } + if dcl.StringCanonicalize(des.Username, initial.Username) || dcl.IsZeroValue(des.Username) { + cDes.Username = initial.Username + } else { + cDes.Username = des.Username + } + + return cDes +} + +func canonicalizeConnectionGithubEnterpriseConfigAuthorizerCredentialSlice(des, initial []ConnectionGithubEnterpriseConfigAuthorizerCredential, opts ...dcl.ApplyOption) []ConnectionGithubEnterpriseConfigAuthorizerCredential { + if dcl.IsEmptyValueIndirect(des) { + return initial + } + + if len(des) != len(initial) { + + items := make([]ConnectionGithubEnterpriseConfigAuthorizerCredential, 0, len(des)) + for _, d := range des { + cd := canonicalizeConnectionGithubEnterpriseConfigAuthorizerCredential(&d, nil, opts...) + if cd != nil { + items = append(items, *cd) + } + } + return items + } + + items := make([]ConnectionGithubEnterpriseConfigAuthorizerCredential, 0, len(des)) + for i, d := range des { + cd := canonicalizeConnectionGithubEnterpriseConfigAuthorizerCredential(&d, &initial[i], opts...) + if cd != nil { + items = append(items, *cd) + } + } + return items + +} + +func canonicalizeNewConnectionGithubEnterpriseConfigAuthorizerCredential(c *Client, des, nw *ConnectionGithubEnterpriseConfigAuthorizerCredential) *ConnectionGithubEnterpriseConfigAuthorizerCredential { + + if des == nil { + return nw + } + + if nw == nil { + if dcl.IsEmptyValueIndirect(des) { + c.Config.Logger.Info("Found explicitly empty value for ConnectionGithubEnterpriseConfigAuthorizerCredential while comparing non-nil desired to nil actual. Returning desired object.") + return des + } + return nil + } + + if dcl.StringCanonicalize(des.Username, nw.Username) { + nw.Username = des.Username + } + + return nw +} + +func canonicalizeNewConnectionGithubEnterpriseConfigAuthorizerCredentialSet(c *Client, des, nw []ConnectionGithubEnterpriseConfigAuthorizerCredential) []ConnectionGithubEnterpriseConfigAuthorizerCredential { + if des == nil { + return nw + } + var reorderedNew []ConnectionGithubEnterpriseConfigAuthorizerCredential + for _, d := range des { + matchedNew := -1 + for idx, n := range nw { + if diffs, _ := compareConnectionGithubEnterpriseConfigAuthorizerCredentialNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { + matchedNew = idx + break + } + } + if matchedNew != -1 { + reorderedNew = append(reorderedNew, nw[matchedNew]) + nw = append(nw[:matchedNew], nw[matchedNew+1:]...) + } + } + reorderedNew = append(reorderedNew, nw...) + + return reorderedNew +} + +func canonicalizeNewConnectionGithubEnterpriseConfigAuthorizerCredentialSlice(c *Client, des, nw []ConnectionGithubEnterpriseConfigAuthorizerCredential) []ConnectionGithubEnterpriseConfigAuthorizerCredential { + if des == nil { + return nw + } + + // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. + // Return the original array. + if len(des) != len(nw) { + return nw + } + + var items []ConnectionGithubEnterpriseConfigAuthorizerCredential + for i, d := range des { + n := nw[i] + items = append(items, *canonicalizeNewConnectionGithubEnterpriseConfigAuthorizerCredential(c, &d, &n)) + } + + return items +} + +func canonicalizeConnectionGithubEnterpriseConfigServiceDirectoryConfig(des, initial *ConnectionGithubEnterpriseConfigServiceDirectoryConfig, opts ...dcl.ApplyOption) *ConnectionGithubEnterpriseConfigServiceDirectoryConfig { + if des == nil { + return initial + } + if des.empty { + return des + } + + if initial == nil { + return des + } + + cDes := &ConnectionGithubEnterpriseConfigServiceDirectoryConfig{} + + if dcl.IsZeroValue(des.Service) || (dcl.IsEmptyValueIndirect(des.Service) && dcl.IsEmptyValueIndirect(initial.Service)) { + // Desired and initial values are equivalent, so set canonical desired value to initial value. + cDes.Service = initial.Service + } else { + cDes.Service = des.Service + } + + return cDes +} + +func canonicalizeConnectionGithubEnterpriseConfigServiceDirectoryConfigSlice(des, initial []ConnectionGithubEnterpriseConfigServiceDirectoryConfig, opts ...dcl.ApplyOption) []ConnectionGithubEnterpriseConfigServiceDirectoryConfig { + if dcl.IsEmptyValueIndirect(des) { + return initial + } + + if len(des) != len(initial) { + + items := make([]ConnectionGithubEnterpriseConfigServiceDirectoryConfig, 0, len(des)) + for _, d := range des { + cd := canonicalizeConnectionGithubEnterpriseConfigServiceDirectoryConfig(&d, nil, opts...) + if cd != nil { + items = append(items, *cd) + } + } + return items + } + + items := make([]ConnectionGithubEnterpriseConfigServiceDirectoryConfig, 0, len(des)) + for i, d := range des { + cd := canonicalizeConnectionGithubEnterpriseConfigServiceDirectoryConfig(&d, &initial[i], opts...) + if cd != nil { + items = append(items, *cd) + } + } + return items + +} + +func canonicalizeNewConnectionGithubEnterpriseConfigServiceDirectoryConfig(c *Client, des, nw *ConnectionGithubEnterpriseConfigServiceDirectoryConfig) *ConnectionGithubEnterpriseConfigServiceDirectoryConfig { + + if des == nil { + return nw + } + + if nw == nil { + if dcl.IsEmptyValueIndirect(des) { + c.Config.Logger.Info("Found explicitly empty value for ConnectionGithubEnterpriseConfigServiceDirectoryConfig while comparing non-nil desired to nil actual. Returning desired object.") + return des + } + return nil + } + + return nw +} + +func canonicalizeNewConnectionGithubEnterpriseConfigServiceDirectoryConfigSet(c *Client, des, nw []ConnectionGithubEnterpriseConfigServiceDirectoryConfig) []ConnectionGithubEnterpriseConfigServiceDirectoryConfig { + if des == nil { + return nw + } + var reorderedNew []ConnectionGithubEnterpriseConfigServiceDirectoryConfig + for _, d := range des { + matchedNew := -1 + for idx, n := range nw { + if diffs, _ := compareConnectionGithubEnterpriseConfigServiceDirectoryConfigNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { + matchedNew = idx + break + } + } + if matchedNew != -1 { + reorderedNew = append(reorderedNew, nw[matchedNew]) + nw = append(nw[:matchedNew], nw[matchedNew+1:]...) + } + } + reorderedNew = append(reorderedNew, nw...) + + return reorderedNew +} + +func canonicalizeNewConnectionGithubEnterpriseConfigServiceDirectoryConfigSlice(c *Client, des, nw []ConnectionGithubEnterpriseConfigServiceDirectoryConfig) []ConnectionGithubEnterpriseConfigServiceDirectoryConfig { + if des == nil { + return nw + } + + // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. + // Return the original array. + if len(des) != len(nw) { + return nw + } + + var items []ConnectionGithubEnterpriseConfigServiceDirectoryConfig + for i, d := range des { + n := nw[i] + items = append(items, *canonicalizeNewConnectionGithubEnterpriseConfigServiceDirectoryConfig(c, &d, &n)) + } + + return items +} + +func canonicalizeConnectionInstallationState(des, initial *ConnectionInstallationState, opts ...dcl.ApplyOption) *ConnectionInstallationState { + if des == nil { + return initial + } + if des.empty { + return des + } + + if initial == nil { + return des + } + + cDes := &ConnectionInstallationState{} + + return cDes +} + +func canonicalizeConnectionInstallationStateSlice(des, initial []ConnectionInstallationState, opts ...dcl.ApplyOption) []ConnectionInstallationState { + if dcl.IsEmptyValueIndirect(des) { + return initial + } + + if len(des) != len(initial) { + + items := make([]ConnectionInstallationState, 0, len(des)) + for _, d := range des { + cd := canonicalizeConnectionInstallationState(&d, nil, opts...) + if cd != nil { + items = append(items, *cd) + } + } + return items + } + + items := make([]ConnectionInstallationState, 0, len(des)) + for i, d := range des { + cd := canonicalizeConnectionInstallationState(&d, &initial[i], opts...) + if cd != nil { + items = append(items, *cd) + } + } + return items + +} + +func canonicalizeNewConnectionInstallationState(c *Client, des, nw *ConnectionInstallationState) *ConnectionInstallationState { + + if des == nil { + return nw + } + + if nw == nil { + if dcl.IsEmptyValueIndirect(des) { + c.Config.Logger.Info("Found explicitly empty value for ConnectionInstallationState while comparing non-nil desired to nil actual. Returning desired object.") + return des + } + return nil + } + + if dcl.StringCanonicalize(des.Message, nw.Message) { + nw.Message = des.Message + } + if dcl.StringCanonicalize(des.ActionUri, nw.ActionUri) { + nw.ActionUri = des.ActionUri + } + + return nw +} + +func canonicalizeNewConnectionInstallationStateSet(c *Client, des, nw []ConnectionInstallationState) []ConnectionInstallationState { + if des == nil { + return nw + } + var reorderedNew []ConnectionInstallationState + for _, d := range des { + matchedNew := -1 + for idx, n := range nw { + if diffs, _ := compareConnectionInstallationStateNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { + matchedNew = idx + break + } + } + if matchedNew != -1 { + reorderedNew = append(reorderedNew, nw[matchedNew]) + nw = append(nw[:matchedNew], nw[matchedNew+1:]...) + } + } + reorderedNew = append(reorderedNew, nw...) + + return reorderedNew +} + +func canonicalizeNewConnectionInstallationStateSlice(c *Client, des, nw []ConnectionInstallationState) []ConnectionInstallationState { + if des == nil { + return nw + } + + // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. + // Return the original array. + if len(des) != len(nw) { + return nw + } + + var items []ConnectionInstallationState + for i, d := range des { + n := nw[i] + items = append(items, *canonicalizeNewConnectionInstallationState(c, &d, &n)) + } + + return items +} + +// The differ returns a list of diffs, along with a list of operations that should be taken +// to remedy them. Right now, it does not attempt to consolidate operations - if several +// fields can be fixed with a patch update, it will perform the patch several times. +// Diffs on some fields will be ignored if the `desired` state has an empty (nil) +// value. This empty value indicates that the user does not care about the state for +// the field. Empty fields on the actual object will cause diffs. +// TODO(magic-modules-eng): for efficiency in some resources, add batching. +func diffConnection(c *Client, desired, actual *Connection, opts ...dcl.ApplyOption) ([]*dcl.FieldDiff, error) { + if desired == nil || actual == nil { + return nil, fmt.Errorf("nil resource passed to diff - always a programming error: %#v, %#v", desired, actual) + } + + c.Config.Logger.Infof("Diff function called with desired state: %v", desired) + c.Config.Logger.Infof("Diff function called with actual state: %v", actual) + + var fn dcl.FieldName + var newDiffs []*dcl.FieldDiff + // New style diffs. + if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Name")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.CreateTime, actual.CreateTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("CreateTime")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.UpdateTime, actual.UpdateTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("UpdateTime")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.GithubConfig, actual.GithubConfig, dcl.DiffInfo{ObjectFunction: compareConnectionGithubConfigNewStyle, EmptyObject: EmptyConnectionGithubConfig, OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("GithubConfig")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.GithubEnterpriseConfig, actual.GithubEnterpriseConfig, dcl.DiffInfo{ObjectFunction: compareConnectionGithubEnterpriseConfigNewStyle, EmptyObject: EmptyConnectionGithubEnterpriseConfig, OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("GithubEnterpriseConfig")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.InstallationState, actual.InstallationState, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareConnectionInstallationStateNewStyle, EmptyObject: EmptyConnectionInstallationState, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("InstallationState")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.Disabled, actual.Disabled, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("Disabled")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.Reconciling, actual.Reconciling, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Reconciling")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.Annotations, actual.Annotations, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("Annotations")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.Etag, actual.Etag, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Etag")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.Project, actual.Project, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Project")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.Location, actual.Location, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Location")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + return newDiffs, nil +} +func compareConnectionGithubConfigNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { + var diffs []*dcl.FieldDiff + + desired, ok := d.(*ConnectionGithubConfig) + if !ok { + desiredNotPointer, ok := d.(ConnectionGithubConfig) + if !ok { + return nil, fmt.Errorf("obj %v is not a ConnectionGithubConfig or *ConnectionGithubConfig", d) + } + desired = &desiredNotPointer + } + actual, ok := a.(*ConnectionGithubConfig) + if !ok { + actualNotPointer, ok := a.(ConnectionGithubConfig) + if !ok { + return nil, fmt.Errorf("obj %v is not a ConnectionGithubConfig", a) + } + actual = &actualNotPointer + } + + if ds, err := dcl.Diff(desired.AuthorizerCredential, actual.AuthorizerCredential, dcl.DiffInfo{ObjectFunction: compareConnectionGithubConfigAuthorizerCredentialNewStyle, EmptyObject: EmptyConnectionGithubConfigAuthorizerCredential, OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("AuthorizerCredential")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.AppInstallationId, actual.AppInstallationId, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("AppInstallationId")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + return diffs, nil +} + +func compareConnectionGithubConfigAuthorizerCredentialNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { + var diffs []*dcl.FieldDiff + + desired, ok := d.(*ConnectionGithubConfigAuthorizerCredential) + if !ok { + desiredNotPointer, ok := d.(ConnectionGithubConfigAuthorizerCredential) + if !ok { + return nil, fmt.Errorf("obj %v is not a ConnectionGithubConfigAuthorizerCredential or *ConnectionGithubConfigAuthorizerCredential", d) + } + desired = &desiredNotPointer + } + actual, ok := a.(*ConnectionGithubConfigAuthorizerCredential) + if !ok { + actualNotPointer, ok := a.(ConnectionGithubConfigAuthorizerCredential) + if !ok { + return nil, fmt.Errorf("obj %v is not a ConnectionGithubConfigAuthorizerCredential", a) + } + actual = &actualNotPointer + } + + if ds, err := dcl.Diff(desired.OAuthTokenSecretVersion, actual.OAuthTokenSecretVersion, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("OauthTokenSecretVersion")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.Username, actual.Username, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("Username")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + return diffs, nil +} + +func compareConnectionGithubEnterpriseConfigNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { + var diffs []*dcl.FieldDiff + + desired, ok := d.(*ConnectionGithubEnterpriseConfig) + if !ok { + desiredNotPointer, ok := d.(ConnectionGithubEnterpriseConfig) + if !ok { + return nil, fmt.Errorf("obj %v is not a ConnectionGithubEnterpriseConfig or *ConnectionGithubEnterpriseConfig", d) + } + desired = &desiredNotPointer + } + actual, ok := a.(*ConnectionGithubEnterpriseConfig) + if !ok { + actualNotPointer, ok := a.(ConnectionGithubEnterpriseConfig) + if !ok { + return nil, fmt.Errorf("obj %v is not a ConnectionGithubEnterpriseConfig", a) + } + actual = &actualNotPointer + } + + if ds, err := dcl.Diff(desired.HostUri, actual.HostUri, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("HostUri")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.AppId, actual.AppId, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("AppId")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.AppSlug, actual.AppSlug, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("AppSlug")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.PrivateKeySecretVersion, actual.PrivateKeySecretVersion, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("PrivateKeySecretVersion")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.WebhookSecretSecretVersion, actual.WebhookSecretSecretVersion, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("WebhookSecretSecretVersion")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.OAuthSecretSecretVersion, actual.OAuthSecretSecretVersion, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("OauthSecretSecretVersion")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.OAuthClientIdSecretVersion, actual.OAuthClientIdSecretVersion, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("OauthClientIdSecretVersion")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.AuthorizerCredential, actual.AuthorizerCredential, dcl.DiffInfo{ObjectFunction: compareConnectionGithubEnterpriseConfigAuthorizerCredentialNewStyle, EmptyObject: EmptyConnectionGithubEnterpriseConfigAuthorizerCredential, OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("AuthorizerCredential")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.AppInstallationId, actual.AppInstallationId, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("AppInstallationId")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.ServiceDirectoryConfig, actual.ServiceDirectoryConfig, dcl.DiffInfo{ObjectFunction: compareConnectionGithubEnterpriseConfigServiceDirectoryConfigNewStyle, EmptyObject: EmptyConnectionGithubEnterpriseConfigServiceDirectoryConfig, OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("ServiceDirectoryConfig")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.SslCa, actual.SslCa, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("SslCa")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + return diffs, nil +} + +func compareConnectionGithubEnterpriseConfigAuthorizerCredentialNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { + var diffs []*dcl.FieldDiff + + desired, ok := d.(*ConnectionGithubEnterpriseConfigAuthorizerCredential) + if !ok { + desiredNotPointer, ok := d.(ConnectionGithubEnterpriseConfigAuthorizerCredential) + if !ok { + return nil, fmt.Errorf("obj %v is not a ConnectionGithubEnterpriseConfigAuthorizerCredential or *ConnectionGithubEnterpriseConfigAuthorizerCredential", d) + } + desired = &desiredNotPointer + } + actual, ok := a.(*ConnectionGithubEnterpriseConfigAuthorizerCredential) + if !ok { + actualNotPointer, ok := a.(ConnectionGithubEnterpriseConfigAuthorizerCredential) + if !ok { + return nil, fmt.Errorf("obj %v is not a ConnectionGithubEnterpriseConfigAuthorizerCredential", a) + } + actual = &actualNotPointer + } + + if ds, err := dcl.Diff(desired.OAuthTokenSecretVersion, actual.OAuthTokenSecretVersion, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("OauthTokenSecretVersion")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.Username, actual.Username, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("Username")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + return diffs, nil +} + +func compareConnectionGithubEnterpriseConfigServiceDirectoryConfigNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { + var diffs []*dcl.FieldDiff + + desired, ok := d.(*ConnectionGithubEnterpriseConfigServiceDirectoryConfig) + if !ok { + desiredNotPointer, ok := d.(ConnectionGithubEnterpriseConfigServiceDirectoryConfig) + if !ok { + return nil, fmt.Errorf("obj %v is not a ConnectionGithubEnterpriseConfigServiceDirectoryConfig or *ConnectionGithubEnterpriseConfigServiceDirectoryConfig", d) + } + desired = &desiredNotPointer + } + actual, ok := a.(*ConnectionGithubEnterpriseConfigServiceDirectoryConfig) + if !ok { + actualNotPointer, ok := a.(ConnectionGithubEnterpriseConfigServiceDirectoryConfig) + if !ok { + return nil, fmt.Errorf("obj %v is not a ConnectionGithubEnterpriseConfigServiceDirectoryConfig", a) + } + actual = &actualNotPointer + } + + if ds, err := dcl.Diff(desired.Service, actual.Service, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateConnectionUpdateConnectionOperation")}, fn.AddNest("Service")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + return diffs, nil +} + +func compareConnectionInstallationStateNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { + var diffs []*dcl.FieldDiff + + desired, ok := d.(*ConnectionInstallationState) + if !ok { + desiredNotPointer, ok := d.(ConnectionInstallationState) + if !ok { + return nil, fmt.Errorf("obj %v is not a ConnectionInstallationState or *ConnectionInstallationState", d) + } + desired = &desiredNotPointer + } + actual, ok := a.(*ConnectionInstallationState) + if !ok { + actualNotPointer, ok := a.(ConnectionInstallationState) + if !ok { + return nil, fmt.Errorf("obj %v is not a ConnectionInstallationState", a) + } + actual = &actualNotPointer + } + + if ds, err := dcl.Diff(desired.Stage, actual.Stage, dcl.DiffInfo{OutputOnly: true, Type: "EnumType", OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Stage")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.Message, actual.Message, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Message")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + + if ds, err := dcl.Diff(desired.ActionUri, actual.ActionUri, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("ActionUri")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + diffs = append(diffs, ds...) + } + return diffs, nil +} + +// urlNormalized returns a copy of the resource struct with values normalized +// for URL substitutions. For instance, it converts long-form self-links to +// short-form so they can be substituted in. +func (r *Connection) urlNormalized() *Connection { + normalized := dcl.Copy(*r).(Connection) + normalized.Name = dcl.SelfLinkToName(r.Name) + normalized.Etag = dcl.SelfLinkToName(r.Etag) + normalized.Project = dcl.SelfLinkToName(r.Project) + normalized.Location = dcl.SelfLinkToName(r.Location) + return &normalized +} + +func (r *Connection) updateURL(userBasePath, updateName string) (string, error) { + nr := r.urlNormalized() + if updateName == "UpdateConnection" { + fields := map[string]interface{}{ + "project": dcl.ValueOrEmptyString(nr.Project), + "location": dcl.ValueOrEmptyString(nr.Location), + "name": dcl.ValueOrEmptyString(nr.Name), + } + return dcl.URL("projects/{{project}}/locations/{{location}}/connections/{{name}}", nr.basePath(), userBasePath, fields), nil + + } + + return "", fmt.Errorf("unknown update name: %s", updateName) +} + +// marshal encodes the Connection resource into JSON for a Create request, and +// performs transformations from the resource schema to the API schema if +// necessary. +func (r *Connection) marshal(c *Client) ([]byte, error) { + m, err := expandConnection(c, r) + if err != nil { + return nil, fmt.Errorf("error marshalling Connection: %w", err) + } + + return json.Marshal(m) +} + +// unmarshalConnection decodes JSON responses into the Connection resource schema. +func unmarshalConnection(b []byte, c *Client, res *Connection) (*Connection, error) { + var m map[string]interface{} + if err := json.Unmarshal(b, &m); err != nil { + return nil, err + } + return unmarshalMapConnection(m, c, res) +} + +func unmarshalMapConnection(m map[string]interface{}, c *Client, res *Connection) (*Connection, error) { + + flattened := flattenConnection(c, m, res) + if flattened == nil { + return nil, fmt.Errorf("attempted to flatten empty json object") + } + return flattened, nil +} + +// expandConnection expands Connection into a JSON request object. +func expandConnection(c *Client, f *Connection) (map[string]interface{}, error) { + m := make(map[string]interface{}) + res := f + _ = res + if v, err := dcl.DeriveField("projects/%s/locations/%s/connections/%s", f.Name, dcl.SelfLinkToName(f.Project), dcl.SelfLinkToName(f.Location), dcl.SelfLinkToName(f.Name)); err != nil { + return nil, fmt.Errorf("error expanding Name into name: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + m["name"] = v + } + if v, err := expandConnectionGithubConfig(c, f.GithubConfig, res); err != nil { + return nil, fmt.Errorf("error expanding GithubConfig into githubConfig: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + m["githubConfig"] = v + } + if v, err := expandConnectionGithubEnterpriseConfig(c, f.GithubEnterpriseConfig, res); err != nil { + return nil, fmt.Errorf("error expanding GithubEnterpriseConfig into githubEnterpriseConfig: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + m["githubEnterpriseConfig"] = v + } + if v := f.Disabled; dcl.ValueShouldBeSent(v) { + m["disabled"] = v + } + if v := f.Annotations; dcl.ValueShouldBeSent(v) { + m["annotations"] = v + } + if v, err := dcl.EmptyValue(); err != nil { + return nil, fmt.Errorf("error expanding Project into project: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + m["project"] = v + } + if v, err := dcl.EmptyValue(); err != nil { + return nil, fmt.Errorf("error expanding Location into location: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + m["location"] = v + } + + return m, nil +} + +// flattenConnection flattens Connection from a JSON request object into the +// Connection type. +func flattenConnection(c *Client, i interface{}, res *Connection) *Connection { + m, ok := i.(map[string]interface{}) + if !ok { + return nil + } + if len(m) == 0 { + return nil + } + + resultRes := &Connection{} + resultRes.Name = dcl.FlattenString(m["name"]) + resultRes.CreateTime = dcl.FlattenString(m["createTime"]) + resultRes.UpdateTime = dcl.FlattenString(m["updateTime"]) + resultRes.GithubConfig = flattenConnectionGithubConfig(c, m["githubConfig"], res) + resultRes.GithubEnterpriseConfig = flattenConnectionGithubEnterpriseConfig(c, m["githubEnterpriseConfig"], res) + resultRes.InstallationState = flattenConnectionInstallationState(c, m["installationState"], res) + resultRes.Disabled = dcl.FlattenBool(m["disabled"]) + resultRes.Reconciling = dcl.FlattenBool(m["reconciling"]) + resultRes.Annotations = dcl.FlattenKeyValuePairs(m["annotations"]) + resultRes.Etag = dcl.FlattenString(m["etag"]) + resultRes.Project = dcl.FlattenString(m["project"]) + resultRes.Location = dcl.FlattenString(m["location"]) + + return resultRes +} + +// expandConnectionGithubConfigMap expands the contents of ConnectionGithubConfig into a JSON +// request object. +func expandConnectionGithubConfigMap(c *Client, f map[string]ConnectionGithubConfig, res *Connection) (map[string]interface{}, error) { + if f == nil { + return nil, nil + } + + items := make(map[string]interface{}) + for k, item := range f { + i, err := expandConnectionGithubConfig(c, &item, res) + if err != nil { + return nil, err + } + if i != nil { + items[k] = i + } + } + + return items, nil +} + +// expandConnectionGithubConfigSlice expands the contents of ConnectionGithubConfig into a JSON +// request object. +func expandConnectionGithubConfigSlice(c *Client, f []ConnectionGithubConfig, res *Connection) ([]map[string]interface{}, error) { + if f == nil { + return nil, nil + } + + items := []map[string]interface{}{} + for _, item := range f { + i, err := expandConnectionGithubConfig(c, &item, res) + if err != nil { + return nil, err + } + + items = append(items, i) + } + + return items, nil +} + +// flattenConnectionGithubConfigMap flattens the contents of ConnectionGithubConfig from a JSON +// response object. +func flattenConnectionGithubConfigMap(c *Client, i interface{}, res *Connection) map[string]ConnectionGithubConfig { + a, ok := i.(map[string]interface{}) + if !ok { + return map[string]ConnectionGithubConfig{} + } + + if len(a) == 0 { + return map[string]ConnectionGithubConfig{} + } + + items := make(map[string]ConnectionGithubConfig) + for k, item := range a { + items[k] = *flattenConnectionGithubConfig(c, item.(map[string]interface{}), res) + } + + return items +} + +// flattenConnectionGithubConfigSlice flattens the contents of ConnectionGithubConfig from a JSON +// response object. +func flattenConnectionGithubConfigSlice(c *Client, i interface{}, res *Connection) []ConnectionGithubConfig { + a, ok := i.([]interface{}) + if !ok { + return []ConnectionGithubConfig{} + } + + if len(a) == 0 { + return []ConnectionGithubConfig{} + } + + items := make([]ConnectionGithubConfig, 0, len(a)) + for _, item := range a { + items = append(items, *flattenConnectionGithubConfig(c, item.(map[string]interface{}), res)) + } + + return items +} + +// expandConnectionGithubConfig expands an instance of ConnectionGithubConfig into a JSON +// request object. +func expandConnectionGithubConfig(c *Client, f *ConnectionGithubConfig, res *Connection) (map[string]interface{}, error) { + if dcl.IsEmptyValueIndirect(f) { + return nil, nil + } + + m := make(map[string]interface{}) + if v, err := expandConnectionGithubConfigAuthorizerCredential(c, f.AuthorizerCredential, res); err != nil { + return nil, fmt.Errorf("error expanding AuthorizerCredential into authorizerCredential: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + m["authorizerCredential"] = v + } + if v := f.AppInstallationId; !dcl.IsEmptyValueIndirect(v) { + m["appInstallationId"] = v + } + + return m, nil +} + +// flattenConnectionGithubConfig flattens an instance of ConnectionGithubConfig from a JSON +// response object. +func flattenConnectionGithubConfig(c *Client, i interface{}, res *Connection) *ConnectionGithubConfig { + m, ok := i.(map[string]interface{}) + if !ok { + return nil + } + + r := &ConnectionGithubConfig{} + + if dcl.IsEmptyValueIndirect(i) { + return EmptyConnectionGithubConfig + } + r.AuthorizerCredential = flattenConnectionGithubConfigAuthorizerCredential(c, m["authorizerCredential"], res) + r.AppInstallationId = dcl.FlattenInteger(m["appInstallationId"]) + + return r +} + +// expandConnectionGithubConfigAuthorizerCredentialMap expands the contents of ConnectionGithubConfigAuthorizerCredential into a JSON +// request object. +func expandConnectionGithubConfigAuthorizerCredentialMap(c *Client, f map[string]ConnectionGithubConfigAuthorizerCredential, res *Connection) (map[string]interface{}, error) { + if f == nil { + return nil, nil + } + + items := make(map[string]interface{}) + for k, item := range f { + i, err := expandConnectionGithubConfigAuthorizerCredential(c, &item, res) + if err != nil { + return nil, err + } + if i != nil { + items[k] = i + } + } + + return items, nil +} + +// expandConnectionGithubConfigAuthorizerCredentialSlice expands the contents of ConnectionGithubConfigAuthorizerCredential into a JSON +// request object. +func expandConnectionGithubConfigAuthorizerCredentialSlice(c *Client, f []ConnectionGithubConfigAuthorizerCredential, res *Connection) ([]map[string]interface{}, error) { + if f == nil { + return nil, nil + } + + items := []map[string]interface{}{} + for _, item := range f { + i, err := expandConnectionGithubConfigAuthorizerCredential(c, &item, res) + if err != nil { + return nil, err + } + + items = append(items, i) + } + + return items, nil +} + +// flattenConnectionGithubConfigAuthorizerCredentialMap flattens the contents of ConnectionGithubConfigAuthorizerCredential from a JSON +// response object. +func flattenConnectionGithubConfigAuthorizerCredentialMap(c *Client, i interface{}, res *Connection) map[string]ConnectionGithubConfigAuthorizerCredential { + a, ok := i.(map[string]interface{}) + if !ok { + return map[string]ConnectionGithubConfigAuthorizerCredential{} + } + + if len(a) == 0 { + return map[string]ConnectionGithubConfigAuthorizerCredential{} + } + + items := make(map[string]ConnectionGithubConfigAuthorizerCredential) + for k, item := range a { + items[k] = *flattenConnectionGithubConfigAuthorizerCredential(c, item.(map[string]interface{}), res) + } + + return items +} + +// flattenConnectionGithubConfigAuthorizerCredentialSlice flattens the contents of ConnectionGithubConfigAuthorizerCredential from a JSON +// response object. +func flattenConnectionGithubConfigAuthorizerCredentialSlice(c *Client, i interface{}, res *Connection) []ConnectionGithubConfigAuthorizerCredential { + a, ok := i.([]interface{}) + if !ok { + return []ConnectionGithubConfigAuthorizerCredential{} + } + + if len(a) == 0 { + return []ConnectionGithubConfigAuthorizerCredential{} + } + + items := make([]ConnectionGithubConfigAuthorizerCredential, 0, len(a)) + for _, item := range a { + items = append(items, *flattenConnectionGithubConfigAuthorizerCredential(c, item.(map[string]interface{}), res)) + } + + return items +} + +// expandConnectionGithubConfigAuthorizerCredential expands an instance of ConnectionGithubConfigAuthorizerCredential into a JSON +// request object. +func expandConnectionGithubConfigAuthorizerCredential(c *Client, f *ConnectionGithubConfigAuthorizerCredential, res *Connection) (map[string]interface{}, error) { + if dcl.IsEmptyValueIndirect(f) { + return nil, nil + } + + m := make(map[string]interface{}) + if v := f.OAuthTokenSecretVersion; !dcl.IsEmptyValueIndirect(v) { + m["oauthTokenSecretVersion"] = v + } + if v := f.Username; !dcl.IsEmptyValueIndirect(v) { + m["username"] = v + } + + return m, nil +} + +// flattenConnectionGithubConfigAuthorizerCredential flattens an instance of ConnectionGithubConfigAuthorizerCredential from a JSON +// response object. +func flattenConnectionGithubConfigAuthorizerCredential(c *Client, i interface{}, res *Connection) *ConnectionGithubConfigAuthorizerCredential { + m, ok := i.(map[string]interface{}) + if !ok { + return nil + } + + r := &ConnectionGithubConfigAuthorizerCredential{} + + if dcl.IsEmptyValueIndirect(i) { + return EmptyConnectionGithubConfigAuthorizerCredential + } + r.OAuthTokenSecretVersion = dcl.FlattenString(m["oauthTokenSecretVersion"]) + r.Username = dcl.FlattenString(m["username"]) + + return r +} + +// expandConnectionGithubEnterpriseConfigMap expands the contents of ConnectionGithubEnterpriseConfig into a JSON +// request object. +func expandConnectionGithubEnterpriseConfigMap(c *Client, f map[string]ConnectionGithubEnterpriseConfig, res *Connection) (map[string]interface{}, error) { + if f == nil { + return nil, nil + } + + items := make(map[string]interface{}) + for k, item := range f { + i, err := expandConnectionGithubEnterpriseConfig(c, &item, res) + if err != nil { + return nil, err + } + if i != nil { + items[k] = i + } + } + + return items, nil +} + +// expandConnectionGithubEnterpriseConfigSlice expands the contents of ConnectionGithubEnterpriseConfig into a JSON +// request object. +func expandConnectionGithubEnterpriseConfigSlice(c *Client, f []ConnectionGithubEnterpriseConfig, res *Connection) ([]map[string]interface{}, error) { + if f == nil { + return nil, nil + } + + items := []map[string]interface{}{} + for _, item := range f { + i, err := expandConnectionGithubEnterpriseConfig(c, &item, res) + if err != nil { + return nil, err + } + + items = append(items, i) + } + + return items, nil +} + +// flattenConnectionGithubEnterpriseConfigMap flattens the contents of ConnectionGithubEnterpriseConfig from a JSON +// response object. +func flattenConnectionGithubEnterpriseConfigMap(c *Client, i interface{}, res *Connection) map[string]ConnectionGithubEnterpriseConfig { + a, ok := i.(map[string]interface{}) + if !ok { + return map[string]ConnectionGithubEnterpriseConfig{} + } + + if len(a) == 0 { + return map[string]ConnectionGithubEnterpriseConfig{} + } + + items := make(map[string]ConnectionGithubEnterpriseConfig) + for k, item := range a { + items[k] = *flattenConnectionGithubEnterpriseConfig(c, item.(map[string]interface{}), res) + } + + return items +} + +// flattenConnectionGithubEnterpriseConfigSlice flattens the contents of ConnectionGithubEnterpriseConfig from a JSON +// response object. +func flattenConnectionGithubEnterpriseConfigSlice(c *Client, i interface{}, res *Connection) []ConnectionGithubEnterpriseConfig { + a, ok := i.([]interface{}) + if !ok { + return []ConnectionGithubEnterpriseConfig{} + } + + if len(a) == 0 { + return []ConnectionGithubEnterpriseConfig{} + } + + items := make([]ConnectionGithubEnterpriseConfig, 0, len(a)) + for _, item := range a { + items = append(items, *flattenConnectionGithubEnterpriseConfig(c, item.(map[string]interface{}), res)) + } + + return items +} + +// expandConnectionGithubEnterpriseConfig expands an instance of ConnectionGithubEnterpriseConfig into a JSON +// request object. +func expandConnectionGithubEnterpriseConfig(c *Client, f *ConnectionGithubEnterpriseConfig, res *Connection) (map[string]interface{}, error) { + if dcl.IsEmptyValueIndirect(f) { + return nil, nil + } + + m := make(map[string]interface{}) + if v := f.HostUri; !dcl.IsEmptyValueIndirect(v) { + m["hostUri"] = v + } + if v := f.AppId; !dcl.IsEmptyValueIndirect(v) { + m["appId"] = v + } + if v := f.AppSlug; !dcl.IsEmptyValueIndirect(v) { + m["appSlug"] = v + } + if v := f.PrivateKeySecretVersion; !dcl.IsEmptyValueIndirect(v) { + m["privateKeySecretVersion"] = v + } + if v := f.WebhookSecretSecretVersion; !dcl.IsEmptyValueIndirect(v) { + m["webhookSecretSecretVersion"] = v + } + if v := f.OAuthSecretSecretVersion; !dcl.IsEmptyValueIndirect(v) { + m["oauthSecretSecretVersion"] = v + } + if v := f.OAuthClientIdSecretVersion; !dcl.IsEmptyValueIndirect(v) { + m["oauthClientIdSecretVersion"] = v + } + if v, err := expandConnectionGithubEnterpriseConfigAuthorizerCredential(c, f.AuthorizerCredential, res); err != nil { + return nil, fmt.Errorf("error expanding AuthorizerCredential into authorizerCredential: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + m["authorizerCredential"] = v + } + if v := f.AppInstallationId; !dcl.IsEmptyValueIndirect(v) { + m["appInstallationId"] = v + } + if v, err := expandConnectionGithubEnterpriseConfigServiceDirectoryConfig(c, f.ServiceDirectoryConfig, res); err != nil { + return nil, fmt.Errorf("error expanding ServiceDirectoryConfig into serviceDirectoryConfig: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + m["serviceDirectoryConfig"] = v + } + if v := f.SslCa; !dcl.IsEmptyValueIndirect(v) { + m["sslCa"] = v + } + + return m, nil +} + +// flattenConnectionGithubEnterpriseConfig flattens an instance of ConnectionGithubEnterpriseConfig from a JSON +// response object. +func flattenConnectionGithubEnterpriseConfig(c *Client, i interface{}, res *Connection) *ConnectionGithubEnterpriseConfig { + m, ok := i.(map[string]interface{}) + if !ok { + return nil + } + + r := &ConnectionGithubEnterpriseConfig{} + + if dcl.IsEmptyValueIndirect(i) { + return EmptyConnectionGithubEnterpriseConfig + } + r.HostUri = dcl.FlattenString(m["hostUri"]) + r.AppId = dcl.FlattenInteger(m["appId"]) + r.AppSlug = dcl.FlattenString(m["appSlug"]) + r.PrivateKeySecretVersion = dcl.FlattenString(m["privateKeySecretVersion"]) + r.WebhookSecretSecretVersion = dcl.FlattenString(m["webhookSecretSecretVersion"]) + r.OAuthSecretSecretVersion = dcl.FlattenString(m["oauthSecretSecretVersion"]) + r.OAuthClientIdSecretVersion = dcl.FlattenString(m["oauthClientIdSecretVersion"]) + r.AuthorizerCredential = flattenConnectionGithubEnterpriseConfigAuthorizerCredential(c, m["authorizerCredential"], res) + r.AppInstallationId = dcl.FlattenInteger(m["appInstallationId"]) + r.ServiceDirectoryConfig = flattenConnectionGithubEnterpriseConfigServiceDirectoryConfig(c, m["serviceDirectoryConfig"], res) + r.SslCa = dcl.FlattenString(m["sslCa"]) + + return r +} + +// expandConnectionGithubEnterpriseConfigAuthorizerCredentialMap expands the contents of ConnectionGithubEnterpriseConfigAuthorizerCredential into a JSON +// request object. +func expandConnectionGithubEnterpriseConfigAuthorizerCredentialMap(c *Client, f map[string]ConnectionGithubEnterpriseConfigAuthorizerCredential, res *Connection) (map[string]interface{}, error) { + if f == nil { + return nil, nil + } + + items := make(map[string]interface{}) + for k, item := range f { + i, err := expandConnectionGithubEnterpriseConfigAuthorizerCredential(c, &item, res) + if err != nil { + return nil, err + } + if i != nil { + items[k] = i + } + } + + return items, nil +} + +// expandConnectionGithubEnterpriseConfigAuthorizerCredentialSlice expands the contents of ConnectionGithubEnterpriseConfigAuthorizerCredential into a JSON +// request object. +func expandConnectionGithubEnterpriseConfigAuthorizerCredentialSlice(c *Client, f []ConnectionGithubEnterpriseConfigAuthorizerCredential, res *Connection) ([]map[string]interface{}, error) { + if f == nil { + return nil, nil + } + + items := []map[string]interface{}{} + for _, item := range f { + i, err := expandConnectionGithubEnterpriseConfigAuthorizerCredential(c, &item, res) + if err != nil { + return nil, err + } + + items = append(items, i) + } + + return items, nil +} + +// flattenConnectionGithubEnterpriseConfigAuthorizerCredentialMap flattens the contents of ConnectionGithubEnterpriseConfigAuthorizerCredential from a JSON +// response object. +func flattenConnectionGithubEnterpriseConfigAuthorizerCredentialMap(c *Client, i interface{}, res *Connection) map[string]ConnectionGithubEnterpriseConfigAuthorizerCredential { + a, ok := i.(map[string]interface{}) + if !ok { + return map[string]ConnectionGithubEnterpriseConfigAuthorizerCredential{} + } + + if len(a) == 0 { + return map[string]ConnectionGithubEnterpriseConfigAuthorizerCredential{} + } + + items := make(map[string]ConnectionGithubEnterpriseConfigAuthorizerCredential) + for k, item := range a { + items[k] = *flattenConnectionGithubEnterpriseConfigAuthorizerCredential(c, item.(map[string]interface{}), res) + } + + return items +} + +// flattenConnectionGithubEnterpriseConfigAuthorizerCredentialSlice flattens the contents of ConnectionGithubEnterpriseConfigAuthorizerCredential from a JSON +// response object. +func flattenConnectionGithubEnterpriseConfigAuthorizerCredentialSlice(c *Client, i interface{}, res *Connection) []ConnectionGithubEnterpriseConfigAuthorizerCredential { + a, ok := i.([]interface{}) + if !ok { + return []ConnectionGithubEnterpriseConfigAuthorizerCredential{} + } + + if len(a) == 0 { + return []ConnectionGithubEnterpriseConfigAuthorizerCredential{} + } + + items := make([]ConnectionGithubEnterpriseConfigAuthorizerCredential, 0, len(a)) + for _, item := range a { + items = append(items, *flattenConnectionGithubEnterpriseConfigAuthorizerCredential(c, item.(map[string]interface{}), res)) + } + + return items +} + +// expandConnectionGithubEnterpriseConfigAuthorizerCredential expands an instance of ConnectionGithubEnterpriseConfigAuthorizerCredential into a JSON +// request object. +func expandConnectionGithubEnterpriseConfigAuthorizerCredential(c *Client, f *ConnectionGithubEnterpriseConfigAuthorizerCredential, res *Connection) (map[string]interface{}, error) { + if dcl.IsEmptyValueIndirect(f) { + return nil, nil + } + + m := make(map[string]interface{}) + if v := f.OAuthTokenSecretVersion; !dcl.IsEmptyValueIndirect(v) { + m["oauthTokenSecretVersion"] = v + } + if v := f.Username; !dcl.IsEmptyValueIndirect(v) { + m["username"] = v + } + + return m, nil +} + +// flattenConnectionGithubEnterpriseConfigAuthorizerCredential flattens an instance of ConnectionGithubEnterpriseConfigAuthorizerCredential from a JSON +// response object. +func flattenConnectionGithubEnterpriseConfigAuthorizerCredential(c *Client, i interface{}, res *Connection) *ConnectionGithubEnterpriseConfigAuthorizerCredential { + m, ok := i.(map[string]interface{}) + if !ok { + return nil + } + + r := &ConnectionGithubEnterpriseConfigAuthorizerCredential{} + + if dcl.IsEmptyValueIndirect(i) { + return EmptyConnectionGithubEnterpriseConfigAuthorizerCredential + } + r.OAuthTokenSecretVersion = dcl.FlattenString(m["oauthTokenSecretVersion"]) + r.Username = dcl.FlattenString(m["username"]) + + return r +} + +// expandConnectionGithubEnterpriseConfigServiceDirectoryConfigMap expands the contents of ConnectionGithubEnterpriseConfigServiceDirectoryConfig into a JSON +// request object. +func expandConnectionGithubEnterpriseConfigServiceDirectoryConfigMap(c *Client, f map[string]ConnectionGithubEnterpriseConfigServiceDirectoryConfig, res *Connection) (map[string]interface{}, error) { + if f == nil { + return nil, nil + } + + items := make(map[string]interface{}) + for k, item := range f { + i, err := expandConnectionGithubEnterpriseConfigServiceDirectoryConfig(c, &item, res) + if err != nil { + return nil, err + } + if i != nil { + items[k] = i + } + } + + return items, nil +} + +// expandConnectionGithubEnterpriseConfigServiceDirectoryConfigSlice expands the contents of ConnectionGithubEnterpriseConfigServiceDirectoryConfig into a JSON +// request object. +func expandConnectionGithubEnterpriseConfigServiceDirectoryConfigSlice(c *Client, f []ConnectionGithubEnterpriseConfigServiceDirectoryConfig, res *Connection) ([]map[string]interface{}, error) { + if f == nil { + return nil, nil + } + + items := []map[string]interface{}{} + for _, item := range f { + i, err := expandConnectionGithubEnterpriseConfigServiceDirectoryConfig(c, &item, res) + if err != nil { + return nil, err + } + + items = append(items, i) + } + + return items, nil +} + +// flattenConnectionGithubEnterpriseConfigServiceDirectoryConfigMap flattens the contents of ConnectionGithubEnterpriseConfigServiceDirectoryConfig from a JSON +// response object. +func flattenConnectionGithubEnterpriseConfigServiceDirectoryConfigMap(c *Client, i interface{}, res *Connection) map[string]ConnectionGithubEnterpriseConfigServiceDirectoryConfig { + a, ok := i.(map[string]interface{}) + if !ok { + return map[string]ConnectionGithubEnterpriseConfigServiceDirectoryConfig{} + } + + if len(a) == 0 { + return map[string]ConnectionGithubEnterpriseConfigServiceDirectoryConfig{} + } + + items := make(map[string]ConnectionGithubEnterpriseConfigServiceDirectoryConfig) + for k, item := range a { + items[k] = *flattenConnectionGithubEnterpriseConfigServiceDirectoryConfig(c, item.(map[string]interface{}), res) + } + + return items +} + +// flattenConnectionGithubEnterpriseConfigServiceDirectoryConfigSlice flattens the contents of ConnectionGithubEnterpriseConfigServiceDirectoryConfig from a JSON +// response object. +func flattenConnectionGithubEnterpriseConfigServiceDirectoryConfigSlice(c *Client, i interface{}, res *Connection) []ConnectionGithubEnterpriseConfigServiceDirectoryConfig { + a, ok := i.([]interface{}) + if !ok { + return []ConnectionGithubEnterpriseConfigServiceDirectoryConfig{} + } + + if len(a) == 0 { + return []ConnectionGithubEnterpriseConfigServiceDirectoryConfig{} + } + + items := make([]ConnectionGithubEnterpriseConfigServiceDirectoryConfig, 0, len(a)) + for _, item := range a { + items = append(items, *flattenConnectionGithubEnterpriseConfigServiceDirectoryConfig(c, item.(map[string]interface{}), res)) + } + + return items +} + +// expandConnectionGithubEnterpriseConfigServiceDirectoryConfig expands an instance of ConnectionGithubEnterpriseConfigServiceDirectoryConfig into a JSON +// request object. +func expandConnectionGithubEnterpriseConfigServiceDirectoryConfig(c *Client, f *ConnectionGithubEnterpriseConfigServiceDirectoryConfig, res *Connection) (map[string]interface{}, error) { + if dcl.IsEmptyValueIndirect(f) { + return nil, nil + } + + m := make(map[string]interface{}) + if v := f.Service; !dcl.IsEmptyValueIndirect(v) { + m["service"] = v + } + + return m, nil +} + +// flattenConnectionGithubEnterpriseConfigServiceDirectoryConfig flattens an instance of ConnectionGithubEnterpriseConfigServiceDirectoryConfig from a JSON +// response object. +func flattenConnectionGithubEnterpriseConfigServiceDirectoryConfig(c *Client, i interface{}, res *Connection) *ConnectionGithubEnterpriseConfigServiceDirectoryConfig { + m, ok := i.(map[string]interface{}) + if !ok { + return nil + } + + r := &ConnectionGithubEnterpriseConfigServiceDirectoryConfig{} + + if dcl.IsEmptyValueIndirect(i) { + return EmptyConnectionGithubEnterpriseConfigServiceDirectoryConfig + } + r.Service = dcl.FlattenString(m["service"]) + + return r +} + +// expandConnectionInstallationStateMap expands the contents of ConnectionInstallationState into a JSON +// request object. +func expandConnectionInstallationStateMap(c *Client, f map[string]ConnectionInstallationState, res *Connection) (map[string]interface{}, error) { + if f == nil { + return nil, nil + } + + items := make(map[string]interface{}) + for k, item := range f { + i, err := expandConnectionInstallationState(c, &item, res) + if err != nil { + return nil, err + } + if i != nil { + items[k] = i + } + } + + return items, nil +} + +// expandConnectionInstallationStateSlice expands the contents of ConnectionInstallationState into a JSON +// request object. +func expandConnectionInstallationStateSlice(c *Client, f []ConnectionInstallationState, res *Connection) ([]map[string]interface{}, error) { + if f == nil { + return nil, nil + } + + items := []map[string]interface{}{} + for _, item := range f { + i, err := expandConnectionInstallationState(c, &item, res) + if err != nil { + return nil, err + } + + items = append(items, i) + } + + return items, nil +} + +// flattenConnectionInstallationStateMap flattens the contents of ConnectionInstallationState from a JSON +// response object. +func flattenConnectionInstallationStateMap(c *Client, i interface{}, res *Connection) map[string]ConnectionInstallationState { + a, ok := i.(map[string]interface{}) + if !ok { + return map[string]ConnectionInstallationState{} + } + + if len(a) == 0 { + return map[string]ConnectionInstallationState{} + } + + items := make(map[string]ConnectionInstallationState) + for k, item := range a { + items[k] = *flattenConnectionInstallationState(c, item.(map[string]interface{}), res) + } + + return items +} + +// flattenConnectionInstallationStateSlice flattens the contents of ConnectionInstallationState from a JSON +// response object. +func flattenConnectionInstallationStateSlice(c *Client, i interface{}, res *Connection) []ConnectionInstallationState { + a, ok := i.([]interface{}) + if !ok { + return []ConnectionInstallationState{} + } + + if len(a) == 0 { + return []ConnectionInstallationState{} + } + + items := make([]ConnectionInstallationState, 0, len(a)) + for _, item := range a { + items = append(items, *flattenConnectionInstallationState(c, item.(map[string]interface{}), res)) + } + + return items +} + +// expandConnectionInstallationState expands an instance of ConnectionInstallationState into a JSON +// request object. +func expandConnectionInstallationState(c *Client, f *ConnectionInstallationState, res *Connection) (map[string]interface{}, error) { + if dcl.IsEmptyValueIndirect(f) { + return nil, nil + } + + m := make(map[string]interface{}) + + return m, nil +} + +// flattenConnectionInstallationState flattens an instance of ConnectionInstallationState from a JSON +// response object. +func flattenConnectionInstallationState(c *Client, i interface{}, res *Connection) *ConnectionInstallationState { + m, ok := i.(map[string]interface{}) + if !ok { + return nil + } + + r := &ConnectionInstallationState{} + + if dcl.IsEmptyValueIndirect(i) { + return EmptyConnectionInstallationState + } + r.Stage = flattenConnectionInstallationStateStageEnum(m["stage"]) + r.Message = dcl.FlattenString(m["message"]) + r.ActionUri = dcl.FlattenString(m["actionUri"]) + + return r +} + +// flattenConnectionInstallationStateStageEnumMap flattens the contents of ConnectionInstallationStateStageEnum from a JSON +// response object. +func flattenConnectionInstallationStateStageEnumMap(c *Client, i interface{}, res *Connection) map[string]ConnectionInstallationStateStageEnum { + a, ok := i.(map[string]interface{}) + if !ok { + return map[string]ConnectionInstallationStateStageEnum{} + } + + if len(a) == 0 { + return map[string]ConnectionInstallationStateStageEnum{} + } + + items := make(map[string]ConnectionInstallationStateStageEnum) + for k, item := range a { + items[k] = *flattenConnectionInstallationStateStageEnum(item.(interface{})) + } + + return items +} + +// flattenConnectionInstallationStateStageEnumSlice flattens the contents of ConnectionInstallationStateStageEnum from a JSON +// response object. +func flattenConnectionInstallationStateStageEnumSlice(c *Client, i interface{}, res *Connection) []ConnectionInstallationStateStageEnum { + a, ok := i.([]interface{}) + if !ok { + return []ConnectionInstallationStateStageEnum{} + } + + if len(a) == 0 { + return []ConnectionInstallationStateStageEnum{} + } + + items := make([]ConnectionInstallationStateStageEnum, 0, len(a)) + for _, item := range a { + items = append(items, *flattenConnectionInstallationStateStageEnum(item.(interface{}))) + } + + return items +} + +// flattenConnectionInstallationStateStageEnum asserts that an interface is a string, and returns a +// pointer to a *ConnectionInstallationStateStageEnum with the same value as that string. +func flattenConnectionInstallationStateStageEnum(i interface{}) *ConnectionInstallationStateStageEnum { + s, ok := i.(string) + if !ok { + return nil + } + + return ConnectionInstallationStateStageEnumRef(s) +} + +// This function returns a matcher that checks whether a serialized resource matches this resource +// in its parameters (as defined by the fields in a Get, which definitionally define resource +// identity). This is useful in extracting the element from a List call. +func (r *Connection) matcher(c *Client) func([]byte) bool { + return func(b []byte) bool { + cr, err := unmarshalConnection(b, c, r) + if err != nil { + c.Config.Logger.Warning("failed to unmarshal provided resource in matcher.") + return false + } + nr := r.urlNormalized() + ncr := cr.urlNormalized() + c.Config.Logger.Infof("looking for %v\nin %v", nr, ncr) + + if nr.Project == nil && ncr.Project == nil { + c.Config.Logger.Info("Both Project fields null - considering equal.") + } else if nr.Project == nil || ncr.Project == nil { + c.Config.Logger.Info("Only one Project field is null - considering unequal.") + return false + } else if *nr.Project != *ncr.Project { + return false + } + if nr.Location == nil && ncr.Location == nil { + c.Config.Logger.Info("Both Location fields null - considering equal.") + } else if nr.Location == nil || ncr.Location == nil { + c.Config.Logger.Info("Only one Location field is null - considering unequal.") + return false + } else if *nr.Location != *ncr.Location { + return false + } + if nr.Name == nil && ncr.Name == nil { + c.Config.Logger.Info("Both Name fields null - considering equal.") + } else if nr.Name == nil || ncr.Name == nil { + c.Config.Logger.Info("Only one Name field is null - considering unequal.") + return false + } else if *nr.Name != *ncr.Name { + return false + } + return true + } +} + +type connectionDiff struct { + // The diff should include one or the other of RequiresRecreate or UpdateOp. + RequiresRecreate bool + UpdateOp connectionApiOperation +} + +func convertFieldDiffsToConnectionDiffs(config *dcl.Config, fds []*dcl.FieldDiff, opts []dcl.ApplyOption) ([]connectionDiff, error) { + opNamesToFieldDiffs := make(map[string][]*dcl.FieldDiff) + // Map each operation name to the field diffs associated with it. + for _, fd := range fds { + for _, ro := range fd.ResultingOperation { + if fieldDiffs, ok := opNamesToFieldDiffs[ro]; ok { + fieldDiffs = append(fieldDiffs, fd) + opNamesToFieldDiffs[ro] = fieldDiffs + } else { + config.Logger.Infof("%s required due to diff: %v", ro, fd) + opNamesToFieldDiffs[ro] = []*dcl.FieldDiff{fd} + } + } + } + var diffs []connectionDiff + // For each operation name, create a connectionDiff which contains the operation. + for opName, fieldDiffs := range opNamesToFieldDiffs { + diff := connectionDiff{} + if opName == "Recreate" { + diff.RequiresRecreate = true + } else { + apiOp, err := convertOpNameToConnectionApiOperation(opName, fieldDiffs, opts...) + if err != nil { + return diffs, err + } + diff.UpdateOp = apiOp + } + diffs = append(diffs, diff) + } + return diffs, nil +} + +func convertOpNameToConnectionApiOperation(opName string, fieldDiffs []*dcl.FieldDiff, opts ...dcl.ApplyOption) (connectionApiOperation, error) { + switch opName { + + case "updateConnectionUpdateConnectionOperation": + return &updateConnectionUpdateConnectionOperation{FieldDiffs: fieldDiffs}, nil + + default: + return nil, fmt.Errorf("no such operation with name: %v", opName) + } +} + +func extractConnectionFields(r *Connection) error { + vGithubConfig := r.GithubConfig + if vGithubConfig == nil { + // note: explicitly not the empty object. + vGithubConfig = &ConnectionGithubConfig{} + } + if err := extractConnectionGithubConfigFields(r, vGithubConfig); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(vGithubConfig) { + r.GithubConfig = vGithubConfig + } + vGithubEnterpriseConfig := r.GithubEnterpriseConfig + if vGithubEnterpriseConfig == nil { + // note: explicitly not the empty object. + vGithubEnterpriseConfig = &ConnectionGithubEnterpriseConfig{} + } + if err := extractConnectionGithubEnterpriseConfigFields(r, vGithubEnterpriseConfig); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(vGithubEnterpriseConfig) { + r.GithubEnterpriseConfig = vGithubEnterpriseConfig + } + vInstallationState := r.InstallationState + if vInstallationState == nil { + // note: explicitly not the empty object. + vInstallationState = &ConnectionInstallationState{} + } + if err := extractConnectionInstallationStateFields(r, vInstallationState); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(vInstallationState) { + r.InstallationState = vInstallationState + } + return nil +} +func extractConnectionGithubConfigFields(r *Connection, o *ConnectionGithubConfig) error { + vAuthorizerCredential := o.AuthorizerCredential + if vAuthorizerCredential == nil { + // note: explicitly not the empty object. + vAuthorizerCredential = &ConnectionGithubConfigAuthorizerCredential{} + } + if err := extractConnectionGithubConfigAuthorizerCredentialFields(r, vAuthorizerCredential); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(vAuthorizerCredential) { + o.AuthorizerCredential = vAuthorizerCredential + } + return nil +} +func extractConnectionGithubConfigAuthorizerCredentialFields(r *Connection, o *ConnectionGithubConfigAuthorizerCredential) error { + return nil +} +func extractConnectionGithubEnterpriseConfigFields(r *Connection, o *ConnectionGithubEnterpriseConfig) error { + vAuthorizerCredential := o.AuthorizerCredential + if vAuthorizerCredential == nil { + // note: explicitly not the empty object. + vAuthorizerCredential = &ConnectionGithubEnterpriseConfigAuthorizerCredential{} + } + if err := extractConnectionGithubEnterpriseConfigAuthorizerCredentialFields(r, vAuthorizerCredential); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(vAuthorizerCredential) { + o.AuthorizerCredential = vAuthorizerCredential + } + vServiceDirectoryConfig := o.ServiceDirectoryConfig + if vServiceDirectoryConfig == nil { + // note: explicitly not the empty object. + vServiceDirectoryConfig = &ConnectionGithubEnterpriseConfigServiceDirectoryConfig{} + } + if err := extractConnectionGithubEnterpriseConfigServiceDirectoryConfigFields(r, vServiceDirectoryConfig); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(vServiceDirectoryConfig) { + o.ServiceDirectoryConfig = vServiceDirectoryConfig + } + return nil +} +func extractConnectionGithubEnterpriseConfigAuthorizerCredentialFields(r *Connection, o *ConnectionGithubEnterpriseConfigAuthorizerCredential) error { + return nil +} +func extractConnectionGithubEnterpriseConfigServiceDirectoryConfigFields(r *Connection, o *ConnectionGithubEnterpriseConfigServiceDirectoryConfig) error { + return nil +} +func extractConnectionInstallationStateFields(r *Connection, o *ConnectionInstallationState) error { + return nil +} + +func postReadExtractConnectionFields(r *Connection) error { + vGithubConfig := r.GithubConfig + if vGithubConfig == nil { + // note: explicitly not the empty object. + vGithubConfig = &ConnectionGithubConfig{} + } + if err := postReadExtractConnectionGithubConfigFields(r, vGithubConfig); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(vGithubConfig) { + r.GithubConfig = vGithubConfig + } + vGithubEnterpriseConfig := r.GithubEnterpriseConfig + if vGithubEnterpriseConfig == nil { + // note: explicitly not the empty object. + vGithubEnterpriseConfig = &ConnectionGithubEnterpriseConfig{} + } + if err := postReadExtractConnectionGithubEnterpriseConfigFields(r, vGithubEnterpriseConfig); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(vGithubEnterpriseConfig) { + r.GithubEnterpriseConfig = vGithubEnterpriseConfig + } + vInstallationState := r.InstallationState + if vInstallationState == nil { + // note: explicitly not the empty object. + vInstallationState = &ConnectionInstallationState{} + } + if err := postReadExtractConnectionInstallationStateFields(r, vInstallationState); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(vInstallationState) { + r.InstallationState = vInstallationState + } + return nil +} +func postReadExtractConnectionGithubConfigFields(r *Connection, o *ConnectionGithubConfig) error { + vAuthorizerCredential := o.AuthorizerCredential + if vAuthorizerCredential == nil { + // note: explicitly not the empty object. + vAuthorizerCredential = &ConnectionGithubConfigAuthorizerCredential{} + } + if err := extractConnectionGithubConfigAuthorizerCredentialFields(r, vAuthorizerCredential); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(vAuthorizerCredential) { + o.AuthorizerCredential = vAuthorizerCredential + } + return nil +} +func postReadExtractConnectionGithubConfigAuthorizerCredentialFields(r *Connection, o *ConnectionGithubConfigAuthorizerCredential) error { + return nil +} +func postReadExtractConnectionGithubEnterpriseConfigFields(r *Connection, o *ConnectionGithubEnterpriseConfig) error { + vAuthorizerCredential := o.AuthorizerCredential + if vAuthorizerCredential == nil { + // note: explicitly not the empty object. + vAuthorizerCredential = &ConnectionGithubEnterpriseConfigAuthorizerCredential{} + } + if err := extractConnectionGithubEnterpriseConfigAuthorizerCredentialFields(r, vAuthorizerCredential); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(vAuthorizerCredential) { + o.AuthorizerCredential = vAuthorizerCredential + } + vServiceDirectoryConfig := o.ServiceDirectoryConfig + if vServiceDirectoryConfig == nil { + // note: explicitly not the empty object. + vServiceDirectoryConfig = &ConnectionGithubEnterpriseConfigServiceDirectoryConfig{} + } + if err := extractConnectionGithubEnterpriseConfigServiceDirectoryConfigFields(r, vServiceDirectoryConfig); err != nil { + return err + } + if !dcl.IsEmptyValueIndirect(vServiceDirectoryConfig) { + o.ServiceDirectoryConfig = vServiceDirectoryConfig + } + return nil +} +func postReadExtractConnectionGithubEnterpriseConfigAuthorizerCredentialFields(r *Connection, o *ConnectionGithubEnterpriseConfigAuthorizerCredential) error { + return nil +} +func postReadExtractConnectionGithubEnterpriseConfigServiceDirectoryConfigFields(r *Connection, o *ConnectionGithubEnterpriseConfigServiceDirectoryConfig) error { + return nil +} +func postReadExtractConnectionInstallationStateFields(r *Connection, o *ConnectionInstallationState) error { + return nil +} diff --git a/services/google/cloudbuildv2/alpha/connection_schema.go b/services/google/cloudbuildv2/alpha/connection_schema.go new file mode 100755 index 000000000..2e5f6d025 --- /dev/null +++ b/services/google/cloudbuildv2/alpha/connection_schema.go @@ -0,0 +1,397 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +package alpha + +import ( + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" +) + +func DCLConnectionSchema() *dcl.Schema { + return &dcl.Schema{ + Info: &dcl.Info{ + Title: "Cloudbuildv2/Connection", + Description: "The Cloudbuildv2 Connection resource", + StructName: "Connection", + }, + Paths: &dcl.Paths{ + Get: &dcl.Path{ + Description: "The function used to get information about a Connection", + Parameters: []dcl.PathParameters{ + dcl.PathParameters{ + Name: "Connection", + Required: true, + Description: "A full instance of a Connection", + }, + }, + }, + Apply: &dcl.Path{ + Description: "The function used to apply information about a Connection", + Parameters: []dcl.PathParameters{ + dcl.PathParameters{ + Name: "Connection", + Required: true, + Description: "A full instance of a Connection", + }, + }, + }, + Delete: &dcl.Path{ + Description: "The function used to delete a Connection", + Parameters: []dcl.PathParameters{ + dcl.PathParameters{ + Name: "Connection", + Required: true, + Description: "A full instance of a Connection", + }, + }, + }, + DeleteAll: &dcl.Path{ + Description: "The function used to delete all Connection", + Parameters: []dcl.PathParameters{ + dcl.PathParameters{ + Name: "project", + Required: true, + Schema: &dcl.PathParametersSchema{ + Type: "string", + }, + }, + dcl.PathParameters{ + Name: "location", + Required: true, + Schema: &dcl.PathParametersSchema{ + Type: "string", + }, + }, + }, + }, + List: &dcl.Path{ + Description: "The function used to list information about many Connection", + Parameters: []dcl.PathParameters{ + dcl.PathParameters{ + Name: "project", + Required: true, + Schema: &dcl.PathParametersSchema{ + Type: "string", + }, + }, + dcl.PathParameters{ + Name: "location", + Required: true, + Schema: &dcl.PathParametersSchema{ + Type: "string", + }, + }, + }, + }, + }, + Components: &dcl.Components{ + Schemas: map[string]*dcl.Component{ + "Connection": &dcl.Component{ + Title: "Connection", + ID: "projects/{{project}}/locations/{{location}}/connections/{{name}}", + ParentContainer: "project", + HasCreate: true, + SchemaProperty: dcl.Property{ + Type: "object", + Required: []string{ + "name", + "project", + "location", + }, + Properties: map[string]*dcl.Property{ + "annotations": &dcl.Property{ + Type: "object", + AdditionalProperties: &dcl.Property{ + Type: "string", + }, + GoName: "Annotations", + Description: "Allows clients to store small amounts of arbitrary data.", + }, + "createTime": &dcl.Property{ + Type: "string", + Format: "date-time", + GoName: "CreateTime", + ReadOnly: true, + Description: "Output only. Server assigned timestamp for when the connection was created.", + Immutable: true, + }, + "disabled": &dcl.Property{ + Type: "boolean", + GoName: "Disabled", + Description: "If disabled is set to true, functionality is disabled for this connection. Repository based API methods and webhooks processing for repositories in this connection will be disabled.", + }, + "etag": &dcl.Property{ + Type: "string", + GoName: "Etag", + ReadOnly: true, + Description: "This checksum is computed by the server based on the value of other fields, and may be sent on update and delete requests to ensure the client has an up-to-date value before proceeding.", + Immutable: true, + }, + "githubConfig": &dcl.Property{ + Type: "object", + GoName: "GithubConfig", + GoType: "ConnectionGithubConfig", + Description: "Configuration for connections to github.com.", + Conflicts: []string{ + "githubEnterpriseConfig", + }, + Properties: map[string]*dcl.Property{ + "appInstallationId": &dcl.Property{ + Type: "integer", + Format: "int64", + GoName: "AppInstallationId", + Description: "GitHub App installation id.", + }, + "authorizerCredential": &dcl.Property{ + Type: "object", + GoName: "AuthorizerCredential", + GoType: "ConnectionGithubConfigAuthorizerCredential", + Description: "OAuth credential of the account that authorized the Cloud Build GitHub App. It is recommended to use a robot account instead of a human user account. The OAuth token must be tied to the Cloud Build GitHub App.", + Properties: map[string]*dcl.Property{ + "oauthTokenSecretVersion": &dcl.Property{ + Type: "string", + GoName: "OAuthTokenSecretVersion", + Description: "A SecretManager resource containing the OAuth token that authorizes the Cloud Build connection. Format: `projects/*/secrets/*/versions/*`.", + ResourceReferences: []*dcl.PropertyResourceReference{ + &dcl.PropertyResourceReference{ + Resource: "Secretmanager/SecretVersion", + Field: "selfLink", + }, + }, + }, + "username": &dcl.Property{ + Type: "string", + GoName: "Username", + Description: "The username associated to this token.", + }, + }, + }, + }, + }, + "githubEnterpriseConfig": &dcl.Property{ + Type: "object", + GoName: "GithubEnterpriseConfig", + GoType: "ConnectionGithubEnterpriseConfig", + Description: "Configuration for connections to an instance of GitHub Enterprise.", + Conflicts: []string{ + "githubConfig", + }, + Required: []string{ + "hostUri", + }, + Properties: map[string]*dcl.Property{ + "appId": &dcl.Property{ + Type: "integer", + Format: "int64", + GoName: "AppId", + Description: "Id of the GitHub App created from the manifest.", + }, + "appInstallationId": &dcl.Property{ + Type: "integer", + Format: "int64", + GoName: "AppInstallationId", + Description: "ID of the installation of the GitHub App.", + }, + "appSlug": &dcl.Property{ + Type: "string", + GoName: "AppSlug", + Description: "The URL-friendly name of the GitHub App.", + }, + "authorizerCredential": &dcl.Property{ + Type: "object", + GoName: "AuthorizerCredential", + GoType: "ConnectionGithubEnterpriseConfigAuthorizerCredential", + Description: "OAuth credential of the account that authorized the Cloud Build GitHub App. It is recommended to use a robot account instead of a human user account The OAuth token must be tied to the Cloud Build GitHub App.", + Properties: map[string]*dcl.Property{ + "oauthTokenSecretVersion": &dcl.Property{ + Type: "string", + GoName: "OAuthTokenSecretVersion", + Description: "A SecretManager resource containing the OAuth token that authorizes the Cloud Build connection. Format: `projects/*/secrets/*/versions/*`.", + ResourceReferences: []*dcl.PropertyResourceReference{ + &dcl.PropertyResourceReference{ + Resource: "Secretmanager/SecretVersion", + Field: "selfLink", + }, + }, + }, + "username": &dcl.Property{ + Type: "string", + GoName: "Username", + Description: "The username associated to this token.", + }, + }, + }, + "hostUri": &dcl.Property{ + Type: "string", + GoName: "HostUri", + Description: "Required. The URI of the GitHub Enterprise host this connection is for.", + }, + "oauthClientIdSecretVersion": &dcl.Property{ + Type: "string", + GoName: "OAuthClientIdSecretVersion", + Description: "SecretManager resource containing the OAuth client_id of the GitHub App, formatted as `projects/*/secrets/*/versions/*`.", + ResourceReferences: []*dcl.PropertyResourceReference{ + &dcl.PropertyResourceReference{ + Resource: "Secretmanager/SecretVersion", + Field: "selfLink", + }, + }, + }, + "oauthSecretSecretVersion": &dcl.Property{ + Type: "string", + GoName: "OAuthSecretSecretVersion", + Description: "SecretManager resource containing the OAuth secret of the GitHub App, formatted as `projects/*/secrets/*/versions/*`.", + ResourceReferences: []*dcl.PropertyResourceReference{ + &dcl.PropertyResourceReference{ + Resource: "Secretmanager/SecretVersion", + Field: "selfLink", + }, + }, + }, + "privateKeySecretVersion": &dcl.Property{ + Type: "string", + GoName: "PrivateKeySecretVersion", + Description: "SecretManager resource containing the private key of the GitHub App, formatted as `projects/*/secrets/*/versions/*`.", + ResourceReferences: []*dcl.PropertyResourceReference{ + &dcl.PropertyResourceReference{ + Resource: "Secretmanager/SecretVersion", + Field: "selfLink", + }, + }, + }, + "serviceDirectoryConfig": &dcl.Property{ + Type: "object", + GoName: "ServiceDirectoryConfig", + GoType: "ConnectionGithubEnterpriseConfigServiceDirectoryConfig", + Description: "Configuration for using Service Directory to privately connect to a GitHub Enterprise server. This should only be set if the GitHub Enterprise server is hosted on-premises and not reachable by public internet. If this field is left empty, calls to the GitHub Enterprise server will be made over the public internet.", + Required: []string{ + "service", + }, + Properties: map[string]*dcl.Property{ + "service": &dcl.Property{ + Type: "string", + GoName: "Service", + Description: "Required. The Service Directory service name. Format: projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}.", + ResourceReferences: []*dcl.PropertyResourceReference{ + &dcl.PropertyResourceReference{ + Resource: "Servicedirectory/Service", + Field: "selfLink", + }, + }, + }, + }, + }, + "sslCa": &dcl.Property{ + Type: "string", + GoName: "SslCa", + Description: "SSL certificate to use for requests to GitHub Enterprise.", + }, + "webhookSecretSecretVersion": &dcl.Property{ + Type: "string", + GoName: "WebhookSecretSecretVersion", + Description: "SecretManager resource containing the webhook secret of the GitHub App, formatted as `projects/*/secrets/*/versions/*`.", + ResourceReferences: []*dcl.PropertyResourceReference{ + &dcl.PropertyResourceReference{ + Resource: "Secretmanager/SecretVersion", + Field: "selfLink", + }, + }, + }, + }, + }, + "installationState": &dcl.Property{ + Type: "object", + GoName: "InstallationState", + GoType: "ConnectionInstallationState", + ReadOnly: true, + Description: "Output only. Installation state of the Connection.", + Immutable: true, + Properties: map[string]*dcl.Property{ + "actionUri": &dcl.Property{ + Type: "string", + GoName: "ActionUri", + ReadOnly: true, + Description: "Output only. Link to follow for next action. Empty string if the installation is already complete.", + Immutable: true, + }, + "message": &dcl.Property{ + Type: "string", + GoName: "Message", + ReadOnly: true, + Description: "Output only. Message of what the user should do next to continue the installation. Empty string if the installation is already complete.", + Immutable: true, + }, + "stage": &dcl.Property{ + Type: "string", + GoName: "Stage", + GoType: "ConnectionInstallationStateStageEnum", + ReadOnly: true, + Description: "Output only. Current step of the installation process. Possible values: STAGE_UNSPECIFIED, PENDING_CREATE_APP, PENDING_USER_OAUTH, PENDING_INSTALL_APP, COMPLETE", + Immutable: true, + Enum: []string{ + "STAGE_UNSPECIFIED", + "PENDING_CREATE_APP", + "PENDING_USER_OAUTH", + "PENDING_INSTALL_APP", + "COMPLETE", + }, + }, + }, + }, + "location": &dcl.Property{ + Type: "string", + GoName: "Location", + Description: "The location for the resource", + Immutable: true, + }, + "name": &dcl.Property{ + Type: "string", + GoName: "Name", + Description: "Immutable. The resource name of the connection, in the format `projects/{project}/locations/{location}/connections/{connection_id}`.", + Immutable: true, + }, + "project": &dcl.Property{ + Type: "string", + GoName: "Project", + Description: "The project for the resource", + Immutable: true, + ResourceReferences: []*dcl.PropertyResourceReference{ + &dcl.PropertyResourceReference{ + Resource: "Cloudresourcemanager/Project", + Field: "name", + Parent: true, + }, + }, + }, + "reconciling": &dcl.Property{ + Type: "boolean", + GoName: "Reconciling", + ReadOnly: true, + Description: "Output only. Set to true when the connection is being set up or updated in the background.", + Immutable: true, + }, + "updateTime": &dcl.Property{ + Type: "string", + Format: "date-time", + GoName: "UpdateTime", + ReadOnly: true, + Description: "Output only. Server assigned timestamp for when the connection was updated.", + Immutable: true, + }, + }, + }, + }, + }, + }, + } +} diff --git a/services/google/cloudbuildv2/alpha/repository.go b/services/google/cloudbuildv2/alpha/repository.go new file mode 100755 index 000000000..939c11f6f --- /dev/null +++ b/services/google/cloudbuildv2/alpha/repository.go @@ -0,0 +1,379 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +package alpha + +import ( + "context" + "fmt" + "time" + + "google.golang.org/api/googleapi" + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" +) + +type Repository struct { + Name *string `json:"name"` + RemoteUri *string `json:"remoteUri"` + CreateTime *string `json:"createTime"` + UpdateTime *string `json:"updateTime"` + Annotations map[string]string `json:"annotations"` + Etag *string `json:"etag"` + Project *string `json:"project"` + Location *string `json:"location"` + Connection *string `json:"connection"` +} + +func (r *Repository) String() string { + return dcl.SprintResource(r) +} + +// Describe returns a simple description of this resource to ensure that automated tools +// can identify it. +func (r *Repository) Describe() dcl.ServiceTypeVersion { + return dcl.ServiceTypeVersion{ + Service: "cloudbuildv2", + Type: "Repository", + Version: "alpha", + } +} + +func (r *Repository) ID() (string, error) { + if err := extractRepositoryFields(r); err != nil { + return "", err + } + nr := r.urlNormalized() + params := map[string]interface{}{ + "name": dcl.ValueOrEmptyString(nr.Name), + "remote_uri": dcl.ValueOrEmptyString(nr.RemoteUri), + "create_time": dcl.ValueOrEmptyString(nr.CreateTime), + "update_time": dcl.ValueOrEmptyString(nr.UpdateTime), + "annotations": dcl.ValueOrEmptyString(nr.Annotations), + "etag": dcl.ValueOrEmptyString(nr.Etag), + "project": dcl.ValueOrEmptyString(nr.Project), + "location": dcl.ValueOrEmptyString(nr.Location), + "connection": dcl.ValueOrEmptyString(nr.Connection), + } + return dcl.Nprintf("projects/{{project}}/locations/{{location}}/connections/{{connection}}/repositories/{{name}}", params), nil +} + +const RepositoryMaxPage = -1 + +type RepositoryList struct { + Items []*Repository + + nextToken string + + pageSize int32 + + resource *Repository +} + +func (l *RepositoryList) HasNext() bool { + return l.nextToken != "" +} + +func (l *RepositoryList) Next(ctx context.Context, c *Client) error { + ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) + defer cancel() + + if !l.HasNext() { + return fmt.Errorf("no next page") + } + items, token, err := c.listRepository(ctx, l.resource, l.nextToken, l.pageSize) + if err != nil { + return err + } + l.Items = items + l.nextToken = token + return err +} + +func (c *Client) ListRepository(ctx context.Context, project, location, connection string) (*RepositoryList, error) { + ctx = dcl.ContextWithRequestID(ctx) + ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) + defer cancel() + + return c.ListRepositoryWithMaxResults(ctx, project, location, connection, RepositoryMaxPage) + +} + +func (c *Client) ListRepositoryWithMaxResults(ctx context.Context, project, location, connection string, pageSize int32) (*RepositoryList, error) { + ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) + defer cancel() + + // Create a resource object so that we can use proper url normalization methods. + r := &Repository{ + Project: &project, + Location: &location, + Connection: &connection, + } + items, token, err := c.listRepository(ctx, r, "", pageSize) + if err != nil { + return nil, err + } + return &RepositoryList{ + Items: items, + nextToken: token, + pageSize: pageSize, + resource: r, + }, nil +} + +func (c *Client) GetRepository(ctx context.Context, r *Repository) (*Repository, error) { + ctx = dcl.ContextWithRequestID(ctx) + ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) + defer cancel() + + // This is *purposefully* supressing errors. + // This function is used with url-normalized values + not URL normalized values. + // URL Normalized values will throw unintentional errors, since those values are not of the proper parent form. + extractRepositoryFields(r) + + b, err := c.getRepositoryRaw(ctx, r) + if err != nil { + if dcl.IsNotFound(err) { + return nil, &googleapi.Error{ + Code: 404, + Message: err.Error(), + } + } + return nil, err + } + result, err := unmarshalRepository(b, c, r) + if err != nil { + return nil, err + } + result.Project = r.Project + result.Location = r.Location + result.Connection = r.Connection + result.Name = r.Name + + c.Config.Logger.InfoWithContextf(ctx, "Retrieved raw result state: %v", result) + c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with specified state: %v", r) + result, err = canonicalizeRepositoryNewState(c, result, r) + if err != nil { + return nil, err + } + if err := postReadExtractRepositoryFields(result); err != nil { + return result, err + } + c.Config.Logger.InfoWithContextf(ctx, "Created result state: %v", result) + + return result, nil +} + +func (c *Client) DeleteRepository(ctx context.Context, r *Repository) error { + ctx = dcl.ContextWithRequestID(ctx) + ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) + defer cancel() + + if r == nil { + return fmt.Errorf("Repository resource is nil") + } + c.Config.Logger.InfoWithContext(ctx, "Deleting Repository...") + deleteOp := deleteRepositoryOperation{} + return deleteOp.do(ctx, r, c) +} + +// DeleteAllRepository deletes all resources that the filter functions returns true on. +func (c *Client) DeleteAllRepository(ctx context.Context, project, location, connection string, filter func(*Repository) bool) error { + listObj, err := c.ListRepository(ctx, project, location, connection) + if err != nil { + return err + } + + err = c.deleteAllRepository(ctx, filter, listObj.Items) + if err != nil { + return err + } + for listObj.HasNext() { + err = listObj.Next(ctx, c) + if err != nil { + return nil + } + err = c.deleteAllRepository(ctx, filter, listObj.Items) + if err != nil { + return err + } + } + return nil +} + +func (c *Client) ApplyRepository(ctx context.Context, rawDesired *Repository, opts ...dcl.ApplyOption) (*Repository, error) { + ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) + defer cancel() + + ctx = dcl.ContextWithRequestID(ctx) + var resultNewState *Repository + err := dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) { + newState, err := applyRepositoryHelper(c, ctx, rawDesired, opts...) + resultNewState = newState + if err != nil { + // If the error is 409, there is conflict in resource update. + // Here we want to apply changes based on latest state. + if dcl.IsConflictError(err) { + return &dcl.RetryDetails{}, dcl.OperationNotDone{Err: err} + } + return nil, err + } + return nil, nil + }, c.Config.RetryProvider) + return resultNewState, err +} + +func applyRepositoryHelper(c *Client, ctx context.Context, rawDesired *Repository, opts ...dcl.ApplyOption) (*Repository, error) { + c.Config.Logger.InfoWithContext(ctx, "Beginning ApplyRepository...") + c.Config.Logger.InfoWithContextf(ctx, "User specified desired state: %v", rawDesired) + + // 1.1: Validation of user-specified fields in desired state. + if err := rawDesired.validate(); err != nil { + return nil, err + } + + if err := extractRepositoryFields(rawDesired); err != nil { + return nil, err + } + + initial, desired, fieldDiffs, err := c.repositoryDiffsForRawDesired(ctx, rawDesired, opts...) + if err != nil { + return nil, fmt.Errorf("failed to create a diff: %w", err) + } + + diffs, err := convertFieldDiffsToRepositoryDiffs(c.Config, fieldDiffs, opts) + if err != nil { + return nil, err + } + + // TODO(magic-modules-eng): 2.2 Feasibility check (all updates are feasible so far). + + // 2.3: Lifecycle Directive Check + var create bool + lp := dcl.FetchLifecycleParams(opts) + if initial == nil { + if dcl.HasLifecycleParam(lp, dcl.BlockCreation) { + return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Creation blocked by lifecycle params: %#v.", desired)} + } + create = true + } else if dcl.HasLifecycleParam(lp, dcl.BlockAcquire) { + return nil, dcl.ApplyInfeasibleError{ + Message: fmt.Sprintf("Resource already exists - apply blocked by lifecycle params: %#v.", initial), + } + } else { + for _, d := range diffs { + if d.RequiresRecreate { + return nil, dcl.ApplyInfeasibleError{ + Message: fmt.Sprintf("infeasible update: (%v) would require recreation", d), + } + } + if dcl.HasLifecycleParam(lp, dcl.BlockModification) { + return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Modification blocked, diff (%v) unresolvable.", d)} + } + } + } + + // 2.4 Imperative Request Planning + var ops []repositoryApiOperation + if create { + ops = append(ops, &createRepositoryOperation{}) + } else { + for _, d := range diffs { + ops = append(ops, d.UpdateOp) + } + } + c.Config.Logger.InfoWithContextf(ctx, "Created plan: %#v", ops) + + // 2.5 Request Actuation + for _, op := range ops { + c.Config.Logger.InfoWithContextf(ctx, "Performing operation %T %+v", op, op) + if err := op.do(ctx, desired, c); err != nil { + c.Config.Logger.InfoWithContextf(ctx, "Failed operation %T %+v: %v", op, op, err) + return nil, err + } + c.Config.Logger.InfoWithContextf(ctx, "Finished operation %T %+v", op, op) + } + return applyRepositoryDiff(c, ctx, desired, rawDesired, ops, opts...) +} + +func applyRepositoryDiff(c *Client, ctx context.Context, desired *Repository, rawDesired *Repository, ops []repositoryApiOperation, opts ...dcl.ApplyOption) (*Repository, error) { + // 3.1, 3.2a Retrieval of raw new state & canonicalization with desired state + c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state...") + rawNew, err := c.GetRepository(ctx, desired) + if err != nil { + return nil, err + } + // Get additional values from the first response. + // These values should be merged into the newState above. + if len(ops) > 0 { + lastOp := ops[len(ops)-1] + if o, ok := lastOp.(*createRepositoryOperation); ok { + if r, hasR := o.FirstResponse(); hasR { + + c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state from operation...") + + fullResp, err := unmarshalMapRepository(r, c, rawDesired) + if err != nil { + return nil, err + } + + rawNew, err = canonicalizeRepositoryNewState(c, rawNew, fullResp) + if err != nil { + return nil, err + } + } + } + } + + c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with raw desired state: %v", rawDesired) + // 3.2b Canonicalization of raw new state using raw desired state + newState, err := canonicalizeRepositoryNewState(c, rawNew, rawDesired) + if err != nil { + return rawNew, err + } + + c.Config.Logger.InfoWithContextf(ctx, "Created canonical new state: %v", newState) + // 3.3 Comparison of the new state and raw desired state. + // TODO(magic-modules-eng): EVENTUALLY_CONSISTENT_UPDATE + newDesired, err := canonicalizeRepositoryDesiredState(rawDesired, newState) + if err != nil { + return newState, err + } + + if err := postReadExtractRepositoryFields(newState); err != nil { + return newState, err + } + + // Need to ensure any transformations made here match acceptably in differ. + if err := postReadExtractRepositoryFields(newDesired); err != nil { + return newState, err + } + + c.Config.Logger.InfoWithContextf(ctx, "Diffing using canonicalized desired state: %v", newDesired) + newDiffs, err := diffRepository(c, newDesired, newState) + if err != nil { + return newState, err + } + + if len(newDiffs) == 0 { + c.Config.Logger.InfoWithContext(ctx, "No diffs found. Apply was successful.") + } else { + c.Config.Logger.InfoWithContextf(ctx, "Found diffs: %v", newDiffs) + diffMessages := make([]string, len(newDiffs)) + for i, d := range newDiffs { + diffMessages[i] = fmt.Sprintf("%v", d) + } + return newState, dcl.DiffAfterApplyError{Diffs: diffMessages} + } + c.Config.Logger.InfoWithContext(ctx, "Done Apply.") + return newState, nil +} diff --git a/services/google/cloudbuildv2/alpha/repository.yaml b/services/google/cloudbuildv2/alpha/repository.yaml new file mode 100755 index 000000000..c933790d2 --- /dev/null +++ b/services/google/cloudbuildv2/alpha/repository.yaml @@ -0,0 +1,150 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +info: + title: Cloudbuildv2/Repository + description: The Cloudbuildv2 Repository resource + x-dcl-struct-name: Repository + x-dcl-has-iam: false +paths: + get: + description: The function used to get information about a Repository + parameters: + - name: Repository + required: true + description: A full instance of a Repository + apply: + description: The function used to apply information about a Repository + parameters: + - name: Repository + required: true + description: A full instance of a Repository + delete: + description: The function used to delete a Repository + parameters: + - name: Repository + required: true + description: A full instance of a Repository + deleteAll: + description: The function used to delete all Repository + parameters: + - name: project + required: true + schema: + type: string + - name: location + required: true + schema: + type: string + - name: connection + required: true + schema: + type: string + list: + description: The function used to list information about many Repository + parameters: + - name: project + required: true + schema: + type: string + - name: location + required: true + schema: + type: string + - name: connection + required: true + schema: + type: string +components: + schemas: + Repository: + title: Repository + x-dcl-id: projects/{{project}}/locations/{{location}}/connections/{{connection}}/repositories/{{name}} + x-dcl-parent-container: project + x-dcl-has-create: true + x-dcl-has-iam: false + x-dcl-read-timeout: 0 + x-dcl-apply-timeout: 0 + x-dcl-delete-timeout: 0 + type: object + required: + - name + - remoteUri + - connection + properties: + annotations: + type: object + additionalProperties: + type: string + x-dcl-go-name: Annotations + description: Allows clients to store small amounts of arbitrary data. + x-kubernetes-immutable: true + connection: + type: string + x-dcl-go-name: Connection + description: The connection for the resource + x-kubernetes-immutable: true + x-dcl-references: + - resource: Cloudbuildv2/Connection + field: name + parent: true + createTime: + type: string + format: date-time + x-dcl-go-name: CreateTime + readOnly: true + description: Output only. Server assigned timestamp for when the connection + was created. + x-kubernetes-immutable: true + etag: + type: string + x-dcl-go-name: Etag + readOnly: true + description: This checksum is computed by the server based on the value + of other fields, and may be sent on update and delete requests to ensure + the client has an up-to-date value before proceeding. + x-kubernetes-immutable: true + location: + type: string + x-dcl-go-name: Location + description: The location for the resource + x-kubernetes-immutable: true + x-dcl-extract-if-empty: true + name: + type: string + x-dcl-go-name: Name + description: Name of the repository. + x-kubernetes-immutable: true + project: + type: string + x-dcl-go-name: Project + description: The project for the resource + x-kubernetes-immutable: true + x-dcl-references: + - resource: Cloudresourcemanager/Project + field: name + parent: true + x-dcl-extract-if-empty: true + remoteUri: + type: string + x-dcl-go-name: RemoteUri + description: Required. Git Clone HTTPS URI. + x-kubernetes-immutable: true + updateTime: + type: string + format: date-time + x-dcl-go-name: UpdateTime + readOnly: true + description: Output only. Server assigned timestamp for when the connection + was updated. + x-kubernetes-immutable: true diff --git a/services/google/cloudbuildv2/alpha/repository_alpha_yaml_embed.go b/services/google/cloudbuildv2/alpha/repository_alpha_yaml_embed.go new file mode 100755 index 000000000..975e2776f --- /dev/null +++ b/services/google/cloudbuildv2/alpha/repository_alpha_yaml_embed.go @@ -0,0 +1,23 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// GENERATED BY gen_go_data.go +// gen_go_data -package alpha -var YAML_repository blaze-out/k8-fastbuild/genfiles/cloud/graphite/mmv2/services/google/cloudbuildv2/alpha/repository.yaml + +package alpha + +// blaze-out/k8-fastbuild/genfiles/cloud/graphite/mmv2/services/google/cloudbuildv2/alpha/repository.yaml +var YAML_repository = []byte("info:\n title: Cloudbuildv2/Repository\n description: The Cloudbuildv2 Repository resource\n x-dcl-struct-name: Repository\n x-dcl-has-iam: false\npaths:\n get:\n description: The function used to get information about a Repository\n parameters:\n - name: Repository\n required: true\n description: A full instance of a Repository\n apply:\n description: The function used to apply information about a Repository\n parameters:\n - name: Repository\n required: true\n description: A full instance of a Repository\n delete:\n description: The function used to delete a Repository\n parameters:\n - name: Repository\n required: true\n description: A full instance of a Repository\n deleteAll:\n description: The function used to delete all Repository\n parameters:\n - name: project\n required: true\n schema:\n type: string\n - name: location\n required: true\n schema:\n type: string\n - name: connection\n required: true\n schema:\n type: string\n list:\n description: The function used to list information about many Repository\n parameters:\n - name: project\n required: true\n schema:\n type: string\n - name: location\n required: true\n schema:\n type: string\n - name: connection\n required: true\n schema:\n type: string\ncomponents:\n schemas:\n Repository:\n title: Repository\n x-dcl-id: projects/{{project}}/locations/{{location}}/connections/{{connection}}/repositories/{{name}}\n x-dcl-parent-container: project\n x-dcl-has-create: true\n x-dcl-has-iam: false\n x-dcl-read-timeout: 0\n x-dcl-apply-timeout: 0\n x-dcl-delete-timeout: 0\n type: object\n required:\n - name\n - remoteUri\n - connection\n properties:\n annotations:\n type: object\n additionalProperties:\n type: string\n x-dcl-go-name: Annotations\n description: Allows clients to store small amounts of arbitrary data.\n x-kubernetes-immutable: true\n connection:\n type: string\n x-dcl-go-name: Connection\n description: The connection for the resource\n x-kubernetes-immutable: true\n x-dcl-references:\n - resource: Cloudbuildv2/Connection\n field: name\n parent: true\n createTime:\n type: string\n format: date-time\n x-dcl-go-name: CreateTime\n readOnly: true\n description: Output only. Server assigned timestamp for when the connection\n was created.\n x-kubernetes-immutable: true\n etag:\n type: string\n x-dcl-go-name: Etag\n readOnly: true\n description: This checksum is computed by the server based on the value\n of other fields, and may be sent on update and delete requests to ensure\n the client has an up-to-date value before proceeding.\n x-kubernetes-immutable: true\n location:\n type: string\n x-dcl-go-name: Location\n description: The location for the resource\n x-kubernetes-immutable: true\n x-dcl-extract-if-empty: true\n name:\n type: string\n x-dcl-go-name: Name\n description: Name of the repository.\n x-kubernetes-immutable: true\n project:\n type: string\n x-dcl-go-name: Project\n description: The project for the resource\n x-kubernetes-immutable: true\n x-dcl-references:\n - resource: Cloudresourcemanager/Project\n field: name\n parent: true\n x-dcl-extract-if-empty: true\n remoteUri:\n type: string\n x-dcl-go-name: RemoteUri\n description: Required. Git Clone HTTPS URI.\n x-kubernetes-immutable: true\n updateTime:\n type: string\n format: date-time\n x-dcl-go-name: UpdateTime\n readOnly: true\n description: Output only. Server assigned timestamp for when the connection\n was updated.\n x-kubernetes-immutable: true\n") + +// 4169 bytes +// MD5: ec03440b80ffa8d9ccd2d016a42c0ffb diff --git a/services/google/cloudbuildv2/alpha/repository_internal.go b/services/google/cloudbuildv2/alpha/repository_internal.go new file mode 100755 index 000000000..3a9580f9e --- /dev/null +++ b/services/google/cloudbuildv2/alpha/repository_internal.go @@ -0,0 +1,753 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +package alpha + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io/ioutil" + "strings" + + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl/operations" +) + +func (r *Repository) validate() error { + + if err := dcl.Required(r, "name"); err != nil { + return err + } + if err := dcl.Required(r, "remoteUri"); err != nil { + return err + } + if err := dcl.RequiredParameter(r.Connection, "Connection"); err != nil { + return err + } + return nil +} +func (r *Repository) basePath() string { + params := map[string]interface{}{} + return dcl.Nprintf("https://cloudbuild.googleapis.com/v2/", params) +} + +func (r *Repository) getURL(userBasePath string) (string, error) { + nr := r.urlNormalized() + params := map[string]interface{}{ + "project": dcl.ValueOrEmptyString(nr.Project), + "location": dcl.ValueOrEmptyString(nr.Location), + "connection": dcl.ValueOrEmptyString(nr.Connection), + "name": dcl.ValueOrEmptyString(nr.Name), + } + return dcl.URL("projects/{{project}}/locations/{{location}}/connections/{{connection}}/repositories/{{name}}", nr.basePath(), userBasePath, params), nil +} + +func (r *Repository) listURL(userBasePath string) (string, error) { + nr := r.urlNormalized() + params := map[string]interface{}{ + "project": dcl.ValueOrEmptyString(nr.Project), + "location": dcl.ValueOrEmptyString(nr.Location), + "connection": dcl.ValueOrEmptyString(nr.Connection), + } + return dcl.URL("projects/{{project}}/locations/{{location}}/connections/{{connection}}/repositories", nr.basePath(), userBasePath, params), nil + +} + +func (r *Repository) createURL(userBasePath string) (string, error) { + nr := r.urlNormalized() + params := map[string]interface{}{ + "project": dcl.ValueOrEmptyString(nr.Project), + "location": dcl.ValueOrEmptyString(nr.Location), + "connection": dcl.ValueOrEmptyString(nr.Connection), + "name": dcl.ValueOrEmptyString(nr.Name), + } + return dcl.URL("projects/{{project}}/locations/{{location}}/connections/{{connection}}/repositories?repositoryId={{name}}", nr.basePath(), userBasePath, params), nil + +} + +func (r *Repository) deleteURL(userBasePath string) (string, error) { + nr := r.urlNormalized() + params := map[string]interface{}{ + "project": dcl.ValueOrEmptyString(nr.Project), + "location": dcl.ValueOrEmptyString(nr.Location), + "connection": dcl.ValueOrEmptyString(nr.Connection), + "name": dcl.ValueOrEmptyString(nr.Name), + } + return dcl.URL("projects/{{project}}/locations/{{location}}/connections/{{connection}}/repositories/{{name}}", nr.basePath(), userBasePath, params), nil +} + +// repositoryApiOperation represents a mutable operation in the underlying REST +// API such as Create, Update, or Delete. +type repositoryApiOperation interface { + do(context.Context, *Repository, *Client) error +} + +func (c *Client) listRepositoryRaw(ctx context.Context, r *Repository, pageToken string, pageSize int32) ([]byte, error) { + u, err := r.urlNormalized().listURL(c.Config.BasePath) + if err != nil { + return nil, err + } + + m := make(map[string]string) + if pageToken != "" { + m["pageToken"] = pageToken + } + + if pageSize != RepositoryMaxPage { + m["pageSize"] = fmt.Sprintf("%v", pageSize) + } + + u, err = dcl.AddQueryParams(u, m) + if err != nil { + return nil, err + } + resp, err := dcl.SendRequest(ctx, c.Config, "GET", u, &bytes.Buffer{}, c.Config.RetryProvider) + if err != nil { + return nil, err + } + defer resp.Response.Body.Close() + return ioutil.ReadAll(resp.Response.Body) +} + +type listRepositoryOperation struct { + Repositories []map[string]interface{} `json:"repositories"` + Token string `json:"nextPageToken"` +} + +func (c *Client) listRepository(ctx context.Context, r *Repository, pageToken string, pageSize int32) ([]*Repository, string, error) { + b, err := c.listRepositoryRaw(ctx, r, pageToken, pageSize) + if err != nil { + return nil, "", err + } + + var m listRepositoryOperation + if err := json.Unmarshal(b, &m); err != nil { + return nil, "", err + } + + var l []*Repository + for _, v := range m.Repositories { + res, err := unmarshalMapRepository(v, c, r) + if err != nil { + return nil, m.Token, err + } + res.Project = r.Project + res.Location = r.Location + res.Connection = r.Connection + l = append(l, res) + } + + return l, m.Token, nil +} + +func (c *Client) deleteAllRepository(ctx context.Context, f func(*Repository) bool, resources []*Repository) error { + var errors []string + for _, res := range resources { + if f(res) { + // We do not want deleteAll to fail on a deletion or else it will stop deleting other resources. + err := c.DeleteRepository(ctx, res) + if err != nil { + errors = append(errors, err.Error()) + } + } + } + if len(errors) > 0 { + return fmt.Errorf("%v", strings.Join(errors, "\n")) + } else { + return nil + } +} + +type deleteRepositoryOperation struct{} + +func (op *deleteRepositoryOperation) do(ctx context.Context, r *Repository, c *Client) error { + r, err := c.GetRepository(ctx, r) + if err != nil { + if dcl.IsNotFound(err) { + c.Config.Logger.InfoWithContextf(ctx, "Repository not found, returning. Original error: %v", err) + return nil + } + c.Config.Logger.WarningWithContextf(ctx, "GetRepository checking for existence. error: %v", err) + return err + } + + u, err := r.deleteURL(c.Config.BasePath) + if err != nil { + return err + } + + // Delete should never have a body + body := &bytes.Buffer{} + resp, err := dcl.SendRequest(ctx, c.Config, "DELETE", u, body, c.Config.RetryProvider) + if err != nil { + return err + } + + // wait for object to be deleted. + var o operations.StandardGCPOperation + if err := dcl.ParseResponse(resp.Response, &o); err != nil { + return err + } + if err := o.Wait(context.WithValue(ctx, dcl.DoNotLogRequestsKey, true), c.Config, r.basePath(), "GET"); err != nil { + return err + } + + // We saw a race condition where for some successful delete operation, the Get calls returned resources for a short duration. + // This is the reason we are adding retry to handle that case. + retriesRemaining := 10 + dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) { + _, err := c.GetRepository(ctx, r) + if dcl.IsNotFound(err) { + return nil, nil + } + if retriesRemaining > 0 { + retriesRemaining-- + return &dcl.RetryDetails{}, dcl.OperationNotDone{} + } + return nil, dcl.NotDeletedError{ExistingResource: r} + }, c.Config.RetryProvider) + return nil +} + +// Create operations are similar to Update operations, although they do not have +// specific request objects. The Create request object is the json encoding of +// the resource, which is modified by res.marshal to form the base request body. +type createRepositoryOperation struct { + response map[string]interface{} +} + +func (op *createRepositoryOperation) FirstResponse() (map[string]interface{}, bool) { + return op.response, len(op.response) > 0 +} + +func (op *createRepositoryOperation) do(ctx context.Context, r *Repository, c *Client) error { + c.Config.Logger.InfoWithContextf(ctx, "Attempting to create %v", r) + u, err := r.createURL(c.Config.BasePath) + if err != nil { + return err + } + + req, err := r.marshal(c) + if err != nil { + return err + } + resp, err := dcl.SendRequest(ctx, c.Config, "POST", u, bytes.NewBuffer(req), c.Config.RetryProvider) + if err != nil { + return err + } + // wait for object to be created. + var o operations.StandardGCPOperation + if err := dcl.ParseResponse(resp.Response, &o); err != nil { + return err + } + if err := o.Wait(context.WithValue(ctx, dcl.DoNotLogRequestsKey, true), c.Config, r.basePath(), "GET"); err != nil { + c.Config.Logger.Warningf("Creation failed after waiting for operation: %v", err) + return err + } + c.Config.Logger.InfoWithContextf(ctx, "Successfully waited for operation") + op.response, _ = o.FirstResponse() + + if _, err := c.GetRepository(ctx, r); err != nil { + c.Config.Logger.WarningWithContextf(ctx, "get returned error: %v", err) + return err + } + + return nil +} + +func (c *Client) getRepositoryRaw(ctx context.Context, r *Repository) ([]byte, error) { + + u, err := r.getURL(c.Config.BasePath) + if err != nil { + return nil, err + } + resp, err := dcl.SendRequest(ctx, c.Config, "GET", u, &bytes.Buffer{}, c.Config.RetryProvider) + if err != nil { + return nil, err + } + defer resp.Response.Body.Close() + b, err := ioutil.ReadAll(resp.Response.Body) + if err != nil { + return nil, err + } + + return b, nil +} + +func (c *Client) repositoryDiffsForRawDesired(ctx context.Context, rawDesired *Repository, opts ...dcl.ApplyOption) (initial, desired *Repository, diffs []*dcl.FieldDiff, err error) { + c.Config.Logger.InfoWithContext(ctx, "Fetching initial state...") + // First, let us see if the user provided a state hint. If they did, we will start fetching based on that. + var fetchState *Repository + if sh := dcl.FetchStateHint(opts); sh != nil { + if r, ok := sh.(*Repository); !ok { + c.Config.Logger.WarningWithContextf(ctx, "Initial state hint was of the wrong type; expected Repository, got %T", sh) + } else { + fetchState = r + } + } + if fetchState == nil { + fetchState = rawDesired + } + + // 1.2: Retrieval of raw initial state from API + rawInitial, err := c.GetRepository(ctx, fetchState) + if rawInitial == nil { + if !dcl.IsNotFound(err) { + c.Config.Logger.WarningWithContextf(ctx, "Failed to retrieve whether a Repository resource already exists: %s", err) + return nil, nil, nil, fmt.Errorf("failed to retrieve Repository resource: %v", err) + } + c.Config.Logger.InfoWithContext(ctx, "Found that Repository resource did not exist.") + // Perform canonicalization to pick up defaults. + desired, err = canonicalizeRepositoryDesiredState(rawDesired, rawInitial) + return nil, desired, nil, err + } + c.Config.Logger.InfoWithContextf(ctx, "Found initial state for Repository: %v", rawInitial) + c.Config.Logger.InfoWithContextf(ctx, "Initial desired state for Repository: %v", rawDesired) + + // The Get call applies postReadExtract and so the result may contain fields that are not part of API version. + if err := extractRepositoryFields(rawInitial); err != nil { + return nil, nil, nil, err + } + + // 1.3: Canonicalize raw initial state into initial state. + initial, err = canonicalizeRepositoryInitialState(rawInitial, rawDesired) + if err != nil { + return nil, nil, nil, err + } + c.Config.Logger.InfoWithContextf(ctx, "Canonicalized initial state for Repository: %v", initial) + + // 1.4: Canonicalize raw desired state into desired state. + desired, err = canonicalizeRepositoryDesiredState(rawDesired, rawInitial, opts...) + if err != nil { + return nil, nil, nil, err + } + c.Config.Logger.InfoWithContextf(ctx, "Canonicalized desired state for Repository: %v", desired) + + // 2.1: Comparison of initial and desired state. + diffs, err = diffRepository(c, desired, initial, opts...) + return initial, desired, diffs, err +} + +func canonicalizeRepositoryInitialState(rawInitial, rawDesired *Repository) (*Repository, error) { + // TODO(magic-modules-eng): write canonicalizer once relevant traits are added. + return rawInitial, nil +} + +/* +* Canonicalizers +* +* These are responsible for converting either a user-specified config or a +* GCP API response to a standard format that can be used for difference checking. +* */ + +func canonicalizeRepositoryDesiredState(rawDesired, rawInitial *Repository, opts ...dcl.ApplyOption) (*Repository, error) { + + if rawInitial == nil { + // Since the initial state is empty, the desired state is all we have. + // We canonicalize the remaining nested objects with nil to pick up defaults. + + return rawDesired, nil + } + canonicalDesired := &Repository{} + if dcl.PartialSelfLinkToSelfLink(rawDesired.Name, rawInitial.Name) { + canonicalDesired.Name = rawInitial.Name + } else { + canonicalDesired.Name = rawDesired.Name + } + if dcl.StringCanonicalize(rawDesired.RemoteUri, rawInitial.RemoteUri) { + canonicalDesired.RemoteUri = rawInitial.RemoteUri + } else { + canonicalDesired.RemoteUri = rawDesired.RemoteUri + } + if dcl.IsZeroValue(rawDesired.Annotations) || (dcl.IsEmptyValueIndirect(rawDesired.Annotations) && dcl.IsEmptyValueIndirect(rawInitial.Annotations)) { + // Desired and initial values are equivalent, so set canonical desired value to initial value. + canonicalDesired.Annotations = rawInitial.Annotations + } else { + canonicalDesired.Annotations = rawDesired.Annotations + } + if dcl.NameToSelfLink(rawDesired.Project, rawInitial.Project) { + canonicalDesired.Project = rawInitial.Project + } else { + canonicalDesired.Project = rawDesired.Project + } + if dcl.NameToSelfLink(rawDesired.Location, rawInitial.Location) { + canonicalDesired.Location = rawInitial.Location + } else { + canonicalDesired.Location = rawDesired.Location + } + if dcl.NameToSelfLink(rawDesired.Connection, rawInitial.Connection) { + canonicalDesired.Connection = rawInitial.Connection + } else { + canonicalDesired.Connection = rawDesired.Connection + } + + return canonicalDesired, nil +} + +func canonicalizeRepositoryNewState(c *Client, rawNew, rawDesired *Repository) (*Repository, error) { + + if dcl.IsEmptyValueIndirect(rawNew.Name) && dcl.IsEmptyValueIndirect(rawDesired.Name) { + rawNew.Name = rawDesired.Name + } else { + if dcl.PartialSelfLinkToSelfLink(rawDesired.Name, rawNew.Name) { + rawNew.Name = rawDesired.Name + } + } + + if dcl.IsEmptyValueIndirect(rawNew.RemoteUri) && dcl.IsEmptyValueIndirect(rawDesired.RemoteUri) { + rawNew.RemoteUri = rawDesired.RemoteUri + } else { + if dcl.StringCanonicalize(rawDesired.RemoteUri, rawNew.RemoteUri) { + rawNew.RemoteUri = rawDesired.RemoteUri + } + } + + if dcl.IsEmptyValueIndirect(rawNew.CreateTime) && dcl.IsEmptyValueIndirect(rawDesired.CreateTime) { + rawNew.CreateTime = rawDesired.CreateTime + } else { + } + + if dcl.IsEmptyValueIndirect(rawNew.UpdateTime) && dcl.IsEmptyValueIndirect(rawDesired.UpdateTime) { + rawNew.UpdateTime = rawDesired.UpdateTime + } else { + } + + if dcl.IsEmptyValueIndirect(rawNew.Annotations) && dcl.IsEmptyValueIndirect(rawDesired.Annotations) { + rawNew.Annotations = rawDesired.Annotations + } else { + } + + if dcl.IsEmptyValueIndirect(rawNew.Etag) && dcl.IsEmptyValueIndirect(rawDesired.Etag) { + rawNew.Etag = rawDesired.Etag + } else { + if dcl.StringCanonicalize(rawDesired.Etag, rawNew.Etag) { + rawNew.Etag = rawDesired.Etag + } + } + + rawNew.Project = rawDesired.Project + + rawNew.Location = rawDesired.Location + + rawNew.Connection = rawDesired.Connection + + return rawNew, nil +} + +// The differ returns a list of diffs, along with a list of operations that should be taken +// to remedy them. Right now, it does not attempt to consolidate operations - if several +// fields can be fixed with a patch update, it will perform the patch several times. +// Diffs on some fields will be ignored if the `desired` state has an empty (nil) +// value. This empty value indicates that the user does not care about the state for +// the field. Empty fields on the actual object will cause diffs. +// TODO(magic-modules-eng): for efficiency in some resources, add batching. +func diffRepository(c *Client, desired, actual *Repository, opts ...dcl.ApplyOption) ([]*dcl.FieldDiff, error) { + if desired == nil || actual == nil { + return nil, fmt.Errorf("nil resource passed to diff - always a programming error: %#v, %#v", desired, actual) + } + + c.Config.Logger.Infof("Diff function called with desired state: %v", desired) + c.Config.Logger.Infof("Diff function called with actual state: %v", actual) + + var fn dcl.FieldName + var newDiffs []*dcl.FieldDiff + // New style diffs. + if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Name")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.RemoteUri, actual.RemoteUri, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("RemoteUri")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.CreateTime, actual.CreateTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("CreateTime")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.UpdateTime, actual.UpdateTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("UpdateTime")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.Annotations, actual.Annotations, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Annotations")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.Etag, actual.Etag, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Etag")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.Project, actual.Project, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Project")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.Location, actual.Location, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Location")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + if ds, err := dcl.Diff(desired.Connection, actual.Connection, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Connection")); len(ds) != 0 || err != nil { + if err != nil { + return nil, err + } + newDiffs = append(newDiffs, ds...) + } + + return newDiffs, nil +} + +// urlNormalized returns a copy of the resource struct with values normalized +// for URL substitutions. For instance, it converts long-form self-links to +// short-form so they can be substituted in. +func (r *Repository) urlNormalized() *Repository { + normalized := dcl.Copy(*r).(Repository) + normalized.Name = dcl.SelfLinkToName(r.Name) + normalized.RemoteUri = dcl.SelfLinkToName(r.RemoteUri) + normalized.Etag = dcl.SelfLinkToName(r.Etag) + normalized.Project = dcl.SelfLinkToName(r.Project) + normalized.Location = dcl.SelfLinkToName(r.Location) + normalized.Connection = dcl.SelfLinkToName(r.Connection) + return &normalized +} + +func (r *Repository) updateURL(userBasePath, updateName string) (string, error) { + return "", fmt.Errorf("unknown update name: %s", updateName) +} + +// marshal encodes the Repository resource into JSON for a Create request, and +// performs transformations from the resource schema to the API schema if +// necessary. +func (r *Repository) marshal(c *Client) ([]byte, error) { + m, err := expandRepository(c, r) + if err != nil { + return nil, fmt.Errorf("error marshalling Repository: %w", err) + } + + return json.Marshal(m) +} + +// unmarshalRepository decodes JSON responses into the Repository resource schema. +func unmarshalRepository(b []byte, c *Client, res *Repository) (*Repository, error) { + var m map[string]interface{} + if err := json.Unmarshal(b, &m); err != nil { + return nil, err + } + return unmarshalMapRepository(m, c, res) +} + +func unmarshalMapRepository(m map[string]interface{}, c *Client, res *Repository) (*Repository, error) { + + flattened := flattenRepository(c, m, res) + if flattened == nil { + return nil, fmt.Errorf("attempted to flatten empty json object") + } + return flattened, nil +} + +// expandRepository expands Repository into a JSON request object. +func expandRepository(c *Client, f *Repository) (map[string]interface{}, error) { + m := make(map[string]interface{}) + res := f + _ = res + if v, err := dcl.DeriveField("projects/%s/locations/%s/connections/%s/repositories/%s", f.Name, dcl.SelfLinkToName(f.Project), dcl.SelfLinkToName(f.Location), dcl.SelfLinkToName(f.Connection), dcl.SelfLinkToName(f.Name)); err != nil { + return nil, fmt.Errorf("error expanding Name into name: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + m["name"] = v + } + if v := f.RemoteUri; dcl.ValueShouldBeSent(v) { + m["remoteUri"] = v + } + if v := f.Annotations; dcl.ValueShouldBeSent(v) { + m["annotations"] = v + } + if v, err := dcl.EmptyValue(); err != nil { + return nil, fmt.Errorf("error expanding Project into project: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + m["project"] = v + } + if v, err := dcl.EmptyValue(); err != nil { + return nil, fmt.Errorf("error expanding Location into location: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + m["location"] = v + } + if v, err := dcl.EmptyValue(); err != nil { + return nil, fmt.Errorf("error expanding Connection into connection: %w", err) + } else if !dcl.IsEmptyValueIndirect(v) { + m["connection"] = v + } + + return m, nil +} + +// flattenRepository flattens Repository from a JSON request object into the +// Repository type. +func flattenRepository(c *Client, i interface{}, res *Repository) *Repository { + m, ok := i.(map[string]interface{}) + if !ok { + return nil + } + if len(m) == 0 { + return nil + } + + resultRes := &Repository{} + resultRes.Name = dcl.FlattenString(m["name"]) + resultRes.RemoteUri = dcl.FlattenString(m["remoteUri"]) + resultRes.CreateTime = dcl.FlattenString(m["createTime"]) + resultRes.UpdateTime = dcl.FlattenString(m["updateTime"]) + resultRes.Annotations = dcl.FlattenKeyValuePairs(m["annotations"]) + resultRes.Etag = dcl.FlattenString(m["etag"]) + resultRes.Project = dcl.FlattenString(m["project"]) + resultRes.Location = dcl.FlattenString(m["location"]) + resultRes.Connection = dcl.FlattenString(m["connection"]) + + return resultRes +} + +// This function returns a matcher that checks whether a serialized resource matches this resource +// in its parameters (as defined by the fields in a Get, which definitionally define resource +// identity). This is useful in extracting the element from a List call. +func (r *Repository) matcher(c *Client) func([]byte) bool { + return func(b []byte) bool { + cr, err := unmarshalRepository(b, c, r) + if err != nil { + c.Config.Logger.Warning("failed to unmarshal provided resource in matcher.") + return false + } + nr := r.urlNormalized() + ncr := cr.urlNormalized() + c.Config.Logger.Infof("looking for %v\nin %v", nr, ncr) + + if nr.Project == nil && ncr.Project == nil { + c.Config.Logger.Info("Both Project fields null - considering equal.") + } else if nr.Project == nil || ncr.Project == nil { + c.Config.Logger.Info("Only one Project field is null - considering unequal.") + return false + } else if *nr.Project != *ncr.Project { + return false + } + if nr.Location == nil && ncr.Location == nil { + c.Config.Logger.Info("Both Location fields null - considering equal.") + } else if nr.Location == nil || ncr.Location == nil { + c.Config.Logger.Info("Only one Location field is null - considering unequal.") + return false + } else if *nr.Location != *ncr.Location { + return false + } + if nr.Connection == nil && ncr.Connection == nil { + c.Config.Logger.Info("Both Connection fields null - considering equal.") + } else if nr.Connection == nil || ncr.Connection == nil { + c.Config.Logger.Info("Only one Connection field is null - considering unequal.") + return false + } else if *nr.Connection != *ncr.Connection { + return false + } + if nr.Name == nil && ncr.Name == nil { + c.Config.Logger.Info("Both Name fields null - considering equal.") + } else if nr.Name == nil || ncr.Name == nil { + c.Config.Logger.Info("Only one Name field is null - considering unequal.") + return false + } else if *nr.Name != *ncr.Name { + return false + } + return true + } +} + +type repositoryDiff struct { + // The diff should include one or the other of RequiresRecreate or UpdateOp. + RequiresRecreate bool + UpdateOp repositoryApiOperation +} + +func convertFieldDiffsToRepositoryDiffs(config *dcl.Config, fds []*dcl.FieldDiff, opts []dcl.ApplyOption) ([]repositoryDiff, error) { + opNamesToFieldDiffs := make(map[string][]*dcl.FieldDiff) + // Map each operation name to the field diffs associated with it. + for _, fd := range fds { + for _, ro := range fd.ResultingOperation { + if fieldDiffs, ok := opNamesToFieldDiffs[ro]; ok { + fieldDiffs = append(fieldDiffs, fd) + opNamesToFieldDiffs[ro] = fieldDiffs + } else { + config.Logger.Infof("%s required due to diff: %v", ro, fd) + opNamesToFieldDiffs[ro] = []*dcl.FieldDiff{fd} + } + } + } + var diffs []repositoryDiff + // For each operation name, create a repositoryDiff which contains the operation. + for opName, fieldDiffs := range opNamesToFieldDiffs { + diff := repositoryDiff{} + if opName == "Recreate" { + diff.RequiresRecreate = true + } else { + apiOp, err := convertOpNameToRepositoryApiOperation(opName, fieldDiffs, opts...) + if err != nil { + return diffs, err + } + diff.UpdateOp = apiOp + } + diffs = append(diffs, diff) + } + return diffs, nil +} + +func convertOpNameToRepositoryApiOperation(opName string, fieldDiffs []*dcl.FieldDiff, opts ...dcl.ApplyOption) (repositoryApiOperation, error) { + switch opName { + + default: + return nil, fmt.Errorf("no such operation with name: %v", opName) + } +} + +func extractRepositoryFields(r *Repository) error { + vProject, err := dcl.ValueFromRegexOnField("Project", r.Project, r.Connection, "projects/([a-z0-9A-Z-]*)/locations/.*") + if err != nil { + return err + } + r.Project = vProject + vLocation, err := dcl.ValueFromRegexOnField("Location", r.Location, r.Connection, "projects/.*/locations/([a-z0-9A-Z-]*)/connections/.*") + if err != nil { + return err + } + r.Location = vLocation + return nil +} + +func postReadExtractRepositoryFields(r *Repository) error { + return nil +} diff --git a/services/google/cloudbuildv2/alpha/repository_schema.go b/services/google/cloudbuildv2/alpha/repository_schema.go new file mode 100755 index 000000000..edae49499 --- /dev/null +++ b/services/google/cloudbuildv2/alpha/repository_schema.go @@ -0,0 +1,210 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +package alpha + +import ( + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" +) + +func DCLRepositorySchema() *dcl.Schema { + return &dcl.Schema{ + Info: &dcl.Info{ + Title: "Cloudbuildv2/Repository", + Description: "The Cloudbuildv2 Repository resource", + StructName: "Repository", + }, + Paths: &dcl.Paths{ + Get: &dcl.Path{ + Description: "The function used to get information about a Repository", + Parameters: []dcl.PathParameters{ + dcl.PathParameters{ + Name: "Repository", + Required: true, + Description: "A full instance of a Repository", + }, + }, + }, + Apply: &dcl.Path{ + Description: "The function used to apply information about a Repository", + Parameters: []dcl.PathParameters{ + dcl.PathParameters{ + Name: "Repository", + Required: true, + Description: "A full instance of a Repository", + }, + }, + }, + Delete: &dcl.Path{ + Description: "The function used to delete a Repository", + Parameters: []dcl.PathParameters{ + dcl.PathParameters{ + Name: "Repository", + Required: true, + Description: "A full instance of a Repository", + }, + }, + }, + DeleteAll: &dcl.Path{ + Description: "The function used to delete all Repository", + Parameters: []dcl.PathParameters{ + dcl.PathParameters{ + Name: "project", + Required: true, + Schema: &dcl.PathParametersSchema{ + Type: "string", + }, + }, + dcl.PathParameters{ + Name: "location", + Required: true, + Schema: &dcl.PathParametersSchema{ + Type: "string", + }, + }, + dcl.PathParameters{ + Name: "connection", + Required: true, + Schema: &dcl.PathParametersSchema{ + Type: "string", + }, + }, + }, + }, + List: &dcl.Path{ + Description: "The function used to list information about many Repository", + Parameters: []dcl.PathParameters{ + dcl.PathParameters{ + Name: "project", + Required: true, + Schema: &dcl.PathParametersSchema{ + Type: "string", + }, + }, + dcl.PathParameters{ + Name: "location", + Required: true, + Schema: &dcl.PathParametersSchema{ + Type: "string", + }, + }, + dcl.PathParameters{ + Name: "connection", + Required: true, + Schema: &dcl.PathParametersSchema{ + Type: "string", + }, + }, + }, + }, + }, + Components: &dcl.Components{ + Schemas: map[string]*dcl.Component{ + "Repository": &dcl.Component{ + Title: "Repository", + ID: "projects/{{project}}/locations/{{location}}/connections/{{connection}}/repositories/{{name}}", + ParentContainer: "project", + HasCreate: true, + SchemaProperty: dcl.Property{ + Type: "object", + Required: []string{ + "name", + "remoteUri", + "connection", + }, + Properties: map[string]*dcl.Property{ + "annotations": &dcl.Property{ + Type: "object", + AdditionalProperties: &dcl.Property{ + Type: "string", + }, + GoName: "Annotations", + Description: "Allows clients to store small amounts of arbitrary data.", + Immutable: true, + }, + "connection": &dcl.Property{ + Type: "string", + GoName: "Connection", + Description: "The connection for the resource", + Immutable: true, + ResourceReferences: []*dcl.PropertyResourceReference{ + &dcl.PropertyResourceReference{ + Resource: "Cloudbuildv2/Connection", + Field: "name", + Parent: true, + }, + }, + }, + "createTime": &dcl.Property{ + Type: "string", + Format: "date-time", + GoName: "CreateTime", + ReadOnly: true, + Description: "Output only. Server assigned timestamp for when the connection was created.", + Immutable: true, + }, + "etag": &dcl.Property{ + Type: "string", + GoName: "Etag", + ReadOnly: true, + Description: "This checksum is computed by the server based on the value of other fields, and may be sent on update and delete requests to ensure the client has an up-to-date value before proceeding.", + Immutable: true, + }, + "location": &dcl.Property{ + Type: "string", + GoName: "Location", + Description: "The location for the resource", + Immutable: true, + ExtractIfEmpty: true, + }, + "name": &dcl.Property{ + Type: "string", + GoName: "Name", + Description: "Name of the repository.", + Immutable: true, + }, + "project": &dcl.Property{ + Type: "string", + GoName: "Project", + Description: "The project for the resource", + Immutable: true, + ResourceReferences: []*dcl.PropertyResourceReference{ + &dcl.PropertyResourceReference{ + Resource: "Cloudresourcemanager/Project", + Field: "name", + Parent: true, + }, + }, + ExtractIfEmpty: true, + }, + "remoteUri": &dcl.Property{ + Type: "string", + GoName: "RemoteUri", + Description: "Required. Git Clone HTTPS URI.", + Immutable: true, + }, + "updateTime": &dcl.Property{ + Type: "string", + Format: "date-time", + GoName: "UpdateTime", + ReadOnly: true, + Description: "Output only. Server assigned timestamp for when the connection was updated.", + Immutable: true, + }, + }, + }, + }, + }, + }, + } +} diff --git a/services/google/cloudbuildv2/samples/ghe.repository.json b/services/google/cloudbuildv2/samples/ghe.repository.json new file mode 100755 index 000000000..5c8d75279 --- /dev/null +++ b/services/google/cloudbuildv2/samples/ghe.repository.json @@ -0,0 +1,10 @@ +{ + "project": "{{project}}", + "location": "{{region}}", + "connection": "projects/{{project}}/locations/{{region}}/connections/{{ref:ghe_complete.connection.json:name}}", + "name": "{{repository}}", + "remoteUri": "https://ghe.proctor-staging-test.com/proctorteam/regional_test.git", + "annotations": { + "some-key": "some-value" + } +} diff --git a/services/google/cloudbuildv2/samples/ghe_complete.connection.json b/services/google/cloudbuildv2/samples/ghe_complete.connection.json new file mode 100755 index 000000000..35352afe7 --- /dev/null +++ b/services/google/cloudbuildv2/samples/ghe_complete.connection.json @@ -0,0 +1,18 @@ +{ + "name": "{{connection}}", + "githubEnterpriseConfig": { + "hostUri": "https://ghe.proctor-staging-test.com", + "oauthClientIdSecretVersion":"projects/1033762898806/secrets/gcbrepos-dcltest-oauth-clientid/versions/1", + "oauthSecretSecretVersion":"projects/1033762898806/secrets/gcbrepos-dcltest-oauth-client-secret/versions/1", + "privateKeySecretVersion":"projects/1033762898806/secrets/gcbrepos-dcltest-private-key/versions/1", + "webhookSecretSecretVersion":"projects/1033762898806/secrets/gcbrepos-dcltest-webhook-secret/versions/1", + "appId":516, + "appSlug":"myapp", + "authorizerCredential": { + "oauthTokenSecretVersion": "projects/1033762898806/secrets/gcbrepos-dcltest-ghe-token/versions/1" + }, + "appInstallationId": 243 + }, + "project": "{{project}}", + "location": "{{region}}" +} diff --git a/services/google/cloudbuildv2/samples/ghe_complete_connection.yaml b/services/google/cloudbuildv2/samples/ghe_complete_connection.yaml new file mode 100755 index 000000000..3f53da3ab --- /dev/null +++ b/services/google/cloudbuildv2/samples/ghe_complete_connection.yaml @@ -0,0 +1,26 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: ghe_complete_connection +description: Creates a GitHub Enterprise connection. +type: connection +versions: +- alpha +resource: samples/ghe_complete.connection.json +variables: +- name: connection + type: resource_name +- name: project + type: project +- name: region + type: region diff --git a/services/google/cloudbuildv2/samples/ghe_connection.yaml b/services/google/cloudbuildv2/samples/ghe_connection.yaml new file mode 100755 index 000000000..68cb19156 --- /dev/null +++ b/services/google/cloudbuildv2/samples/ghe_connection.yaml @@ -0,0 +1,29 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: ghe_connection +description: Creates and updates a GitHub Enterprise connection. +type: connection +versions: +- alpha +resource: samples/ghe_initial.connection.json +updates: +- resource: samples/ghe_complete.connection.json + dependencies: [] +variables: +- name: connection + type: resource_name +- name: project + type: project +- name: region + type: region diff --git a/services/google/cloudbuildv2/samples/ghe_initial.connection.json b/services/google/cloudbuildv2/samples/ghe_initial.connection.json new file mode 100755 index 000000000..d9fa4a547 --- /dev/null +++ b/services/google/cloudbuildv2/samples/ghe_initial.connection.json @@ -0,0 +1,8 @@ +{ + "name": "{{connection}}", + "githubEnterpriseConfig": { + "hostUri": "https://ghe.proctor-staging-test.com" + }, + "project": "{{project}}", + "location": "{{region}}" +} diff --git a/services/google/cloudbuildv2/samples/ghe_priv.connection.json b/services/google/cloudbuildv2/samples/ghe_priv.connection.json new file mode 100755 index 000000000..b5e328d8e --- /dev/null +++ b/services/google/cloudbuildv2/samples/ghe_priv.connection.json @@ -0,0 +1,12 @@ +{ + "name": "{{connection}}", + "githubEnterpriseConfig": { + "hostUri": "https://ghe.proctor-private-ca.com", + "serviceDirectoryConfig": { + "service": "projects/1033762898806/locations/{{region}}/namespaces/ghe-sd/services/ghe-proctor-private-ca-com" + }, + "sslCa": "-----BEGIN CERTIFICATE-----\nMIIEXTCCA0WgAwIBAgIUANaBCc9j/xdKJHU0sgmv6yE2WCIwDQYJKoZIhvcNAQEL\nBQAwLDEUMBIGA1UEChMLUHJvY3RvciBFbmcxFDASBgNVBAMTC1Byb2N0b3ItZW5n\nMB4XDTIxMDcxNTIwMDcwMloXDTIyMDcxNTIwMDcwMVowADCCASIwDQYJKoZIhvcN\nAQEBBQADggEPADCCAQoCggEBAMVel7I88DkhwW445BNPBZvJNTV1AreHdz4um4U1\nop2+4L7JeNrUs5SRc0fzeOyOmA9ZzTDu9hBC7zj/sVNUy6cIQGCj32sr5SCAEIat\nnFZlzmVqJPT4J5NAaE37KO5347myTJEBrvpq8az4CtvX0yUzPK0gbUmaSaztVi4o\ndbJLKyv575xCLC/Hu6fIHBDH19eG1Ath9VpuAOkttRRoxu2VqijJZrGqaS+0o+OX\nrLi5HMtZbZjgQB4mc1g3ZDKX/gynxr+CDNaqNOqxuog33Tl5OcOk9DrR3MInaE7F\nyQFuH9mzF64AqOoTf7Tr/eAIz5XVt8K51nk+fSybEfKVwtMCAwEAAaOCAaEwggGd\nMA4GA1UdDwEB/wQEAwIFoDAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBQU/9dYyqMz\nv9rOMwPZcoIRMDAQCjAfBgNVHSMEGDAWgBTkQGTiCkLCmv/Awxdz5TAVRmyFfDCB\njQYIKwYBBQUHAQEEgYAwfjB8BggrBgEFBQcwAoZwaHR0cDovL3ByaXZhdGVjYS1j\nb250ZW50LTYxYWEyYzA5LTAwMDAtMjJjMi05ZjYyLWQ0ZjU0N2Y4MDIwMC5zdG9y\nYWdlLmdvb2dsZWFwaXMuY29tLzQxNGU4ZTJjZjU2ZWEyYzQxNmM0L2NhLmNydDAo\nBgNVHREBAf8EHjAcghpnaGUucHJvY3Rvci1wcml2YXRlLWNhLmNvbTCBggYDVR0f\nBHsweTB3oHWgc4ZxaHR0cDovL3ByaXZhdGVjYS1jb250ZW50LTYxYWEyYzA5LTAw\nMDAtMjJjMi05ZjYyLWQ0ZjU0N2Y4MDIwMC5zdG9yYWdlLmdvb2dsZWFwaXMuY29t\nLzQxNGU4ZTJjZjU2ZWEyYzQxNmM0L2NybC5jcmwwDQYJKoZIhvcNAQELBQADggEB\nABo6BQLEZZ+YNiDuv2sRvcxSopQQb7fZjqIA9XOA35pNSKay2SncODnNvfsdRnOp\ncoy25sQSIzWyJ9zWl8DZ6evoOu5csZ2PoFqx5LsIq37w+ZcwD6DM8Zm7JqASxmxx\nGqTF0nHC4Aw8q8aJBeRD3PsSkfN5Q3DP3nTDnLyd0l+yPIkHUbZMoiFHX3BkhCng\nG96mYy/y3t16ghfV9lZkXpD/JK5aiN0bTHCDRc69owgfYiAcAqzBJ9gfZ90MBgzv\ngTTQel5dHg49SYXfnUpTy0HdQLEcoggOF8Q8V+xKdKa6eVbrvjJrkEJmvIQI5iCR\nhNvKR25mx8JUopqEXmONmqU=\n-----END CERTIFICATE-----\n\n-----BEGIN CERTIFICATE-----\nMIIDSDCCAjCgAwIBAgITMwWN+62nLcgyLa7p+jD1K90g6TANBgkqhkiG9w0BAQsF\nADAsMRQwEgYDVQQKEwtQcm9jdG9yIEVuZzEUMBIGA1UEAxMLUHJvY3Rvci1lbmcw\nHhcNMjEwNzEyMTM1OTQ0WhcNMzEwNzEwMTM1OTQzWjAsMRQwEgYDVQQKEwtQcm9j\ndG9yIEVuZzEUMBIGA1UEAxMLUHJvY3Rvci1lbmcwggEiMA0GCSqGSIb3DQEBAQUA\nA4IBDwAwggEKAoIBAQCYqJP5Qt90jIbld2dtuUV/zIkBFsTe4fapJfhBji03xBpN\nO1Yxj/jPSZ67Kdeoy0lEwvc2hL5FQGhIjLMR0mzOyN4fk/DZiA/4tAVi7hJyqpUC\n71JSwp7MwXL1b26CSE1MhcoCqA/E4iZxfJfF/ef4lhmC24UEmu8FEbldoy+6OysB\nRu7dGDwicW5F9h7eSkpGAsCRdJHh65iUx/IH0C4Ux2UZRDZdj6wVbuVu9tb938xF\nyRuVClONoLSn/lwdzeV7hQmBSm8qmfgbNPbYRaNLz3hOpsT+27aDQp2/pxue8hFJ\nd7We3+Lr5O4IL45PBwhVEAiFZqde6d4qViNEB2qTAgMBAAGjYzBhMA4GA1UdDwEB\n/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTkQGTiCkLCmv/Awxdz\n5TAVRmyFfDAfBgNVHSMEGDAWgBTkQGTiCkLCmv/Awxdz5TAVRmyFfDANBgkqhkiG\n9w0BAQsFAAOCAQEAfy5BJsWdx0oWWi7SFg9MbryWjBVPJl93UqACgG0Cgh813O/x\nlDZQhGO/ZFVhHz/WgooE/HgVNoVJTubKLLzz+zCkOB0wa3GMqJDyFjhFmUtd/3VM\nZh0ZQ+JWYsAiZW4VITj5xEn/d/B3xCFWGC1vhvhptEJ8Fo2cE1yM2pzk08NqFWoY\n4FaH0sbxWgyCKwTmtcYDbnx4FYuddryGCIxbYizqUK1dr4DGKeHonhm/d234Ew3x\n3vIBPoHMOfBec/coP1xAf5o+F+MRMO/sQ3tTGgyOH18lwsHo9SmXCrmOwVQPKrEw\nm+A+5TjXLmenyaBhqXa0vkAZYJhWdROhWC0VTA==\n-----END CERTIFICATE-----\n" + }, + "project": "{{project}}", + "location": "{{region}}" +} diff --git a/services/google/cloudbuildv2/samples/ghe_priv_connection.yaml b/services/google/cloudbuildv2/samples/ghe_priv_connection.yaml new file mode 100755 index 000000000..ef21921cc --- /dev/null +++ b/services/google/cloudbuildv2/samples/ghe_priv_connection.yaml @@ -0,0 +1,26 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: ghe_priv_connection +description: Creates a connection to a private server using Service Directory. +type: connection +versions: +- alpha +resource: samples/ghe_priv.connection.json +variables: +- name: connection + type: resource_name +- name: project + type: project +- name: region + type: region diff --git a/services/google/cloudbuildv2/samples/ghe_priv_update_connection.yaml b/services/google/cloudbuildv2/samples/ghe_priv_update_connection.yaml new file mode 100755 index 000000000..26c4966fd --- /dev/null +++ b/services/google/cloudbuildv2/samples/ghe_priv_update_connection.yaml @@ -0,0 +1,29 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: ghe_priv_update_connection +description: Creates and updates a connection to a private server using Service Directory. +type: connection +versions: +- alpha +resource: samples/ghe_initial.connection.json +updates: +- resource: samples/ghe_priv.connection.json + dependencies: [] +variables: +- name: connection + type: resource_name +- name: project + type: project +- name: region + type: region diff --git a/services/google/cloudbuildv2/samples/ghe_repository.yaml b/services/google/cloudbuildv2/samples/ghe_repository.yaml new file mode 100755 index 000000000..02b073404 --- /dev/null +++ b/services/google/cloudbuildv2/samples/ghe_repository.yaml @@ -0,0 +1,30 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: ghe_repository +description: Creates a GitHub repository. +type: repository +versions: +- alpha +resource: samples/ghe.repository.json +dependencies: +- samples/ghe_complete.connection.json +variables: +- name: connection + type: resource_name +- name: project + type: project +- name: region + type: region +- name: repository + type: resource_name diff --git a/services/google/cloudbuildv2/samples/github.repository.json b/services/google/cloudbuildv2/samples/github.repository.json new file mode 100755 index 000000000..a6dff469d --- /dev/null +++ b/services/google/cloudbuildv2/samples/github.repository.json @@ -0,0 +1,5 @@ +{ + "connection": "projects/{{project}}/locations/{{region}}/connections/{{ref:github_update.connection.json:name}}", + "name": "{{repository}}", + "remoteUri": "https://github.com/proctor-eng/test2.git" +} diff --git a/services/google/cloudbuildv2/samples/github_connection.yaml b/services/google/cloudbuildv2/samples/github_connection.yaml new file mode 100755 index 000000000..a49af8d06 --- /dev/null +++ b/services/google/cloudbuildv2/samples/github_connection.yaml @@ -0,0 +1,29 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: github_connection +description: Creates and updates a GitHub connection. +type: connection +versions: +- alpha +resource: samples/github_initial.connection.json +updates: +- resource: samples/github_update.connection.json + dependencies: [] +variables: +- name: connection + type: resource_name +- name: project + type: project +- name: region + type: region diff --git a/services/google/cloudbuildv2/samples/github_initial.connection.json b/services/google/cloudbuildv2/samples/github_initial.connection.json new file mode 100755 index 000000000..d0cb68d54 --- /dev/null +++ b/services/google/cloudbuildv2/samples/github_initial.connection.json @@ -0,0 +1,13 @@ +{ + "name": "{{connection}}", + "githubConfig": { + "appInstallationId": 633612, + "authorizerCredential": { + "oauthTokenSecretVersion": "projects/1033762898806/secrets/gcbrepos-dcltest-github-token/versions/1" + } + }, + "project": "{{project}}", + "location": "{{region}}", + "annotations": {"somekey": "somevalue"}, + "disabled": true +} diff --git a/services/google/cloudbuildv2/samples/github_repository.yaml b/services/google/cloudbuildv2/samples/github_repository.yaml new file mode 100755 index 000000000..7e67ae509 --- /dev/null +++ b/services/google/cloudbuildv2/samples/github_repository.yaml @@ -0,0 +1,30 @@ +# Copyright 2022 Google LLC. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +name: github_repository +description: Creates a GitHub repository. +type: repository +versions: +- alpha +resource: samples/github.repository.json +dependencies: +- samples/github_update.connection.json +variables: +- name: connection + type: resource_name +- name: project + type: project +- name: region + type: region +- name: repository + type: resource_name diff --git a/services/google/cloudbuildv2/samples/github_update.connection.json b/services/google/cloudbuildv2/samples/github_update.connection.json new file mode 100755 index 000000000..9c092339c --- /dev/null +++ b/services/google/cloudbuildv2/samples/github_update.connection.json @@ -0,0 +1,16 @@ +{ + "name": "{{connection}}", + "githubConfig": { + "appInstallationId": 236578, + "authorizerCredential": { + "oauthTokenSecretVersion": "projects/1033762898806/secrets/gcbrepos-dcltest-github-token/versions/2" + } + }, + "project": "{{project}}", + "location": "{{region}}", + "annotations": { + "somekey": "somevalue", + "otherkey": "othervalue" + }, + "disabled": false +} diff --git a/unstructured/google/cloudbuildv2/alpha/connection.go b/unstructured/google/cloudbuildv2/alpha/connection.go new file mode 100755 index 000000000..f4459ed8b --- /dev/null +++ b/unstructured/google/cloudbuildv2/alpha/connection.go @@ -0,0 +1,538 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +package cloudbuildv2 + +import ( + "context" + "fmt" + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" + dclService "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudbuildv2/alpha" + "github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured" +) + +type Connection struct{} + +func ConnectionToUnstructured(r *dclService.Connection) *unstructured.Resource { + u := &unstructured.Resource{ + STV: unstructured.ServiceTypeVersion{ + Service: "cloudbuildv2", + Version: "alpha", + Type: "Connection", + }, + Object: make(map[string]interface{}), + } + if r.Annotations != nil { + rAnnotations := make(map[string]interface{}) + for k, v := range r.Annotations { + rAnnotations[k] = v + } + u.Object["annotations"] = rAnnotations + } + if r.CreateTime != nil { + u.Object["createTime"] = *r.CreateTime + } + if r.Disabled != nil { + u.Object["disabled"] = *r.Disabled + } + if r.Etag != nil { + u.Object["etag"] = *r.Etag + } + if r.GithubConfig != nil && r.GithubConfig != dclService.EmptyConnectionGithubConfig { + rGithubConfig := make(map[string]interface{}) + if r.GithubConfig.AppInstallationId != nil { + rGithubConfig["appInstallationId"] = *r.GithubConfig.AppInstallationId + } + if r.GithubConfig.AuthorizerCredential != nil && r.GithubConfig.AuthorizerCredential != dclService.EmptyConnectionGithubConfigAuthorizerCredential { + rGithubConfigAuthorizerCredential := make(map[string]interface{}) + if r.GithubConfig.AuthorizerCredential.OAuthTokenSecretVersion != nil { + rGithubConfigAuthorizerCredential["oauthTokenSecretVersion"] = *r.GithubConfig.AuthorizerCredential.OAuthTokenSecretVersion + } + if r.GithubConfig.AuthorizerCredential.Username != nil { + rGithubConfigAuthorizerCredential["username"] = *r.GithubConfig.AuthorizerCredential.Username + } + rGithubConfig["authorizerCredential"] = rGithubConfigAuthorizerCredential + } + u.Object["githubConfig"] = rGithubConfig + } + if r.GithubEnterpriseConfig != nil && r.GithubEnterpriseConfig != dclService.EmptyConnectionGithubEnterpriseConfig { + rGithubEnterpriseConfig := make(map[string]interface{}) + if r.GithubEnterpriseConfig.AppId != nil { + rGithubEnterpriseConfig["appId"] = *r.GithubEnterpriseConfig.AppId + } + if r.GithubEnterpriseConfig.AppInstallationId != nil { + rGithubEnterpriseConfig["appInstallationId"] = *r.GithubEnterpriseConfig.AppInstallationId + } + if r.GithubEnterpriseConfig.AppSlug != nil { + rGithubEnterpriseConfig["appSlug"] = *r.GithubEnterpriseConfig.AppSlug + } + if r.GithubEnterpriseConfig.AuthorizerCredential != nil && r.GithubEnterpriseConfig.AuthorizerCredential != dclService.EmptyConnectionGithubEnterpriseConfigAuthorizerCredential { + rGithubEnterpriseConfigAuthorizerCredential := make(map[string]interface{}) + if r.GithubEnterpriseConfig.AuthorizerCredential.OAuthTokenSecretVersion != nil { + rGithubEnterpriseConfigAuthorizerCredential["oauthTokenSecretVersion"] = *r.GithubEnterpriseConfig.AuthorizerCredential.OAuthTokenSecretVersion + } + if r.GithubEnterpriseConfig.AuthorizerCredential.Username != nil { + rGithubEnterpriseConfigAuthorizerCredential["username"] = *r.GithubEnterpriseConfig.AuthorizerCredential.Username + } + rGithubEnterpriseConfig["authorizerCredential"] = rGithubEnterpriseConfigAuthorizerCredential + } + if r.GithubEnterpriseConfig.HostUri != nil { + rGithubEnterpriseConfig["hostUri"] = *r.GithubEnterpriseConfig.HostUri + } + if r.GithubEnterpriseConfig.OAuthClientIdSecretVersion != nil { + rGithubEnterpriseConfig["oauthClientIdSecretVersion"] = *r.GithubEnterpriseConfig.OAuthClientIdSecretVersion + } + if r.GithubEnterpriseConfig.OAuthSecretSecretVersion != nil { + rGithubEnterpriseConfig["oauthSecretSecretVersion"] = *r.GithubEnterpriseConfig.OAuthSecretSecretVersion + } + if r.GithubEnterpriseConfig.PrivateKeySecretVersion != nil { + rGithubEnterpriseConfig["privateKeySecretVersion"] = *r.GithubEnterpriseConfig.PrivateKeySecretVersion + } + if r.GithubEnterpriseConfig.ServiceDirectoryConfig != nil && r.GithubEnterpriseConfig.ServiceDirectoryConfig != dclService.EmptyConnectionGithubEnterpriseConfigServiceDirectoryConfig { + rGithubEnterpriseConfigServiceDirectoryConfig := make(map[string]interface{}) + if r.GithubEnterpriseConfig.ServiceDirectoryConfig.Service != nil { + rGithubEnterpriseConfigServiceDirectoryConfig["service"] = *r.GithubEnterpriseConfig.ServiceDirectoryConfig.Service + } + rGithubEnterpriseConfig["serviceDirectoryConfig"] = rGithubEnterpriseConfigServiceDirectoryConfig + } + if r.GithubEnterpriseConfig.SslCa != nil { + rGithubEnterpriseConfig["sslCa"] = *r.GithubEnterpriseConfig.SslCa + } + if r.GithubEnterpriseConfig.WebhookSecretSecretVersion != nil { + rGithubEnterpriseConfig["webhookSecretSecretVersion"] = *r.GithubEnterpriseConfig.WebhookSecretSecretVersion + } + u.Object["githubEnterpriseConfig"] = rGithubEnterpriseConfig + } + if r.InstallationState != nil && r.InstallationState != dclService.EmptyConnectionInstallationState { + rInstallationState := make(map[string]interface{}) + if r.InstallationState.ActionUri != nil { + rInstallationState["actionUri"] = *r.InstallationState.ActionUri + } + if r.InstallationState.Message != nil { + rInstallationState["message"] = *r.InstallationState.Message + } + if r.InstallationState.Stage != nil { + rInstallationState["stage"] = string(*r.InstallationState.Stage) + } + u.Object["installationState"] = rInstallationState + } + if r.Location != nil { + u.Object["location"] = *r.Location + } + if r.Name != nil { + u.Object["name"] = *r.Name + } + if r.Project != nil { + u.Object["project"] = *r.Project + } + if r.Reconciling != nil { + u.Object["reconciling"] = *r.Reconciling + } + if r.UpdateTime != nil { + u.Object["updateTime"] = *r.UpdateTime + } + return u +} + +func UnstructuredToConnection(u *unstructured.Resource) (*dclService.Connection, error) { + r := &dclService.Connection{} + if _, ok := u.Object["annotations"]; ok { + if rAnnotations, ok := u.Object["annotations"].(map[string]interface{}); ok { + m := make(map[string]string) + for k, v := range rAnnotations { + if s, ok := v.(string); ok { + m[k] = s + } + } + r.Annotations = m + } else { + return nil, fmt.Errorf("r.Annotations: expected map[string]interface{}") + } + } + if _, ok := u.Object["createTime"]; ok { + if s, ok := u.Object["createTime"].(string); ok { + r.CreateTime = dcl.String(s) + } else { + return nil, fmt.Errorf("r.CreateTime: expected string") + } + } + if _, ok := u.Object["disabled"]; ok { + if b, ok := u.Object["disabled"].(bool); ok { + r.Disabled = dcl.Bool(b) + } else { + return nil, fmt.Errorf("r.Disabled: expected bool") + } + } + if _, ok := u.Object["etag"]; ok { + if s, ok := u.Object["etag"].(string); ok { + r.Etag = dcl.String(s) + } else { + return nil, fmt.Errorf("r.Etag: expected string") + } + } + if _, ok := u.Object["githubConfig"]; ok { + if rGithubConfig, ok := u.Object["githubConfig"].(map[string]interface{}); ok { + r.GithubConfig = &dclService.ConnectionGithubConfig{} + if _, ok := rGithubConfig["appInstallationId"]; ok { + if i, ok := rGithubConfig["appInstallationId"].(int64); ok { + r.GithubConfig.AppInstallationId = dcl.Int64(i) + } else { + return nil, fmt.Errorf("r.GithubConfig.AppInstallationId: expected int64") + } + } + if _, ok := rGithubConfig["authorizerCredential"]; ok { + if rGithubConfigAuthorizerCredential, ok := rGithubConfig["authorizerCredential"].(map[string]interface{}); ok { + r.GithubConfig.AuthorizerCredential = &dclService.ConnectionGithubConfigAuthorizerCredential{} + if _, ok := rGithubConfigAuthorizerCredential["oauthTokenSecretVersion"]; ok { + if s, ok := rGithubConfigAuthorizerCredential["oauthTokenSecretVersion"].(string); ok { + r.GithubConfig.AuthorizerCredential.OAuthTokenSecretVersion = dcl.String(s) + } else { + return nil, fmt.Errorf("r.GithubConfig.AuthorizerCredential.OAuthTokenSecretVersion: expected string") + } + } + if _, ok := rGithubConfigAuthorizerCredential["username"]; ok { + if s, ok := rGithubConfigAuthorizerCredential["username"].(string); ok { + r.GithubConfig.AuthorizerCredential.Username = dcl.String(s) + } else { + return nil, fmt.Errorf("r.GithubConfig.AuthorizerCredential.Username: expected string") + } + } + } else { + return nil, fmt.Errorf("r.GithubConfig.AuthorizerCredential: expected map[string]interface{}") + } + } + } else { + return nil, fmt.Errorf("r.GithubConfig: expected map[string]interface{}") + } + } + if _, ok := u.Object["githubEnterpriseConfig"]; ok { + if rGithubEnterpriseConfig, ok := u.Object["githubEnterpriseConfig"].(map[string]interface{}); ok { + r.GithubEnterpriseConfig = &dclService.ConnectionGithubEnterpriseConfig{} + if _, ok := rGithubEnterpriseConfig["appId"]; ok { + if i, ok := rGithubEnterpriseConfig["appId"].(int64); ok { + r.GithubEnterpriseConfig.AppId = dcl.Int64(i) + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.AppId: expected int64") + } + } + if _, ok := rGithubEnterpriseConfig["appInstallationId"]; ok { + if i, ok := rGithubEnterpriseConfig["appInstallationId"].(int64); ok { + r.GithubEnterpriseConfig.AppInstallationId = dcl.Int64(i) + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.AppInstallationId: expected int64") + } + } + if _, ok := rGithubEnterpriseConfig["appSlug"]; ok { + if s, ok := rGithubEnterpriseConfig["appSlug"].(string); ok { + r.GithubEnterpriseConfig.AppSlug = dcl.String(s) + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.AppSlug: expected string") + } + } + if _, ok := rGithubEnterpriseConfig["authorizerCredential"]; ok { + if rGithubEnterpriseConfigAuthorizerCredential, ok := rGithubEnterpriseConfig["authorizerCredential"].(map[string]interface{}); ok { + r.GithubEnterpriseConfig.AuthorizerCredential = &dclService.ConnectionGithubEnterpriseConfigAuthorizerCredential{} + if _, ok := rGithubEnterpriseConfigAuthorizerCredential["oauthTokenSecretVersion"]; ok { + if s, ok := rGithubEnterpriseConfigAuthorizerCredential["oauthTokenSecretVersion"].(string); ok { + r.GithubEnterpriseConfig.AuthorizerCredential.OAuthTokenSecretVersion = dcl.String(s) + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.AuthorizerCredential.OAuthTokenSecretVersion: expected string") + } + } + if _, ok := rGithubEnterpriseConfigAuthorizerCredential["username"]; ok { + if s, ok := rGithubEnterpriseConfigAuthorizerCredential["username"].(string); ok { + r.GithubEnterpriseConfig.AuthorizerCredential.Username = dcl.String(s) + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.AuthorizerCredential.Username: expected string") + } + } + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.AuthorizerCredential: expected map[string]interface{}") + } + } + if _, ok := rGithubEnterpriseConfig["hostUri"]; ok { + if s, ok := rGithubEnterpriseConfig["hostUri"].(string); ok { + r.GithubEnterpriseConfig.HostUri = dcl.String(s) + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.HostUri: expected string") + } + } + if _, ok := rGithubEnterpriseConfig["oauthClientIdSecretVersion"]; ok { + if s, ok := rGithubEnterpriseConfig["oauthClientIdSecretVersion"].(string); ok { + r.GithubEnterpriseConfig.OAuthClientIdSecretVersion = dcl.String(s) + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.OAuthClientIdSecretVersion: expected string") + } + } + if _, ok := rGithubEnterpriseConfig["oauthSecretSecretVersion"]; ok { + if s, ok := rGithubEnterpriseConfig["oauthSecretSecretVersion"].(string); ok { + r.GithubEnterpriseConfig.OAuthSecretSecretVersion = dcl.String(s) + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.OAuthSecretSecretVersion: expected string") + } + } + if _, ok := rGithubEnterpriseConfig["privateKeySecretVersion"]; ok { + if s, ok := rGithubEnterpriseConfig["privateKeySecretVersion"].(string); ok { + r.GithubEnterpriseConfig.PrivateKeySecretVersion = dcl.String(s) + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.PrivateKeySecretVersion: expected string") + } + } + if _, ok := rGithubEnterpriseConfig["serviceDirectoryConfig"]; ok { + if rGithubEnterpriseConfigServiceDirectoryConfig, ok := rGithubEnterpriseConfig["serviceDirectoryConfig"].(map[string]interface{}); ok { + r.GithubEnterpriseConfig.ServiceDirectoryConfig = &dclService.ConnectionGithubEnterpriseConfigServiceDirectoryConfig{} + if _, ok := rGithubEnterpriseConfigServiceDirectoryConfig["service"]; ok { + if s, ok := rGithubEnterpriseConfigServiceDirectoryConfig["service"].(string); ok { + r.GithubEnterpriseConfig.ServiceDirectoryConfig.Service = dcl.String(s) + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.ServiceDirectoryConfig.Service: expected string") + } + } + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.ServiceDirectoryConfig: expected map[string]interface{}") + } + } + if _, ok := rGithubEnterpriseConfig["sslCa"]; ok { + if s, ok := rGithubEnterpriseConfig["sslCa"].(string); ok { + r.GithubEnterpriseConfig.SslCa = dcl.String(s) + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.SslCa: expected string") + } + } + if _, ok := rGithubEnterpriseConfig["webhookSecretSecretVersion"]; ok { + if s, ok := rGithubEnterpriseConfig["webhookSecretSecretVersion"].(string); ok { + r.GithubEnterpriseConfig.WebhookSecretSecretVersion = dcl.String(s) + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig.WebhookSecretSecretVersion: expected string") + } + } + } else { + return nil, fmt.Errorf("r.GithubEnterpriseConfig: expected map[string]interface{}") + } + } + if _, ok := u.Object["installationState"]; ok { + if rInstallationState, ok := u.Object["installationState"].(map[string]interface{}); ok { + r.InstallationState = &dclService.ConnectionInstallationState{} + if _, ok := rInstallationState["actionUri"]; ok { + if s, ok := rInstallationState["actionUri"].(string); ok { + r.InstallationState.ActionUri = dcl.String(s) + } else { + return nil, fmt.Errorf("r.InstallationState.ActionUri: expected string") + } + } + if _, ok := rInstallationState["message"]; ok { + if s, ok := rInstallationState["message"].(string); ok { + r.InstallationState.Message = dcl.String(s) + } else { + return nil, fmt.Errorf("r.InstallationState.Message: expected string") + } + } + if _, ok := rInstallationState["stage"]; ok { + if s, ok := rInstallationState["stage"].(string); ok { + r.InstallationState.Stage = dclService.ConnectionInstallationStateStageEnumRef(s) + } else { + return nil, fmt.Errorf("r.InstallationState.Stage: expected string") + } + } + } else { + return nil, fmt.Errorf("r.InstallationState: expected map[string]interface{}") + } + } + if _, ok := u.Object["location"]; ok { + if s, ok := u.Object["location"].(string); ok { + r.Location = dcl.String(s) + } else { + return nil, fmt.Errorf("r.Location: expected string") + } + } + if _, ok := u.Object["name"]; ok { + if s, ok := u.Object["name"].(string); ok { + r.Name = dcl.String(s) + } else { + return nil, fmt.Errorf("r.Name: expected string") + } + } + if _, ok := u.Object["project"]; ok { + if s, ok := u.Object["project"].(string); ok { + r.Project = dcl.String(s) + } else { + return nil, fmt.Errorf("r.Project: expected string") + } + } + if _, ok := u.Object["reconciling"]; ok { + if b, ok := u.Object["reconciling"].(bool); ok { + r.Reconciling = dcl.Bool(b) + } else { + return nil, fmt.Errorf("r.Reconciling: expected bool") + } + } + if _, ok := u.Object["updateTime"]; ok { + if s, ok := u.Object["updateTime"].(string); ok { + r.UpdateTime = dcl.String(s) + } else { + return nil, fmt.Errorf("r.UpdateTime: expected string") + } + } + return r, nil +} + +func GetConnection(ctx context.Context, config *dcl.Config, u *unstructured.Resource) (*unstructured.Resource, error) { + c := dclService.NewClient(config) + r, err := UnstructuredToConnection(u) + if err != nil { + return nil, err + } + r, err = c.GetConnection(ctx, r) + if err != nil { + return nil, err + } + return ConnectionToUnstructured(r), nil +} + +func ListConnection(ctx context.Context, config *dcl.Config, project string, location string) ([]*unstructured.Resource, error) { + c := dclService.NewClient(config) + l, err := c.ListConnection(ctx, project, location) + if err != nil { + return nil, err + } + var resources []*unstructured.Resource + for { + for _, r := range l.Items { + resources = append(resources, ConnectionToUnstructured(r)) + } + if !l.HasNext() { + break + } + if err := l.Next(ctx, c); err != nil { + return nil, err + } + } + return resources, nil +} + +func ApplyConnection(ctx context.Context, config *dcl.Config, u *unstructured.Resource, opts ...dcl.ApplyOption) (*unstructured.Resource, error) { + c := dclService.NewClient(config) + r, err := UnstructuredToConnection(u) + if err != nil { + return nil, err + } + if ush := unstructured.FetchStateHint(opts); ush != nil { + sh, err := UnstructuredToConnection(ush) + if err != nil { + return nil, err + } + opts = append(opts, dcl.WithStateHint(sh)) + } + r, err = c.ApplyConnection(ctx, r, opts...) + if err != nil { + return nil, err + } + return ConnectionToUnstructured(r), nil +} + +func ConnectionHasDiff(ctx context.Context, config *dcl.Config, u *unstructured.Resource, opts ...dcl.ApplyOption) (bool, error) { + c := dclService.NewClient(config) + r, err := UnstructuredToConnection(u) + if err != nil { + return false, err + } + if ush := unstructured.FetchStateHint(opts); ush != nil { + sh, err := UnstructuredToConnection(ush) + if err != nil { + return false, err + } + opts = append(opts, dcl.WithStateHint(sh)) + } + opts = append(opts, dcl.WithLifecycleParam(dcl.BlockDestruction), dcl.WithLifecycleParam(dcl.BlockCreation), dcl.WithLifecycleParam(dcl.BlockModification)) + _, err = c.ApplyConnection(ctx, r, opts...) + if err != nil { + if _, ok := err.(dcl.ApplyInfeasibleError); ok { + return true, nil + } + return false, err + } + return false, nil +} + +func DeleteConnection(ctx context.Context, config *dcl.Config, u *unstructured.Resource) error { + c := dclService.NewClient(config) + r, err := UnstructuredToConnection(u) + if err != nil { + return err + } + return c.DeleteConnection(ctx, r) +} + +func ConnectionID(u *unstructured.Resource) (string, error) { + r, err := UnstructuredToConnection(u) + if err != nil { + return "", err + } + return r.ID() +} + +func (r *Connection) STV() unstructured.ServiceTypeVersion { + return unstructured.ServiceTypeVersion{ + "cloudbuildv2", + "Connection", + "alpha", + } +} + +func (r *Connection) SetPolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, member *unstructured.Resource) (*unstructured.Resource, error) { + return nil, unstructured.ErrNoSuchMethod +} + +func (r *Connection) GetPolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, role, member string) (*unstructured.Resource, error) { + return nil, unstructured.ErrNoSuchMethod +} + +func (r *Connection) DeletePolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, member *unstructured.Resource) error { + return unstructured.ErrNoSuchMethod +} + +func (r *Connection) SetPolicy(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, policy *unstructured.Resource) (*unstructured.Resource, error) { + return nil, unstructured.ErrNoSuchMethod +} + +func (r *Connection) SetPolicyWithEtag(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, policy *unstructured.Resource) (*unstructured.Resource, error) { + return nil, unstructured.ErrNoSuchMethod +} + +func (r *Connection) GetPolicy(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) (*unstructured.Resource, error) { + return nil, unstructured.ErrNoSuchMethod +} + +func (r *Connection) Get(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) (*unstructured.Resource, error) { + return GetConnection(ctx, config, resource) +} + +func (r *Connection) Apply(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, opts ...dcl.ApplyOption) (*unstructured.Resource, error) { + return ApplyConnection(ctx, config, resource, opts...) +} + +func (r *Connection) HasDiff(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, opts ...dcl.ApplyOption) (bool, error) { + return ConnectionHasDiff(ctx, config, resource, opts...) +} + +func (r *Connection) Delete(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) error { + return DeleteConnection(ctx, config, resource) +} + +func (r *Connection) ID(resource *unstructured.Resource) (string, error) { + return ConnectionID(resource) +} + +func init() { + unstructured.Register(&Connection{}) +} diff --git a/unstructured/google/cloudbuildv2/alpha/repository.go b/unstructured/google/cloudbuildv2/alpha/repository.go new file mode 100755 index 000000000..518d06d06 --- /dev/null +++ b/unstructured/google/cloudbuildv2/alpha/repository.go @@ -0,0 +1,292 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +package cloudbuildv2 + +import ( + "context" + "fmt" + "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" + dclService "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudbuildv2/alpha" + "github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured" +) + +type Repository struct{} + +func RepositoryToUnstructured(r *dclService.Repository) *unstructured.Resource { + u := &unstructured.Resource{ + STV: unstructured.ServiceTypeVersion{ + Service: "cloudbuildv2", + Version: "alpha", + Type: "Repository", + }, + Object: make(map[string]interface{}), + } + if r.Annotations != nil { + rAnnotations := make(map[string]interface{}) + for k, v := range r.Annotations { + rAnnotations[k] = v + } + u.Object["annotations"] = rAnnotations + } + if r.Connection != nil { + u.Object["connection"] = *r.Connection + } + if r.CreateTime != nil { + u.Object["createTime"] = *r.CreateTime + } + if r.Etag != nil { + u.Object["etag"] = *r.Etag + } + if r.Location != nil { + u.Object["location"] = *r.Location + } + if r.Name != nil { + u.Object["name"] = *r.Name + } + if r.Project != nil { + u.Object["project"] = *r.Project + } + if r.RemoteUri != nil { + u.Object["remoteUri"] = *r.RemoteUri + } + if r.UpdateTime != nil { + u.Object["updateTime"] = *r.UpdateTime + } + return u +} + +func UnstructuredToRepository(u *unstructured.Resource) (*dclService.Repository, error) { + r := &dclService.Repository{} + if _, ok := u.Object["annotations"]; ok { + if rAnnotations, ok := u.Object["annotations"].(map[string]interface{}); ok { + m := make(map[string]string) + for k, v := range rAnnotations { + if s, ok := v.(string); ok { + m[k] = s + } + } + r.Annotations = m + } else { + return nil, fmt.Errorf("r.Annotations: expected map[string]interface{}") + } + } + if _, ok := u.Object["connection"]; ok { + if s, ok := u.Object["connection"].(string); ok { + r.Connection = dcl.String(s) + } else { + return nil, fmt.Errorf("r.Connection: expected string") + } + } + if _, ok := u.Object["createTime"]; ok { + if s, ok := u.Object["createTime"].(string); ok { + r.CreateTime = dcl.String(s) + } else { + return nil, fmt.Errorf("r.CreateTime: expected string") + } + } + if _, ok := u.Object["etag"]; ok { + if s, ok := u.Object["etag"].(string); ok { + r.Etag = dcl.String(s) + } else { + return nil, fmt.Errorf("r.Etag: expected string") + } + } + if _, ok := u.Object["location"]; ok { + if s, ok := u.Object["location"].(string); ok { + r.Location = dcl.String(s) + } else { + return nil, fmt.Errorf("r.Location: expected string") + } + } + if _, ok := u.Object["name"]; ok { + if s, ok := u.Object["name"].(string); ok { + r.Name = dcl.String(s) + } else { + return nil, fmt.Errorf("r.Name: expected string") + } + } + if _, ok := u.Object["project"]; ok { + if s, ok := u.Object["project"].(string); ok { + r.Project = dcl.String(s) + } else { + return nil, fmt.Errorf("r.Project: expected string") + } + } + if _, ok := u.Object["remoteUri"]; ok { + if s, ok := u.Object["remoteUri"].(string); ok { + r.RemoteUri = dcl.String(s) + } else { + return nil, fmt.Errorf("r.RemoteUri: expected string") + } + } + if _, ok := u.Object["updateTime"]; ok { + if s, ok := u.Object["updateTime"].(string); ok { + r.UpdateTime = dcl.String(s) + } else { + return nil, fmt.Errorf("r.UpdateTime: expected string") + } + } + return r, nil +} + +func GetRepository(ctx context.Context, config *dcl.Config, u *unstructured.Resource) (*unstructured.Resource, error) { + c := dclService.NewClient(config) + r, err := UnstructuredToRepository(u) + if err != nil { + return nil, err + } + r, err = c.GetRepository(ctx, r) + if err != nil { + return nil, err + } + return RepositoryToUnstructured(r), nil +} + +func ListRepository(ctx context.Context, config *dcl.Config, project string, location string, connection string) ([]*unstructured.Resource, error) { + c := dclService.NewClient(config) + l, err := c.ListRepository(ctx, project, location, connection) + if err != nil { + return nil, err + } + var resources []*unstructured.Resource + for { + for _, r := range l.Items { + resources = append(resources, RepositoryToUnstructured(r)) + } + if !l.HasNext() { + break + } + if err := l.Next(ctx, c); err != nil { + return nil, err + } + } + return resources, nil +} + +func ApplyRepository(ctx context.Context, config *dcl.Config, u *unstructured.Resource, opts ...dcl.ApplyOption) (*unstructured.Resource, error) { + c := dclService.NewClient(config) + r, err := UnstructuredToRepository(u) + if err != nil { + return nil, err + } + if ush := unstructured.FetchStateHint(opts); ush != nil { + sh, err := UnstructuredToRepository(ush) + if err != nil { + return nil, err + } + opts = append(opts, dcl.WithStateHint(sh)) + } + r, err = c.ApplyRepository(ctx, r, opts...) + if err != nil { + return nil, err + } + return RepositoryToUnstructured(r), nil +} + +func RepositoryHasDiff(ctx context.Context, config *dcl.Config, u *unstructured.Resource, opts ...dcl.ApplyOption) (bool, error) { + c := dclService.NewClient(config) + r, err := UnstructuredToRepository(u) + if err != nil { + return false, err + } + if ush := unstructured.FetchStateHint(opts); ush != nil { + sh, err := UnstructuredToRepository(ush) + if err != nil { + return false, err + } + opts = append(opts, dcl.WithStateHint(sh)) + } + opts = append(opts, dcl.WithLifecycleParam(dcl.BlockDestruction), dcl.WithLifecycleParam(dcl.BlockCreation), dcl.WithLifecycleParam(dcl.BlockModification)) + _, err = c.ApplyRepository(ctx, r, opts...) + if err != nil { + if _, ok := err.(dcl.ApplyInfeasibleError); ok { + return true, nil + } + return false, err + } + return false, nil +} + +func DeleteRepository(ctx context.Context, config *dcl.Config, u *unstructured.Resource) error { + c := dclService.NewClient(config) + r, err := UnstructuredToRepository(u) + if err != nil { + return err + } + return c.DeleteRepository(ctx, r) +} + +func RepositoryID(u *unstructured.Resource) (string, error) { + r, err := UnstructuredToRepository(u) + if err != nil { + return "", err + } + return r.ID() +} + +func (r *Repository) STV() unstructured.ServiceTypeVersion { + return unstructured.ServiceTypeVersion{ + "cloudbuildv2", + "Repository", + "alpha", + } +} + +func (r *Repository) SetPolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, member *unstructured.Resource) (*unstructured.Resource, error) { + return nil, unstructured.ErrNoSuchMethod +} + +func (r *Repository) GetPolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, role, member string) (*unstructured.Resource, error) { + return nil, unstructured.ErrNoSuchMethod +} + +func (r *Repository) DeletePolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, member *unstructured.Resource) error { + return unstructured.ErrNoSuchMethod +} + +func (r *Repository) SetPolicy(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, policy *unstructured.Resource) (*unstructured.Resource, error) { + return nil, unstructured.ErrNoSuchMethod +} + +func (r *Repository) SetPolicyWithEtag(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, policy *unstructured.Resource) (*unstructured.Resource, error) { + return nil, unstructured.ErrNoSuchMethod +} + +func (r *Repository) GetPolicy(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) (*unstructured.Resource, error) { + return nil, unstructured.ErrNoSuchMethod +} + +func (r *Repository) Get(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) (*unstructured.Resource, error) { + return GetRepository(ctx, config, resource) +} + +func (r *Repository) Apply(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, opts ...dcl.ApplyOption) (*unstructured.Resource, error) { + return ApplyRepository(ctx, config, resource, opts...) +} + +func (r *Repository) HasDiff(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, opts ...dcl.ApplyOption) (bool, error) { + return RepositoryHasDiff(ctx, config, resource, opts...) +} + +func (r *Repository) Delete(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) error { + return DeleteRepository(ctx, config, resource) +} + +func (r *Repository) ID(resource *unstructured.Resource) (string, error) { + return RepositoryID(resource) +} + +func init() { + unstructured.Register(&Repository{}) +} diff --git a/unstructured/google/imports.go b/unstructured/google/imports.go index c72e36fd7..881d885b6 100755 --- a/unstructured/google/imports.go +++ b/unstructured/google/imports.go @@ -38,6 +38,7 @@ import ( _ "github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured/google/cloudbuild" _ "github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured/google/cloudbuild/alpha" _ "github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured/google/cloudbuild/beta" + _ "github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured/google/cloudbuildv2/alpha" _ "github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured/google/clouddeploy" _ "github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured/google/clouddeploy/alpha" _ "github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured/google/clouddeploy/beta"