3 """Given a filename as an argument, sort the #include/#imports in that file.
5 Shows a diff and prompts for confirmation before doing the deed.
15 """Prompts with a yes/no question, returns True if yes."""
18 # http://code.activestate.com/recipes/134892/
19 fd
= sys
.stdin
.fileno()
20 old_settings
= termios
.tcgetattr(fd
)
23 tty
.setraw(sys
.stdin
.fileno())
24 ch
= sys
.stdin
.read(1)
26 termios
.tcsetattr(fd
, termios
.TCSADRAIN
, old_settings
)
28 return ch
in ('Y', 'y')
31 def IncludeCompareKey(line
):
32 """Sorting comparator key used for comparing two #include lines.
33 Returns the filename without the #include/#import prefix.
35 for prefix
in ('#include ', '#import '):
36 if line
.startswith(prefix
):
37 return line
[len(prefix
):]
42 """Returns True if the line is an #include/#import line."""
43 return line
.startswith('#include ') or line
.startswith('#import ')
46 def SortHeader(infile
, outfile
):
47 """Sorts the headers in infile, writing the sorted file to outfile."""
51 while IsInclude(line
):
52 headerblock
.append(line
)
54 for header
in sorted(headerblock
, key
=IncludeCompareKey
):
56 # Intentionally fall through, to write the line that caused
57 # the above while loop to exit.
62 parser
= optparse
.OptionParser(usage
='%prog filename1 filename2 ...')
63 opts
, args
= parser
.parse_args()
70 fixfilename
= filename
+ '.new'
71 infile
= open(filename
, 'r')
72 outfile
= open(fixfilename
, 'w')
73 SortHeader(infile
, outfile
)
75 outfile
.close() # Important so the below diff gets the updated contents.
78 diff
= os
.system('diff -u %s %s' % (filename
, fixfilename
))
79 if diff
>> 8 == 0: # Check exit code.
80 print '%s: no change' % filename
83 if YesNo('Use new file (y/N)?'):
84 os
.rename(fixfilename
, filename
)
87 os
.remove(fixfilename
)
89 # If the file isn't there, we don't care.
93 if __name__
== '__main__':