blob: a738dea70c0a0a0072bb5ce3365d3ee985b7db5d [file] [log] [blame]
Manuel Klimek64cbdf32011-05-31 23:49:32 +00001#!/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
20import fileinput
21import re
22import sys
23
24for 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