2 # Copyright (c) 2012 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 filename as an argument, sort the #include/#imports 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.
16 from yes_no
import YesNo
19 def IncludeCompareKey(line
):
20 """Sorting comparator key used for comparing two #include lines.
21 Returns the filename without the #include/#import/import prefix.
23 for prefix
in ('#include ', '#import ', 'import '):
24 if line
.startswith(prefix
):
25 line
= line
[len(prefix
):]
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
31 if line
.startswith('<windows.h>'): # Must be before e.g. shellapi.h
33 if line
.startswith('<atlbase.h>'): # Must be before atlapp.h.
35 if line
.startswith('<ole2.h>'): # Must be before e.g. intshcut.h
37 if line
.startswith('<unknwn.h>'): # Must be before e.g. intshcut.h
40 # C++ system headers should come after C system headers.
41 if line
.startswith('<'):
42 if line
.find('.h>') != -1:
43 return '2' + line
.lower()
45 return '3' + line
.lower()
51 """Returns True if the line is an #include/#import/import line."""
52 return any([line
.startswith('#include '), line
.startswith('#import '),
53 line
.startswith('import ')])
56 def SortHeader(infile
, outfile
):
57 """Sorts the headers in infile, writing the sorted file to outfile."""
61 while IsInclude(line
):
62 infile_ended_on_include_line
= False
63 headerblock
.append(line
)
64 # Ensure we don't die due to trying to read beyond the end of the file.
68 infile_ended_on_include_line
= True
70 for header
in sorted(headerblock
, key
=IncludeCompareKey
):
72 if infile_ended_on_include_line
:
73 # We already wrote the last line above; exit to ensure it isn't written
76 # Intentionally fall through, to write the line that caused
77 # the above while loop to exit.
81 def FixFileWithConfirmFunction(filename
, confirm_function
,
82 perform_safety_checks
):
83 """Creates a fixed version of the file, invokes |confirm_function|
84 to decide whether to use the new file, and cleans up.
86 |confirm_function| takes two parameters, the original filename and
87 the fixed-up filename, and returns True to use the fixed-up file,
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
94 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.'
99 fixfilename
= filename
+ '.new'
100 infile
= open(filename
, 'rb')
101 outfile
= open(fixfilename
, 'wb')
102 SortHeader(infile
, outfile
)
104 outfile
.close() # Important so the below diff gets the updated contents.
107 if confirm_function(filename
, fixfilename
):
108 if sys
.platform
== 'win32':
110 os
.rename(fixfilename
, filename
)
113 os
.remove(fixfilename
)
115 # If the file isn't there, we don't care.
119 def DiffAndConfirm(filename
, should_confirm
, perform_safety_checks
):
120 """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.
125 def ConfirmFunction(filename
, fixfilename
):
126 diff
= os
.system('diff -u %s %s' % (filename
, fixfilename
))
127 if sys
.platform
!= 'win32':
129 if diff
== 0: # Check exit code.
130 print '%s: no change' % filename
133 return (not should_confirm
or YesNo('Use new file (y/N)?'))
135 FixFileWithConfirmFunction(filename
, ConfirmFunction
, perform_safety_checks
)
137 def 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:
146 parser
= optparse
.OptionParser(usage
='%prog filename1 filename2 ...')
147 parser
.add_option('-f', '--force', action
='store_false', default
=True,
148 dest
='should_confirm',
149 help='Turn off confirmation prompt.')
150 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.')
156 opts
, filenames
= parser
.parse_args()
158 if len(filenames
) < 1:
162 for filename
in filenames
:
163 DiffAndConfirm(filename
, opts
.should_confirm
, opts
.perform_safety_checks
)
166 if __name__
== '__main__':