OLD | NEW |
(Empty) | |
| 1 # This file is part of Adblock Plus <https://adblockplus.org/>, |
| 2 # Copyright (C) 2006-present eyeo GmbH |
| 3 # |
| 4 # Adblock Plus is free software: you can redistribute it and/or modify |
| 5 # it under the terms of the GNU General Public License version 3 as |
| 6 # published by the Free Software Foundation. |
| 7 # |
| 8 # Adblock Plus is distributed in the hope that it will be useful, |
| 9 # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 # GNU General Public License for more details. |
| 12 # |
| 13 # You should have received a copy of the GNU General Public License |
| 14 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. |
| 15 |
| 16 """Extract blocks of filters separated by comments.""" |
| 17 |
| 18 from __future__ import unicode_literals |
| 19 |
| 20 import re |
| 21 |
| 22 from abp.filters.parser import ParseError |
| 23 |
| 24 VAR_REGEXP = re.compile(r'^:(\w+)=(.*)$') |
| 25 |
| 26 |
| 27 class FilterBlock(object): |
| 28 """A block of filters. |
| 29 |
| 30 Blocks are consecutive groups of filters separated by comments. |
| 31 |
| 32 """ |
| 33 |
| 34 def __init__(self, comments, filters): |
| 35 self.filters = filters |
| 36 descr_lines = [] |
| 37 for comment in comments: |
| 38 match = VAR_REGEXP.search(comment.text) |
| 39 if match: |
| 40 name, value = match.groups() |
| 41 if name.startswith('_') or name in {'filters', 'description'}: |
| 42 raise ParseError('Invalid variable name', |
| 43 comment.to_string()) |
| 44 setattr(self, name, value) |
| 45 else: |
| 46 descr_lines.append(comment.text) |
| 47 self.description = '\n'.join(descr_lines) |
| 48 |
| 49 def _asdict(self): |
| 50 ret = dict(self.__dict__) |
| 51 ret['filters'] = [f._asdict() for f in ret['filters']] |
| 52 return ret |
| 53 |
| 54 |
| 55 def to_blocks(parsed_lines): |
| 56 """Convert a sequence of parser filter list lines to blocks. |
| 57 |
| 58 Parameters |
| 59 ---------- |
| 60 parsed_lines : iterable of namedtuple |
| 61 Parsed filter list (see `parser.py` for details on how it's |
| 62 represented). |
| 63 |
| 64 Returns |
| 65 ------- |
| 66 blocks : iterable of FilterBlock. |
| 67 |
| 68 """ |
| 69 comments = [] |
| 70 filters = [] |
| 71 |
| 72 for line in parsed_lines: |
| 73 if line.type == 'comment': |
| 74 if filters: |
| 75 yield FilterBlock(comments, filters) |
| 76 comments = [] |
| 77 filters = [] |
| 78 comments.append(line) |
| 79 elif line.type == 'filter': |
| 80 filters.append(line) |
| 81 |
| 82 if filters: |
| 83 yield FilterBlock(comments, filters) |
OLD | NEW |