示例#1
0
 def testPromptResponse(self):
     self.SetAnswers('a string', 'a sentence.', '')
     result = console_io.PromptResponse(message='message')
     self.assertIn('message', self.GetErr())
     self.assertEqual(result, 'a string')
     result = console_io.PromptResponse(message='message')
     self.assertEqual(result, 'a sentence.')
     result = console_io.PromptResponse(message='message')
     self.assertEqual(result, '')
示例#2
0
def _ChooseEntrypoint(default_entrypoint, appinfo):
    """Prompt the user for an entrypoint.

  Args:
    default_entrypoint: (str) Default entrypoint determined from the app.
    appinfo: (apphosting.api.appinfo.AppInfoExternal or None) The parsed
      app.yaml file for the module if it exists.

  Returns:
    (str) The actual entrypoint to use.

  Raises:
    RubyConfigError: Unable to get entrypoint from the user.
  """
    if console_io.CanPrompt():
        if default_entrypoint:
            prompt = (
                '\nPlease enter the command to run this Ruby app in '
                'production, or leave blank to accept the default:\n[{0}] ')
            entrypoint = console_io.PromptResponse(
                prompt.format(default_entrypoint))
        else:
            entrypoint = console_io.PromptResponse(
                '\nPlease enter the command to run this Ruby app in production: '
            )
        entrypoint = entrypoint.strip()
        if not entrypoint:
            if not default_entrypoint:
                raise RubyConfigError('Entrypoint command is required.')
            entrypoint = default_entrypoint
        if appinfo:
            # We've got an entrypoint and the user had an app.yaml that didn't
            # specify it.
            # TODO(mmuller): Offer to edit the user's app.yaml
            msg = (
                '\nTo avoid being asked for an entrypoint in the future, please '
                'add it to your app.yaml. e.g.\n  entrypoint: {0}'.format(
                    entrypoint))
            log.status.Print(msg)
        return entrypoint
    else:
        msg = (
            "This appears to be a Ruby app. You'll need to provide the full "
            'command to run the app in production, but gcloud is not running '
            'interactively and cannot ask for the entrypoint{0}. Please either '
            'run gcloud interactively, or create an app.yaml with '
            '"runtime:ruby" and an "entrypoint" field.'.format(
                ext_runtime_adapter.GetNonInteractiveErrorMessage()))
        raise RubyConfigError(msg)
示例#3
0
def _ProxySetupWalkthrough():
    """Walks user through setting up gcloud proxy properties."""
    proxy_type_options = sorted(t.upper()
                                for t in http_proxy_types.PROXY_TYPE_MAP)
    proxy_type_idx = console_io.PromptChoice(proxy_type_options,
                                             message='Select the proxy type:')
    if proxy_type_idx is None:
        return False
    proxy_type = proxy_type_options[proxy_type_idx].lower()

    address = console_io.PromptResponse('Enter the proxy host address: ')
    log.status.Print()
    if not address:
        return False

    port = console_io.PromptResponse('Enter the proxy port: ')
    log.status.Print()
    # Restrict port number to 0-65535.
    if not port:
        return False
    try:
        if not 0 <= int(port) <= 65535:
            log.status.Print('Port number must be between 0 and 65535.')
            return False
    except ValueError:
        log.status.Print('Please enter an integer for the port number.')
        return False

    username, password = None, None
    authenticated = console_io.PromptContinue(
        prompt_string='Is your proxy authenticated', default=False)
    if authenticated:
        username = console_io.PromptResponse('Enter the proxy username: '******'Enter the proxy password: '******'Cloud SDK proxy properties set.\n')
    return True
示例#4
0
 def Run(self, args):
     """Returns the results for one completion."""
     with cache_util.GetCache(args.cache, create=True) as cache:
         log.info('cache name {}'.format(cache.name))
         if not args.kwargs:
             args.kwargs = {}
         completer = _GetCompleter(args.module_path,
                                   cache=cache,
                                   qualify=args.qualify,
                                   **args.kwargs)
         parameter_info = completer.ParameterInfo(
             args, args.GetPositionalArgument('resource_to_complete'))
         if args.resource_to_complete is not None:
             matches = completer.Complete(args.resource_to_complete,
                                          parameter_info)
             return [matches]
         while True:
             name = console_io.PromptResponse('COMPLETE> ')
             if name is None:
                 break
             try:
                 completions = completer.Complete(name, parameter_info)
             except (Exception, SystemExit) as e:  # pylint: disable=broad-except
                 if args.stack_trace:
                     raise Exception(e), None, sys.exc_info()[2]
                 else:
                     log.error(unicode(e))
                 continue
             if completions:
                 print '\n'.join(completions)
         sys.stderr.write('\n')
         return None
