OLD | NEW |
(Empty) | |
| 1 # Copyright 2014 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 from collections import defaultdict |
| 6 import re |
| 7 import os |
| 8 |
| 9 |
| 10 class LineNumber(object): |
| 11 def __init__(self, file, line_number): |
| 12 self.file = file |
| 13 self.line_number = int(line_number) |
| 14 |
| 15 |
| 16 class FileCache(object): |
| 17 _cache = defaultdict(str) |
| 18 |
| 19 def _read(self, file): |
| 20 file = os.path.abspath(file) |
| 21 self._cache[file] = self._cache[file] or open(file, "r").read() |
| 22 return self._cache[file] |
| 23 |
| 24 @staticmethod |
| 25 def read(file): |
| 26 return FileCache()._read(file) |
| 27 |
| 28 |
| 29 class Processor(object): |
| 30 _IF_TAGS_REG = "</?if[^>]*?>" |
| 31 _INCLUDE_REG = "<include[^>]+src=['\"]([^>]*)['\"]>" |
| 32 |
| 33 def __init__(self, file): |
| 34 self._included_files = set() |
| 35 self._index = 0 |
| 36 self._lines = self._get_file(file) |
| 37 |
| 38 while self._index < len(self._lines): |
| 39 current_line = self._lines[self._index] |
| 40 match = re.search(self._INCLUDE_REG, current_line[2]) |
| 41 if match: |
| 42 file_dir = os.path.dirname(current_line[0]) |
| 43 self._include_file(os.path.join(file_dir, match.group(1))) |
| 44 else: |
| 45 self._index += 1 |
| 46 |
| 47 for i, line in enumerate(self._lines): |
| 48 self._lines[i] = line[:2] + (re.sub(self._IF_TAGS_REG, "", line[2]),) |
| 49 |
| 50 self.contents = "\n".join(l[2] for l in self._lines) |
| 51 |
| 52 # Returns a list of tuples in the format: (file, line number, line contents). |
| 53 def _get_file(self, file): |
| 54 lines = FileCache.read(file).splitlines() |
| 55 return [(file, lnum + 1, line) for lnum, line in enumerate(lines)] |
| 56 |
| 57 def _include_file(self, file): |
| 58 self._included_files.add(file) |
| 59 f = self._get_file(file) |
| 60 self._lines = self._lines[:self._index] + f + self._lines[self._index + 1:] |
| 61 |
| 62 def get_file_from_line(self, line_number): |
| 63 line_number = int(line_number) - 1 |
| 64 return LineNumber(self._lines[line_number][0], self._lines[line_number][1]) |
| 65 |
| 66 def included_files(self): |
| 67 return self._included_files |
OLD | NEW |