2 # Copyright 2015 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """Given a GYP/GN filename as an argument, sort C++ source files in that file.
8 Shows a diff and prompts for confirmation before doing the deed.
9 Works great with tools/git/for-all-touched-files.py.
17 from yes_no
import YesNo
20 def SortSources(original_lines
):
21 """Sort source file names in |original_lines|.
24 original_lines: Lines of the original content as a list of strings.
27 Lines of the sorted content as a list of strings.
29 The algorithm is fairly naive. The code tries to find a list of C++ source
30 file names by a simple regex, then sort them. The code does not try to
31 understand the syntax of the build files, hence there are many cases that
32 the code cannot handle correctly (ex. comments within a list of source file
38 for line
in original_lines
:
39 if re
.search(r
'^\s+[\'"].*\.(c|cc|cpp|h)[\'"],$
', line):
43 output_lines.extend(sorted(sources))
45 output_lines.append(line)
49 def ProcessFile(filename, should_confirm):
50 """Process the input file and rewrite if needed.
53 filename: Path to the input file.
54 should_confirm: If true, diff and confirmation prompt are shown.
58 with open(filename, 'r
') as input_file:
59 for line in input_file:
60 original_lines.append(line)
62 new_lines = SortSources(original_lines)
63 if original_lines == new_lines:
64 print '%s: no change
' % filename
68 diff = difflib.unified_diff(original_lines, new_lines)
69 sys.stdout.writelines(diff)
70 if not YesNo('Use new
file (y
/N
)'):
73 with open(filename, 'w
') as output_file:
74 output_file.writelines(new_lines)
78 parser = optparse.OptionParser(usage='%prog filename1 filename2
...')
79 parser.add_option('-f
', '--force
', action='store_false
', default=True,
80 dest='should_confirm
',
81 help='Turn off confirmation prompt
.')
82 opts, filenames = parser.parse_args()
84 if len(filenames) < 1:
88 for filename in filenames:
89 ProcessFile(filename, opts.should_confirm)
92 if __name__ == '__main__
':