rewrite_dirs.py 2.0 KB

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