summaryrefslogtreecommitdiffstats
path: root/examples/Tooling/replace.py
blob: a738dea70c0a0a0072bb5ce3365d3ee985b7db5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python

#===- replace.py - Applying code rewrites --------------------*- python -*--===#
#
#                     The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===------------------------------------------------------------------------===#
#
# This script applies the rewrites generated by replace-cstr-calls on a source
# tree.
#
# Usage:
#   ./replace.py < /path/to/replace-cstr-calls-output
#
#===------------------------------------------------------------------------===#

import fileinput
import re
import sys

for line in sys.stdin.readlines():
  # The format is:
  # <file>:<start_line>:<start_column>:<end_line>:<end_column>:<replacement>
  # FIXME: This currently does not support files with colons, we'll need to
  # figure out a format when we implement more refactoring support.
  match = re.match(r'(.*):(\d+):(\d+):(\d+):(\d+):(.*)$', line)
  if match is not None:
    file_name = match.group(1)
    start_line, start_column = int(match.group(2)), int(match.group(3))
    end_line, end_column = int(match.group(4)), int(match.group(5))
    replacement = match.group(6)
    if start_line != end_line:
      print ('Skipping match "%s": only single line ' +
             'replacements are supported') % line.strip()
      continue
    try:
      replace_file = fileinput.input(file_name, inplace=1)
      for replace_line in replace_file:
        # FIXME: Looping over the file for each replacement is both inefficient
        # and incorrect if replacements add or remove lines.
        if replace_file.lineno() == start_line:
          sys.stdout.write(replace_line[:start_column-1] + replacement +
                           replace_line[end_column:])
        else:
          sys.stdout.write(replace_line)
    except OSError, e:
      print 'Cannot open %s for editing' % file_name