示例#5
0
 def _CreateConfiguration(self):
   configuration_name = console_io.PromptResponse(
       'Enter configuration name:  ')
   named_configs.ConfigurationStore.CreateConfig(configuration_name)
   named_configs.ConfigurationStore.ActivateConfig(configuration_name)
   named_configs.ActivePropertiesFile.Invalidate()
   return configuration_name
示例#6
0
def PickProject(preselected=None):
    """Allows user to select a project.

  Args:
    preselected: str, use this value if not None

  Returns:
    str, project_id or None if was not selected.
  """
    project_ids = _GetProjectIds()

    project_id = preselected or _PromptForProjectId(project_ids)
    if project_ids is None or project_id in project_ids or project_id is None:
        return project_id

    if project_id is _CREATE_PROJECT_SENTINEL:
        project_id = console_io.PromptResponse(_ENTER_PROJECT_ID_MESSAGE)
        if not project_id:
            return None
    else:
        if project_ids:
            message = '[{0}] is not one of your projects [{1}]. '.format(
                project_id, ','.join(project_ids))
        else:
            message = 'This account has no projects.'
        if not console_io.PromptContinue(
                message=message, prompt_string='Would you like to create it?'):
            return None

    _CreateProject(project_id, project_ids)
    return project_id
示例#7
0
    def _CloneRepo(self, repo_name):
        """Queries user for output path and clones selected repo to it."""
        default_clone_path = os.path.join(os.getcwd(), repo_name)
        while True:
            clone_path = console_io.PromptResponse(
                'Where would you like to clone [{0}] repository to [{1}]:'.
                format(repo_name, default_clone_path))
            if not clone_path:
                clone_path = default_clone_path
            if os.path.exists(clone_path):
                log.status.write(
                    'Directory [{0}] already exists\n'.format(clone_path))
                continue
            parent_dir = os.path.dirname(clone_path)
            if not os.path.isdir(parent_dir):
                log.status.write(
                    'No such directory [{0}]\n'.format(parent_dir))
                answer = console_io.PromptContinue(
                    prompt_string='Would you like to create it')
                if answer:
                    files.MakeDir(parent_dir)
                    break
            else:
                break

        self._RunCmd(['source', 'repos', 'clone'], [repo_name, clone_path])
        log.status.write(
            '\nGit repository has been cloned to [{0}]\n'.format(clone_path))
def PromptWithValidator(prompt_string,
                        validator,
                        error_message,
                        message=None,
                        default=None):
  """Prompt for user input and validate output.

  Args:
    prompt_string: Message to print in the line with prompt.
    validator: Validation function (str) -> bool.
    error_message: Message to print if provided value is not correct.
    message: Optional message to print before prompt.
    default: Optional default value.

  Returns:
    Valid user provided value or default if not None and user chose it.
  """
  if message:
    log.status.Print(message)
  while True:
    if default is not None:
      answer = console_io.PromptWithDefault(
          message=prompt_string, default=default)
      if not answer:
        return default
    else:
      answer = console_io.PromptResponse(prompt_string)
    if validator(answer):
      return answer
    else:
      log.status.Print(error_message)
示例#9
0
def _PromptForProjectId(project_ids):
    """Prompt the user for a project ID, based on the list of available IDs.

  Also allows an option to create a project.

  Args:
    project_ids: list of str or None, the project IDs to prompt for. If this
      value is None, the listing was unsuccessful and we prompt the user
      free-form (and do not validate the input). If it's empty, we offer to
      create a project for the user.

  Returns:
    str, the project ID to use, or _CREATE_PROJECT_SENTINEL (if a project should
      be created), or None
  """
    if project_ids is None:
        return console_io.PromptResponse(
            'Enter project id you would like to use:  ') or None
    elif not project_ids:
        if not console_io.PromptContinue(
                'This account has no projects.',
                prompt_string='Would you like to create one?'):
            return None
        return _CREATE_PROJECT_SENTINEL
    else:
        idx = console_io.PromptChoice(
            project_ids + ['Create a new project'],
            message='Pick cloud project to use: ',
            allow_freeform=True,
            freeform_suggester=usage_text.TextChoiceSuggester())
        if idx is None:
            return None
        elif idx == len(project_ids):
            return _CREATE_PROJECT_SENTINEL
        return project_ids[idx]
 def _CreateConfiguration(self):
   configuration_name = console_io.PromptResponse(
       'Enter configuration name. Names start with a lower case letter and '
       'contain only lower case letters a-z, digits 0-9, and hyphens \'-\':  ')
   named_configs.ConfigurationStore.CreateConfig(configuration_name)
   named_configs.ConfigurationStore.ActivateConfig(configuration_name)
   named_configs.ActivePropertiesFile.Invalidate()
   return configuration_name
