feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 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.
"""The command group for Google Cloud Build."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import transforms
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Triggers(base.Group):
"""Create and manage build triggers for Google Cloud Build."""
category = base.CI_CD_CATEGORY
@staticmethod
def Args(parser):
parser.display_info.AddTransforms(transforms.GetTransforms())

View File

@@ -0,0 +1,28 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 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.
"""Command group for managing Google Cloud Build trigger configurations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class Config(base.Group):
"""Manage Google Cloud Build trigger configurations."""
category = base.CI_CD_CATEGORY

View File

@@ -0,0 +1,38 @@
release_tracks: [ALPHA]
command_type: CONFIG_EXPORT
help_text:
brief: Export the configuration for a Cloud Build trigger.
description: |
*{command}* exports the configuration for a Cloud Build trigger.
Trigger configurations can be exported in
Kubernetes Resource Model (krm) or Terraform HCL formats. The
default format is `krm`.
Specifying `--all` allows you to export the configurations for all
triggers within the project.
Specifying `--path` allows you to export the configuration(s) to
a local directory.
examples: |
To export the configuration for a trigger, run:
$ {command} my-trigger
To export the configuration for a trigger to a file, run:
$ {command} my-trigger --path=/path/to/dir/
To export the configuration for a trigger in Terraform
HCL format, run:
$ {command} my-trigger --resource-format=terraform
To export the configurations for all triggers within a
project, run:
$ {command} --all
arguments:
resource:
help_text: Trigger to export the configuration for.
spec: !REF googlecloudsdk.command_lib.cloudbuild.resources:trigger

View File

