示例#1
0
def IPV4Argument(value):
  """Argparse argument type that checks for a valid ipv4 address."""
  if not IsValidIPV4(value):
    raise arg_parsers.ArgumentTypeError(
        "invalid ipv4 value: '{0}'".format(value))

  return value
示例#2
0
 def _ParseDayOfWeek(value):
     value_upper = value.upper()
     if value_upper not in visible_choices_set:
         raise arg_parsers.ArgumentTypeError(
             '{value} must be one of [{choices}]'.format(
                 value=value, choices=', '.join(visible_choices)))
     return day_of_week_enum.lookup_by_name(value_upper)
示例#3
0
def ValidateAndStandarizeBucketUriOrRaise(bucket):
    """Checks if a bucket uri provided by user is valid.

  If the Bucket uri is valid, converts it to a standard form.

  Args:
    bucket: Bucket uri provided by user.
  Returns:
    Sanitized bucket uri.
  Raises:
    ArgumentTypeError: If the name provided by user is not valid.
  """
    if _BUCKET_RESOURCE_URI_RE.match(bucket):
        bucket_ref = storage_util.BucketReference.FromBucketUrl(bucket)
    else:
        try:
            bucket_ref = storage_util.BucketReference.FromArgument(
                bucket, require_prefix=False)
        except argparse.ArgumentTypeError as e:
            raise arg_parsers.ArgumentTypeError(
                "Invalid value '{}': {}".format(bucket, e))

    # strip any extrenuous '/' and append single '/'
    bucket = bucket_ref.ToBucketUrl().rstrip('/') + '/'
    return bucket
示例#4
0
 def _Parse(value):
   value = six.text_type(value.lower())
   if value not in valid_choices:
     raise arg_parsers.ArgumentTypeError(
         '[type] must be one of [{0}]'.format(
             ','.join(valid_choices)))
   return value
示例#5
0
 def _Parse(value):
     value = six.text_type(value.lower())
     if value not in _AUTOSCALING_MODES:
         raise arg_parsers.ArgumentTypeError(
             '[mode] must be one of [{0}]'.format(
                 ','.join(_AUTOSCALING_MODES)))
     return value
