@@ -0,0 +1,2457 @@
+#!/usr/bin/python%0A%0A%22%22%22Given a filename as an argument, sort the #include/#imports in that file.%0A%0AShows a diff and prompts for confirmation before doing the deed.%0A%22%22%22%0A%0Aimport optparse%0Aimport os%0Aimport sys%0Aimport termios%0Aimport tty%0A%0Adef YesNo(prompt):%0A  %22%22%22Prompts with a yes/no question, returns True if yes.%22%22%22%0A  print prompt,%0A  sys.stdout.flush()%0A  # http://code.activestate.com/recipes/134892/%0A  fd = sys.stdin.fileno()%0A  old_settings = termios.tcgetattr(fd)%0A  ch = 'n'%0A  try:%0A    tty.setraw(sys.stdin.fileno())%0A    ch = sys.stdin.read(1)%0A  finally:%0A    termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)%0A  print ch%0A  return ch in ('Y', 'y')%0A%0A%0Adef IncludeCompareKey(line):%0A  %22%22%22Sorting comparator key used for comparing two #include lines.%0A  Returns the filename without the #include/#import prefix.%0A  %22%22%22%0A  for prefix in ('#include ', '#import '):%0A    if line.startswith(prefix):%0A      return line%5Blen(prefix):%5D%0A  return line%0A%0A%0Adef IsInclude(line):%0A  %22%22%22Returns True if the line is an #include/#import line.%22%22%22%0A  return line.startswith('#include ') or line.startswith('#import ')%0A%0A%0Adef SortHeader(infile, outfile):%0A  %22%22%22Sorts the headers in infile, writing the sorted file to outfile.%22%22%22%0A  for line in infile:%0A    if IsInclude(line):%0A      headerblock = %5B%5D%0A      while IsInclude(line):%0A        headerblock.append(line)%0A        line = infile.next()%0A      for header in sorted(headerblock, key=IncludeCompareKey):%0A        outfile.write(header)%0A      # Intentionally fall through, to write the line that caused%0A      # the above while loop to exit.%0A    outfile.write(line)%0A%0A%0Adef main():%0A  parser = optparse.OptionParser(usage='%25prog filename1 filename2 ...')%0A  opts, args = parser.parse_args()%0A%0A  if len(args) %3C 1:%0A    parser.print_help()%0A    sys.exit(1)%0A%0A  for filename in args:%0A    fixfilename = filename + '.new'%0A    infile = open(filename, 'r')%0A    outfile = open(fixfilename, 'w')%0A    SortHeader(infile, outfile)%0A    infile.close()%0A    outfile.close()  # Important so the below diff gets the updated contents.%0A%0A    try:%0A      diff = os.system('diff -u %25s %25s' %25 (filename, fixfilename))%0A      if diff %3E%3E 8 == 0:  # Check exit code.%0A        print '%25s: no change' %25 filename%0A        continue%0A%0A      if YesNo('Use new file (y/N)?'):%0A        os.rename(fixfilename, filename)%0A    finally:%0A      try:%0A        os.remove(fixfilename)%0A      except OSError:%0A        # If the file isn't there, we don't care.%0A        pass%0A%0A%0Aif __name__ == '__main__':%0A  main()%0A

Check in a quick tool for sorting the #includes in a file.