Exemple #1
0
 def validate(self, value):
     if not value:
         if self._none_ok:
             return
         else:
             raise configexc.ValidationError(value, "may not be empty")
     if not value.endswith('%'):
         raise configexc.ValidationError(value, "does not end with %")
     try:
         intval = int(value[:-1])
     except ValueError:
         raise configexc.ValidationError(value, "invalid percentage!")
     if self.minval is not None and intval < self.minval:
         raise configexc.ValidationError(
             value, "must be {}% or "
             "more!".format(self.minval))
     if self.maxval is not None and intval > self.maxval:
         raise configexc.ValidationError(
             value, "must be {}% or "
             "less!".format(self.maxval))
Exemple #2
0
    def _validate_str(self, value, what):
        """Check if the given thing is an ascii-only string.

        Raises ValidationError if not.

        Args:
            value: The value to check.
            what: Either 'key' or 'value'.
        """
        if not isinstance(value, str):
            msg = "Expected string for {} {!r} but got {}".format(
                what, value, type(value))
            raise configexc.ValidationError(value, msg)

        try:
            value.encode('ascii')
        except UnicodeEncodeError as e:
            msg = "{} {!r} contains non-ascii characters: {}".format(
                what.capitalize(), value, e)
            raise configexc.ValidationError(value, msg)
    def from_str(self, value):
        self._basic_str_validation(value)
        if not value:
            return None

        try:
            intval = int(value)
        except ValueError:
            raise configexc.ValidationError(value, "must be an integer!")
        self.to_py(intval)
        return intval
    def from_str(self, value):
        self._basic_str_validation(value)
        if not value:
            return None

        try:
            floatval = float(value)
        except ValueError:
            raise configexc.ValidationError(value, "must be a float!")
        self.to_py(floatval)
        return floatval
    def to_py(self, value):
        value = super().to_py(value)
        if not value:
            return None

        # Check for duplicate values
        if len(set(value)) != len(value):
            raise configexc.ValidationError(
                value, "String contains duplicate values!")

        return value
    def to_py(self, value):
        self._basic_py_validation(value, str)
        if not value:
            return None

        qurl = QUrl.fromUserInput(value)
        if not qurl.isValid():
            raise configexc.ValidationError(
                value, "invalid URL - "
                "{}".format(qurl.errorString()))
        return qurl
    def to_py(self, value):
        self._basic_py_validation(value, str)
        if not value:
            return None

        value = os.path.expanduser(value)
        value = os.path.expandvars(value)
        try:
            if not os.path.isabs(value):
                value = os.path.join(standarddir.config(), value)
                not_isfile_message = ("must be a valid path relative to the "
                                      "config directory!")
            else:
                not_isfile_message = "must be a valid file!"
            if self.required and not os.path.isfile(value):
                raise configexc.ValidationError(value, not_isfile_message)
        except UnicodeEncodeError as e:
            raise configexc.ValidationError(value, e)

        return value
Exemple #8
0
 def validate(self, value):
     self._basic_validation(value)
     if not value:
         return
     try:
         # Dummy check to see if the template is valid
         datetime.datetime.now().strftime(value)
     except ValueError as error:
         # thrown on invalid template string
         raise configexc.ValidationError(
             value, "Invalid format string: {}".format(error))
Exemple #9
0
 def validate(self, value):
     self._basic_validation(value)
     if not value:
         return
     elif value.startswith('-'):
         # custom function name, won't validate.
         pass
     elif QColor.isValidColor(value):
         pass
     else:
         raise configexc.ValidationError(value, "must be a valid color")
Exemple #10
0
    def to_py(self, value):
        self._basic_py_validation(value, str)
        if not value:
            return None

        self._validate_encoding(value)
        self._validate_valid_values(value)

        if self.forbidden is not None and any(c in value
                                              for c in self.forbidden):
            raise configexc.ValidationError(value, "may not contain the chars "
                                            "'{}'".format(self.forbidden))
        if self.minlen is not None and len(value) < self.minlen:
            raise configexc.ValidationError(value, "must be at least {} chars "
                                            "long!".format(self.minlen))
        if self.maxlen is not None and len(value) > self.maxlen:
            raise configexc.ValidationError(value, "must be at most {} chars "
                                            "long!".format(self.maxlen))

        return value
Exemple #11
0
 def validate(self, value):
     self._basic_validation(value)
     if not value:
         return
     vals = value.split(',')
     if self.length is not None and len(vals) != self.length:
         raise configexc.ValidationError(
             value, "Exactly {} values need to "
             "be set!".format(self.length))
     for val in vals:
         self.inner_type.validate(val.strip())
Exemple #12
0
 def validate(self, value):
     self._basic_validation(value)
     if not value:
         return
     vals = super().transform(value)
     for val in vals:
         self.bytestype.validate(val)
     if self.length is not None and len(vals) != self.length:
         raise configexc.ValidationError(
             value, "exactly {} values need to "
             "be set!".format(self.length))