示例#11
0
def _PromptForSingleContact(unused_current_contact=None):
    """Asks a user for a single contact data."""
    messages = registrations.GetMessagesModule()

    contact = messages.Contact()
    contact.postalAddress = messages.PostalAddress()

    # TODO(b/166210862): Use defaults from current_contact.
    #                      But then: How to clear a value?
    # TODO(b/166210862): Better validation: Call validate_only after each prompt.
    contact.postalAddress.recipients.append(
        util.PromptWithValidator(validator=util.ValidateNonEmpty,
                                 error_message=' Name must not be empty.',
                                 prompt_string='Full name:  '))
    contact.postalAddress.organization = console_io.PromptResponse(
        'Organization (if applicable):  ')
    contact.email = util.PromptWithValidator(
        validator=util.ValidateEmail,
        error_message=' Invalid email address.',
        prompt_string='Email',
        default=properties.VALUES.core.account.Get())
    contact.phoneNumber = util.PromptWithValidator(
        validator=util.ValidateNonEmpty,
        error_message=' Phone number must not be empty.',
        prompt_string='Phone number:  ',
        message='Enter phone number with country code, e.g. "+1.8005550123".')
    contact.faxNumber = util.Prompt(
        prompt_string='Fax number (if applicable):  ',
        message='Enter fax number with country code, e.g. "+1.8005550123".')
    contact.postalAddress.regionCode = util.PromptWithValidator(
        validator=util.ValidateRegionCode,
        error_message=
        (' Country code must be in ISO 3166-1 format, e.g. "US" or "PL".\n'
         ' See https://support.google.com/business/answer/6270107 for a list '
         'of valid choices.'),
        prompt_string='Country code:  ',
        message='Enter two-letter country code, e.g. "US" or "PL".')
    contact.postalAddress.postalCode = console_io.PromptResponse(
        'Postal code/zipcode:  ')
    contact.postalAddress.administrativeArea = console_io.PromptResponse(
        'State (if applicable):  ')
    contact.postalAddress.locality = console_io.PromptResponse('City:  ')
    contact.postalAddress.addressLines.append(
        console_io.PromptResponse('Street address (incl. building, apt):  '))
    return contact
示例#12
0
 def _CreateConfiguration(self):
     configuration_name = console_io.PromptResponse(
         'Enter configuration name:')
     new_config_name = self._RunCmd(
         ['alpha', 'config', 'configurations', 'create'],
         [configuration_name])
     if new_config_name:
         properties.PropertiesFile.Invalidate()
     return new_config_name
示例#13
0
    def _PickProject(self, preselected=None):
        """Allows user to select a project.

    Args:
      preselected: str, use this value if not None

    Returns:
      str, project_id or None if was not selected.
    """
        try:
            projects = list(projects_api.List())
        except Exception:  # pylint: disable=broad-except
            log.debug('Failed to execute projects list: %s, %s, %s',
                      *sys.exc_info())
            projects = None

        if projects is None:  # Failed to get the list.
            project_id = preselected or console_io.PromptResponse(
                'Enter project id you would like to use:  ')
            if not project_id:
                return None
        else:
            projects = sorted(projects, key=lambda prj: prj.projectId)
            choices = [project.projectId for project in projects]
            if not choices:
                log.status.write(
                    '\nThis account has no projects. Please create one in '
                    'developers console '
                    '(https://console.developers.google.com/project) '
                    'before running this command.\n')
                return None
            if preselected:
                project_id = preselected
                project_names = [project.projectId for project in projects]
                if project_id not in project_names:
                    log.status.write(
                        '\n[{0}] is not one of your projects [{1}].\n'.format(
                            project_id, ','.join(project_names)))
                    return None
            elif len(choices) == 1:
                project_id = projects[0].projectId
            else:
                idx = console_io.PromptChoice(
                    choices,
                    message='Pick cloud project to use: ',
                    allow_freeform=True,
                    freeform_suggester=usage_text.TextChoiceSuggester())
                if idx is None:
                    return None
                project_id = projects[idx].projectId

        self._RunCmd(['config', 'set'], ['project', project_id])
        log.status.write(
            'Your current project has been set to: [{0}].\n\n'.format(
                project_id))
        return project_id
