OLD | NEW |
(Empty) | |
| 1 # Copyright (c) 2011 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 __future__ import with_statement |
| 6 import os |
| 7 import re |
| 8 |
| 9 |
| 10 class MangleBase(object): |
| 11 """For each of the modified file, process the file.""" |
| 12 def __init__(self, max_lines_search=None, once=False): |
| 13 self.max_lines_search = max_lines_search |
| 14 self.once = once |
| 15 |
| 16 def process(self, checkout, patches): |
| 17 for patch in patches.patches: |
| 18 if patch.is_delete or patch.is_binary: |
| 19 pass |
| 20 filepath = os.path.join(checkout.project_path, patch.filename) |
| 21 with open(filepath, 'rb') as f: |
| 22 content = f.read().splitlines(True) |
| 23 if not content: |
| 24 continue |
| 25 if self.process_lines(content): |
| 26 with open(filepath, 'wb') as f: |
| 27 f.write(''.join(content)) |
| 28 |
| 29 def process_lines(self, lines): |
| 30 """Modifies lines in-place.""" |
| 31 modified = False |
| 32 for i in xrange(min(self.max_lines_search, len(lines))): |
| 33 old_line = lines[i] |
| 34 lines[i] = self.process_line(lines[i]) |
| 35 modified |= (old_line != lines[i]) |
| 36 if self.once and modified: |
| 37 break |
| 38 return modified |
| 39 |
| 40 def process_line(self, line): |
| 41 raise NotImplementedError('Modifies a single line') |
| 42 |
| 43 |
| 44 class CopyrightMangle(MangleBase): |
| 45 """Process the copyright in the first 5 lines.""" |
| 46 def __init__(self, pattern, replacement, max_lines_search=5): |
| 47 """Replaces |pattern| with |replacement| once if found within first |
| 48 |max_lines_search| lines of the file. |
| 49 """ |
| 50 super(CopyrightMangle, self).__init__(max_lines_search, True) |
| 51 self.pattern = pattern |
| 52 self.replacement = replacement |
| 53 |
| 54 def process_line(self, line): |
| 55 return re.sub(self.pattern, self.replacement, line) |
OLD | NEW |