Exemple #13
0
 def validate(self, value):
     self._basic_validation(value)
     if not value:
         return
     elif any(re.match(r, value) for r in self.color_func_regexes):
         # QColor doesn't handle these, so we do the best we can easily
         pass
     elif QColor.isValidColor(value):
         pass
     else:
         raise configexc.ValidationError(value, "must be a valid color")
Exemple #14
0
    def validate(self, value):
        from qutebrowser.utils import urlutils
        self._basic_validation(value)
        if not value:
            return
        elif value in self.valid_values:
            return

        try:
            self.transform(value)
        except (urlutils.InvalidUrlError, urlutils.InvalidProxyTypeError) as e:
            raise configexc.ValidationError(value, e)
Exemple #15
0
    def validate(self, value):
        self._basic_validation(value)
        if not value:
            return

        if self.valid_values is not None:
            if value not in self.valid_values:
                raise configexc.ValidationError(
                    value, "valid values: {}".format(', '.join(
                        self.valid_values)))

        if self.forbidden is not None and any(c in value
                                              for c in self.forbidden):
            raise configexc.ValidationError(value, "may not contain the chars "
                                            "'{}'".format(self.forbidden))
        if self.minlen is not None and len(value) < self.minlen:
            raise configexc.ValidationError(value, "must be at least {} chars "
                                            "long!".format(self.minlen))
        if self.maxlen is not None and len(value) > self.maxlen:
            raise configexc.ValidationError(value, "must be at most {} chars "
                                            "long!".format(self.maxlen))
Exemple #16
0
    def validate(self, value):
        self._basic_validation(value)
        if not value:
            return

        vals = self.transform(value)
        if None in vals and not self.none_ok:
            raise configexc.ValidationError(
                value, "May not contain empty values!")

        # Check for duplicate values
        if len(set(vals)) != len(vals):
            raise configexc.ValidationError(
                value, "List contains duplicate values!")

        # Check if each value is valid, ignores None values
        set_vals = set(val for val in vals if val)
        if (self.valid_values is not None and
                not set_vals.issubset(set(self.valid_values))):
            raise configexc.ValidationError(
                value, "List contains invalid values!")
    def to_py(self, value):
        self._basic_py_validation(value, list)
        if not value:
            return []

        for val in value:
            self._validate_surrogate_escapes(value, val)

        if self.length is not None and len(value) != self.length:
            raise configexc.ValidationError(value, "Exactly {} values need to "
                                            "be set!".format(self.length))
        return [self.valtype.to_py(v) for v in value]
Exemple #18
0
 def validate(self, value):
     self._basic_validation(value)
     if not value:
         return
     vals = super().transform(value)
     perctype = Perc(minval=self.minval, maxval=self.maxval)
     try:
         for val in vals:
             if val is None:
                 if self.none_ok:
                     continue
                 else:
                     raise configexc.ValidationError(
                         value, "items may not "
                         "be empty!")
             else:
                 perctype.validate(val)
     except configexc.ValidationError:
         raise configexc.ValidationError(
             value, "must be a list of "
             "percentages!")
Exemple #19
0
 def validate(self, value):
     self._basic_validation(value)
     if not value:
         return
     elif value.endswith('%'):
         try:
             intval = int(value[:-1])
         except ValueError:
             raise configexc.ValidationError(value, "invalid percentage!")
         if self.minperc is not None and intval < self.minperc:
             raise configexc.ValidationError(value, "must be {}% or "
                                             "more!".format(self.minperc))
         if self.maxperc is not None and intval > self.maxperc:
             raise configexc.ValidationError(value, "must be {}% or "
                                             "less!".format(self.maxperc))
     else:
         try:
             intval = int(value)
         except ValueError:
             raise configexc.ValidationError(value, "must be integer or "
                                             "percentage!")
         if self.minint is not None and intval < self.minint:
             raise configexc.ValidationError(value, "must be {} or "
                                             "bigger!".format(self.minint))
         if self.maxint is not None and intval > self.maxint:
             raise configexc.ValidationError(value, "must be {} or "
                                             "smaller!".format(self.maxint))
Exemple #20
0
    def to_py(self, value):
        self._basic_py_validation(value, str)
        if not value:
            return None

        if not ('{}' in value or '{0}' in value):
            raise configexc.ValidationError(value, "must contain \"{}\"")

        try:
            value.format("")
        except (KeyError, IndexError) as e:
            raise configexc.ValidationError(
                value, "may not contain {...} (use {{ and }} for literal {/})")
        except ValueError as e:
            raise configexc.ValidationError(value, str(e))

        url = QUrl(value.replace('{}', 'foobar'))
        if not url.isValid():
            raise configexc.ValidationError(
                value, "invalid url, {}".format(url.errorString()))

        return value
Exemple #21
0
    def to_py(self, value):
        self._basic_py_validation(value, str)
        if not value:
            return None

        if not self.font_regex.match(value):  # pragma: no cover
            # This should never happen, as the regex always matches everything
            # as family.
            raise configexc.ValidationError(value, "must be a valid font")

        if value.endswith(' monospace') and self.monospace_fonts is not None:
            return value.replace('monospace', self.monospace_fonts)
        return value
Exemple #22
0
 def validate(self, value):
     self._basic_validation(value)
     if not value:
         return
     value = os.path.expanduser(value)
     value = os.path.expandvars(value)
     try:
         if not os.path.isabs(value):
             cfgdir = standarddir.config()
             if cfgdir is None:
                 raise configexc.ValidationError(
                     value, "must be an absolute path when not using a "
                     "config directory!")
             value = os.path.join(cfgdir, value)
             not_isfile_message = ("must be a valid path relative to the "
                                   "config directory!")
         else:
             not_isfile_message = "must be a valid file!"
         if self.required and not os.path.isfile(value):
             raise configexc.ValidationError(value, not_isfile_message)
     except UnicodeEncodeError as e:
         raise configexc.ValidationError(value, e)
Exemple #23
0
    def validate(self, value):
        if self.inner_type.valid_values is not None:
            super().validate(value)
        else:
            self._basic_validation(value)
        if not value:
            return
        vals = super().transform(value)

        # Check for duplicate values
        if len(set(vals)) != len(vals):
            raise configexc.ValidationError(
                value, "List contains duplicate values!")
Exemple #24
0
    def validate(self, value):
        self._basic_validation(value)
        if not value:
            return
        vals = super().transform(value)

        for val in vals:
            if val is None:
                if not self.none_ok:
                    raise configexc.ValidationError(
                        value, "items may not be empty!")
            else:
                _validate_regex(val, self.flags)
Exemple #25
0
    def validate(self, value):
        self._basic_validation(value)
        if not value:
            return

        try:
            json_val = json.loads(value)
        except ValueError as e:
            raise configexc.ValidationError(value, str(e))

        if not isinstance(json_val, dict):
            raise configexc.ValidationError(value, "Expected json dict, but "
                                            "got {}".format(type(json_val)))
        if not json_val:
            if self.none_ok:
                return
            else:
                raise configexc.ValidationError(value, "may not be empty!")

        for key, val in json_val.items():
            self._validate_str(key, 'key')
            self._validate_str(val, 'value')
Exemple #26
0
 def validate(self, value):
     if not value:
         if self._none_ok:
             return
         else:
             raise configexc.ValidationError(value, "may not be empty!")
     value = os.path.expandvars(value)
     value = os.path.expanduser(value)
     try:
         if not os.path.isabs(value):
             # probably a CSS, so we don't handle it as filename.
             # FIXME We just try if it is encodable, maybe we should
             # validate CSS?
             # https://github.com/The-Compiler/qutebrowser/issues/115
             try:
                 value.encode('utf-8')
             except UnicodeEncodeError as e:
                 raise configexc.ValidationError(value, str(e))
             return
         elif not os.path.isfile(value):
             raise configexc.ValidationError(value, "must be a valid file!")
     except UnicodeEncodeError as e:
         raise configexc.ValidationError(value, e)
Exemple #27
0
    def _validate_valid_values(self, value):
        """Validate value against possible values.

        The default implementation checks the value against self.valid_values
        if it was defined.

        Args:
            value: The value to validate.
        """
        if self.valid_values is not None:
            if value not in self.valid_values:
                raise configexc.ValidationError(
                    value,
                    "valid values: {}".format(', '.join(self.valid_values)))
Exemple #28
0
    def from_str(self, value):
        self._basic_str_validation(value)
        if not value:
            return None

        try:
            yaml_val = utils.yaml_load(value)
        except yaml.YAMLError as e:
            raise configexc.ValidationError(value, str(e))

        # For the values, we actually want to call to_py, as we did parse them
        # from YAML, so they are numbers/booleans/... already.
        self.to_py(yaml_val)
        return yaml_val
Exemple #29
0
    def to_py(self, value):
        self._basic_py_validation(value, (float, int, str))
        if not value:
            return None

        if isinstance(value, str):
            value = value.rstrip('%')
            try:
                value = float(value)
            except ValueError:
                raise configexc.ValidationError(value,
                                                "must be a valid number!")
        self._validate_bounds(value, suffix='%')
        return value
Exemple #30
0
    def from_str(self, value):
        self._basic_str_validation(value)
        if not value:
            return None

        if value.endswith('%'):
            self.to_py(value)
            return value

        try:
            intval = int(value)
        except ValueError:
            raise configexc.ValidationError(value,
                                            "must be integer or percentage!")
        self.to_py(intval)
        return intval