示例#14
0
def _PromptForProjectId(project_ids, limit_exceeded):
    """Prompt the user for a project ID, based on the list of available IDs.

  Also allows an option to create a project.

  Args:
    project_ids: list of str or None, the project IDs to prompt for. If this
      value is None, the listing was unsuccessful and we prompt the user
      free-form (and do not validate the input). If it's empty, we offer to
      create a project for the user.
    limit_exceeded: bool, whether or not the project list limit was reached. If
      this limit is reached, then user will be prompted with a choice to
      manually enter a project id, create a new project, or list all projects.

  Returns:
    str, the project ID to use, or _CREATE_PROJECT_SENTINEL (if a project should
      be created), or None
  """
    if project_ids is None:
        return console_io.PromptResponse(
            'Enter project id you would like to use:  ') or None
    elif not project_ids:
        if not console_io.PromptContinue(
                'This account has no projects.',
                prompt_string='Would you like to create one?'):
            return None
        return _CREATE_PROJECT_SENTINEL
    elif limit_exceeded:
        idx = console_io.PromptChoice(
            ['Enter a project ID', 'Create a new project', 'List projects'],
            message=(
                'This account has a lot of projects! Listing them all can '
                'take a while.'))
        if idx is None:
            return None
        elif idx == 0:
            return console_io.PromptWithValidator(
                _IsExistingProject,
                'Project ID does not exist or is not active. Please enter an '
                'existing and active Project ID.',
                'Enter an existing project id you would like to use:  ')
        elif idx == 1:
            return _CREATE_PROJECT_SENTINEL
        else:
            project_ids = _GetProjectIds()

    idx = console_io.PromptChoice(
        project_ids + ['Create a new project'],
        message='Pick cloud project to use: ',
        allow_freeform=True,
        freeform_suggester=usage_text.TextChoiceSuggester())
    if idx is None:
        return None
    elif idx == len(project_ids):
        return _CREATE_PROJECT_SENTINEL
    return project_ids[idx]
示例#15
0
    def Run(self, args):
        """Returns the results for one completion."""
        presentation_kwargs = args.resource_presentation_kwargs or {}
        with cache_util.GetCache(args.cache, create=True) as cache:
            log.info('cache name {}'.format(cache.name))
            if not args.kwargs:
                args.kwargs = {}
            # Create the ResourceInfo object that is used to hook up the parameter
            # info to the argparse namespace for resource argument completers.
            if args.resource_spec_path:
                spec = _GetPresentationSpec(args.resource_spec_path,
                                            **presentation_kwargs)
                spec.required = False
                resource_info = concept_parsers.ConceptParser([spec]).GetInfo(
                    spec.name)

                # Since the argument being completed doesn't have the correct
                # dest, make sure the handler always gives the same ResourceInfo
                # object.
                def ResourceInfoMonkeyPatch(*args, **kwargs):
                    del args, kwargs
                    return resource_info

                args.CONCEPTS.ArgNameToConceptInfo = ResourceInfoMonkeyPatch

            completer = _GetCompleter(args.module_path,
                                      cache=cache,
                                      qualify=args.qualify,
                                      resource_spec=args.resource_spec_path,
                                      presentation_kwargs=presentation_kwargs,
                                      attribute=args.attribute,
                                      **args.kwargs)
            parameter_info = completer.ParameterInfo(
                args, args.GetPositionalArgument('resource_to_complete'))
            if args.resource_to_complete is not None:
                matches = completer.Complete(args.resource_to_complete,
                                             parameter_info)
                return [matches]
            while True:
                name = console_io.PromptResponse('COMPLETE> ')
                if name is None:
                    break
                try:
                    completions = completer.Complete(name, parameter_info)
                except (Exception, SystemExit) as e:  # pylint: disable=broad-except
                    if args.stack_trace:
                        exceptions.reraise(Exception(e))
                    else:
                        log.error(six.text_type(e))
                    continue
                if completions:
                    print('\n'.join(completions))
            sys.stderr.write('\n')
            return None