@@ -0,0 +1,34 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 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.
"""The command group for Google Cloud Build."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import transforms
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class TriggerCreate(base.Group):
"""Create build triggers for Google Cloud Build."""
category = base.CI_CD_CATEGORY
@staticmethod
def Args(parser):
parser.display_info.AddTransforms(transforms.GetTransforms())

View File

@@ -0,0 +1,172 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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.
"""Create Bitbucket Cloud trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateBitbuckeCloud(base.CreateCommand):
"""Create a build trigger for a 2nd-gen Bitbucket Cloud repository."""
detailed_help = {
'EXAMPLES': """\
To create a push trigger with a 2nd-gen repository for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/repositories/myrepo" --branch-pattern=".*" --build-config="cloudbuild.yaml" --region=us-central1
To create a pull request trigger with a 2nd-gen repository for main:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/repositories/myrepo" --build-config="cloudbuild.yaml" --pull-request-pattern="^main$" --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
flag_config.add_argument(
'--repository',
help=(
'Repository resource (2nd gen) to use, in the format'
' "projects/*/locations/*/connections/*/repositories/*".'
),
)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
Regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""",
)
trigger_utils.AddCommentControlArg(pr_config)
trigger_utils.AddBuildConfigArgs(flag_config, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.repositoryEventConfig = messages.RepositoryEventConfig(
repository=args.repository
)
cfg = trigger.repositoryEventConfig
if args.pull_request_pattern:
cfg.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern
)
if args.comment_control:
cfg.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
cfg.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern
)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, '')
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some values that we want to print later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location,
).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger
)
)
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
},
)
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,172 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""Create Bitbucket Data Center trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateBitbucketDataCenter(base.CreateCommand):
"""Create a build trigger for a 2nd-gen Bitbucket Data Center repository."""
detailed_help = {
'EXAMPLES': """\
To create a push trigger with a 2nd-gen repository for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/repositories/myrepo" --branch-pattern=".*" --build-config="cloudbuild.yaml" --region=us-central1
To create a pull request trigger with a 2nd-gen repository for main:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/repositories/myrepo" --build-config="cloudbuild.yaml" --pull-request-pattern="^main$" --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
flag_config.add_argument(
'--repository',
help=(
'Repository resource (2nd gen) to use, in the format'
' "projects/*/locations/*/connections/*/repositories/*".'
),
)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
Regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""",
)
trigger_utils.AddCommentControlArg(pr_config)
trigger_utils.AddBuildConfigArgs(flag_config, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.repositoryEventConfig = messages.RepositoryEventConfig(
repository=args.repository
)
cfg = trigger.repositoryEventConfig
if args.pull_request_pattern:
cfg.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern
)
if args.comment_control:
cfg.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
cfg.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern
)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, '')
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some values that we want to print later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location,
).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger
)
)
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
},
)
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,177 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 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.
"""Create Bitbucket Server trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateBitbucketServer(base.CreateCommand):
"""Create a build trigger for a Bitbucket Server repository."""
detailed_help = {
'EXAMPLES':
"""\
To create a push trigger for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --project-key="GoogleCloudPlatform" --repo-slug="cloud-builders" --bitbucket-server-config-resource="projects/1234/locations/global/bitbucketServerConfigs/5678" --branch-pattern=".*" --build-config="cloudbuild.yaml"
To create a pull request trigger for main:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --project-key="GoogleCloudPlatform" --repo-slug="cloud-builders" --bitbucket-server-config-resource="projects/1234/locations/global/bitbucketServerConfigs/5678" --pull-request-pattern="^main$" --build-config="cloudbuild.yaml"
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
flag_config.add_argument(
'--repo-slug', help='Bitbucket Server repository slug.', required=True)
flag_config.add_argument(
'--project-key', help='Bitbucket Server project key.', required=True)
flag_config.add_argument(
'--bitbucket-server-config-resource',
help='Bitbucket Server config resource name.',
required=True)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
Regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""")
trigger_utils.AddCommentControlArg(pr_config)
trigger_utils.AddBuildConfigArgs(flag_config)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
project = properties.VALUES.core.project.Get(required=True)
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
# Bitbucket Server config
bbs = messages.BitbucketServerTriggerConfig(
repoSlug=args.repo_slug,
projectKey=args.project_key,
bitbucketServerConfigResource=args.bitbucket_server_config_resource,
)
if args.pull_request_pattern:
bbs.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern
)
if args.comment_control:
bbs.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
bbs.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern
)
trigger.bitbucketServerTriggerConfig = bbs
default_image = 'gcr.io/%s/bitbucketserver-%s/%s:$COMMIT_SHA' % (
project,
args.project_key,
args.repo_slug,
)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, default_image)
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,143 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 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.
"""Create Cloud Source Repositories trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.source import resource_args as repo_resource
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.command_lib.util.concepts import presentation_specs
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateCSR(base.CreateCommand):
"""Create a build trigger from a Cloud Source Repository."""
detailed_help = {
'EXAMPLES':
"""\
To create a push trigger for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repo="my-repo" --branch-pattern=".*" --build-config="cloudbuild.yaml"
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
repo_spec = presentation_specs.ResourcePresentationSpec(
'--repo', # This defines how the "anchor" or leaf argument is named.
repo_resource.GetRepoResourceSpec(),
'Cloud Source Repository.',
required=True,
prefixes=False)
concept_parsers.ConceptParser([repo_spec]).AddToParser(flag_config)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
trigger_utils.AddBuildConfigArgs(flag_config)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
repo_ref = args.CONCEPTS.repo.Parse()
repo = repo_ref.reposId
trigger = messages.BuildTrigger(
name=args.name,
description=args.description,
serviceAccount=args.service_account,
triggerTemplate=messages.RepoSource(
repoName=repo,
branchName=args.branch_pattern,
tagName=args.tag_pattern,
),
)
trigger_utils.ParseRequireApproval(trigger, args, messages)
# Build Config
project = properties.VALUES.core.project.Get(required=True)
default_image = 'gcr.io/%s/%s:$COMMIT_SHA' % (project, repo)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, default_image)
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
client = cloudbuild_util.GetClientInstance()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,173 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 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.
"""Create Developer Connect trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class CreateDeveloperConnect(base.CreateCommand):
"""Create a build trigger for a Developer Connect repository."""
detailed_help = {
'EXAMPLES': """\
To create a push trigger with a DC repository for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --git-repository-link="projects/1234/locations/us-central1/connections/myconn/gitRepositoryLinks/mylink" --branch-pattern=".*" --build-config="cloudbuild.yaml" --region=us-central1
To create a pull request trigger with a DC repository for main:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/gitRepositoryLinks/mylink" --build-config="cloudbuild.yaml" --pull-request-pattern="^main$" --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
flag_config.add_argument(
'--git-repository-link',
help=(
'Developer Connect resource to use, in the format'
' "projects/*/locations/*/connections/*/gitRepositoryLinks/*".'
),
)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
Regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""",
)
trigger_utils.AddCommentControlArg(pr_config)
trigger_utils.AddBuildConfigArgs(flag_config, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.developerConnectEventConfig = messages.DeveloperConnectEventConfig(
gitRepositoryLink=args.git_repository_link
)
cfg = trigger.developerConnectEventConfig
if args.pull_request_pattern:
cfg.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern
)
if args.comment_control:
cfg.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
cfg.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern
)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, '')
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some values that we want to print later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location,
).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger
)
)
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
},
)
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,204 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 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.
"""Create GitHub trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateGitHub(base.CreateCommand):
"""Create a build trigger for a GitHub repository."""
detailed_help = {
'EXAMPLES':
"""\
To create a push trigger with a 1st-gen repository for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repo-owner="GoogleCloudPlatform" --repo-name="cloud-builders" --branch-pattern=".*" --build-config="cloudbuild.yaml"
To create a pull request trigger with a 1st-gen repository for master:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repo-owner="GoogleCloudPlatform" --repo-name="cloud-builders" --pull-request-pattern="^master$" --build-config="cloudbuild.yaml"
To create a pull request trigger with a 2nd gen repository for master:
$ {command} --name="my-trigger" --repository=projects/my-project/locations/us-central1/connections/my-conn/repositories/my-repo --pull-request-pattern="^master$" --build-config="cloudbuild.yaml" --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
gen_config = flag_config.add_mutually_exclusive_group(required=True)
gen_config.add_argument(
'--repository',
help=("""\
Repository resource (2nd gen) to use, in the format
"projects/*/locations/*/connections/*/repositories/*".
"""),
)
v1_config = gen_config.add_argument_group(
help='1st-gen repository settings.')
v1_config.add_argument(
'--repo-owner',
help='Owner of the GitHub Repository (1st gen).',
required=True)
v1_config.add_argument(
'--repo-name',
help='Name of the GitHub Repository (1st gen).',
required=True)
v1_config.add_argument(
'--enterprise-config',
help="""\
Resource name of the GitHub Enterprise config that should be applied to this
installation.
For example: "projects/{$project_id}/locations/{$location_id}/githubEnterpriseConfigs/{$config_id}
""")
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
A regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""")
trigger_utils.AddCommentControlArg(pr_config)
trigger_utils.AddBuildConfigArgs(flag_config)
trigger_utils.AddRepoEventArgs(flag_config)
trigger_utils.AddIncludeLogsArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
project = properties.VALUES.core.project.Get(required=True)
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
if args.repo_owner and args.repo_name: # 1st-gen GitHub config
trigger.github = messages.GitHubEventsConfig(
owner=args.repo_owner,
name=args.repo_name,
enterpriseConfigResourceName=args.enterprise_config)
rcfg = trigger.github
else: # 2nd-gen (Repos API) config
trigger.repositoryEventConfig = messages.RepositoryEventConfig(
repository=args.repository)
rcfg = trigger.repositoryEventConfig
if args.pull_request_pattern:
rcfg.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern)
if args.comment_control:
rcfg.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
rcfg.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern)
default_image = 'gcr.io/%s/github.com/%s/%s:$COMMIT_SHA' % (
project, args.repo_owner, args.repo_name)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, default_image)
trigger_utils.ParseRepoEventArgs(trigger, args)
trigger_utils.ParseIncludeLogsWithStatus(trigger, args, messages)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,167 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""Create GitLab trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateGitLab(base.CreateCommand):
"""Create a build trigger for a 2nd-gen GitLab repository."""
detailed_help = {
'EXAMPLES': """\
To create a push trigger with a 2nd-gen repository for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/repositories/myrepo" --branch-pattern=".*" --build-config="cloudbuild.yaml" --region=us-central1
To create a pull request trigger with a 2nd-gen repository for main:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository="projects/1234/locations/us-central1/connections/myconn/repositories/myrepo" --build-config="cloudbuild.yaml" --pull-request-pattern="^main$" --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
flag_config = trigger_utils.AddGitLabEnterpriseTriggerArgs(parser)
flag_config.add_argument(
'--repository',
help=(
'Repository resource (2nd gen) to use, in the format'
' "projects/*/locations/*/connections/*/repositories/*".'
),
)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
Regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""")
trigger_utils.AddCommentControlArg(pr_config)
trigger_utils.AddBuildConfigArgs(flag_config, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.repositoryEventConfig = messages.RepositoryEventConfig(
repository=args.repository
)
cfg = trigger.repositoryEventConfig
if args.pull_request_pattern:
cfg.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern
)
if args.comment_control:
cfg.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
cfg.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern
)
trigger_utils.ParseBuildConfigArgs(trigger, args, messages, '')
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some values that we want to print later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,131 @@
# -*- coding: utf-8 -*- #
# 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.
"""Create manual trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateManual(base.CreateCommand):
"""Create a build trigger with a manual trigger event."""
detailed_help = {
'EXAMPLES':
"""\
To create a manual trigger that builds off branch `my-branch` in a GitHub repository named `my-repo`:
$ {command} --name=my-manual-trigger --build-config=cloudbuild.yaml --repo=https://www.github.com/owner/repo --repo-type=GITHUB --branch=my-branch
To create a manual trigger that builds off branch `my-branch` in a 2nd-gen GitHub repository resource:
$ {command} --name=my-manual-trigger --build-config=cloudbuild.yaml --repository=projects/my-proj/locations/us-west1/connections/my-conn/repositories/my-repo --branch=my-branch
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
trigger_utils.AddBuildConfigArgs(flag_config)
trigger_utils.AddGitRepoSource(flag_config)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The newly created trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = messages.BuildTrigger()
if args.trigger_config:
trigger = cloudbuild_util.LoadMessageFromPath(
path=args.trigger_config,
msg_type=messages.BuildTrigger,
msg_friendly_name='build trigger config',
skip_camel_case=['substitutions'])
else:
trigger = ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger
def ParseTriggerFromFlags(args):
"""Parse arguments into a BuildTrigger proto.
Args:
args: An argparse.Namespace. All the arguments that were provided to this
command invocation.
Returns:
A BuildTrigger proto object.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.name = args.name
# Build Config
project = properties.VALUES.core.project.Get(required=True)
default_image = 'gcr.io/%s/gcb-%s:$COMMIT_SHA' % (project, args.name)
trigger_utils.ParseBuildConfigArgs(
trigger, args, messages, default_image, need_repo=True)
return trigger

View File

@@ -0,0 +1,139 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 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.
"""Create Pub/Sub trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreatePubSub(base.CreateCommand):
"""Create a build trigger with a Pub/Sub trigger event."""
detailed_help = {
'EXAMPLES':
"""\
To create a Pub/Sub trigger that listens to topic `my-topic` and builds off branch `my-branch` in a GitHub repository named `my-repo`:
$ {command} --name=my-pubsub-trigger --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --topic=projects/my-project/topics/my-topic --repo=https://www.github.com/owner/repo --repo-type=GITHUB --branch=my-branch
To create a Pub/Sub trigger that listens to topic `my-topic` and builds off branch `my-branch` in a 2nd-gen GitHub repository resource:
$ {command} --name=my-pubsub-trigger --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository=projects/my-proj/locations/us-west1/connections/my-conn/repositories/my-repo --branch=my-branch
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
flag_config.add_argument(
'--topic',
help='The topic to which this trigger should subscribe.',
required=True)
trigger_utils.AddBuildConfigArgs(flag_config)
trigger_utils.AddGitRepoSource(flag_config)
trigger_utils.AddFilterArg(flag_config)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The newly created trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = messages.BuildTrigger()
if args.trigger_config:
trigger = cloudbuild_util.LoadMessageFromPath(
path=args.trigger_config,
msg_type=messages.BuildTrigger,
msg_friendly_name='build trigger config',
skip_camel_case=['substitutions'])
else:
trigger = ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger
def ParseTriggerFromFlags(args):
"""Parse arguments into a BuildTrigger proto.
Args:
args: An argparse.Namespace. All the arguments that were provided to this
command invocation.
Returns:
A BuildTrigger proto object.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.name = args.name
trigger.pubsubConfig = messages.PubsubConfig(topic=args.topic)
# Build Config
project = properties.VALUES.core.project.Get(required=True)
default_image = 'gcr.io/%s/gcb-%s:$COMMIT_SHA' % (project, args.name)
trigger_utils.ParseBuildConfigArgs(
trigger, args, messages, default_image, need_repo=True)
trigger.filter = args.subscription_filter
return trigger

View File

@@ -0,0 +1,186 @@
# -*- coding: utf-8 -*- #
# 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.
"""Create GCB v2 repo trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope.concepts import concepts
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
# TODO(b/224569250): Remove hidden label once GCB repo trigger is released.
@base.Hidden
class CreateRepository(base.CreateCommand):
"""Create a build trigger for a GCB v2 repository."""
detailed_help = {
'EXAMPLES':
"""\
To create a push trigger for all branches:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository=projects/my-project/locations/my-location/connections/my-connection/repositories/my-repository --branch-pattern=".*" --build-config="cloudbuild.yaml"
To create a pull request trigger for master:
$ {command} --name="my-trigger" --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --repository=projects/my-project/locations/my-location/connections/my-connection/repositories/my-repository --pull-request-pattern="^master$" --build-config="cloudbuild.yaml"
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
region_spec = concepts.ResourceSpec(
'cloudbuild.projects.locations',
resource_name='region',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=resource_args.RegionAttributeConfig())
concept_parsers.ConceptParser.ForResource(
'--region',
region_spec,
'Cloud region',
required=True).AddToParser(parser)
messages = cloudbuild_util.GetMessagesModule()
flag_config = trigger_utils.AddTriggerArgs(parser, add_region_flag=False)
flag_config.add_argument(
'--repository', help='Resource name of the GCB v2 repository.',
required=True)
ref_config = flag_config.add_mutually_exclusive_group(required=True)
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
required=True,
help="""\
A regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""")
pr_config.add_argument(
'--comment-control',
default=messages.PullRequestFilter.CommentControlValueValuesEnum
.COMMENTS_ENABLED,
help='Require a repository collaborator or owner to comment \'/gcbrun\' on a pull request before running the build.'
)
build_config = (
trigger_utils.AddBuildConfigArgs(flag_config, add_docker_args=False))
trigger_utils.AddBuildDockerArgs(build_config, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
# GCB v2 Repo config
repo = messages.RepositoryEventConfig(repository=args.repository)
if args.pull_request_pattern:
repo.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern)
if args.comment_control:
repo.pullRequest.commentControl = messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control)
else:
# Push event
repo.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern)
trigger.repositoryEventConfig = repo
trigger_utils.ParseBuildConfigArgs(
trigger, args, messages, default_image=None)
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = self.ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
location = args.region
if location is None:
location = properties.VALUES.builds.region.Get(required=True)
location = location.split('/')[-1]
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger

View File

@@ -0,0 +1,145 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 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.
"""Create Webhook trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateWebhook(base.CreateCommand):
"""Create a build trigger with a Webhook trigger event."""
detailed_help = {
'EXAMPLES':
"""\
To create a Webhook trigger that requires secret `projects/my-project/secrets/my-secret/versions/2` and builds off branch `my-branch` in a GitHub repository named `my-repo`:
$ {command} --name=my-webhook-trigger --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --secret=projects/my-project/secrets/my-secret/versions/2 --repo=https://www.github.com/owner/repo --repo-type=GITHUB --branch=my-branch
To create a Webhook trigger that requires secret `projects/my-project/secrets/my-secret/versions/2` and builds off branch `my-branch` in a 2nd-gen GitHub repository:
$ {command} --name=my-webhook-trigger --service-account="projects/my-project/serviceAccounts/my-byosa@my-project.iam.gserviceaccount.com" --secret=projects/my-project/secrets/my-secret/versions/2 --branch=my-branch --repository=projects/my-proj/locations/us-west1/connections/my-conn/repositories/my-repo
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object.
"""
flag_config = trigger_utils.AddTriggerArgs(parser)
flag_config.add_argument(
'--secret',
help=("""\
The full path of the secret version required to validate webhook requests
against this trigger.
For example, projects/my-project/secrets/my-secret/versions/1.
"""),
required=True,
)
trigger_utils.AddBuildConfigArgs(flag_config)
trigger_utils.AddGitRepoSource(flag_config)
trigger_utils.AddFilterArg(flag_config)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The newly created trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
trigger = messages.BuildTrigger()
if args.trigger_config:
trigger = cloudbuild_util.LoadMessageFromPath(
path=args.trigger_config,
msg_type=messages.BuildTrigger,
msg_friendly_name='build trigger config',
skip_camel_case=['substitutions'])
else:
trigger = ParseTriggerFromFlags(args)
# Send the Create request
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
created_trigger = client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
trigger_resource = resources.REGISTRY.Parse(
None,
collection='cloudbuild.projects.locations.triggers',
api_version='v1',
params={
'projectsId': project,
'locationsId': location,
'triggersId': created_trigger.id,
})
log.CreatedResource(trigger_resource)
return created_trigger
def ParseTriggerFromFlags(args):
"""Parse arguments into a BuildTrigger proto.
Args:
args: An argparse.Namespace. All the arguments that were provided to this
command invocation.
Returns:
A BuildTrigger proto object.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
if done:
return trigger
trigger.name = args.name
trigger.webhookConfig = messages.WebhookConfig(secret=args.secret)
# Build Config
project = properties.VALUES.core.project.Get(required=True)
default_image = 'gcr.io/%s/gcb-%s:$COMMIT_SHA' % (project, args.name)
trigger_utils.ParseBuildConfigArgs(
trigger, args, messages, default_image, need_repo=True)
trigger.filter = args.subscription_filter
return trigger

View File

@@ -0,0 +1,82 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 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.
"""Delete trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class Delete(base.DeleteCommand):
"""Delete a build trigger."""
detailed_help = {
'DESCRIPTION':
'Delete a build trigger.',
'EXAMPLES': ("""
To delete a build trigger, run:
$ {command} MY-TRIGGER
"""),
}
@staticmethod
def Args(parser):
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.',
required=True).AddToParser(parser)
def Run(self, args):
"""Deletes a build trigger.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
client = cloudbuild_util.GetClientInstance()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
trigger = args.TRIGGER
name = resources.REGISTRY.Parse(
trigger,
params={
'projectsId': project,
'locationsId': location,
'triggersId': trigger,
},
collection='cloudbuild.projects.locations.triggers').RelativeName()
client.projects_locations_triggers.Delete(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersDeleteRequest(
name=name, triggerId=trigger))
log.DeletedResource(name)

View File

@@ -0,0 +1,79 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 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.
"""Describe trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class Describe(base.DescribeCommand):
"""Get information about a particular trigger."""
detailed_help = {
'DESCRIPTION':
'Get information about the specified build trigger.',
'EXAMPLES': ("""
To describe a build trigger, run:
$ {command} MY-TRIGGER
"""),
}
@staticmethod
def Args(parser):
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.',
required=True).AddToParser(parser)
def Run(self, args):
"""Describes a build trigger..
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
client = cloudbuild_util.GetClientInstance()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
trigger = args.TRIGGER
name = resources.REGISTRY.Parse(
trigger,
params={
'projectsId': project,
'locationsId': location,
'triggersId': trigger,
},
collection='cloudbuild.projects.locations.triggers').RelativeName()
return client.projects_locations_triggers.Get(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersGetRequest(
name=name, triggerId=trigger))

View File

@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 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.
"""Export Cloud Build trigger to file command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import encoding
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
from googlecloudsdk.core import yaml
from googlecloudsdk.core.util import files
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Export(base.Command):
"""Export a build trigger."""
detailed_help = {
'EXAMPLES': ("""
To export a build trigger to a file called trigger.yaml, run:
$ {command} MY-TRIGGER --destination=trigger.yaml
"""),
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.',
required=True).AddToParser(parser)
parser.add_argument(
'--destination',
metavar='PATH',
required=True,
help="""\
File path where trigger should be exported.
""")
def Run(self, args):
"""Exports a build trigger.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
trigger = args.TRIGGER
name = resources.REGISTRY.Parse(
trigger,
params={
'projectsId': project,
'locationsId': location,
'triggersId': trigger,
},
collection='cloudbuild.projects.locations.triggers').RelativeName()
got_trigger = client.projects_locations_triggers.Get(
messages.CloudbuildProjectsLocationsTriggersGetRequest(
name=name, triggerId=trigger))
with files.FileWriter(args.destination) as out:
yaml.dump(encoding.MessageToDict(got_trigger), stream=out)

View File

@@ -0,0 +1,141 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 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.
"""Export Cloud Build trigger to file command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import exceptions as apitools_exceptions
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.builds import flags as build_flags
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class Import(base.Command):
"""Import a build trigger."""
detailed_help = {
'DESCRIPTION':
"""\
To import a trigger from a file:
$ cat > trigger.yaml <<EOF
name: my-trigger
github:
owner: GoogleCloudPlatform
name: cloud-builders
push:
branch: .*
EOF
""",
'EXAMPLES': ("""
To import a build trigger from a file called trigger.yaml, run:
$ {command} --source=trigger.yaml
"""),
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
build_flags.AddRegionFlag(parser)
parser.add_argument(
'--source',
metavar='PATH',
required=True,
help="""\
File path where trigger should be imported from.
""")
def _UpdateTrigger(self, client, messages, project_id, location_id, trigger):
trigger_id = trigger.id
if not trigger_id:
trigger_id = trigger.name
name = resources.REGISTRY.Parse(
trigger.id,
params={
'projectsId': project_id,
'locationsId': location_id,
'triggersId': trigger_id,
},
collection='cloudbuild.projects.locations.triggers').RelativeName()
trigger.resourceName = name
return client.projects_locations_triggers.Patch(
messages.CloudbuildProjectsLocationsTriggersPatchRequest(
resourceName=name, triggerId=trigger_id, buildTrigger=trigger))
def _CreateTrigger(self, client, messages, project, location, trigger):
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
return client.projects_locations_triggers.Create(
messages.CloudbuildProjectsLocationsTriggersCreateRequest(
parent=parent, buildTrigger=trigger))
def _CreateOrUpdateTrigger(self, client, messages, project, location,
trigger):
if trigger.id:
# Trigger already has an ID - only try update.
return self._UpdateTrigger(client, messages, project, location, trigger)
elif trigger.name:
# No ID specified, but trigger with given name could still exist.
# Try to update an existing trigger; if it doesn't exist, then
# create it.
try:
return self._UpdateTrigger(client, messages, project, location, trigger)
except apitools_exceptions.HttpNotFoundError:
return self._CreateTrigger(client, messages, project, location, trigger)
else:
# No identifying information specified. Create a trigger with the given
# specification.
return self._CreateTrigger(client, messages, project, location, trigger)
def Run(self, args):
"""Imports a build trigger.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
triggers = cloudbuild_util.LoadMessagesFromPath(
args.source,
messages.BuildTrigger,
'BuildTrigger',
skip_camel_case=['substitutions'])
return [
self._CreateOrUpdateTrigger(client, messages, project, location,
trigger) for trigger in triggers
]

View File

@@ -0,0 +1,69 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 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.
"""List triggers command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.builds import flags as build_flags
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class List(base.ListCommand):
"""List Cloud Build triggers for a project."""
detailed_help = {
'DESCRIPTION':
'List Cloud Build triggers for a project.',
'EXAMPLES': ("""
To list build triggers, run:
$ {command}
"""),
}
@staticmethod
def Args(parser):
build_flags.AddRegionFlag(parser)
def Run(self, args):
"""Lists the build triggers in a project.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
client = cloudbuild_util.GetClientInstance()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
parent = resources.REGISTRY.Create(
collection='cloudbuild.projects.locations',
projectsId=project,
locationsId=location).RelativeName()
return client.projects_locations_triggers.List(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersListRequest(
parent=parent)).triggers

View File

@@ -0,0 +1,104 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 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.
"""Run trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class Run(base.Command):
"""Run a build trigger."""
detailed_help = {
'DESCRIPTION':
'Run a build trigger.',
'EXAMPLES': ("""
To run a build trigger, run:
$ {command} MY-TRIGGER --branch=master
"""),
}
@staticmethod
def Args(parser):
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.',
required=True).AddToParser(parser)
revision_config = parser.add_mutually_exclusive_group()
revision_config.add_argument('--branch', help='Branch to run.')
revision_config.add_argument('--tag', help='Tag to run.')
revision_config.add_argument('--sha', help='SHA to run.')
trigger_utils.AddSubstitutions(parser)
def Run(self, args):
"""Runs a build trigger.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
trigger = args.TRIGGER
name = resources.REGISTRY.Parse(
trigger,
params={
'projectsId': project,
'locationsId': location,
'triggersId': trigger,
},
collection='cloudbuild.projects.locations.triggers').RelativeName()
request = messages.RunBuildTriggerRequest(triggerId=trigger)
if args.branch:
request.source = messages.RepoSource(branchName=args.branch)
elif args.tag:
request.source = messages.RepoSource(tagName=args.tag)
elif args.sha:
request.source = messages.RepoSource(commitSha=args.sha)
if args.substitutions:
if request.source is None:
request.source = messages.RepoSource()
request.source.substitutions = cloudbuild_util.EncodeTriggerSubstitutions(
args.substitutions, messages.RepoSource.SubstitutionsValue)
return client.projects_locations_triggers.Run(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersRunRequest(
name=name,
runBuildTriggerRequest=request,
))

View File

@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""The command group for Google Cloud Build's Connections."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class TriggerUpdate(base.Group):
"""Update Triggers in Google Cloud Build."""
category = base.CI_CD_CATEGORY

View File

@@ -0,0 +1,253 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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.
"""Update Bitbucket Cloud trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class UpdateBitbucketCloud(base.UpdateCommand):
"""Updates Bitbucket Cloud trigger used by Cloud Build."""
detailed_help = {
'EXAMPLES': """\
To update the branch pattern of the trigger:
$ {command} my-trigger --branch-pattern=".*"
To update the build config of the trigger:
$ {command} my-trigger --build-config="cloudbuild.yaml"
To update the substitutions of the trigger:
$ {command} my-trigger --update-substitutions=_REPO_NAME=my-repo,_BRANCH_NAME=master
To update the 2nd-gen repository resource of the trigger:
$ {command} my-trigger --repository=projects/my-project/locations/us-west1/connections/my-conn/repositories/my-repo
""",
}
@staticmethod
def Args(parser):
"""Registers flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.',
required=True,
).AddToParser(parser)
flag_config = trigger_utils.AddTriggerArgs(
parser, add_region_flag=False, add_name=False
)
flag_config.add_argument(
'--repository',
help=(
'Repository resource (2nd gen) to use, in the format'
' "projects/*/locations/*/connections/*/repositories/*".'
),
)
ref_config = flag_config.add_mutually_exclusive_group()
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
help="""\
A regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regular expression search for the base branch (the
branch you are trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""",
)
pr_config.add_argument(
'--comment-control',
choices={
'COMMENTS_DISABLED': """
Do not require comments on Pull Requests before builds are triggered.""",
'COMMENTS_ENABLED': """
Enforce that repository owners or collaborators must comment on Pull Requests
before builds are triggered.""",
'COMMENTS_ENABLED_FOR_EXTERNAL_CONTRIBUTORS_ONLY': """
Enforce that repository owners or collaborators must comment on external
contributors' Pull Requests before builds are triggered.""",
},
help=("""\
Require a repository collaborator or owner to comment '/gcbrun' on a pull
request before running the build.
"""),
)
trigger_utils.AddBuildConfigArgsForUpdate(
flag_config, has_build_config=True, require_docker_image=True
)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args, old_trigger, update_mask):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
old_trigger: The existing trigger to be updated.
update_mask: The update mask.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgsForUpdate(args, messages)
if done:
return trigger
if args.repository: # 2nd-gen (Repos API) config
repo = messages.RepositoryEventConfig(repository=args.repository)
trigger.repositoryEventConfig = repo
# Only updating event information.
if args.branch_pattern:
if trigger.repositoryEventConfig is None:
trigger.repositoryEventConfig = messages.RepositoryEventConfig()
trigger.repositoryEventConfig.push = messages.PushFilter(
branch=args.branch_pattern
)
update_mask.append('repository_event_config.pull_request')
if args.tag_pattern:
if trigger.repositoryEventConfig is None:
trigger.repositoryEventConfig = messages.RepositoryEventConfig()
trigger.repositoryEventConfig.push = messages.PushFilter(
tag=args.tag_pattern
)
update_mask.append('repository_event_config.pull_request')
if args.pull_request_pattern:
pull_request_pattern = args.pull_request_pattern
if trigger.repositoryEventConfig is None:
trigger.repositoryEventConfig = messages.RepositoryEventConfig()
trigger.repositoryEventConfig.pullRequest = messages.PullRequestFilter(
branch=pull_request_pattern,
)
update_mask.append('repository_event_config.push')
if args.comment_control:
if trigger.repositoryEventConfig is None:
trigger.repositoryEventConfig = messages.RepositoryEventConfig()
if trigger.repositoryEventConfig.pullRequest is None:
trigger.repositoryEventConfig.pullRequest = messages.PullRequestFilter()
trigger.repositoryEventConfig.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
update_mask.append('repository_event_config.push')
trigger_utils.ParseBuildConfigArgsForUpdate(
trigger,
old_trigger,
args,
messages,
update_mask,
None,
has_build_config=True,
)
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated Bitbucket Cloud trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
triggerid = args.TRIGGER
name = resources.REGISTRY.Parse(
triggerid,
params={
'projectsId': project,
'locationsId': location,
'triggersId': triggerid,
},
collection='cloudbuild.projects.locations.triggers',
).RelativeName()
old_trigger = client.projects_locations_triggers.Get(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersGetRequest(
name=name, triggerId=triggerid
)
)
update_mask = []
trigger = self.ParseTriggerFromFlags(args, old_trigger, update_mask)
# Overwrite the substitutions.additionalProperties in updateMask.
sub = 'substitutions'
update_mask.extend(cloudbuild_util.MessageToFieldPaths(trigger))
update_mask = list(
set(map(lambda m: sub if m.startswith(sub) else m, update_mask))
)
# Sort for tests.
update_mask.sort()
req = messages.CloudbuildProjectsLocationsTriggersPatchRequest(
resourceName=name,
triggerId=triggerid,
buildTrigger=trigger,
updateMask=','.join(update_mask),
)
updated_trigger = client.projects_locations_triggers.Patch(req)
log.UpdatedResource(triggerid, kind='build_trigger')
return updated_trigger

