예제 #1
0
    def Run(self, args):
        """Clone a GCP repository to the current directory.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      The path to the new git repository.
    """
        # Ensure that we're logged in.
        c_store.Load()

        res = sourcerepo.ParseRepo(args.src)
        source_handler = sourcerepo.Source()

        repo = source_handler.GetRepo(res)
        if hasattr(repo, 'mirrorConfig') and repo.mirrorConfig:
            mirror_url = repo.mirrorConfig.url
            self.ActionIfMirror(project=res.projectsId,
                                repo=args.src,
                                mirror_url=mirror_url)
        # do the actual clone
        git_helper = git.Git(res.projectsId, args.src, uri=repo.url)
        path = git_helper.Clone(destination_path=args.dst or args.src,
                                dry_run=args.dry_run,
                                full_path=self.UseFullGcloudPath(args))
        if path and not args.dry_run:
            log.status.write('Project [{prj}] repository [{repo}] was cloned '
                             'to [{path}].\n'.format(prj=res.projectsId,
                                                     path=path,
                                                     repo=args.src))
예제 #2
0
    def Run(self, args):
        """Delete a named GCP repository in the current project.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      The path to the deleted git repository.

    Raises:
      ToolException: on project initialization errors.
    """
        res = resources.REGISTRY.Parse(
            args.repository_name,
            params={'projectsId': properties.VALUES.core.project.GetOrFail},
            collection='sourcerepo.projects.repos')
        delete_warning = (
            'If {repo} is deleted, the name cannot be reused for up '
            'to seven days.'.format(repo=res.Name()))
        prompt_string = ('Delete "{repo}" in project "{prj}"'.format(
            repo=res.Name(), prj=res.projectsId))
        if console_io.PromptContinue(message=delete_warning,
                                     prompt_string=prompt_string,
                                     default=True):
            sourcerepo_handler = sourcerepo.Source()
            # This returns an empty proto buffer as a response, so there's
            # nothing to return.
            sourcerepo_handler.DeleteRepo(res)
            log.DeletedResource(res.Name())
            return res.Name()
예제 #3
0
    def Run(self, args):
        """Delete a named GCP repository in the current project.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      The path to the deleted git repository.

    Raises:
      sourcerepo.RepoResourceError: on resource initialization errors.
      apitools.base.py.exceptions.HttpError: on request errors.
    """
        res = sourcerepo.ParseRepo(args.repository_name)
        delete_warning = (
            'If {repo} is deleted, the name cannot be reused for up '
            'to seven days.'.format(repo=res.Name()))
        prompt_string = ('Delete "{repo}" in project "{prj}"'.format(
            repo=res.Name(), prj=res.projectsId))
        if console_io.PromptContinue(message=delete_warning,
                                     prompt_string=prompt_string,
                                     default=True):
            sourcerepo_handler = sourcerepo.Source()
            # This returns an empty proto buffer as a response, so there's
            # nothing to return.
            sourcerepo_handler.DeleteRepo(res)
            log.DeletedResource(res.Name())
            return res.Name()
예제 #4
0
 def Run(self, args):
     """Run the list command."""
     res = sourcerepo.GetDefaultProject()
     source_handler = sourcerepo.Source()
     return source_handler.ListRepos(res,
                                     limit=args.limit,
                                     page_size=args.page_size)
예제 #5
0
    def Run(self, args):
        """Create a GCP repository to the current directory.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      (sourcerepo_v1_messages.Repo) The created respository.

    Raises:
      ToolException: on project initialization errors, on missing billing
        account, and when the repo name is already in use.
    """
        res = sourcerepo.ParseRepo(args.repository_name)
        # check that the name does not have forbidden characters.
        # we'd like to do this by putting the validator in the flag type, but
        # we cannot for now because it needs to work on the parsed name.
        flags.REPO_NAME_VALIDATOR(res.Name())
        source_handler = sourcerepo.Source()

        try:
            repo = source_handler.CreateRepo(res)
            if repo:
                log.CreatedResource(res.Name())
                log.warn('You may be billed for this repository. '
                         'See {url} for details.'.format(url=_BILLING_URL))
                return repo
        except exceptions.HttpError as error:
            exc = c_exc.HttpException(error)
            exc.error_format = _ERROR_FORMAT
            if 'API is not enabled' in unicode(exc):
                link = _LINK_FORMAT.format(
                    project=properties.VALUES.core.project.GetOrFail())
                exc.error_format += link
            raise exc
예제 #6
0
 def Run(self, args):
     """Run the list command."""
     res = resources.REGISTRY.Parse(
         None,
         params={'projectsId': properties.VALUES.core.project.GetOrFail},
         collection='sourcerepo.projects')
     source_handler = sourcerepo.Source()
     return source_handler.ListRepos(res,
                                     limit=args.limit,
                                     page_size=args.page_size)