示例#16
0
def PromptForWhoisContact():
    """Interactively prompts for Whois Contact information."""
    if not console_io.PromptContinue(
            'Registrant contact information not provided',
            prompt_string='Do you want to enter it interactively',
            default=False):
        return None
    messages = registrations.GetMessagesModule()
    whois_contact = messages.WhoisContact()
    whois_contact.postalAddress = messages.PostalAddress()
    # TODO(b/110077203): Improve interactive address info.
    whois_contact.postalAddress.recipients.append(
        console_io.PromptWithValidator(validator=_ValidateNonEmpty,
                                       error_message='Name must not be empty.',
                                       prompt_string=' full name:  '))
    whois_contact.postalAddress.organization = console_io.PromptResponse(
        ' organization (if applicable):  ')
    whois_contact.email = console_io.PromptWithDefault(
        message=' email', default=properties.VALUES.core.account.Get())
    whois_contact.phoneNumber = console_io.PromptWithValidator(
        validator=_ValidateNonEmpty,
        error_message='Phone number must not be empty.',
        prompt_string=' phone number:  ',
        message='Enter phone number with country code, e.g. "+1.1234567890".')
    whois_contact.postalAddress.regionCode = console_io.PromptWithValidator(
        validator=_ValidateRegionCode,
        error_message=(
            'Country code must be in ISO 3166-1 format, e.g. "US" or "PL".\n'
            'See https://support.google.com/business/answer/6270107 for a list '
            'of valid choices.'),
        prompt_string=' country code:  ',
        message='Enter two-letter country code, e.g. "US" or "PL".')
    whois_contact.postalAddress.postalCode = console_io.PromptResponse(
        ' postal code/zipcode:  ')
    whois_contact.postalAddress.administrativeArea = console_io.PromptResponse(
        ' state (if applicable):  ')
    whois_contact.postalAddress.locality = console_io.PromptResponse(
        ' city:  ')
    whois_contact.postalAddress.addressLines.append(
        console_io.PromptResponse(' street address (incl. building, apt):  '))
    return whois_contact
示例#17
0
 def _Prompt(self, parsed_args):
   image = None
   if hasattr(parsed_args, 'image'):
     image = parsed_args.image
   message = 'Service name'
   if image:
     default_name = GenerateServiceName(image)
     service_name = console_io.PromptWithDefault(
         message=message, default=default_name)
   else:
     service_name = console_io.PromptResponse(message='{}: '.format(message))
   return service_name
示例#18
0
def _GetAnswerToQuestion(question):
    """Prompts user for the answer to the question."""
    prompt_msg = question.instruction
    while True:
        answer = console_io.PromptResponse(prompt_msg)
        if answer == survey.Survey.ControlOperation.SKIP_QUESTION.value:  # s
            return survey.Survey.ControlOperation.SKIP_QUESTION
        elif answer == survey.Survey.ControlOperation.EXIT_SURVEY.value:  # x
            return survey.Survey.ControlOperation.EXIT_SURVEY
        elif question.AcceptAnswer(answer):
            return answer
        else:
            prompt_msg = question.instruction_on_rejection
def Prompt(prompt_string, message=None):
  """Prompt for user input.

  Args:
    prompt_string: Message to print in the line with prompt.
    message: Optional message to print before prompt.

  Returns:
    User provided value.
  """
  if message:
    log.status.Print(message)
  return console_io.PromptResponse(prompt_string)
示例#20
0
 def _Call(self, parsed_args):
   if not console_io.CanPrompt():
     return None
   source_ref = None
   if hasattr(parsed_args, 'source') or hasattr(parsed_args, 'image'):
     source_ref = flags.GetSourceRef(parsed_args.source, parsed_args.image)
   message = 'Service name:'
   if source_ref:
     default_name = GenerateServiceName(source_ref)
     service_name = console_io.PromptWithDefault(
         message=message, default=default_name)
   else:
     service_name = console_io.PromptResponse(message=message)
   return service_name
