21def SanitizeFilesWithModifiers(directory, file_modifiers, line_modifiers):
22 """Sanitizes source files with the specified file and line modifiers.
23
24 Args:
25 directory: string - The directory which will be recursively traversed to
26 find source files to apply modifiers to.
27 file_modifiers: list - file-modification methods which should be applied to
28 the complete file content (Eg: EOFOneAndOnlyOneNewlineAdder).
29 line_modifiers: list - line-modification methods which should be applied to
30 lines in a file (Eg: TabReplacer).
31 """
32 for item in os.listdir(directory):
33
34 full_item_path = os.path.join(directory, item)
35
36 if os.path.isfile(full_item_path):
37
38
39 if (len(full_item_path.split('.')) > 1 and
40 full_item_path.split('.')[-1] in _FILE_EXTENSIONS_TO_SANITIZE):
41 f = file(full_item_path)
42 try:
43 lines = f.readlines()
44 finally:
45 f.close()
46
47 new_lines = []
48 line_number = 0
49 write_to_file = False
50
51
52 for line in lines:
53 original_line = line
54 line_number += 1
55
56 for modifier in line_modifiers:
57 line = modifier(line, full_item_path, line_number)
58 if original_line != line:
59 write_to_file = True
60 new_lines.append(line)
61
62
63 old_content = ''.join(lines)
64 new_content = ''.join(new_lines)
65 for modifier in file_modifiers:
66 new_content = modifier(new_content, full_item_path)
67 if new_content != old_content:
68 write_to_file = True
69
70
71 if write_to_file:
72 f = file(full_item_path, 'w')
73 try:
74 f.write(new_content)
75 finally:
76 f.close()
77 print(
'Made changes to %s' % full_item_path)
78
79 elif item not in _SUBDIRS_TO_IGNORE:
80
81 SanitizeFilesWithModifiers(full_item_path, file_modifiers, line_modifiers)
82
83