rectify_include_paths.py 1.8 KB

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