def Run(self, args): if not args.IsSpecified('service_name'): dir_name = os.path.basename(os.path.dirname(args.dockerfile)) service_name = console_io.PromptWithDefault(message='Service name', default=dir_name) else: service_name = args.service_name if not args.IsSpecified('image_name'): default_image_name = 'gcr.io/{project}/{service}'.format( project=properties.VALUES.core.project.Get(required=True), service=service_name) image_name = console_io.PromptWithDefault( message='Docker image tag', default=default_image_name) else: image_name = args.image_name kubernetes_configs = local.CreatePodAndService(service_name, image_name) with files.FileWriter(args.kubernetes_file) as output: yaml.dump_all(kubernetes_configs, output) skaffold_yaml_text = _SKAFFOLD_TEMPLATE.format( image_name=image_name, context_path=args.build_context_directory or os.path.dirname(args.dockerfile) or '.') with files.FileWriter(args.skaffold_file) as output: output.write(skaffold_yaml_text)
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)
def _GetEnvironment(args): """Prompt for environment if not provided. Environment is decided in the following order: - environment argument; - kuberun/environment gcloud config; - prompt user. Args: args: Environment, The args environment. Returns: A str representing the environment name. Raises: A ValueError if no environment is specified. """ env = None if getattr(args, 'environment', None): env = args.environment elif properties.VALUES.kuberun.environment.IsExplicitlySet(): env = properties.VALUES.kuberun.environment.Get() elif console_io.CanPrompt(): env = console_io.PromptWithDefault('Environment name', default=None) log.status.Print( 'To make this the default environment, run ' '`gcloud config set kuberun/environment {}`.\n'.format(env)) if env: return env raise ValueError('Please specify an ENVIRONMENT to use this command.')
def testPromptWithDefault(self): self.SetAnswers('', 'user value') result = console_io.PromptWithDefault(message='message', default='default value') self.assertIn('message (default value): ', self.GetErr()) self.assertEqual(result, 'default value') result = console_io.PromptWithDefault(message='message', default='default value') self.assertEqual(result, 'user value') # Test without a default. self.SetAnswers('', 'user value') result = console_io.PromptWithDefault(message='message') self.assertIn('message: ', self.GetErr()) self.assertEqual(result, None) result = console_io.PromptWithDefault(message='message') self.assertEqual(result, 'user value')
def _PromptForNewCondition(): prompt_message = ( 'Condition is either `None` or a list of key=value pairs. ' 'If not `None`, `expression` and `title` are required keys.\n' 'Example: --condition=expression=[expression],title=[title],' 'description=[description].\nSpecify the condition') condition_string = console_io.PromptWithDefault(prompt_message) condition_dict = _ConditionArgDict()(condition_string) return condition_dict
def Run(self, args): project_name = properties.VALUES.core.project.Get(required=True) if not args.IsSpecified('service_name'): dir_name = os.path.basename( os.path.dirname(os.path.join(files.GetCWD(), args.dockerfile))) service_name = console_io.PromptWithDefault( message='Service name', default=dir_name) else: service_name = args.service_name if not args.IsSpecified('image_name'): default_image_name = 'gcr.io/{project}/{service}'.format( project=project_name, service=service_name) image_name = console_io.PromptWithDefault( message='Docker image tag', default=default_image_name) else: image_name = args.image_name kubernetes_yaml_paths = [] kubernetes_configs = local.CreatePodAndService(service_name, image_name) if args.service_account: service_account = local.CreateDevelopmentServiceAccount( args.service_account) private_key_json = local.CreateServiceAccountKey(service_account) secret_yaml = local.LocalDevelopmentSecretSpec(private_key_json) kubernetes_configs.append(secret_yaml) local.AddServiceAccountSecret(kubernetes_configs) with files.FileWriter(args.kubernetes_file) as output: yaml.dump_all(kubernetes_configs, output) kubernetes_yaml_paths.append(args.kubernetes_file) skaffold_yaml_text = _SKAFFOLD_TEMPLATE.format( image_name=image_name, context_path=args.build_context_directory or os.path.dirname(args.dockerfile) or '.') skaffold_yaml = yaml.load(skaffold_yaml_text) manifests = yaml_helper.GetOrCreate( skaffold_yaml, ('deploy', 'kubectl', 'manifests'), constructor=list) manifests.extend(kubernetes_yaml_paths) with files.FileWriter(args.skaffold_file) as output: yaml.dump(skaffold_yaml, output)
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
def FromArgs(cls, args): """Create a LocalRuntimeFiles object from an args object.""" project_name = properties.VALUES.core.project.Get(required=True) if not args.IsSpecified('service_name'): dir_name = os.path.basename( os.path.dirname(os.path.join(files.GetCWD(), args.dockerfile))) service_name = console_io.PromptWithDefault( message='Service name', default=dir_name) else: service_name = args.service_name if not args.IsSpecified('image_name'): default_image_name = 'gcr.io/{project}/{service}'.format( project=project_name, service=service_name) image_name = console_io.PromptWithDefault( message='Docker image tag', default=default_image_name) else: image_name = args.image_name return cls(service_name, image_name, args.service_account, args.dockerfile, args.build_context_directory)
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 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)
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)
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
def _Prompt(self, parsed_args): message = self.resource_type_lower.capitalize() + ' name' default_name = self._DefaultNameFromArgs(parsed_args) return console_io.PromptWithDefault(message=message, default=default_name)