Exemplo n.º 1
0
 def wrapper(loader, node):
     try:
         return fn(loader, node)
     except Exception as e:
         msg = getattr(e, 'message', str(e))
         raise InvalidNode("line {}: {}.".format(node.start_mark.line + 1,
                                                 msg))
Exemplo n.º 2
0
def settings(loader, node):
    values = loader.construct_mapping(node)
    try:
        return Settings(**values)
    except TypeError:
        for field in Settings._fields:
            if field not in values:
                raise InvalidNode(
                    "!settings node missing required field `{}`.".format(
                        field))
        raise
Exemplo n.º 3
0
def parse_rule(rule_name, rule_values, default_settings=None):
    rule_description = rule_values.get('description')
    if rule_description is None:
        raise InvalidNode("No description provided.")

    rule_expr = rule_values.get('expr')
    if rule_expr is None:
        raise InvalidNode("No expression provided.".format(rule_name))
    matches = (lambda x: find_in_ast(
        file_contents_to_xml_ast(x), rule_expr.path, return_lines=False)
               if isinstance(rule_expr, XPath) else x.match)

    rule_example = rule_values.get('example')
    if rule_example is not None:
        validate_syntax(rule_example, clause_type='example')
        if not matches(rule_example):
            raise InvalidNode("`example` clause is not matched by expression.")

    rule_instead = rule_values.get('instead')
    if rule_instead is not None:
        validate_syntax(rule_instead, clause_type='instead')
        if matches(rule_instead):
            raise InvalidNode("`instead` clause is matched by expression.")

    rule_settings = rule_values.get('settings', default_settings)
    if rule_settings is None:
        raise InvalidNode("No settings or default settings specified.")
    if not isinstance(rule_settings, Settings):
        raise InvalidNode("Settings must be a !settings node.")

    return Rule(
        name=rule_name,
        description=rule_description,
        expr=rule_expr,
        example=rule_example,
        instead=rule_instead,
        settings=rule_settings,
    )
Exemplo n.º 4
0
 def wrapper(rule_name, *args, **kwargs):
     try:
         return fn(rule_name, *args, **kwargs)
     except Exception as e:
         msg = getattr(e, 'message', str(e))
         raise InvalidNode("rule `{}`: {}".format(rule_name, msg))
Exemplo n.º 5
0
def validate_syntax(rule_clause, clause_type):
    try:
        ast.parse(rule_clause)
    except SyntaxError as e:
        raise InvalidNode("Invalid syntax in `{}` clause.".format(clause_type))
Exemplo n.º 6
0
def validate_syntax(rule_example):
    try:
        ast.parse(rule_example)
    except SyntaxError as e:
        raise InvalidNode("Invalid syntax in rule example.")