def ParseTriggerArgs(args, messages): """Parses flags generic to all triggers. Args: args: An argparse arguments object. messages: A Cloud Build messages module Returns: A partially populated build trigger and a boolean indicating whether or not the full trigger was loaded from a file. """ 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']) return trigger, True trigger = messages.BuildTrigger() trigger.name = args.name trigger.description = args.description trigger.serviceAccount = args.service_account ParseRequireApproval(trigger, args, messages) return trigger, False
def test_export(self): trigger = self.msg.BuildTrigger( github=self.msg.GitHubEventsConfig( owner='gcb', name='test', pullRequest=self.msg.PullRequestFilter( branch='.*', commentControl=self.msg.PullRequestFilter. CommentControlValueValuesEnum.COMMENTS_ENABLED, ), ), filename='cloudbuild.yaml', substitutions=encoding.PyValueToMessage( self.msg.BuildTrigger.SubstitutionsValue, {'_FAVORITE_COLOR': 'blue'}), ) path = self.Touch('.', 'trigger.yaml', contents='') self.mocked_cloudbuild_v1.projects_triggers.Get.Expect( self.msg.CloudbuildProjectsTriggersGetRequest( projectId='my-project', triggerId='my-trigger'), response=trigger) properties.VALUES.core.user_output_enabled.Set(False) self.Run([ 'alpha', 'builds', 'triggers', 'export', 'my-trigger', '--destination', path ]) got = cloudbuild_util.LoadMessageFromPath( path, self.msg.BuildTrigger, 'BuildTrigger', skip_camel_case=['substitutions']) self.assertEqual(trigger, got)
def ParseBuildConfigArgs(trigger, args, messages, default_image, need_repo=False): """Parses build-config flags. Args: trigger: The trigger to populate. args: An argparse arguments object. messages: A Cloud Build messages module. default_image: The docker image to use if args.dockerfile_image is empty. need_repo: Whether or not a repo needs to be included explicitly in flags. """ if args.build_config: # If we don't need a repo, then the repository information is already known # and we just need the filename. Otherwise, this trigger needs to # be a GitFileSource trigger (which is taken care of in ParseGitRepoSource). if not need_repo: trigger.filename = args.build_config trigger.substitutions = cloudbuild_util.EncodeTriggerSubstitutions( args.substitutions, messages) if args.dockerfile: if args.substitutions: raise c_exceptions.ConflictingArgumentsException( 'Dockerfile and substitutions', 'Substitutions are not supported with a Dockerfile configuration.') image = args.dockerfile_image or default_image trigger.build = messages.Build(steps=[ messages.BuildStep( name='gcr.io/cloud-builders/docker', dir=args.dockerfile_dir, args=['build', '-t', image, '-f', args.dockerfile, '.'], ) ]) if args.inline_config: trigger.build = cloudbuild_util.LoadMessageFromPath(args.inline_config, messages.Build, 'inline build config', ['substitutions']) trigger.substitutions = cloudbuild_util.EncodeTriggerSubstitutions( args.substitutions, messages) if need_repo: # Repo is required if a build config (filename) or dockerfile was provided. required = args.build_config or args.dockerfile ParseGitRepoSource(trigger, args, messages, required=required)
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) location = args.region 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 LoadWorkerpoolConfigFromPath(path, messages): """Load a workerpool config file into a WorkerPool message. Args: path: str. Path to the JSON or YAML data to be decoded. messages: module, The messages module that has a WorkerPool type. Raises: files.MissingFileError: If the file does not exist. ParserError: If there was a problem parsing the file as a dict. ParseProtoException: If there was a problem interpreting the file as the given message type. Returns: WorkerPool message, The worker pool that got decoded. """ wp = cloudbuild_util.LoadMessageFromPath(path, messages.WorkerPool, _WORKERPOOL_CONFIG_FRIENDLY_NAME) return wp
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 = 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 = self.ParseTriggerFromFlags(args) # Send the Create request project = properties.VALUES.core.project.Get(required=True) created_trigger = client.projects_triggers.Create( messages.CloudbuildProjectsTriggersCreateRequest( buildTrigger=trigger, projectId=project)) trigger_resource = resources.REGISTRY.Parse( None, collection='cloudbuild.projects.triggers', api_version='v1', params={ 'projectId': project, 'triggerId': created_trigger.id, }) log.CreatedResource(trigger_resource) return created_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() project = properties.VALUES.core.project.Get(required=True) trigger = cloudbuild_util.LoadMessageFromPath( args.source, messages.BuildTrigger, 'BuildTrigger', skip_camel_case=['substitutions']) resp = None if trigger.id: # Trigger already has an ID - only try update. resp = self._UpdateTrigger(client, messages, project, trigger.id, 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: resp = self._UpdateTrigger(client, messages, project, trigger.name, trigger) except apitools_exceptions.HttpNotFoundError: resp = self._CreateTrigger(client, messages, project, trigger) else: # No identifying information specified. Create a trigger with the given # specification. resp = self._CreateTrigger(client, messages, project, trigger) if resp and resp != trigger: with files.FileWriter(args.source) as out: yaml.dump(encoding.MessageToDict(resp), stream=out) return resp
def LoadCloudbuildConfigFromPath(path, messages, params=None): """Load a cloudbuild config file into a Build message. Args: path: str. Path to the JSON or YAML data to be decoded. messages: module, The messages module that has a Build type. params: dict, parameters to substitute into a templated Build spec. Raises: files.MissingFileError: If the file does not exist. ParserError: If there was a problem parsing the file as a dict. ParseProtoException: If there was a problem interpreting the file as the given message type. InvalidBuildConfigException: If the build config has illegal values. Returns: Build message, The build that got decoded. """ build = cloudbuild_util.LoadMessageFromPath(path, messages.Build, _BUILD_CONFIG_FRIENDLY_NAME, _SKIP_CAMEL_CASE) build = FinalizeCloudbuildConfig(build, path, params) return build
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 = 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: repo_ref = args.CONCEPTS.repo.Parse() repo = repo_ref.reposId trigger = messages.BuildTrigger( description=args.description, triggerTemplate=messages.RepoSource( repoName=repo, branchName=args.branch_pattern, tagName=args.tag_pattern, ), ) # Build Config if args.build_config: trigger.filename = args.build_config trigger.substitutions = cloudbuild_util.EncodeTriggerSubstitutions( args.substitutions, messages) if args.dockerfile: project = properties.VALUES.core.project.Get(required=True) image = args.dockerfile_image if args.dockerfile_image else 'gcr.io/%s/%s:$COMMIT_SHA' % ( project, repo) trigger.build = messages.Build(steps=[ messages.BuildStep( name='gcr.io/cloud-builders/docker', dir=args.dockerfile_dir, args=[ 'build', '-t', image, '-f', args.dockerfile, '.' ], ) ]) # Include/Exclude files if args.included_files: trigger.includedFiles = args.included_files if args.ignored_files: trigger.ignoredFiles = args.ignored_files # Send the Create request project = properties.VALUES.core.project.Get(required=True) created_trigger = client.projects_triggers.Create( messages.CloudbuildProjectsTriggersCreateRequest( buildTrigger=trigger, projectId=project)) trigger_resource = resources.REGISTRY.Parse( None, collection='cloudbuild.projects.triggers', api_version='v1', params={ 'projectId': project, 'triggerId': created_trigger.id, }) log.CreatedResource(trigger_resource) return created_trigger
def ParseSamplingInfo(path): messages = edge_util.GetMessagesModule() sampling_info = cloudbuild_util.LoadMessageFromPath( path, messages.MlSamplingInfo, 'Edge ML sampling info') return sampling_info
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() # Convert 'repo type' input string to proto. git_file_source_type = messages.GitFileSource.RepoTypeValueValuesEnum.UNKNOWN git_repo_source_type = messages.GitRepoSource.RepoTypeValueValuesEnum.UNKNOWN if args.repo_type == 'CLOUD_SOURCE_REPOSITORIES': git_file_source_type = messages.GitFileSource.RepoTypeValueValuesEnum.CLOUD_SOURCE_REPOSITORIES git_repo_source_type = messages.GitRepoSource.RepoTypeValueValuesEnum.CLOUD_SOURCE_REPOSITORIES elif args.repo_type == 'GITHUB': git_file_source_type = messages.GitFileSource.RepoTypeValueValuesEnum.GITHUB git_repo_source_type = messages.GitRepoSource.RepoTypeValueValuesEnum.GITHUB 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 = messages.BuildTrigger( name=args.name, description=args.description, cron=messages.CronConfig( schedule=args.schedule, timeZone=args.time_zone, ), ) # Source To Build trigger.sourceToBuild = messages.GitRepoSource( uri=args.repo_uri, ref=args.revision, repoType=git_repo_source_type, ) # Build Config if args.build_config: trigger.gitFileSource = messages.GitFileSource( path=args.build_config, uri=args.repo_uri, repoType=git_file_source_type, revision=args.revision, ) trigger.substitutions = cloudbuild_util.EncodeTriggerSubstitutions( args.substitutions, messages) # Send the Create request project = properties.VALUES.core.project.Get(required=True) created_trigger = client.projects_triggers.Create( messages.CloudbuildProjectsTriggersCreateRequest( buildTrigger=trigger, projectId=project)) trigger_resource = resources.REGISTRY.Parse( None, collection='cloudbuild.projects.triggers', api_version='v1', params={ 'projectId': project, 'triggerId': created_trigger.id, }) log.CreatedResource(trigger_resource) return created_trigger
def ParseTopicBridgingTable(unused_ref, args, req): messages = util.GetMessagesModule() parsed_table = cloudbuild_util.LoadMessageFromPath( args.rule_file, messages.TopicBridgingTable, 'topic bridging table') req.rules = parsed_table.rules return req