View File

@@ -0,0 +1,253 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""Update Bitbucket Data Center trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class UpdateBitbucketDataCenter(base.UpdateCommand):
"""Updates Bitbucket Data Center trigger used by Cloud Build."""
detailed_help = {
'EXAMPLES': """\
To update the branch pattern of the trigger:
$ {command} my-trigger --branch-pattern=".*"
To update the build config of the trigger:
$ {command} my-trigger --build-config="cloudbuild.yaml"
To update the substitutions of the trigger:
$ {command} my-trigger --update-substitutions=_REPO_NAME=my-repo,_BRANCH_NAME=master
To update the 2nd-gen repository resource of the trigger:
$ {command} my-trigger --repository=projects/my-project/locations/us-west1/connections/my-conn/repositories/my-repo
""",
}
@staticmethod
def Args(parser):
"""Registers flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.',
required=True,
).AddToParser(parser)
flag_config = trigger_utils.AddTriggerArgs(
parser, add_region_flag=False, add_name=False
)
flag_config.add_argument(
'--repository',
help=(
'Repository resource (2nd gen) to use, in the format'
' "projects/*/locations/*/connections/*/repositories/*".'
),
)
ref_config = flag_config.add_mutually_exclusive_group()
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
help="""\
A regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regular expression search for the base branch (the
branch you are trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""",
)
pr_config.add_argument(
'--comment-control',
choices={
'COMMENTS_DISABLED': """
Do not require comments on Pull Requests before builds are triggered.""",
'COMMENTS_ENABLED': """
Enforce that repository owners or collaborators must comment on Pull Requests
before builds are triggered.""",
'COMMENTS_ENABLED_FOR_EXTERNAL_CONTRIBUTORS_ONLY': """
Enforce that repository owners or collaborators must comment on external
contributors' Pull Requests before builds are triggered.""",
},
help=("""\
Require a repository collaborator or owner to comment '/gcbrun' on a pull
request before running the build.
"""),
)
trigger_utils.AddBuildConfigArgsForUpdate(
flag_config, has_build_config=True, require_docker_image=True
)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args, old_trigger, update_mask):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
old_trigger: The existing trigger to be updated.
update_mask: The update mask.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgsForUpdate(args, messages)
if done:
return trigger
if args.repository: # 2nd-gen (Repos API) config
repo = messages.RepositoryEventConfig(repository=args.repository)
trigger.repositoryEventConfig = repo
# Only updating event information.
if args.branch_pattern:
if trigger.repositoryEventConfig is None:
trigger.repositoryEventConfig = messages.RepositoryEventConfig()
trigger.repositoryEventConfig.push = messages.PushFilter(
branch=args.branch_pattern
)
update_mask.append('repository_event_config.pull_request')
if args.tag_pattern:
if trigger.repositoryEventConfig is None:
trigger.repositoryEventConfig = messages.RepositoryEventConfig()
trigger.repositoryEventConfig.push = messages.PushFilter(
tag=args.tag_pattern
)
update_mask.append('repository_event_config.pull_request')
if args.pull_request_pattern:
pull_request_pattern = args.pull_request_pattern
if trigger.repositoryEventConfig is None:
trigger.repositoryEventConfig = messages.RepositoryEventConfig()
trigger.repositoryEventConfig.pullRequest = messages.PullRequestFilter(
branch=pull_request_pattern,
)
update_mask.append('repository_event_config.push')
if args.comment_control:
if trigger.repositoryEventConfig is None:
trigger.repositoryEventConfig = messages.RepositoryEventConfig()
if trigger.repositoryEventConfig.pullRequest is None:
trigger.repositoryEventConfig.pullRequest = messages.PullRequestFilter()
trigger.repositoryEventConfig.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
update_mask.append('repository_event_config.push')
trigger_utils.ParseBuildConfigArgsForUpdate(
trigger,
old_trigger,
args,
messages,
update_mask,
None,
has_build_config=True,
)
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated Bitbucket Data Center trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
triggerid = args.TRIGGER
name = resources.REGISTRY.Parse(
triggerid,
params={
'projectsId': project,
'locationsId': location,
'triggersId': triggerid,
},
collection='cloudbuild.projects.locations.triggers',
).RelativeName()
old_trigger = client.projects_locations_triggers.Get(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersGetRequest(
name=name, triggerId=triggerid
)
)
update_mask = []
trigger = self.ParseTriggerFromFlags(args, old_trigger, update_mask)
# Overwrite the substitutions.additionalProperties in updateMask.
sub = 'substitutions'
update_mask.extend(cloudbuild_util.MessageToFieldPaths(trigger))
update_mask = list(
set(map(lambda m: sub if m.startswith(sub) else m, update_mask))
)
# Sort for tests.
update_mask.sort()
req = messages.CloudbuildProjectsLocationsTriggersPatchRequest(
resourceName=name,
triggerId=triggerid,
buildTrigger=trigger,
updateMask=','.join(update_mask),
)
updated_trigger = client.projects_locations_triggers.Patch(req)
log.UpdatedResource(triggerid, kind='build_trigger')
return updated_trigger