def PickProject(preselected=None):
    """Allows user to select a project.

  Args:
    preselected: str, use this value if not None

  Returns:
    str, project_id or None if was not selected.
  """
    project_ids = _GetProjectIds(limit=_PROJECT_LIST_LIMIT + 1)
    limit_exceeded = False
    if project_ids is not None and len(project_ids) > _PROJECT_LIST_LIMIT:
        limit_exceeded = True

    selected = None
    if preselected:
        project_id = preselected
    else:
        project_id = _PromptForProjectId(project_ids, limit_exceeded)
        if project_id is not _CREATE_PROJECT_SENTINEL:
            selected = project_id

    if not limit_exceeded:
        if (project_ids is None or project_id in project_ids
                or project_id is None or selected):
            return project_id
    else:
        # If we fall into limit_exceeded logic and preselected was None, then
        # as long as project_id is not _CREATE_PROJECT_SENTINEL, then we know the
        # project_id is valid.
        if ((preselected and _IsExistingProject(preselected))
                or project_id is not _CREATE_PROJECT_SENTINEL):
            return project_id

    if project_id is _CREATE_PROJECT_SENTINEL:
        project_id = console_io.PromptResponse(_ENTER_PROJECT_ID_MESSAGE)
        if not project_id:
            return None
    else:
        if project_ids:
            message = '[{0}] is not one of your projects [{1}]. '.format(
                project_id, ','.join(project_ids))
        else:
            message = 'This account has no projects.'
        if not console_io.PromptContinue(
                message=message, prompt_string='Would you like to create it?'):
            return None

    return _CreateProject(project_id, project_ids)
示例#22
0
    def Run(self, args):
        """Returns the parsed parameters for one resource."""
        if args.api_version:
            api_name = args.collection.split('.')[0]
            resources.REGISTRY.RegisterApiByName(api_name,
                                                 api_version=args.api_version)

        if args.resources_to_parse:
            parsed_resources = []
            for uri in args.resources_to_parse:
                try:
                    resource = resources.REGISTRY.Parse(
                        uri, collection=args.collection)
                except (Exception, SystemExit) as e:  # pylint: disable=broad-except
                    if args.stack_trace:
                        exceptions.reraise(e)
                    log.error(six.text_type(e))
                    parsed_resources.append({
                        'error': six.text_type(e),
                        'uri': uri,
                    })
                    continue
                collection_info = resource.GetCollectionInfo()
                parsed_resources.append({
                    'api_name': collection_info.api_name,
                    'api_version': collection_info.api_version,
                    'collection': collection_info.full_name,
                    'params': resource.AsDict(),
                    'uri': resource.SelfLink(),
                })
            return parsed_resources

        while True:
            uri = console_io.PromptResponse('PARSE> ')
            if uri is None:
                break
            if not uri:
                continue
            try:
                params = resources.REGISTRY.Parse(
                    uri, collection=args.collection).AsDict()
            except (Exception, SystemExit) as e:  # pylint: disable=broad-except
                if args.stack_trace:
                    exceptions.reraise(e)
                log.error(six.text_type(e))
                continue
            resource_printer.Print(params, 'json')
        sys.stderr.write('\n')
        return None
    def Run(self, args):
        """Run the authentication command."""

        token = args.token or console_io.PromptResponse('Refresh token: ')
        if not token:
            raise c_exc.InvalidArgumentException('token', 'No value provided.')

        refresh_token.ActivateCredentials(args.account, token)

        project = args.project
        if project:
            properties.PersistProperty(properties.VALUES.core.project, project)

        log.status.Print('Activated refresh token credentials: [{0}]'.format(
            args.account))
示例#24
0
    def _CloneRepo(self, repo_name):
        """Queries user for output path and clones selected repo to it."""
        while True:
            clone_path = os.getcwd()
            clone_path = console_io.PromptResponse(
                'Where would you like to clone [{0}] repository to [{1}]:'.
                format(repo_name, clone_path))
            if not clone_path:
                clone_path = os.getcwd()
            if os.path.isdir(clone_path):
                break
            log.status.write('No such directory [{0}]\n'.format(clone_path))

        self._RunCmd(
            ['alpha', 'source', 'repo', 'clone'],
            [repo_name, os.path.join(clone_path, repo_name)])