예제 #7
0
    def Run(self, args):
        """Create a GCP repository to the current directory.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      (sourcerepo_v1_messages.Repo) The created respository.

    Raises:
      ToolException: on project initialization errors, on missing billing
        account, and when the repo name is already in use.
    """
        res = resources.REGISTRY.Parse(
            args.repository_name,
            params={'projectsId': properties.VALUES.core.project.GetOrFail},
            collection='sourcerepo.projects.repos')
        # check that the name does not have forbidden characters.
        # we'd like to do this by putting the validator in the flag type, but
        # we cannot for now because it needs to work on the parsed name.
        flags.REPO_NAME_VALIDATOR(res.Name())
        source_handler = sourcerepo.Source()

        # This service enabled check can be removed when cl/148491846 is ready
        if not enable_api.IsServiceEnabled(res.projectsId,
                                           _SOURCEREPO_SERVICE_NAME):
            message = ('{api} is required for repository creation and is not '
                       'enabled.'.format(api=_SOURCEREPO_SERVICE_NAME))
            if console_io.PromptContinue(
                    message=message,
                    prompt_string='Would you like to enable it?',
                    default=True):
                operation = enable_api.EnableServiceApiCall(
                    res.projectsId, _SOURCEREPO_SERVICE_NAME)
                # wait for the operation to complete, will raise an exception if the
                # operation fails.
                services_util.ProcessOperationResult(operation, async=False)
            else:
                error_message = ('Cannot create a repository without enabling '
                                 '{api}'.format(api=_SOURCEREPO_SERVICE_NAME))
                raise exceptions.Error(error_message)
        try:
            repo = source_handler.CreateRepo(res)
            if repo:
                log.CreatedResource(res.Name())
                log.Print('You may be billed for this repository. '
                          'See {url} for details.'.format(url=_BILLING_URL))
                return repo
        except exceptions.HttpError as error:
            exc = c_exc.HttpException(error)
            exc.error_format = _ERROR_FORMAT
            raise exc
    def Run(self, args):
        """Gets the IAM policy for the repository.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      (sourcerepo_v1_messages.Policy) The IAM policy.

    Raises:
      ToolException: on project initialization errors.
    """
        res = sourcerepo.ParseRepo(args.repository_name)
        source = sourcerepo.Source()
        return source.GetIamPolicy(res)
예제 #9
0
    def Run(self, args):
        """Gets the IAM policy for the repository.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      (sourcerepo_v1_messages.Policy) The IAM policy.

    Raises:
      sourcerepo.RepoResourceError: on resource initialization errors.
      apitools.base.py.exceptions.HttpError: on request errors.
    """
        res = sourcerepo.ParseRepo(args.repository_name)
        source = sourcerepo.Source()
        return source.GetIamPolicy(res)
예제 #10
0
    def Run(self, args):
        """Describe a named GCP repository in the current project.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      (sourcerepo_v1_messages.Repo) The named repository.

    Raises:
      sourcerepo.RepoResourceError: on resource initialization errors.
      apitools.base.py.exceptions.HttpError: on request errors.
    """
        res = sourcerepo.ParseRepo(args.repository_name)
        sourcerepo_handler = sourcerepo.Source()
        return sourcerepo_handler.GetRepo(res)
예제 #11
0
  def Run(self, args):
    """Describe a named GCP repository in the current project.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      (sourcerepo_v1_messages.Repo) The named repository.

    Raises:
      ToolException: on project initialization errors.
    """
    res = resources.REGISTRY.Parse(
        args.repository_name,
        params={'projectsId': properties.VALUES.core.project.GetOrFail},
        collection='sourcerepo.projects.repos')
    sourcerepo_handler = sourcerepo.Source()
    return sourcerepo_handler.GetRepo(res)
예제 #12
0
  def Run(self, args):
    """Gets the IAM policy for the repository.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      (sourcerepo_v1_messages.Policy) The IAM policy.

    Raises:
      ToolException: on project initialization errors.
    """
    res = resources.REGISTRY.Parse(
        args.repository_name,
        params={'projectsId': properties.VALUES.core.project.GetOrFail},
        collection='sourcerepo.projects.repos')
    source = sourcerepo.Source()
    return source.GetIamPolicy(res)
