rewrite_dirs.py (1990B)
1 #!/usr/bin/env python3 2 # Copyright 2011 The Chromium Authors 3 # Use of this source code is governed by a BSD-style license that can be 4 # found in the LICENSE file. 5 6 """Rewrites paths in -I, -L and other option to be relative to a sysroot.""" 7 8 9 import sys 10 import os 11 import optparse 12 13 REWRITE_PREFIX = ['-I', 14 '-idirafter', 15 '-imacros', 16 '-imultilib', 17 '-include', 18 '-iprefix', 19 '-iquote', 20 '-isystem', 21 '-L'] 22 23 def RewritePath(path, opts): 24 """Rewrites a path by stripping the prefix and prepending the sysroot.""" 25 sysroot = opts.sysroot 26 prefix = opts.strip_prefix 27 if os.path.isabs(path) and not path.startswith(sysroot): 28 if path.startswith(prefix): 29 path = path[len(prefix):] 30 path = path.lstrip('/') 31 return os.path.join(sysroot, path) 32 else: 33 return path 34 35 36 def RewriteLine(line, opts): 37 """Rewrites all the paths in recognized options.""" 38 args = line.split() 39 count = len(args) 40 i = 0 41 while i < count: 42 for prefix in REWRITE_PREFIX: 43 # The option can be either in the form "-I /path/to/dir" or 44 # "-I/path/to/dir" so handle both. 45 if args[i] == prefix: 46 i += 1 47 try: 48 args[i] = RewritePath(args[i], opts) 49 except IndexError: 50 sys.stderr.write('Missing argument following %s\n' % prefix) 51 break 52 elif args[i].startswith(prefix): 53 args[i] = prefix + RewritePath(args[i][len(prefix):], opts) 54 i += 1 55 56 return ' '.join(args) 57 58 59 def main(argv): 60 parser = optparse.OptionParser() 61 parser.add_option('-s', '--sysroot', default='/', help='sysroot to prepend') 62 parser.add_option('-p', '--strip-prefix', default='', help='prefix to strip') 63 opts, args = parser.parse_args(argv[1:]) 64 65 for line in sys.stdin.readlines(): 66 line = RewriteLine(line.strip(), opts) 67 print(line) 68 return 0 69 70 71 if __name__ == '__main__': 72 sys.exit(main(sys.argv))