Esempio n. 1
0
 def _VerifyGitHubCSRRepoExists(self, csr_repo_name, github_repo_owner,
                                github_repo_name):
   try:
     csr_repo_ref = sourcerepo.ParseRepo(csr_repo_name)
     csr_repo = sourcerepo.Source().GetRepo(csr_repo_ref)
     if not csr_repo.mirrorConfig:
       raise c_exceptions.InvalidArgumentException(
           '--repo-type',
           "Repo '{}/{}' is found but the resolved repo name '{}' is a "
           'regular CSR repo. Reference it with --repo-type=csr and '
           '--repo-name={}.'
           .format(github_repo_owner, github_repo_name, csr_repo_name,
                   csr_repo_name))
     if (csr_repo.mirrorConfig and
         not csr_repo.mirrorConfig.url.startswith('https://github.com/')):
       log.error("CSR repo '{}' has mirrorConfig.url of {}", csr_repo_name,
                 csr_repo.mirrorConfig.url)
       raise c_exceptions.InvalidArgumentException(
           '--repo-type',
           "Repo '{}/{}' is found but the resolved repo name '{}' is not "
           'connected to a GitHub repo. Specify the correct value for '
           '--repo-type.'
           .format(github_repo_owner, github_repo_name, csr_repo_name))
   except HttpNotFoundError:
     raise SourceRepoNotConnectedException(
         '--repo-name',
         "GitHub repo '{}/{}' is not connected to CSR.".format(
             github_repo_owner, github_repo_name))
Esempio n. 2
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)
Esempio n. 3
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(use_google_auth=True)

        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))
Esempio n. 4
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()
Esempio n. 5
0
 def SetUp(self):
     properties.VALUES.core.project.Set(self.Project())
     self.source_handler = sourcerepo.Source()
     self.repo_ref = resources.REGISTRY.Parse(
         'test_repo',
         params={'projectsId': 'testproject'},
         collection='sourcerepo.projects.repos')
Esempio n. 6
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)
Esempio n. 7
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)
Esempio n. 8
0
 def _VerifyCSRRepoExists(self, csr_repo_name):
     try:
         csr_repo_ref = sourcerepo.ParseRepo(csr_repo_name)
         csr_repo = sourcerepo.Source().GetRepo(csr_repo_ref)
         if csr_repo.mirrorConfig:
             log.error("CSR repo '{}' has mirrorConfig.url of {}",
                       csr_repo_name, csr_repo.mirrorConfig.url)
             raise c_exceptions.InvalidArgumentException(
                 '--repo-type',
                 "Repo '{}' is found but is connected to {}. Specify the correct "
                 'value for --repo-type, along with appropriate values for '
                 '--repo-owner and --repo-name.'.format(
                     csr_repo_name, csr_repo.mirrorConfig.url))
     except HttpNotFoundError:
         raise c_exceptions.InvalidArgumentException(
             '--repo-name',
             "Repo '{}' is not found on CSR.".format(csr_repo_name))
Esempio n. 9
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, unused_mask = iam_util.ParseYamlOrJsonPolicyFile(
            args.policy_file, source.messages.Policy)
        result = source.SetIamPolicy(res, policy)
        iam_util.LogSetIamPolicy(res.Name(), 'repo')
        return result
Esempio n. 10
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:
      sourcerepo.RepoResourceError: on resource initialization errors.
      c_exc.HttpException: 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.warning('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 text_type(exc):
                link = _LINK_FORMAT.format(
                    project=properties.VALUES.core.project.GetOrFail())
                exc.error_format += link
            raise exc
Esempio n. 11
0
    def Upload(self, branch, root_path, ignore_file=None):
        """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.
      ignore_file: (string) The file overrides the `.gcloudignore` file and
        uses the specified file instead.

    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.
    """
        try:
            sourcerepo.Source().GetRepo(sourcerepo.ParseRepo(UPLOAD_REPO_NAME))
        except exceptions.HttpNotFoundError:
            raise RepoNotFoundError(
                REPO_NOT_FOUND_ERROR.format(UPLOAD_REPO_NAME,
                                            self._project_id))

        file_chooser = gcloudignore.GetFileChooserForDir(
            root_path, write_on_disk=False, ignore_file=ignore_file)
        branch = branch or (_GetNow().strftime(TIME_FORMAT) + '.' +
                            _GetUuid().hex)
        all_paths = [
            os.path.join(root_path, f)
            for f in file_chooser.GetIncludedFiles(root_path,
                                                   include_dirs=False)
        ]
        paths = [
            f for f in all_paths if not os.path.islink(f)
            and os.path.getsize(f) <= self.SIZE_THRESHOLD
        ]
        git.Git(self._project_id, UPLOAD_REPO_NAME).ForcePushFilesToBranch(
            branch, root_path, sorted(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])
        }
Esempio n. 12
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')