Beispiel #1
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.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 args.force or 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()
Beispiel #2
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)
Beispiel #3
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.
    """
    project_id = resolvers.FromProperty(properties.VALUES.core.project)
    res = resources.REGISTRY.Parse(
        args.name,
        params={'projectsId': project_id},
        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
Beispiel #4
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()

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

    # Check for the existence of the named repo in the project and maybe ask
    # the user whether they want to create it if it does not already exist.
    #
    # Note that repo creation can fail if there is a concurrent attempt to
    # create the repo (e.g. through another call to gcloud or a concurrent
    # attempt in the developer console through a browser).
    repo = source_handler.GetRepo(res)
    if not repo:
      message = ('Repository "{src}" in project "{prj}" does not yet '
                 'exist.'.format(src=args.src, prj=res.projectsId))
      prompt_string = 'Would you like to create it'
      if args.autocreate or console_io.PromptContinue(
          message=message, prompt_string=prompt_string, default=True):
        repo = source_handler.CreateRepo(res)
      else:
        message = ('Cannot clone from a non-existent repo. Please create it '
                   'with:\n  $ gcloud alpha source repos create {src}\n and '
                   'try cloning again.'.format(src=args.src))
        raise exceptions.InvalidUserInputError(message)
    # 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)
    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))
Beispiel #5
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()

        project_id = resolvers.FromProperty(properties.VALUES.core.project)
        res = resources.REGISTRY.Parse(args.src,
                                       params={'projectsId': project_id},
                                       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
            message = (
                'Repository "{src}" in project "{prj}" is a mirror. Clone the '
                'mirrored repository directly with \n$ git clone '
                '{url}'.format(src=args.src,
                               prj=res.projectsId,
                               url=mirror_url))
            raise c_exc.InvalidArgumentException('REPOSITORY_NAME', message)
        # 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=args.use_full_gcloud_path)
        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))
Beispiel #6
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)
Beispiel #7
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)
Beispiel #8
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.
    """
        project_id = resolvers.FromProperty(properties.VALUES.core.project)

        res = resources.REGISTRY.Parse(args.name,
                                       params={'projectsId': project_id},
                                       collection='sourcerepo.projects.repos')
        policy = iam_util.ParseJsonPolicyFile(args.policy_file,
                                              sourcerepo.messages.Policy)
        source = sourcerepo.Source()
        return source.SetIamPolicy(res, policy)