Exemplo n.º 1
0
    def PromptForScope(self, ambiguous_refs, attribute, service, resource_type,
                       flag_name, prefix_filter):
        """Prompts the user to resolve abiguous resources."""
        # targetInstances -> target instances
        resource_name = utils.CamelCaseToOutputFriendly(resource_type)
        # Resource names should be surrounded by brackets while choices should not
        names = ['[{0}]'.format(name) for name, _ in ambiguous_refs]
        choice_resources = self.FetchChoiceResources(attribute, service,
                                                     flag_name, prefix_filter)
        # Print deprecation state for choices.
        choice_names = []
        for choice_resource in choice_resources:
            deprecated = choice_resource.deprecated
            if deprecated:
                choice_name = '{0} ({1})'.format(choice_resource.name,
                                                 deprecated.state)
            else:
                choice_name = choice_resource.name
            choice_names.append(choice_name)

        title = utils.ConstructList(
            'For the following {0}:'.format(resource_name), names)
        idx = console_io.PromptChoice(options=choice_names,
                                      message='{0}choose a {1}:'.format(
                                          title, attribute))
        if idx is None:
            raise exceptions.ToolException(
                'Unable to prompt. Specify the [{0}] flag.'.format(flag_name))
        choice_resource = choice_resources[idx]
        for _, resource_ref in ambiguous_refs:
            setattr(resource_ref, attribute, choice_resource.name)
Exemplo n.º 2
0
    def _PromptForScopeList(self, ambiguous_refs, attribute, resource_type,
                            choice_resources, raise_on_prompt_failure):
        """Prompt to resolve abiguous resources.  Either returns str or throws."""

        # targetInstances -> target instances
        resource_name = utils.CamelCaseToOutputFriendly(resource_type)
        # Resource names should be surrounded by brackets while choices should not
        names = ['[{0}]'.format(name) for name, _ in ambiguous_refs]
        # Print deprecation state for choices.
        choice_names = []
        for choice_resource in choice_resources:
            deprecated = choice_resource.deprecated
            if deprecated:
                choice_name = '{0} ({1})'.format(choice_resource.name,
                                                 deprecated.state)
            else:
                choice_name = choice_resource.name
            choice_names.append(choice_name)

        title = utils.ConstructList(
            'For the following {0}:'.format(resource_name), names)
        idx = console_io.PromptChoice(options=choice_names,
                                      message='{0}choose a {1}:'.format(
                                          title, attribute))
        if idx is None:
            raise_on_prompt_failure()
        else:
            return choice_resources[idx].name
Exemplo n.º 3
0
  def Run(self, args):
    """Runs the remove command."""
    repos = update_manager.UpdateManager.GetAdditionalRepositories()
    removed_repos = []

    # Removing all URLs.
    if args.all:
      removed_repos.extend(repos)
      repos = []

    # Specifying URLs to remove explicitly.
    elif args.url:
      if not repos:
        raise exceptions.ToolException('You have no registered repositories.')
      for url in args.url:
        if url not in repos:
          raise exceptions.ToolException(
              'URL [{0}] was not a known registered repository.'.format(url))
      for url in args.url:
        repos.remove(url)
      removed_repos.extend(args.url)

    # No URL specified, prompt to choose one.
    else:
      if not repos:
        raise exceptions.ToolException('You have no registered repositories.')
      result = console_io.PromptChoice(
          repos, default=None,
          message='Which repository would you like to remove?')
      if result is None:
        log.status.Print('No repository was removed.')
      else:
        removed_repos.append(repos.pop(result))

    if removed_repos:
      properties.PersistProperty(
          properties.VALUES.component_manager.additional_repositories,
          ','.join(repos) if repos else None,
          scope=properties.Scope.INSTALLATION)

    for removed_repo in removed_repos:
      log.status.Print('Removed repository: [{repo}]'.format(repo=removed_repo))
    return removed_repos
Exemplo n.º 4
0
  def ExpandImageFlag(self, args, return_image_resource=False):
    """Resolves the --image flag value.

    If the value of --image is one of the aliases defined in the
    constants module, both the user's project and the public image
    project for the alias are queried. Otherwise, only the user's
    project is queried. If --image is an alias and --image-project is
    provided, only the given project is queried.

    Args:
      args: The command-line flags. The flags accessed are --image and
        --image-project.
      return_image_resource: If True, always makes an API call to also
        fetch the image resource.

    Returns:
      A tuple where the first element is the self link of the image. If
        return_image_resource is False, the second element is None, otherwise
        it is the image resource.
    """
    image_ref = self.resources.Parse(
        args.image or constants.DEFAULT_IMAGE,
        collection='compute.images',
        resolve=False)

    # If an image project was specified, then assume that image refers
    # to an image in that project.
    if args.image_project:
      image_project_ref = self.resources.Parse(
          args.image_project,
          collection='compute.projects')
      image_ref.project = image_project_ref.Name()
      image_ref.Resolve()
      return (image_ref.SelfLink(),
              self.GetImage(image_ref) if return_image_resource else None)

    image_ref.Resolve()
    alias = constants.IMAGE_ALIASES.get(image_ref.Name())

    # Check for hidden aliases.
    if not alias:
      alias = constants.HIDDEN_IMAGE_ALIASES.get(image_ref.Name())

    # If the image name given is not an alias and no image project was
    # provided, then assume that the image value refers to an image in
    # the user's project.
    if not alias:
      return (image_ref.SelfLink(),
              self.GetImage(image_ref) if return_image_resource else None)

    # At this point, the image is an alias and now we have to find the
    # latest one among the public image project and the user's
    # project.

    errors = []
    images = self.GetMatchingImages(image_ref.Name(), alias, errors)

    user_image = None
    public_images = []

    for image in images:
      if image.deprecated:
        continue
      if '/projects/{0}/'.format(self.project) in image.selfLink:
        user_image = image
      else:
        public_images.append(image)

    if errors or not public_images:
      # This should happen only if there is something wrong with the
      # image project (e.g., operator error) or the global control
      # plane is down.
      utils.RaiseToolException(
          errors,
          'Failed to find image for alias [{0}] in public image project [{1}].'
          .format(image_ref.Name(), alias.project))

    def GetVersion(image):
      """Extracts the "20140718" from an image name like "debian-v20140718"."""
      parts = image.name.rsplit('v', 1)
      if len(parts) != 2:
        log.debug('Skipping image with malformed name [%s].', image.name)
        return None
      return parts[1]

    public_candidate = max(public_images, key=GetVersion)
    if user_image:
      options = [user_image, public_candidate]

      idx = console_io.PromptChoice(
          options=[image.selfLink for image in options],
          default=0,
          message=('Found two possible choices for [--image] value [{0}].'
                   .format(image_ref.Name())))

      res = options[idx]

    else:
      res = public_candidate

    log.debug('Image resolved to [%s].', res.selfLink)
    return (res.selfLink, res if return_image_resource else None)