示例#25
0
 def testNoPrompt(self):
     properties.VALUES.core.disable_prompts.Set(True)
     result = console_io.PromptContinue(message='prompt')
     self.assertEqual('', self.GetErr())
     self.assertTrue(result)
     result = console_io.PromptContinue(default=False)
     self.assertFalse(result)
     result = console_io.PromptResponse(message='prompt')
     self.assertEqual('', self.GetErr())
     self.assertEqual(result, None)
     result = console_io.PromptWithDefault(message='prompt')
     self.assertEqual('', self.GetErr())
     self.assertEqual(result, None)
     result = console_io.PromptChoice(['a', 'b', 'c'])
     self.assertEqual('', self.GetErr())
     self.assertEqual(result, None)
示例#26
0
 def testEOF(self):
     result = console_io.PromptContinue()
     self.assertTrue(result)
     result = console_io.PromptContinue(default=False)
     self.assertFalse(result)
     with self.assertRaisesRegex(console_io.UnattendedPromptError,
                                 'This prompt could not be answered'):
         result = console_io.PromptContinue(throw_if_unattended=True)
     result = console_io.PromptResponse(message='')
     self.assertEqual(result, None)
     result = console_io.PromptWithDefault(message='')
     self.assertEqual(result, None)
     result = console_io.PromptChoice(['a', 'b', 'c'])
     self.assertEqual(result, None)
     result = console_io.PromptChoice(['a', 'b', 'c'], default=2)
     self.assertEqual(result, 2)
示例#27
0
    def _PickProject(self):
        """Allows user to select a project.

    Returns:
      str, project_id or None if was not selected.
    """
        try:
            projects = list(projects_api.List(http=self.Http()))
        except Exception:  # pylint: disable=broad-except
            log.debug('Failed to execute projects list: %s, %s, %s',
                      *sys.exc_info())
            projects = None

        if projects is None:  # Failed to get the list.
            project_id = console_io.PromptResponse(
                'Enter project id you would like to use:  ')
            if not project_id:
                return None
        else:
            projects = sorted(projects, key=lambda prj: prj.projectId)
            choices = [
                '[{0}]'.format(project.projectId) for project in projects
            ]
            if not choices:
                log.status.write(
                    '\nThis account has no projects. Please create one in '
                    'developers console '
                    '(https://console.developers.google.com/project) '
                    'before running this command.\n')
                return None
            if len(choices) == 1:
                project_id = projects[0].projectId
            else:
                idx = console_io.PromptChoice(
                    choices,
                    message='Pick cloud project to use: ',
                    prompt_string=None)
                if idx is None:
                    return
                project_id = projects[idx].projectId

        self._RunCmd(['config', 'set'], ['project', project_id])
        log.status.write(
            'Your current project has been set to: [{0}].\n\n'.format(
                project_id))
        return project_id
示例#28
0
    def testPromptCompleterOnChoices(self):
        self.SetRawKeys([
            'a',
            '\t',
            '\t',
            'g',
            '\t',
            '\t',
            '2',
            '\t',
            '\t',
            'l',
            '\t',
            '\t',
        ])
        choices = list(_MockInstancesCompleter())
        choices[0] = 'aaaa-'
        result = console_io.PromptResponse(message='Complete this: ',
                                           choices=choices)
        self.AssertOutputEquals('')
        self.AssertErrEquals("""\
Complete this: aaaa-
  aaaa-                aaaa-<B>f</B>ffff-222222-*  aaaa-<B>g</B>gggg-444444-*
  aaaa-<B>e</B>eeee-111111-*  aaaa-<B>f</B>ffff-333333-*  aaaa-<B>h</B>hhhh-111111-*
  aaaa-<B>e</B>eeee-222222-*  aaaa-<B>f</B>ffff-444444-*  aaaa-<B>h</B>hhhh-222222-*
  aaaa-<B>e</B>eeee-333333-*  aaaa-<B>g</B>gggg-111111-*  aaaa-<B>h</B>hhhh-333333-*
  aaaa-<B>e</B>eeee-444444-*  aaaa-<B>g</B>gggg-222222-*  aaaa-<B>h</B>hhhh-444444-*
  aaaa-<B>f</B>ffff-111111-*  aaaa-<B>g</B>gggg-333333-*
Complete this: aaaa-ggggg-
  aaaa-ggggg-<B>1</B>11111-iiiiiii  aaaa-ggggg-<B>3</B>33333-iiiiiii
  aaaa-ggggg-<B>1</B>11111-jjjjjjj  aaaa-ggggg-<B>3</B>33333-jjjjjjj
  aaaa-ggggg-<B>1</B>11111-kkkkkkk  aaaa-ggggg-<B>3</B>33333-kkkkkkk
  aaaa-ggggg-<B>1</B>11111-lllllll  aaaa-ggggg-<B>3</B>33333-lllllll
  aaaa-ggggg-<B>2</B>22222-iiiiiii  aaaa-ggggg-<B>4</B>44444-iiiiiii
  aaaa-ggggg-<B>2</B>22222-jjjjjjj  aaaa-ggggg-<B>4</B>44444-jjjjjjj
  aaaa-ggggg-<B>2</B>22222-kkkkkkk  aaaa-ggggg-<B>4</B>44444-kkkkkkk
  aaaa-ggggg-<B>2</B>22222-lllllll  aaaa-ggggg-<B>4</B>44444-lllllll
Complete this: aaaa-ggggg-222222-
  aaaa-ggggg-222222-<B>i</B>iiiiii  aaaa-ggggg-222222-<B>k</B>kkkkkk
  aaaa-ggggg-222222-<B>j</B>jjjjjj  aaaa-ggggg-222222-<B>l</B>llllll
Complete this: aaaa-ggggg-222222-lllllll
""")
        self.assertEqual('aaaa-ggggg-222222-lllllll', result)