View File

@@ -0,0 +1,222 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""Update Bitbucket Server trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class UpdateBitbucketServer(base.UpdateCommand):
"""Updates Bitbucket Server trigger used by Cloud Build."""
detailed_help = {
'EXAMPLES':
"""\
To update the branch pattern of the trigger:
$ {command} my-trigger --branch-pattern=".*"
To update the build config of the trigger:
$ {command} my-trigger --build-config="cloudbuild.yaml"
To update the substitutions of the trigger:
$ {command} my-trigger --update-substitutions=_REPO_NAME=my-repo,_BRANCH_NAME=master
""",
}
@staticmethod
def Args(parser):
"""Registers flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.', required=True).AddToParser(parser)
flag_config = trigger_utils.AddTriggerArgs(
parser, add_region_flag=False, add_name=False)
flag_config.add_argument(
'--repo-slug', help='Bitbucket Server repository slug.')
flag_config.add_argument(
'--project-key', help='Bitbucket Server project key.')
flag_config.add_argument(
'--bitbucket-server-config-resource',
help='Bitbucket Server config resource name.')
ref_config = flag_config.add_mutually_exclusive_group()
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
help="""\
A regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regular expression search for the base branch (the
branch you are trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""")
pr_config.add_argument(
'--comment-control',
choices={
'COMMENTS_DISABLED': ("""
Do not require comments on Pull Requests before builds are triggered."""),
'COMMENTS_ENABLED': ("""
Enforce that repository owners or collaborators must comment on Pull Requests
before builds are triggered."""),
'COMMENTS_ENABLED_FOR_EXTERNAL_CONTRIBUTORS_ONLY': ("""
Enforce that repository owners or collaborators must comment on external
contributors' Pull Requests before builds are triggered."""),
},
default='COMMENTS_ENABLED',
help=("""\
Require a repository collaborator or owner to comment '/gcbrun' on a pull
request before running the build.
"""),
)
trigger_utils.AddBuildConfigArgsForUpdate(
flag_config, has_build_config=True, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args, old_trigger, update_mask):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
old_trigger: The existing trigger to be updated.
update_mask: The fields to be updated.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgsForUpdate(args, messages)
if done:
return trigger
# Bitbucket Server config
bbs = messages.BitbucketServerTriggerConfig(
repoSlug=args.repo_slug,
projectKey=args.project_key,
bitbucketServerConfigResource=args.bitbucket_server_config_resource)
if args.pull_request_pattern:
bbs.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern)
if args.comment_control:
bbs.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
bbs.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern
)
trigger.bitbucketServerTriggerConfig = bbs
trigger_utils.ParseBuildConfigArgsForUpdate(
trigger,
old_trigger,
args,
messages,
update_mask,
None,
has_build_config=True,
)
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated Bitbucket Server trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
triggerid = args.TRIGGER
name = resources.REGISTRY.Parse(
triggerid,
params={
'projectsId': project,
'locationsId': location,
'triggersId': triggerid,
},
collection='cloudbuild.projects.locations.triggers',
).RelativeName()
old_trigger = client.projects_locations_triggers.Get(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersGetRequest(
name=name, triggerId=triggerid
)
)
update_mask = []
trigger = self.ParseTriggerFromFlags(args, old_trigger, update_mask)
# Overwrite the substitutions.additionalProperties in updateMask.
sub = 'substitutions'
update_mask.extend(cloudbuild_util.MessageToFieldPaths(trigger))
update_mask = sorted(
set(map(lambda m: sub if m.startswith(sub) else m, update_mask))
)
req = messages.CloudbuildProjectsLocationsTriggersPatchRequest(
resourceName=name,
triggerId=triggerid,
buildTrigger=trigger,
updateMask=','.join(update_mask),
)
updated_trigger = client.projects_locations_triggers.Patch(req)
log.UpdatedResource(triggerid, kind='build_trigger')
return updated_trigger

