rectify_include_paths.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env python
  2. # Future imports for Python 2.7, mandatory in 3.0
  3. from __future__ import division
  4. from __future__ import print_function
  5. from __future__ import unicode_literals
  6. import os
  7. import os.path
  8. import re
  9. import sys
  10. def warn(msg):
  11. sys.stderr.write("WARNING: %s\n"%msg)
  12. # Find all the include files, map them to their real names.
  13. def exclude(paths, dirnames):
  14. for p in paths:
  15. if p in dirnames:
  16. dirnames.remove(p)
  17. DUPLICATE = object()
  18. def get_include_map():
  19. includes = { }
  20. for dirpath,dirnames,fnames in os.walk("src"):
  21. exclude(["ext", "win32"], dirnames)
  22. for fname in fnames:
  23. # Avoid editor temporary files
  24. if fname.startswith("."):
  25. continue
  26. if fname.startswith("#"):
  27. continue
  28. if fname.endswith(".h"):
  29. if fname in includes:
  30. warn("Multiple headers named %s"%fname)
  31. includes[fname] = DUPLICATE
  32. continue
  33. include = os.path.join(dirpath, fname)
  34. assert include.startswith("src/")
  35. includes[fname] = include[4:]
  36. return includes
  37. INCLUDE_PAT = re.compile(r'( *# *include +")([^"]+)(".*)')
  38. def get_base_header_name(hdr):
  39. return os.path.split(hdr)[1]
  40. def fix_includes(inp, out, mapping):
  41. for line in inp:
  42. m = INCLUDE_PAT.match(line)
  43. if m:
  44. include,hdr,rest = m.groups()
  45. basehdr = get_base_header_name(hdr)
  46. if basehdr in mapping and mapping[basehdr] is not DUPLICATE:
  47. out.write('{}{}{}\n'.format(include,mapping[basehdr],rest))
  48. continue
  49. out.write(line)
  50. incs = get_include_map()
  51. for dirpath,dirnames,fnames in os.walk("src"):
  52. exclude(["trunnel"], dirnames)
  53. for fname in fnames:
  54. # Avoid editor temporary files
  55. if fname.startswith("."):
  56. continue
  57. if fname.startswith("#"):
  58. continue
  59. if fname.endswith(".c") or fname.endswith(".h"):
  60. fname = os.path.join(dirpath, fname)
  61. tmpfile = fname+".tmp"
  62. f_in = open(fname, 'r')
  63. f_out = open(tmpfile, 'w')
  64. fix_includes(f_in, f_out, incs)
  65. f_in.close()
  66. f_out.close()
  67. os.rename(tmpfile, fname)