Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Unified Diff: abp/filters/parser.py

Issue 30053555: Issue 7471 - Add an API for working with blocks of filters (Closed) Base URL: https://hg.adblockplus.org/python-abp
Patch Set: Adjust the API in response to review comments Created May 9, 2019, 4:22 p.m.
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « abp/filters/blocks.py ('k') | abp/filters/rpy.py » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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}')
« no previous file with comments | « abp/filters/blocks.py ('k') | abp/filters/rpy.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld