Index: abp/filters/parser.py |
=================================================================== |
--- a/abp/filters/parser.py |
+++ b/abp/filters/parser.py |
@@ -102,16 +102,60 @@ |
THIRD_PARTY = 'third-party' |
COLLAPSE = 'collapse' |
SITEKEY = 'sitekey' |
DONOTTRACK = 'donottrack' |
CSP = 'csp' |
REWRITE = 'rewrite' |
+def _option_list_to_dict(options): |
+ """Recursively parse filter options into dicts. |
+ |
+ Parameters |
+ ---------- |
+ options: A list of tuples |
+ The filter options |
+ |
+ Returns |
+ ------- |
+ dict |
+ The resulting dictionary |
+ |
+ """ |
+ result = dict(options) |
+ if 'domain' in result: |
+ result['domain'] = _option_list_to_dict(result['domain']) |
+ |
+ return result |
+ |
+ |
+def _to_dict(line): |
+ """Convert a parsed filter list line from a namedtuple to a dict. |
+ |
+ Parameters |
+ ---------- |
+ line: namedtuple |
+ The parsed filter. |
+ |
+ Returns |
+ ------- |
+ dict |
+ The resulting dictionary |
+ |
+ """ |
+ result = dict(line._asdict()) |
+ if 'options' in result: |
+ result['options'] = _option_list_to_dict(result['options']) |
+ |
+ result['type'] = line.__class__.__name__ |
+ |
+ return result |
+ |
+ |
def _line_type(name, field_names, format_string): |
"""Define a line type. |
Parameters |
---------- |
name: str |
The name of the line type to define. |
field_names: str or list |
@@ -127,16 +171,17 @@ |
Class created with `namedtuple` that has `.type` set to lowercased |
`name` and supports conversion back to string with `.to_string()` |
method. |
""" |
lt = namedtuple(name, field_names) |
lt.type = name.lower() |
lt.to_string = lambda self: format_string.format(self) |
+ lt.to_dict = _to_dict |
return lt |
Header = _line_type('Header', 'version', '[{.version}]') |
EmptyLine = _line_type('EmptyLine', '', '') |
Comment = _line_type('Comment', 'text', '! {.text}') |
Metadata = _line_type('Metadata', 'key value', '! {0.key}: {0.value}') |
Filter = _line_type('Filter', 'text selector action options', '{.text}') |