View File

@@ -0,0 +1,181 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""Update Cloud Source Repositories trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.source import resource_args as repo_resource
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.command_lib.util.concepts import presentation_specs
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class UpdateCSR(base.UpdateCommand):
"""Updates Cloud Source Repositories trigger used by Cloud Build."""
detailed_help = {
'EXAMPLES':
"""\
To update the branch pattern of the trigger:
$ {command} my-trigger --branch-pattern=".*"
To update the build config of the trigger:
$ {command} my-trigger --build-config="cloudbuild.yaml"
To update the substitutions of the trigger:
$ {command} my-trigger --update-substitutions=_REPO_NAME=my-repo,_BRANCH_NAME=master
""",
}
@staticmethod
def Args(parser):
"""Registers flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.', required=True).AddToParser(parser)
flag_config = trigger_utils.AddTriggerArgs(
parser, add_region_flag=False, add_name=False)
repo_spec = presentation_specs.ResourcePresentationSpec(
'--repo', # This defines how the "anchor" or leaf argument is named.
repo_resource.GetRepoResourceSpec(),
'Cloud Source Repository.',
prefixes=False)
concept_parsers.ConceptParser([repo_spec]).AddToParser(flag_config)
ref_config = flag_config.add_mutually_exclusive_group()
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
trigger_utils.AddBuildConfigArgsForUpdate(
flag_config, has_build_config=True, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args, old_trigger, update_mask):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
old_trigger: The existing trigger to be updated.
update_mask: The fields to be updated.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgsForUpdate(args, messages)
if done:
return trigger
repo_ref = args.CONCEPTS.repo.Parse()
repo = None
if repo_ref:
repo = repo_ref.reposId
trigger = messages.BuildTrigger(
description=args.description,
serviceAccount=args.service_account,
triggerTemplate=messages.RepoSource(
repoName=repo,
branchName=args.branch_pattern,
tagName=args.tag_pattern,
),
)
trigger_utils.ParseRequireApproval(trigger, args, messages)
# Build Config
trigger_utils.ParseBuildConfigArgsForUpdate(
trigger,
old_trigger,
args,
messages,
update_mask,
'',
has_build_config=True,
)
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated CSR trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
triggerid = args.TRIGGER
name = resources.REGISTRY.Parse(
triggerid,
params={
'projectsId': project,
'locationsId': location,
'triggersId': triggerid,
},
collection='cloudbuild.projects.locations.triggers').RelativeName()
old_trigger = client.projects_locations_triggers.Get(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersGetRequest(
name=name, triggerId=triggerid))
update_mask = []
trigger = self.ParseTriggerFromFlags(args, old_trigger, update_mask)
# Overwrite the substitutions.additionalProperties in updateMask.
sub = 'substitutions'
update_mask.extend(cloudbuild_util.MessageToFieldPaths(trigger))
update_mask = list(
set(map(lambda m: sub if m.startswith(sub) else m, update_mask)))
req = messages.CloudbuildProjectsLocationsTriggersPatchRequest(
resourceName=name,
triggerId=triggerid,
buildTrigger=trigger,
updateMask=','.join(update_mask))
updated_trigger = client.projects_locations_triggers.Patch(req)
log.UpdatedResource(triggerid, kind='build_trigger')
return updated_trigger

View File

@@ -0,0 +1,269 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 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.
"""Update Developer Connect Trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class UpdateDeveloperConnect(base.UpdateCommand):
"""Updates Developer Connect trigger used by Cloud Build."""
detailed_help = {
'EXAMPLES': """\
To update the branch pattern of the trigger:
$ {command} my-trigger --branch-pattern=".*"
To update the build config of the trigger:
$ {command} my-trigger --build-config="cloudbuild.yaml"
To update the substitutions of the trigger:
$ {command} my-trigger --update-substitutions=_REPO_NAME=my-repo,_BRANCH_NAME=master
To update the git repository link of the trigger:
$ {command} my-trigger --git-repository-link=projects/my-project/locations/us-west1/connections/my-conn/gitRepositoryLinks/my-repo
""",
}
@staticmethod
def Args(parser):
"""Registers flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.',
required=True,
).AddToParser(parser)
flag_config = trigger_utils.AddTriggerArgs(
parser, add_region_flag=False, add_name=False
)
flag_config.add_argument(
'--git-repository-link',
help=(
'Git repository link to use, in the format'
' "projects/*/locations/*/connections/*/gitRepositoryLinks/*".'
),
)
ref_config = flag_config.add_mutually_exclusive_group()
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
help="""\
A regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regular expression search for the base branch (the
branch you are trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""",
)
pr_config.add_argument(
'--comment-control',
choices={
'COMMENTS_DISABLED': """
Do not require comments on Pull Requests before builds are triggered.""",
'COMMENTS_ENABLED': """
Enforce that repository owners or collaborators must comment on Pull Requests
before builds are triggered.""",
'COMMENTS_ENABLED_FOR_EXTERNAL_CONTRIBUTORS_ONLY': """
Enforce that repository owners or collaborators must comment on external
contributors' Pull Requests before builds are triggered.""",
},
help=("""\
Require a repository collaborator or owner to comment '/gcbrun' on a pull
request before running the build.
"""),
)
trigger_utils.AddBuildConfigArgsForUpdate(
flag_config, has_build_config=True, require_docker_image=True
)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args, old_trigger, update_mask):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
old_trigger: The existing trigger to be updated.
update_mask: The update mask.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgsForUpdate(args, messages)
if done:
return trigger
if args.git_repository_link: # Git repository link config
cfg = messages.DeveloperConnectEventConfig(
gitRepositoryLink=args.git_repository_link
)
trigger.developerConnectEventConfig = cfg
# Only updating event information.
if args.branch_pattern:
if trigger.developerConnectEventConfig is None:
trigger.developerConnectEventConfig = (
messages.DeveloperConnectEventConfig()
)
trigger.developerConnectEventConfig.push = messages.PushFilter(
branch=args.branch_pattern
)
update_mask.append('developer_connect_event_config.pull_request')
if args.tag_pattern:
if trigger.developerConnectEventConfig is None:
trigger.developerConnectEventConfig = (
messages.DeveloperConnectEventConfig()
)
trigger.developerConnectEventConfig.push = messages.PushFilter(
tag=args.tag_pattern
)
update_mask.append('developer_connect_event_config.pull_request')
if args.pull_request_pattern:
pull_request_pattern = args.pull_request_pattern
if trigger.developerConnectEventConfig is None:
trigger.developerConnectEventConfig = (
messages.DeveloperConnectEventConfig()
)
trigger.developerConnectEventConfig.pullRequest = (
messages.PullRequestFilter(
branch=pull_request_pattern,
)
)
update_mask.append('developer_connect_event_config.push')
if args.comment_control:
if trigger.developerConnectEventConfig is None:
trigger.developerConnectEventConfig = (
messages.DeveloperConnectEventConfig()
)
if trigger.developerConnectEventConfig.pullRequest is None:
trigger.developerConnectEventConfig.pullRequest = (
messages.PullRequestFilter()
)
trigger.developerConnectEventConfig.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
update_mask.append('developer_connect_event_config.push')
trigger_utils.ParseBuildConfigArgsForUpdate(
trigger,
old_trigger,
args,
messages,
update_mask,
None,
has_build_config=True,
)
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated Developer Connect trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
triggerid = args.TRIGGER
name = resources.REGISTRY.Parse(
triggerid,
params={
'projectsId': project,
'locationsId': location,
'triggersId': triggerid,
},
collection='cloudbuild.projects.locations.triggers',
).RelativeName()
old_trigger = client.projects_locations_triggers.Get(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersGetRequest(
name=name, triggerId=triggerid
)
)
update_mask = []
trigger = self.ParseTriggerFromFlags(args, old_trigger, update_mask)
# Overwrite the substitutions.additionalProperties in updateMask.
sub = 'substitutions'
update_mask.extend(cloudbuild_util.MessageToFieldPaths(trigger))
update_mask = list(
set(map(lambda m: sub if m.startswith(sub) else m, update_mask))
)
# Sort for tests.
update_mask.sort()
req = messages.CloudbuildProjectsLocationsTriggersPatchRequest(
resourceName=name,
triggerId=triggerid,
buildTrigger=trigger,
updateMask=','.join(update_mask),
)
updated_trigger = client.projects_locations_triggers.Patch(req)
log.UpdatedResource(triggerid, kind='build_trigger')
return updated_trigger