示例#6
0
    def Run(self, args):
        """Retrieves information about a backup.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object that has the backup run resource if the command ran
      successfully.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        validate.ValidateInstanceName(args.instance)

        try:
            # Check if ID is an integer.
            # TODO(b/21877717): Remove this try clause after deprecation period when
            # re-adding validation above.
            id_integer = int(args.id)
        except ValueError:
            try:
                # If input is not an integer, check if it is a datetime.
                datetime = arg_parsers.Datetime.Parse(args.id)
            except arg_parsers.ArgumentTypeError:
                # If user input is not integer or datetime, throw error.
                raise arg_parsers.ArgumentTypeError('ID must be an integer.')
            return self._GetByDatetime(datetime, args)
        return self._GetById(id_integer, args)
示例#7
0
 def ParseFutureDatetime(s):
     """Parses a string value into a future Datetime object."""
     dt = arg_parsers.Datetime.Parse(s)
     if dt < times.Now():
         raise arg_parsers.ArgumentTypeError(
             'Date/time must be in the future: {0}'.format(s))
     return dt
示例#8
0
def ParseDirectory(directory):
    """Checks if a source directory provided by user is valid.

  Args:
    directory: Path do directory provided by user.
  Returns:
    Path to directory.
  Raises:
    ArgumentTypeError: If the directory provided by user is not valid.
  """
    if not os.path.exists(directory):
        raise arg_parsers.ArgumentTypeError(
            'Provided directory does not exist.')
    if not os.path.isdir(directory):
        raise arg_parsers.ArgumentTypeError(
            'Provided path does not point to a directory.')
    return directory
示例#9
0
 def __call__(self, file_path):
   map_file_dict = yaml.load_path(file_path)
   map_dict = {}
   for key, value in map_file_dict.items():
     if self.key_type:
       try:
         key = self.key_type(key)
       except ValueError:
         raise arg_parsers.ArgumentTypeError('Invalid key [{0}]'.format(key))
     if self.value_type:
       try:
         value = self.value_type(value)
       except ValueError:
         raise arg_parsers.ArgumentTypeError(
             'Invalid value [{0}]'.format(value))
     map_dict[key] = value
   return map_dict
def _InitialDelayValidator(value):
    duration_parser = arg_parsers.Duration(parsed_unit='s')
    parsed_value = duration_parser(value)
    if parsed_value > _MAX_INITIAL_DELAY_DURATION:
        raise arg_parsers.ArgumentTypeError(
            'The value of initial delay must be between 0 and {max_value}'.
            format(max_value=_MAX_INITIAL_DELAY_DURATION_HUMAN_READABLE))
    return parsed_value
 def testParserException(self):
     for arg_value in {'', '123', '21,2', 'uninstalled', 'purged', '^F&^%'}:
         self.Run(
             None,
             arg_value,
             exception=arg_parsers.ArgumentTypeError((
                 'Invalid value [{}] from field [package-state], expected one of '
                 '[installed, removed].').format(arg_value)))
 def testParserException(self):
     for arg_value in {'', '123', '21,2', 'trace', '^F&^%'}:
         self.Run(
             None,
             arg_value,
             exception=arg_parsers.ArgumentTypeError(
                 ('Invalid value [{}] from field [type], expected one of '
                  '[logging, metrics, ops-agent].').format(arg_value)))
示例#13
0
 def _ParseTimeOfDay(value):
     m = re.match(r'^(\d?\d):00$', value)
     if m:
         hour = int(m.group(1))
         if hour <= 23 and hour >= 0:
             return alloydb_messages.GoogleTypeTimeOfDay(hours=hour)
     raise arg_parsers.ArgumentTypeError(
         'Failed to parse time of day: {0}, expected format: HH:00.'.format(
             value))
示例#14
0
def _ValidateArgumentByRegexOrRaise(argument, regex, error_message):
    if isinstance(regex, str):
        match = re.match(regex, argument)
    else:
        match = regex.match(argument)
    if not match:
        raise arg_parsers.ArgumentTypeError("Invalid value '{0}': {1}".format(
            argument, error_message))
    return argument
示例#15
0
def RealmValidator(realm):
    """Validates that the realm argument is a supported RealmValueValuesEnum."""
    messages = api_util.GetMessages()
    try:
        realm = realm.upper()
        messages.RealmConfig.RealmValueValuesEnum(realm)
    except TypeError:
        raise arg_parsers.ArgumentTypeError(
            'invalid realm {}, must be one of:{}'.format(
                realm, GetFormattedSupportedEnums()))
    return realm
示例#16
0
def CheckValidEnumNames(api_names, choices_values):
  """Ensures the api_name given in the spec matches a value from the API."""
  if api_names:
    bad_choices = [name for name in choices_values if not (
        name in api_names or ChoiceToEnumName(
            six.text_type(name)) in api_names)]
  else:
    bad_choices = []
  if bad_choices:
    raise arg_parsers.ArgumentTypeError(
        '{} is/are not valid enum values.'.format(', '.join(bad_choices)))
示例#17
0
 def __call__(self, file_path):
     map_file_dict = yaml.load_path(file_path)
     map_dict = {}
     if not yaml.dict_like(map_file_dict):
         raise arg_parsers.ArgumentTypeError(
             'Invalid YAML/JSON data in [{}], expected map-like data.'.
             format(file_path))
     for key, value in map_file_dict.items():
         if self.key_type:
             try:
                 key = self.key_type(key)
             except ValueError:
                 raise arg_parsers.ArgumentTypeError(
                     'Invalid key [{0}]'.format(key))
         if self.value_type:
             try:
                 value = self.value_type(value)
             except ValueError:
                 raise arg_parsers.ArgumentTypeError(
                     'Invalid value [{0}]'.format(value))
         map_dict[key] = value
     return map_dict
示例#18
0
def ChoiceToEnum(choice, enum_type, item_type='choice', valid_choices=None):
  """Converts the typed choice into an apitools Enum value."""
  if choice is None:
    return None
  name = ChoiceToEnumName(choice)
  valid_choices = (valid_choices or
                   [EnumNameToChoice(n) for n in enum_type.names()])
  try:
    return enum_type.lookup_by_name(name)
  except KeyError:
    raise arg_parsers.ArgumentTypeError(
        'Invalid {item}: {selection}. Valid choices are: [{values}].'.format(
            item=item_type,
            selection=EnumNameToChoice(name),
            values=', '.join(c for c in sorted(valid_choices))))
示例#19
0
def ChoiceToEnum(choice, enum_type, valid_choices=None):
    # type: (str, enum.Enum, list) -> enum.Enum
    """Converts the typed choice into an apitools Enum value."""
    if choice is None:
        return None
    name = choice.replace('-', '_').upper()
    valid_choices = (valid_choices
                     or [EnumNameToChoice(n) for n in enum_type.names()])
    try:
        return enum_type.lookup_by_name(name)
    except KeyError:
        raise arg_parsers.ArgumentTypeError(
            'Invalid choice: {}. Valid choices are: [{}].'.format(
                EnumNameToChoice(name),
                ', '.join(c for c in sorted(valid_choices))))
示例#20
0
def ParseDirectoryOrCloudRepoPath(directory_or_cloud_repo_path):
    """Checks if a source directory or cloud repo path provided by user is valid.

  Args:
    directory_or_cloud_repo_path: A string: a local path do directory provided
                                  by user, or a path to a Cloud Repository.
  Returns:
    The argument provided, if found valid.
  Raises:
    ArgumentTypeError: If the user provided a directory which is not valid.
  """
    if IsCloudRepoPath(directory_or_cloud_repo_path):
        return directory_or_cloud_repo_path

    directory = directory_or_cloud_repo_path
    if not os.path.exists(directory):
        raise arg_parsers.ArgumentTypeError(
            'Provided directory does not exist. If you intended to provide a path '
            'to Google Cloud Repository, it must start with "{0}"'.format(
                _CLOUD_REPO_PREFIX))
    if not os.path.isdir(directory):
        raise arg_parsers.ArgumentTypeError(
            'Provided path does not point to a directory.')
    return directory
示例#21
0
def AspectRatioType(value):
    """A type function to be used to parse aspect ratios."""
    try:
        return float(value)
    except ValueError:
        parts = value.split(':')
        if len(parts) == 2:
            try:
                return float(parts[0]) / float(parts[1])
            except ValueError:
                pass

        raise arg_parsers.ArgumentTypeError(
            'Each aspect ratio must either be specified as a decimal (ex. 1.333) '
            'or as a ratio of width to height (ex 4:3)')
示例#22
0
def ParseFunctionName(name):
    """Checks if a function name provided by user is valid.

  Args:
    name: Function name provided by user.
  Returns:
    Function name.
  Raises:
    ArgumentTypeError: If the name provided by user is not valid.
  """
    match = _FUNCTION_NAME_RE.match(name)
    if not match:
        raise arg_parsers.ArgumentTypeError(
            'Function name must match [{0}]'.format(_FUNCTION_NAME_RE.pattern))
    return name
示例#23
0
def ParseEntryPointName(entry_point):
    """Checks if a entry point name provided by user is valid.

  Args:
    entry_point: Entry point name provided by user.
  Returns:
    Entry point name.
  Raises:
    ArgumentTypeError: If the entry point name provided by user is not valid.
  """
    match = _ENTRY_POINT_NAME_RE.match(entry_point)
    if not match:
        raise arg_parsers.ArgumentTypeError(
            'Entry point name must match [{0}]'.format(
                _ENTRY_POINT_NAME_RE.pattern))
    return entry_point
示例#24
0
def ParsePubsubTopicName(topic):
    """Checks if a Pub/Sub topic name provided by user is valid.

  Args:
    topic: Pub/Sub topic name provided by user.
  Returns:
    Topic name.
  Raises:
    ArgumentTypeError: If the name provided by user is not valid.
  """
    match = _TOPIC_NAME_RE.match(topic)
    if not match:
        raise arg_parsers.ArgumentTypeError('Topic must match [{0}]'.format(
            _TOPIC_NAME_RE.pattern))
    project = properties.VALUES.core.project.Get(required=True)
    return 'projects/{0}/topics/{1}'.format(project, topic)
示例#25
0
    def RoutingPolicyDataArgType(routing_policy_data_value):
        """Converts --routing-policy-data flag value to a list of policy data items.

    Args:
      routing_policy_data_value: String value specified in the
        --routing-policy-data flag.

    Returns:
      A list of policy data items in the format below:

    [
        { 'key': <routing_policy_data_key1>, 'rrdatas': <IP address list> },
        { 'key': <routing_policy_data_key2>, 'rrdatas': <IP address list> },
        ...
    ]

    Where <routing_policy_data_key> is either a weight or location name,
    depending on whether the user specified --routing-policy-type == WRR or
    --routing-policy-type == GEO, respectively. We keep
    <routing_policy_data_key> a string value, even in the case of weights
    (which will eventually be interpereted as floats). This is to keep this
    flag type generic between WRR and GEO types.
    """
        routing_policy_data = []

        # Grab each policy data item, split by ';'
        policy_items = routing_policy_data_value.split(';')
        for policy_item in policy_items:
            # Grab key and value from policy_item, split by ':'
            key_value_split = policy_item.split('=')

            # Ensure that there is only one key and value from the string split on ':'
            if len(key_value_split) != 2:
                raise arg_parsers.ArgumentTypeError(
                    'Must specify exactly one "=" inside each policy data item'
                )
            key = key_value_split[0]
            value = key_value_split[1]

            # Grab list of IPs from value, split by ','
            ip_list = value.split(',')
            routing_policy_data.append({'key': key, 'rrdatas': ip_list})

        return routing_policy_data
示例#26
0
  def __call__(self, arg_value):
    """Interpret the arg value as an item from an allowed value list.

    Args:
      arg_value: str.
        The value of the user input argument.

    Raises:
      arg_parsers.ArgumentTypeError.
        If the arg value is not one of the allowed values.
    Returns:
      The value of the arg.
    """
    str_value = str(arg_value)
    if str_value not in self._allowed_values:
      raise arg_parsers.ArgumentTypeError(
          'Invalid value [{0}] from field [{1}], expected one of [{2}].'.format(
              arg_value, self._field_name, ', '.join(self._allowed_values)))
    return str_value
示例#27
0
def ParseBucketUri(bucket):
    """Checks if a bucket uri provided by user is valid.

  Args:
    bucket: Bucket uri provided by user.
  Returns:
    Sanitized bucket uri.
  Raises:
    ArgumentTypeError: If the name provided by user is not valid.
  """
    if not bucket.endswith('/'):
        bucket += '/'
    if not bucket.startswith('gs://'):
        bucket = 'gs://' + bucket
    match = _BUCKET_URI_RE.match(bucket)
    if not match:
        raise arg_parsers.ArgumentTypeError('Bucket must match [{0}]'.format(
            _BUCKET_URI_RE.pattern))
    return bucket
示例#28
0
def EnvVarKeyType(key):
    """Validates environment variable keys.

  Args:
    key: The environment variable key.

  Returns:
    The environment variable key.

  Raises:
    ArgumentTypeError: If the key is not a valid environment variable key.
  """

    env_var_key_validator = arg_parsers.RegexpValidator(
        r'^[a-zA-Z_][a-zA-Z0-9_]*$',
        'Environment variable keys should only consist of alphanumeric '
        'characters and underscores. The first character cannot be a digit.')
    env_var_key_validator(key)
    if key.startswith('X_GOOGLE_'):
        raise arg_parsers.ArgumentTypeError(
            'Environment variable keys that start with `X_GOOGLE_` are reserved '
            'for use by deployment tools and cannot be specified manually.')
    return key
示例#29
0
def _ValidateAcceleratorCount(accelerator_count):
    count = int(accelerator_count)
    if count <= 0:
        raise arg_parsers.ArgumentTypeError(
            'The count of the accelerator must be greater than 0.')
    return count
def ValidateV1TimeoutFlag(args):
    if args.timeout and args.timeout > 540:
        raise arg_parsers.ArgumentTypeError(
            '--timeout: value must be less than or equal to 540s; received: {}s'
            .format(args.timeout))