blob: 5e8fc2641f261e502fcb30c64ed80ecc9a4944c9 [file] [log] [blame]
[email protected]cb155a82011-11-29 17:25:341#!/usr/bin/env python
[email protected]08079092012-01-05 18:24:382# Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]377bf4a2011-05-19 20:17:113# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
[email protected]50e5a3d2010-08-26 00:23:265
6"""Given a filename as an argument, sort the #include/#imports in that file.
7
8Shows a diff and prompts for confirmation before doing the deed.
[email protected]10ab0ed52011-11-01 11:46:529Works great with tools/git/for-all-touched-files.py.
[email protected]50e5a3d2010-08-26 00:23:2610"""
11
12import optparse
13import os
14import sys
[email protected]50e5a3d2010-08-26 00:23:2615
satorux3d23ca02015-02-10 08:04:5116from yes_no import YesNo
[email protected]50e5a3d2010-08-26 00:23:2617
18
19def IncludeCompareKey(line):
20 """Sorting comparator key used for comparing two #include lines.
[email protected]5650b4a42014-04-09 00:52:1521 Returns the filename without the #include/#import/import prefix.
[email protected]50e5a3d2010-08-26 00:23:2622 """
[email protected]5650b4a42014-04-09 00:52:1523 for prefix in ('#include ', '#import ', 'import '):
[email protected]50e5a3d2010-08-26 00:23:2624 if line.startswith(prefix):
[email protected]d5c49322011-05-19 20:08:5725 line = line[len(prefix):]
26 break
[email protected]51e3da52011-05-20 01:53:0627
28 # The win32 api has all sorts of implicit include order dependencies :-/
29 # Give a few headers special sort keys that make sure they appear before all
30 # other headers.
31 if line.startswith('<windows.h>'): # Must be before e.g. shellapi.h
32 return '0'
[email protected]d5d71052013-02-25 21:01:3533 if line.startswith('<atlbase.h>'): # Must be before atlapp.h.
34 return '1' + line
thestigc5d32952014-08-25 22:32:3535 if line.startswith('<ole2.h>'): # Must be before e.g. intshcut.h
36 return '1' + line
[email protected]51e3da52011-05-20 01:53:0637 if line.startswith('<unknwn.h>'): # Must be before e.g. intshcut.h
[email protected]d5d71052013-02-25 21:01:3538 return '1' + line
[email protected]51e3da52011-05-20 01:53:0639
[email protected]08079092012-01-05 18:24:3840 # C++ system headers should come after C system headers.
41 if line.startswith('<'):
42 if line.find('.h>') != -1:
[email protected]2661bb92013-03-13 21:24:4043 return '2' + line.lower()
[email protected]08079092012-01-05 18:24:3844 else:
[email protected]2661bb92013-03-13 21:24:4045 return '3' + line.lower()
[email protected]08079092012-01-05 18:24:3846
47 return '4' + line
[email protected]50e5a3d2010-08-26 00:23:2648
49
50def IsInclude(line):
[email protected]5650b4a42014-04-09 00:52:1551 """Returns True if the line is an #include/#import/import line."""
52 return any([line.startswith('#include '), line.startswith('#import '),
53 line.startswith('import ')])
[email protected]50e5a3d2010-08-26 00:23:2654
55
56def SortHeader(infile, outfile):
57 """Sorts the headers in infile, writing the sorted file to outfile."""
58 for line in infile:
59 if IsInclude(line):
60 headerblock = []
61 while IsInclude(line):
[email protected]1590a8e2013-06-18 14:25:5862 infile_ended_on_include_line = False
[email protected]50e5a3d2010-08-26 00:23:2663 headerblock.append(line)
[email protected]1590a8e2013-06-18 14:25:5864 # Ensure we don't die due to trying to read beyond the end of the file.
65 try:
66 line = infile.next()
67 except StopIteration:
68 infile_ended_on_include_line = True
69 break
[email protected]50e5a3d2010-08-26 00:23:2670 for header in sorted(headerblock, key=IncludeCompareKey):
71 outfile.write(header)
[email protected]1590a8e2013-06-18 14:25:5872 if infile_ended_on_include_line:
73 # We already wrote the last line above; exit to ensure it isn't written
74 # again.
75 return
[email protected]50e5a3d2010-08-26 00:23:2676 # Intentionally fall through, to write the line that caused
77 # the above while loop to exit.
78 outfile.write(line)
79
80
[email protected]1590a8e2013-06-18 14:25:5881def FixFileWithConfirmFunction(filename, confirm_function,
82 perform_safety_checks):
[email protected]18367222012-11-22 11:28:5783 """Creates a fixed version of the file, invokes |confirm_function|
84 to decide whether to use the new file, and cleans up.
85
86 |confirm_function| takes two parameters, the original filename and
87 the fixed-up filename, and returns True to use the fixed-up file,
88 false to not use it.
[email protected]1590a8e2013-06-18 14:25:5889
90 If |perform_safety_checks| is True, then the function checks whether it is
91 unsafe to reorder headers in this file and skips the reorder with a warning
92 message in that case.
[email protected]10ab0ed52011-11-01 11:46:5293 """
[email protected]1590a8e2013-06-18 14:25:5894 if perform_safety_checks and IsUnsafeToReorderHeaders(filename):
95 print ('Not reordering headers in %s as the script thinks that the '
96 'order of headers in this file is semantically significant.'
97 % (filename))
98 return
[email protected]10ab0ed52011-11-01 11:46:5299 fixfilename = filename + '.new'
[email protected]4a2a50cb2013-06-04 06:27:38100 infile = open(filename, 'rb')
101 outfile = open(fixfilename, 'wb')
[email protected]10ab0ed52011-11-01 11:46:52102 SortHeader(infile, outfile)
103 infile.close()
104 outfile.close() # Important so the below diff gets the updated contents.
105
106 try:
[email protected]18367222012-11-22 11:28:57107 if confirm_function(filename, fixfilename):
[email protected]4a2a50cb2013-06-04 06:27:38108 if sys.platform == 'win32':
109 os.unlink(filename)
[email protected]10ab0ed52011-11-01 11:46:52110 os.rename(fixfilename, filename)
111 finally:
112 try:
113 os.remove(fixfilename)
114 except OSError:
115 # If the file isn't there, we don't care.
116 pass
117
118
[email protected]1590a8e2013-06-18 14:25:58119def DiffAndConfirm(filename, should_confirm, perform_safety_checks):
[email protected]18367222012-11-22 11:28:57120 """Shows a diff of what the tool would change the file named
121 filename to. Shows a confirmation prompt if should_confirm is true.
122 Saves the resulting file if should_confirm is false or the user
123 answers Y to the confirmation prompt.
124 """
125 def ConfirmFunction(filename, fixfilename):
126 diff = os.system('diff -u %s %s' % (filename, fixfilename))
[email protected]4a2a50cb2013-06-04 06:27:38127 if sys.platform != 'win32':
128 diff >>= 8
129 if diff == 0: # Check exit code.
[email protected]18367222012-11-22 11:28:57130 print '%s: no change' % filename
131 return False
132
133 return (not should_confirm or YesNo('Use new file (y/N)?'))
134
[email protected]1590a8e2013-06-18 14:25:58135 FixFileWithConfirmFunction(filename, ConfirmFunction, perform_safety_checks)
[email protected]18367222012-11-22 11:28:57136
[email protected]1590a8e2013-06-18 14:25:58137def IsUnsafeToReorderHeaders(filename):
138 # *_message_generator.cc is almost certainly a file that generates IPC
139 # definitions. Changes in include order in these files can result in them not
140 # building correctly.
141 if filename.find("message_generator.cc") != -1:
142 return True
143 return False
[email protected]18367222012-11-22 11:28:57144
[email protected]50e5a3d2010-08-26 00:23:26145def main():
146 parser = optparse.OptionParser(usage='%prog filename1 filename2 ...')
[email protected]10ab0ed52011-11-01 11:46:52147 parser.add_option('-f', '--force', action='store_false', default=True,
148 dest='should_confirm',
149 help='Turn off confirmation prompt.')
[email protected]1590a8e2013-06-18 14:25:58150 parser.add_option('--no_safety_checks',
151 action='store_false', default=True,
152 dest='perform_safety_checks',
153 help='Do not perform the safety checks via which this '
154 'script refuses to operate on files for which it thinks '
155 'the include ordering is semantically significant.')
[email protected]10ab0ed52011-11-01 11:46:52156 opts, filenames = parser.parse_args()
[email protected]50e5a3d2010-08-26 00:23:26157
[email protected]10ab0ed52011-11-01 11:46:52158 if len(filenames) < 1:
[email protected]50e5a3d2010-08-26 00:23:26159 parser.print_help()
[email protected]cb155a82011-11-29 17:25:34160 return 1
[email protected]50e5a3d2010-08-26 00:23:26161
[email protected]10ab0ed52011-11-01 11:46:52162 for filename in filenames:
[email protected]1590a8e2013-06-18 14:25:58163 DiffAndConfirm(filename, opts.should_confirm, opts.perform_safety_checks)
[email protected]50e5a3d2010-08-26 00:23:26164
165
166if __name__ == '__main__':
[email protected]cb155a82011-11-29 17:25:34167 sys.exit(main())