View File

@@ -0,0 +1,245 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""Update GitHub trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class UpdateGitHub(base.UpdateCommand):
"""Update GitHub trigger used by Cloud Build."""
detailed_help = {
'EXAMPLES':
"""\
To update the branch pattern of the trigger:
$ {command} my-trigger --branch-pattern=".*"
To update the build config of the trigger:
$ {command} my-trigger --build-config="cloudbuild.yaml"
To update the substitutions of the trigger:
$ {command} my-trigger --update-substitutions=_REPO_NAME=my-repo,_BRANCH_NAME=master
""",
}
@staticmethod
def Args(parser):
"""Registers flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.',
required=True).AddToParser(parser)
flag_config = trigger_utils.AddTriggerArgs(
parser, add_region_flag=False, add_name=False)
gen_config = flag_config.add_mutually_exclusive_group()
gen_config.add_argument(
'--repository',
help=("""\
Repository resource (2nd gen) to use, in the format
"projects/*/locations/*/connections/*/repositories/*".
"""),
)
v1_config = gen_config.add_argument_group()
v1_config.add_argument(
'--repo-owner', help='Owner of the GitHub Repository.')
v1_config.add_argument(
'--repo-name', help='Name of the GitHub Repository.')
v1_config.add_argument(
'--enterprise-config',
help="""\
Resource name of the GitHub Enterprise config that should be applied to this
installation.
For example: "projects/{$project_id}/locations/{$location_id}/githubEnterpriseConfigs/{$config_id}
""")
ref_config = flag_config.add_mutually_exclusive_group()
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
help="""\
A regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regex search for the base branch (the branch you are
trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""")
pr_config.add_argument(
'--comment-control',
choices={
'COMMENTS_DISABLED': (
'Do not require comments on Pull Requests before builds are'
' triggered.'
),
'COMMENTS_ENABLED': (
'Enforce that repository owners or collaborators must comment'
' on Pull Requests before builds are triggered.'
),
'COMMENTS_ENABLED_FOR_EXTERNAL_CONTRIBUTORS_ONLY': (
'Enforce that repository owners or collaborators must comment'
" on external contributors' Pull Requests before builds are"
' triggered.'
),
},
default='COMMENTS_ENABLED',
help=(
"Require a repository collaborator or owner to comment '/gcbrun' on"
' a pull request before running the build.'
),
)
trigger_utils.AddBuildConfigArgsForUpdate(
flag_config, has_build_config=True, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
trigger_utils.AddIncludeLogsArgs(flag_config)
def ParseTriggerFromFlags(self, args, old_trigger, update_mask):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
old_trigger: The existing trigger to be updated.
update_mask: The fields to be updated.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgsForUpdate(args, messages)
if done:
return trigger
# GitHub config
gh = messages.GitHubEventsConfig(
owner=args.repo_owner,
name=args.repo_name,
enterpriseConfigResourceName=args.enterprise_config)
if args.pull_request_pattern:
gh.pullRequest = messages.PullRequestFilter(
branch=args.pull_request_pattern)
if args.comment_control:
gh.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
else:
# Push event
gh.push = messages.PushFilter(
branch=args.branch_pattern, tag=args.tag_pattern
)
trigger.github = gh
trigger_utils.ParseBuildConfigArgsForUpdate(
trigger,
old_trigger,
args,
messages,
update_mask,
None,
has_build_config=True,
)
trigger_utils.ParseRepoEventArgs(trigger, args)
trigger_utils.ParseIncludeLogsWithStatus(trigger, args, messages)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated GitHub trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
triggerid = args.TRIGGER
name = resources.REGISTRY.Parse(
triggerid,
params={
'projectsId': project,
'locationsId': location,
'triggersId': triggerid,
},
collection='cloudbuild.projects.locations.triggers',
).RelativeName()
old_trigger = client.projects_locations_triggers.Get(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersGetRequest(
name=name, triggerId=triggerid
)
)
update_mask = []
trigger = self.ParseTriggerFromFlags(args, old_trigger, update_mask)
# Overwrite the substitutions.additionalProperties in updateMask.
sub = 'substitutions'
update_mask.extend(cloudbuild_util.MessageToFieldPaths(trigger))
update_mask = sorted(
set(map(lambda m: sub if m.startswith(sub) else m, update_mask))
)
req = messages.CloudbuildProjectsLocationsTriggersPatchRequest(
resourceName=name,
triggerId=triggerid,
buildTrigger=trigger,
updateMask=','.join(update_mask),
)
updated_trigger = client.projects_locations_triggers.Patch(req)
log.UpdatedResource(triggerid, kind='build_trigger')
return updated_trigger

View File

@@ -0,0 +1,252 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""Update GitLab trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class UpdateGitLab(base.UpdateCommand):
"""Updates GitLab trigger used by Cloud Build."""
detailed_help = {
'EXAMPLES':
"""\
To update the branch pattern of the trigger:
$ {command} my-trigger --branch-pattern=".*"
To update the build config of the trigger:
$ {command} my-trigger --build-config="cloudbuild.yaml"
To update the substitutions of the trigger:
$ {command} my-trigger --update-substitutions=_REPO_NAME=my-repo,_BRANCH_NAME=master
To update the 2nd-gen repository resource of the trigger:
$ {command} my-trigger --repository=projects/my-project/locations/us-west1/connections/my-conn/repositories/my-repo
""",
}
@staticmethod
def Args(parser):
"""Registers flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.', required=True).AddToParser(parser)
flag_config = trigger_utils.AddTriggerArgs(
parser, add_region_flag=False, add_name=False)
flag_config.add_argument(
'--repository',
help=(
'Repository resource (2nd gen) to use, in the format'
' "projects/*/locations/*/connections/*/repositories/*".'
),
)
ref_config = flag_config.add_mutually_exclusive_group()
trigger_utils.AddBranchPattern(ref_config)
trigger_utils.AddTagPattern(ref_config)
pr_config = ref_config.add_argument_group(help='Pull Request settings')
pr_config.add_argument(
'--pull-request-pattern',
metavar='REGEX',
help="""\
A regular expression specifying which base git branch to match for
pull request events.
This pattern is used as a regular expression search for the base branch (the
branch you are trying to merge into) for pull request updates.
For example, --pull-request-pattern=foo will match "foo", "foobar", and "barfoo".
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax.
""")
pr_config.add_argument(
'--comment-control',
choices={
'COMMENTS_DISABLED': ("""
Do not require comments on Pull Requests before builds are triggered."""),
'COMMENTS_ENABLED': ("""
Enforce that repository owners or collaborators must comment on Pull Requests
before builds are triggered."""),
'COMMENTS_ENABLED_FOR_EXTERNAL_CONTRIBUTORS_ONLY': ("""
Enforce that repository owners or collaborators must comment on external
contributors' Pull Requests before builds are triggered."""),
},
help=("""\
Require a repository collaborator or owner to comment '/gcbrun' on a pull
request before running the build.
"""),
)
trigger_utils.AddBuildConfigArgsForUpdate(
flag_config, has_build_config=True, require_docker_image=True)
trigger_utils.AddRepoEventArgs(flag_config)
def ParseTriggerFromFlags(self, args, old_trigger, update_mask):
"""Parses command line arguments into a build trigger.
Args:
args: An argparse arguments object.
old_trigger: The existing trigger to be updated.
update_mask: The update mask.
Returns:
A build trigger object.
Raises:
RequiredArgumentException: If comment_control is defined but
pull_request_pattern isn't.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgsForUpdate(args, messages)
if done:
return trigger
if args.repository: # 2nd-gen (Repos API) config
repo = messages.RepositoryEventConfig(repository=args.repository)
trigger.repositoryEventConfig = repo
update_mask.append('gitlab_events_config')
# Only updating event information.
if args.branch_pattern:
if trigger.repositoryEventConfig is None:
trigger.repositoryEventConfig = messages.RepositoryEventConfig()
trigger.repositoryEventConfig.push = messages.PushFilter(
branch=args.branch_pattern
)
update_mask.append('repository_event_config.pull_request')
if args.tag_pattern:
if trigger.repositoryEventConfig is None:
trigger.repositoryEventConfig = messages.RepositoryEventConfig()
trigger.repositoryEventConfig.push = messages.PushFilter(
tag=args.tag_pattern
)
update_mask.append('repository_event_config.pull_request')
if args.pull_request_pattern:
pull_request_pattern = args.pull_request_pattern
if trigger.repositoryEventConfig is None:
trigger.repositoryEventConfig = messages.RepositoryEventConfig()
trigger.repositoryEventConfig.pullRequest = messages.PullRequestFilter(
branch=pull_request_pattern,
)
update_mask.append('repository_event_config.push')
if args.comment_control:
if trigger.repositoryEventConfig is None:
trigger.repositoryEventConfig = messages.RepositoryEventConfig()
if trigger.repositoryEventConfig.pullRequest is None:
trigger.repositoryEventConfig.pullRequest = (
messages.PullRequestFilter()
)
trigger.repositoryEventConfig.pullRequest.commentControl = (
messages.PullRequestFilter.CommentControlValueValuesEnum(
args.comment_control
)
)
update_mask.append('repository_event_config.push')
trigger_utils.ParseBuildConfigArgsForUpdate(
trigger,
old_trigger,
args,
messages,
update_mask,
None,
has_build_config=True,
)
trigger_utils.ParseRepoEventArgs(trigger, args)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated GitLab trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
triggerid = args.TRIGGER
name = resources.REGISTRY.Parse(
triggerid,
params={
'projectsId': project,
'locationsId': location,
'triggersId': triggerid,
},
collection='cloudbuild.projects.locations.triggers',
).RelativeName()
old_trigger = client.projects_locations_triggers.Get(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersGetRequest(
name=name, triggerId=triggerid
)
)
update_mask = []
trigger = self.ParseTriggerFromFlags(args, old_trigger, update_mask)
# Overwrite the substitutions.additionalProperties in updateMask.
sub = 'substitutions'
update_mask.extend(cloudbuild_util.MessageToFieldPaths(trigger))
update_mask = list(set(
map(lambda m: sub if m.startswith(sub) else m, update_mask)
))
# Sort for tests.
update_mask.sort()
req = messages.CloudbuildProjectsLocationsTriggersPatchRequest(
resourceName=name,
triggerId=triggerid,
buildTrigger=trigger,
updateMask=','.join(update_mask),
)
updated_trigger = client.projects_locations_triggers.Patch(req)
log.UpdatedResource(triggerid, kind='build_trigger')
return updated_trigger

View File

@@ -0,0 +1,151 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""Update manual trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class UpdateManual(base.UpdateCommand):
"""Updates a manual trigger used by Cloud Build."""
detailed_help = {
'EXAMPLES':
"""\
To update the branch from which the trigger clones:
$ {command} my-trigger --source-to-build-branch=my-branch
""",
}
@staticmethod
def Args(parser):
"""Registers flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.',
required=True,
).AddToParser(parser)
flag_config = trigger_utils.AddTriggerArgs(
parser, add_region_flag=False, add_name=False
)
trigger_utils.AddBuildConfigArgsForUpdate(
flag_config, has_file_source=True, require_docker_image=False
)
trigger_utils.AddRepoSourceForUpdate(flag_config)
def ParseTriggerFromFlags(self, args, old_trigger, update_mask):
"""Parses arguments into a build trigger.
Args:
args: An argparse arguments object.
old_trigger: The existing trigger to be updated.
update_mask: The fields to be updated.
Returns:
A build trigger object.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgsForUpdate(args, messages)
if done:
return trigger
project = properties.VALUES.core.project.Get(required=True)
default_image = 'gcr.io/%s/gcb-%s:$COMMIT_SHA' % (project, args.TRIGGER)
trigger_utils.ParseBuildConfigArgsForUpdate(
trigger,
old_trigger,
args,
messages,
update_mask,
default_image,
has_repo_source=True,
has_file_source=True)
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated manual trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
triggerid = args.TRIGGER
name = resources.REGISTRY.Parse(
triggerid,
params={
'projectsId': project,
'locationsId': location,
'triggersId': triggerid,
},
collection='cloudbuild.projects.locations.triggers',
).RelativeName()
old_trigger = client.projects_locations_triggers.Get(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersGetRequest(
name=name, triggerId=triggerid
)
)
update_mask = []
trigger = self.ParseTriggerFromFlags(args, old_trigger, update_mask)
# Overwrite the substitutions.additionalProperties in updateMask.
sub = 'substitutions'
update_mask.extend(cloudbuild_util.MessageToFieldPaths(trigger))
update_mask = sorted(
set(map(lambda m: sub if m.startswith(sub) else m, update_mask))
)
req = messages.CloudbuildProjectsLocationsTriggersPatchRequest(
resourceName=name,
triggerId=triggerid,
buildTrigger=trigger,
updateMask=','.join(update_mask),
)
updated_trigger = client.projects_locations_triggers.Patch(req)
log.UpdatedResource(triggerid, kind='build_trigger')
return updated_trigger

View File

@@ -0,0 +1,168 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""Update Pub/Sub trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions as c_exceptions
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class UpdatePubsub(base.UpdateCommand):
"""Update a Pub/Sub trigger used by Cloud Build."""
detailed_help = {
'EXAMPLES':
"""\
To update the branch from which the trigger clones:
$ {command} my-trigger --source-to-build-branch=my-branch
To update the topic:
$ {command} my-trigger --topic=projects/my-project/topics/my-topic
To update the substitutions of the trigger:
$ {command} my-trigger --update-substitutions=_REPO_NAME=my-repo,_BRANCH_NAME=master
""",
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.', required=True).AddToParser(parser)
flag_config = trigger_utils.AddTriggerArgs(
parser, add_region_flag=False, add_name=False)
flag_config.add_argument(
'--topic',
help='The topic to which this trigger should subscribe.')
trigger_utils.AddBuildConfigArgsForUpdate(
flag_config, has_file_source=True)
trigger_utils.AddRepoSourceForUpdate(flag_config)
trigger_utils.AddFilterArgForUpdate(flag_config)
def ParseTriggerFromFlags(self, args, old_trigger, update_mask):
"""Parses arguments into a build trigger.
Args:
args: An argparse arguments object.
old_trigger: The existing trigger to be updated.
update_mask: The fields to be updated.
Returns:
A build trigger object.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgsForUpdate(args, messages)
if done:
return trigger
if args.topic:
trigger.pubsubConfig = messages.PubsubConfig(topic=args.topic)
project = properties.VALUES.core.project.Get(required=True)
default_image = 'gcr.io/%s/gcb-%s:$COMMIT_SHA' % (project, args.TRIGGER)
trigger_utils.ParseBuildConfigArgsForUpdate(
trigger,
old_trigger,
args,
messages,
update_mask,
default_image,
has_repo_source=True,
has_file_source=True,
)
trigger.filter = args.subscription_filter
if args.subscription_filter is not None and not args.subscription_filter:
raise c_exceptions.InvalidArgumentException(
'--subscription-filter',
'cannot update subscription filter to be empty; please use'
' `--clear-subscription-filter` to clear subscription filter.',
)
elif args.clear_subscription_filter:
trigger.filter = ''
return trigger
def Run(self, args):
"""This is what handles the command execution.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated webhook trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
triggerid = args.TRIGGER
name = resources.REGISTRY.Parse(
triggerid,
params={
'projectsId': project,
'locationsId': location,
'triggersId': triggerid,
},
collection='cloudbuild.projects.locations.triggers').RelativeName()
old_trigger = client.projects_locations_triggers.Get(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersGetRequest(
name=name, triggerId=triggerid))
update_mask = []
trigger = self.ParseTriggerFromFlags(args, old_trigger, update_mask)
# Overwrite the substitutions.additionalProperties in updateMask.
sub = 'substitutions'
update_mask.extend(cloudbuild_util.MessageToFieldPaths(trigger))
update_mask = sorted(
set(map(lambda m: sub if m.startswith(sub) else m, update_mask))
)
req = messages.CloudbuildProjectsLocationsTriggersPatchRequest(
resourceName=name,
triggerId=triggerid,
buildTrigger=trigger,
updateMask=','.join(update_mask))
updated_trigger = client.projects_locations_triggers.Patch(req)
log.UpdatedResource(triggerid, kind='build_trigger')
return updated_trigger

View File

@@ -0,0 +1,171 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""Update Webhook trigger command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util
from googlecloudsdk.api_lib.cloudbuild import trigger_config as trigger_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.cloudbuild import resource_args
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class UpdateWebhook(base.UpdateCommand):
"""Update a Webhook trigger used by Cloud Build."""
detailed_help = {
'EXAMPLES': textwrap.dedent("""\
To update the branch from which the trigger clones:
$ {command} my-webhook-trigger --source-to-build-branch=my-branch
To update the webhook secret:
$ {command} my-webhook-trigger --secret=projects/my-project/secrets/my-secret/versions/2
To update the substitutions of the trigger:
$ {command} my-trigger --update-substitutions=_REPO_NAME=my-repo,_BRANCH_NAME=master
"""),
}
@staticmethod
def Args(parser):
"""Register flags for this command.
Args:
parser: An argparse.ArgumentParser-like object. It is mocked out in order
to capture some information, but behaves like an ArgumentParser.
"""
concept_parsers.ConceptParser.ForResource(
'TRIGGER',
resource_args.GetTriggerResourceSpec(),
'Build Trigger.',
required=True,
).AddToParser(parser)
flag_config = trigger_utils.AddTriggerArgs(
parser, add_region_flag=False, add_name=False
)
flag_config.add_argument(
'--secret',
help=textwrap.dedent("""
The full path of the secret version required to validate webhook requests against this trigger.
For example, projects/my-project/secrets/my-secret/versions/1.
"""),
)
trigger_utils.AddBuildConfigArgsForUpdate(
flag_config, has_file_source=True, require_docker_image=False
)
trigger_utils.AddRepoSourceForUpdate(flag_config)
trigger_utils.AddFilterArg(flag_config)
def ParseTriggerFromFlags(self, args, old_trigger, update_mask):
"""Parses arguments into a build trigger.
Args:
args: An argparse arguments object.
old_trigger: The existing trigger to be updated.
update_mask: The fields to be updated.
Returns:
A build trigger object.
"""
messages = cloudbuild_util.GetMessagesModule()
trigger, done = trigger_utils.ParseTriggerArgsForUpdate(args, messages)
if done:
return trigger
project = properties.VALUES.core.project.Get(required=True)
default_image = 'gcr.io/%s/gcb-%s:$COMMIT_SHA' % (project, args.TRIGGER)
trigger_utils.ParseBuildConfigArgsForUpdate(
trigger,
old_trigger,
args,
messages,
update_mask,
default_image=default_image,
has_repo_source=True,
has_file_source=True,
)
trigger.filter = args.subscription_filter
return trigger
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: An argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated webhook trigger.
"""
client = cloudbuild_util.GetClientInstance()
messages = cloudbuild_util.GetMessagesModule()
project = properties.VALUES.core.project.Get(required=True)
regionprop = properties.VALUES.builds.region.Get()
location = args.region or regionprop or cloudbuild_util.DEFAULT_REGION
triggerid = args.TRIGGER
name = resources.REGISTRY.Parse(
triggerid,
params={
'projectsId': project,
'locationsId': location,
'triggersId': triggerid,
},
collection='cloudbuild.projects.locations.triggers',
).RelativeName()
old_trigger = client.projects_locations_triggers.Get(
client.MESSAGES_MODULE.CloudbuildProjectsLocationsTriggersGetRequest(
name=name, triggerId=triggerid
)
)
update_mask = []
trigger = self.ParseTriggerFromFlags(args, old_trigger, update_mask)
trigger.webhookConfig = messages.WebhookConfig(secret=args.secret)
# Overwrite the substitutions.additionalProperties in updateMask.
sub = 'substitutions'
update_mask.extend(cloudbuild_util.MessageToFieldPaths(trigger))
update_mask = sorted(
set(sub if m.startswith(sub) else m for m in update_mask)
)
req = messages.CloudbuildProjectsLocationsTriggersPatchRequest(
resourceName=name,
triggerId=triggerid,
buildTrigger=trigger,
updateMask=','.join(update_mask),
)
updated_trigger = client.projects_locations_triggers.Patch(req)
log.UpdatedResource(triggerid, kind='build_trigger')
return updated_trigger