예제 #13
0
    def Run(self, args):
        """Clone a GCP repository to the current directory.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Raises:
      ToolException: on project initialization errors.
      RepoCreationError: on repo creation errors.

    Returns:
      The path to the new git repository.
    """
        # Ensure that we're logged in.
        c_store.Load()

        res = resources.REGISTRY.Parse(
            args.src,
            params={'projectsId': properties.VALUES.core.project.GetOrFail},
            collection='sourcerepo.projects.repos')
        source_handler = sourcerepo.Source()

        repo = source_handler.GetRepo(res)
        if not repo:
            message = ('Repository "{src}" in project "{prj}" does not '
                       'exist.\nList current repos with\n'
                       '$ gcloud beta source repos list\n'
                       'or create with\n'
                       '$ gcloud beta source repos create {src}'.format(
                           src=args.src, prj=res.projectsId))
            raise c_exc.InvalidArgumentException('REPOSITORY_NAME', message)
        if hasattr(repo, 'mirrorConfig') and repo.mirrorConfig:
            mirror_url = repo.mirrorConfig.url
            self.ActionIfMirror(args.src, res.projectsId, mirror_url)
        # do the actual clone
        git_helper = git.Git(res.projectsId, args.src, uri=repo.url)
        path = git_helper.Clone(destination_path=args.dst or args.src,
                                dry_run=args.dry_run,
                                full_path=self.UseFullGcloudPath(args))
        if path and not args.dry_run:
            log.status.write('Project [{prj}] repository [{repo}] was cloned '
                             'to [{path}].\n'.format(prj=res.projectsId,
                                                     path=path,
                                                     repo=args.src))
    def Run(self, args):
        """Sets the IAM policy for the repository.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      (sourcerepo_v1_messsages.Policy) The IAM policy.

    Raises:
      ToolException: on project initialization errors.
    """
        res = sourcerepo.ParseRepo(args.name)
        source = sourcerepo.Source()
        policy = iam_util.ParseYamlorJsonPolicyFile(args.policy_file,
                                                    source.messages.Policy)
        result = source.SetIamPolicy(res, policy)
        iam_util.LogSetIamPolicy(res.Name(), 'repo')
        return result
예제 #15
0
    def Run(self, args):
        """Sets the IAM policy for the repository.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      (sourcerepo_v1_messsages.Policy) The IAM policy.

    Raises:
      sourcerepo.RepoResourceError: on resource initialization errors.
      iam_util.BadFileException: if the YAML or JSON file is malformed.
      iam_util.IamEtagReadError: if the etag is badly formatted.
      apitools.base.py.exceptions.HttpError: on request errors.
    """
        res = sourcerepo.ParseRepo(args.name)
        source = sourcerepo.Source()
        policy = iam_util.ParseYamlorJsonPolicyFile(args.policy_file,
                                                    source.messages.Policy)
        result = source.SetIamPolicy(res, policy)
        iam_util.LogSetIamPolicy(res.Name(), 'repo')
        return result
예제 #16
0
    def Run(self, args):
        """Sets the IAM policy for the repository.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      (sourcerepo_v1_messsages.Policy) The IAM policy.

    Raises:
      ToolException: on project initialization errors.
    """
        res = resources.REGISTRY.Parse(
            args.name,
            params={'projectsId': properties.VALUES.core.project.GetOrFail},
            collection='sourcerepo.projects.repos')
        source = sourcerepo.Source()
        policy = iam_util.ParseYamlorJsonPolicyFile(args.policy_file,
                                                    source.messages.Policy)
        result = source.SetIamPolicy(res, policy)
        iam_util.LogSetIamPolicy(res.Name(), 'repo')
        return result
    def Upload(self, branch, root_path):
        """Uploads files to a branch in Cloud Source Repositories.

    Args:
      branch: (string) The name of the branch to upload to. If empty, a
        name will be generated.
      root_path: (string) The path of a directory tree to upload.

    Returns:
      A dictionary containing various status information:
        'branch': The name of the branch.
        'source_contexts': One or more dictionaries compatible with the
          ExtendedSourceContext message, including one context pointing
          to the upload. This context will be the only one with the value
          'capture' for its 'category' label.
        'files_written': The number of files uploaded.
        'files_skipped': The number of files skipped.
        'size_written': The total number of bytes in all files uploaded.
    """
        if not sourcerepo.Source().GetRepo(
                sourcerepo.ParseRepo(UPLOAD_REPO_NAME)):
            raise exceptions.Error(
                REPO_NOT_FOUND_ERROR.format(UPLOAD_REPO_NAME,
                                            self._project_id))

        branch = branch or (_GetNow().strftime(TIME_FORMAT) + '.' +
                            _GetUuid().hex)
        all_paths = [
            f
            for f in self._ignore_handler.GetFiles(os.path.abspath(root_path))
            if not os.path.islink(f)
        ]
        paths = [
            f for f in all_paths if os.path.getsize(f) <= self.SIZE_THRESHOLD
        ]
        git.Git(self._project_id, UPLOAD_REPO_NAME).ForcePushFilesToBranch(
            branch, root_path, paths)

        source_context = {
            'context': {
                'cloudRepo': {
                    'repoId': {
                        'projectRepoId': {
                            'projectId': self._project_id,
                            'repoName': UPLOAD_REPO_NAME
                        }
                    },
                    'aliasContext': {
                        'kind': 'MOVABLE',
                        'name': branch
                    }
                }
            },
            'labels': {
                'category': 'capture'
            }
        }

        return {
            'branch': branch,
            'source_contexts': [source_context],
            'files_written': len(paths),
            'files_skipped': len(all_paths) - len(paths),
            'size_written': sum([os.path.getsize(f) for f in paths])
        }
예제 #18
0
 def Run(self, args):
     client = sourcerepo.Source()
     repo_ref = args.CONCEPTS.repo.Parse()
     repo = client.GetRepo(repo_ref)
     updated_repo = util.ParseSourceRepoWithModifiedTopic(args, repo)
     return client.PatchRepo(updated_repo, 'pubsubConfigs')