示例#29
0
    def _PickProject(self):
        """Allows user to select a project.

    Returns:
      str, project_id or None if was not selected.
    """
        projects = self._RunExperimentalCmd(['beta', 'projects', 'list'])

        if projects is None:  # Failed to get the list.
            project_id = console_io.PromptResponse(
                'Enter project id you would like to use:  ')
            if not project_id:
                return None
        else:
            projects = sorted(projects, key=lambda prj: prj.projectId)
            choices = [
                '[{0}]'.format(project.projectId) for project in projects
            ]
            if not choices:
                log.status.write(
                    '\nThis account has no projects. Please create one in '
                    'developers console '
                    '(https://console.developers.google.com/project) '
                    'before running this command.\n')
                return None
            if len(choices) == 1:
                project_id = projects[0].projectId
            else:
                idx = console_io.PromptChoice(
                    choices,
                    message='Pick cloud project to use: ',
                    prompt_string=None)
                if idx is None:
                    return
                project_id = projects[idx].projectId

        self._RunCmd(['config', 'set'], ['project', project_id])
        log.status.write(
            'Your current project has been set to: [{0}].\n\n'.format(
                project_id))
        return project_id
示例#30
0
def _GetAndUpdateRcPath(completion_update, path_update, rc_path, host_os):
    """Returns an rc path based on the default rc path or user input.

  Gets default rc path based on environment. If prompts are enabled,
  allows user to update to preferred file path. Otherwise, prints a warning
  that the default rc path will be updated.

  Args:
    completion_update: bool, Whether or not to do command completion.
    path_update: bool, Whether or not to update PATH.
    rc_path: str, the rc path given by the user, from --rc-path arg.
    host_os: str, The host os identification string.

  Returns:
    str, A path to the rc file to update.
  """
    # If we aren't updating the RC file for either completions or PATH, there's
    # no point.
    if not (completion_update or path_update):
        return None
    if rc_path:
        return rc_path
    # A first guess at user preferred shell.
    preferred_shell = _GetPreferredShell(
        encoding.GetEncodedValue(os.environ, 'SHELL', '/bin/sh'))
    default_rc_path = os.path.join(
        platforms.GetHomePath(), _GetShellRcFileName(preferred_shell, host_os))
    # If in quiet mode, we'll use default path.
    if not console_io.CanPrompt():
        _TraceAction(
            'You specified that you wanted to update your rc file. The '
            'default file will be updated: [{rc_path}]'.format(
                rc_path=default_rc_path))
        return default_rc_path
    rc_path_update = console_io.PromptResponse(
        ('The Google Cloud SDK installer will now prompt you to update an rc '
         'file to bring the Google Cloud CLIs into your environment.\n\n'
         'Enter a path to an rc file to update, or leave blank to use '
         '[{rc_path}]:  ').format(rc_path=default_rc_path))
    return (os.path.expanduser(rc_path_update)
            if rc_path_update else default_rc_path)