def Parse(self, dependencies): """Parses the dict from dependencies and returns it.""" dict_value = {} try: value = dependencies.value except deps_lib.AttributeNotFoundError as e: if not self.required: return None raise exceptions.MissingRequiredArgumentError( self.GetPresentationName(), e) items, self._delim = self._Split(value) for item in items: key, val = item.split('=', 1) entry = self._entries.get(key) if not entry: if not self._additional: raise exceptions.ParseError( self.GetPresentationName(), 'Unknown dictionary key [{}].'.format(key)) entry = self._additional(key) item_dependencies = copy.copy( dependencies.marshalled_dependencies.get(key)) try: item_dependencies.value = val except AttributeError: item_dependencies = dependency_managers.DependencyViewFromValue( val) dict_value[key] = entry.Parse(item_dependencies) dict_value = self.Convert(dict_value) self.Validate(dict_value) return self.Normalize(dict_value)
def _Split(self, string): """Splits string on _DEFAULT_DELIM or the alternate delimiter expression. By default, splits on commas: 'a,b,c' -> ['a', 'b', 'c'] Alternate delimiter syntax: '^:^a,b:c' -> ['a,b', 'c'] '^::^a:b::c' -> ['a:b', 'c'] '^,^^a^,b,c' -> ['^a^', ',b', 'c'] See `gcloud topic escaping` for details. Args: string: The string with optional alternate delimiter expression. Raises: exceptions.ParseError: on invalid delimiter expression. Returns: (string, delimiter) string with the delimiter expression stripped, if any. """ if not string: return None, None delim = self._DEFAULT_DELIM if string.startswith( self._ALT_DELIM) and self._ALT_DELIM in string[1:]: delim, string = string[1:].split(self._ALT_DELIM, 1) if not delim: raise exceptions.ParseError( self.GetPresentationName(), 'Invalid delimiter. Please see $ gcloud topic escaping for ' 'information on escaping list or dictionary flag values.') return string.split(delim), delim
def Parse(self, dependencies): """Parses the concept. Args: dependencies: googlecloudsdk.command_lib.concepts.dependency_managers .DependencyView, the dependency namespace for the concept. Raises: exceptions.MissingRequiredArgumentException, if no value is provided and one is required. exceptions.ParseError, if the value provided is incorrect. Returns: str | None, the day of the week, abbreviated to the first three letters in upper-case format, or None if no day was given and the attribute is not required. """ given = super(DayOfTheWeek, self).Parse(dependencies) if given is None: return given fixed = given.upper()[:3] if fixed not in self._DAYS: raise exceptions.ParseError( self.GetPresentationName(), 'Value for day of the week should be one of: [{}]. ' 'You gave: [{}]'.format(', '.join(self._DAYS), given)) return fixed
def Convert(self, string): if string is None: return None try: return int(string) except ValueError as e: if self._unlimited and string == 'unlimited': return None raise exceptions.ParseError(self.GetPresentationName(), '{}.'.format(_SubException(e)))
def Convert(self, string): if not string: return None try: return scaled_integer.ParseBinaryInteger(string, self._default_unit) except ValueError as e: raise exceptions.ParseError( self.GetPresentationName(), 'Failed to parse binary scaled integer [{}]: {}.'.format( string, _SubException(e)))
def Convert(self, string): """Converts a datetime value from string returns it.""" if not string: return None try: return times.ParseDateTime(string, tzinfo=self._tzinfo) except times.Error as e: raise exceptions.ParseError( self.GetPresentationName(), 'Failed to parse duration [{}]: {}.'.format( string, _SubException(e)))
def Convert(self, string): """Converts a day of week from string returns it.""" if not string: return None value = string.upper()[:3] if value not in self._DAYS: raise exceptions.ParseError( self.GetPresentationName(), 'A day of week value [{}] must be one of: [{}].'.format( string, ', '.join(self._DAYS))) return value
def Convert(self, string): # TODO(b/117144623): add and use an IsSpecified() method. if string is None: return False if string == '1' or string.lower() == 'true': return True if string == '0' or string.lower() == 'false': return False raise exceptions.ParseError( self.GetPresentationName(), 'Invalid Boolean value [{}].'.format(string))
def Convert(self, string): try: choice = string.lower() if choice not in self.choices and choice.upper() not in self.choices: raise exceptions.ParseError( self.GetPresentationName(), 'Invalid choice [{}], must be one of [{}].'.format( string, ','.join(sorted(self.choices.keys())))) return choice except (AttributeError, ValueError): return string
def Convert(self, string): if not string: return None try: return float(string) except ValueError as e: if self._unlimited and string == 'unlimited': return None raise exceptions.ParseError( self.GetPresentationName(), 'Failed to parse floating point number [{}]: {}.'.format( string, _SubException(e)))
def Convert(self, string): """Converts a SemVer object from string returns it.""" if not string: return None try: parts = string.split('.') while len(parts) < 3: parts.append('0') string = '.'.join(parts) return semver.SemVer(string) except semver.ParseError as e: raise exceptions.ParseError(self.GetPresentationName(), _SubException(e))
def Convert(self, string): """Converts a duration from string returns it.""" if not string: return None try: d = times.ParseDuration( string, default_suffix=self._default_suffix).total_seconds return d if self._subsecond else int(d) except times.Error as e: raise exceptions.ParseError( self.GetPresentationName(), 'Failed to parse duration [{}]: {}.'.format( string, _SubException(e)))
def Convert(self, string): if not string: return None try: value = scaled_integer.ParseInteger( string, default_unit=self._default_unit, type_abbr=self._type_abbr) if self._output_unit_value: value //= self._output_unit_value return value except ValueError as e: raise exceptions.ParseError( self.GetPresentationName(), 'Failed to parse binary/decimal scaled integer [{}]: {}.'.format( string, _SubException(e)))