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