sort_includes.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import os
  2. import sys
  3. def sort_file(path):
  4. lines = open(path, "r").readlines()
  5. if len(lines) == 0:
  6. return
  7. skipped = 0
  8. while True:
  9. line = lines[skipped]
  10. if line.startswith("#pragma once") or line == "\n" or line.startswith("//"):
  11. skipped += 1
  12. else:
  13. break
  14. n = skipped
  15. for line in lines[skipped:]:
  16. if not line.startswith("#include") and not line.startswith("//#include") and not line == "\n":
  17. break
  18. n += 1
  19. includes = set(lines[skipped:n])
  20. def cm(s1, s2):
  21. return s1 >= s2
  22. (fname, ext) = os.path.splitext(path)
  23. fname = os.path.split(fname)[1]
  24. pair_header = "\"{}.h\"".format(fname)
  25. def k(s):
  26. w = 0
  27. def getw(s):
  28. if s.find("<") != -1 and s.find(">") != -1:
  29. return 5
  30. if s.find("oxygine-include") != -1:
  31. return 1
  32. parts = len(s.split("/"))
  33. if ext == ".cpp" and parts == 1 and s.find(pair_header) != -1:
  34. return 0
  35. if parts == 1:
  36. return 2
  37. return 3#parts
  38. w = getw(s)
  39. return (w, s)
  40. includes = sorted(includes, key = k)
  41. includes = filter(lambda s: s != "\n", includes)
  42. if len(includes) == 0:
  43. print("skipped {}".format(path))
  44. return
  45. includes += "\n"
  46. with open(path, "w") as fh:
  47. fh.writelines(lines[0:skipped])
  48. fh.writelines(includes)
  49. fh.writelines(lines[n:])
  50. #print path
  51. def run(folder):
  52. items = os.listdir(folder)
  53. for item in items:
  54. path = os.path.join(folder, item)
  55. if os.path.isdir(path):
  56. run(path)
  57. continue
  58. sort_file(path)
  59. if __name__ == "__main__":
  60. if len(sys.argv) > 1:
  61. path = sys.argv[1]
  62. else:
  63. path = "../../oxygine/src/oxygine"
  64. run(path)
  65. #sort_file("../project/src/packs/app_packs.cpp")
  66. #sort_file("../../oxygine/src/oxygine/stdrenderer.cpp")