| Manuel Klimek | 64cbdf3 | 2011-05-31 23:49:32 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | #===- replace.py - Applying code rewrites --------------------*- python -*--===# |
| 4 | # |
| 5 | # The LLVM Compiler Infrastructure |
| 6 | # |
| 7 | # This file is distributed under the University of Illinois Open Source |
| 8 | # License. See LICENSE.TXT for details. |
| 9 | # |
| 10 | #===------------------------------------------------------------------------===# |
| 11 | # |
| 12 | # This script applies the rewrites generated by replace-cstr-calls on a source |
| 13 | # tree. |
| 14 | # |
| 15 | # Usage: |
| 16 | # ./replace.py < /path/to/replace-cstr-calls-output |
| 17 | # |
| 18 | #===------------------------------------------------------------------------===# |
| 19 | |
| 20 | import fileinput |
| 21 | import re |
| 22 | import sys |
| 23 | |
| 24 | for line in sys.stdin.readlines(): |
| 25 | # The format is: |
| 26 | # <file>:<start_line>:<start_column>:<end_line>:<end_column>:<replacement> |
| 27 | # FIXME: This currently does not support files with colons, we'll need to |
| 28 | # figure out a format when we implement more refactoring support. |
| 29 | match = re.match(r'(.*):(\d+):(\d+):(\d+):(\d+):(.*)$', line) |
| 30 | if match is not None: |
| 31 | file_name = match.group(1) |
| 32 | start_line, start_column = int(match.group(2)), int(match.group(3)) |
| 33 | end_line, end_column = int(match.group(4)), int(match.group(5)) |
| 34 | replacement = match.group(6) |
| 35 | if start_line != end_line: |
| 36 | print ('Skipping match "%s": only single line ' + |
| 37 | 'replacements are supported') % line.strip() |
| 38 | continue |
| 39 | try: |
| 40 | replace_file = fileinput.input(file_name, inplace=1) |
| 41 | for replace_line in replace_file: |
| 42 | # FIXME: Looping over the file for each replacement is both inefficient |
| 43 | # and incorrect if replacements add or remove lines. |
| 44 | if replace_file.lineno() == start_line: |
| 45 | sys.stdout.write(replace_line[:start_column-1] + replacement + |
| 46 | replace_line[end_column:]) |
| 47 | else: |
| 48 | sys.stdout.write(replace_line) |
| 49 | except OSError, e: |
| 50 | print 'Cannot open %s for editing' % file_name |