rewrite_dirs.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. from __future__ import print_function
  7. import sys
  8. import os
  9. import optparse
  10. REWRITE_PREFIX = ['-I',
  11. '-idirafter',
  12. '-imacros',
  13. '-imultilib',
  14. '-include',
  15. '-iprefix',
  16. '-iquote',
  17. '-isystem',
  18. '-L']
  19. def RewritePath(path, opts):
  20. """Rewrites a path by stripping the prefix and prepending the sysroot."""
  21. sysroot = opts.sysroot
  22. prefix = opts.strip_prefix
  23. if os.path.isabs(path) and not path.startswith(sysroot):
  24. if path.startswith(prefix):
  25. path = path[len(prefix):]
  26. path = path.lstrip('/')
  27. return os.path.join(sysroot, path)
  28. else:
  29. return path
  30. def RewriteLine(line, opts):
  31. """Rewrites all the paths in recognized options."""
  32. args = line.split()
  33. count = len(args)
  34. i = 0
  35. while i < count:
  36. for prefix in REWRITE_PREFIX:
  37. # The option can be either in the form "-I /path/to/dir" or
  38. # "-I/path/to/dir" so handle both.
  39. if args[i] == prefix:
  40. i += 1
  41. try:
  42. args[i] = RewritePath(args[i], opts)
  43. except IndexError:
  44. sys.stderr.write('Missing argument following %s\n' % prefix)
  45. break
  46. elif args[i].startswith(prefix):
  47. args[i] = prefix + RewritePath(args[i][len(prefix):], opts)
  48. i += 1
  49. return ' '.join(args)
  50. def main(argv):
  51. parser = optparse.OptionParser()
  52. parser.add_option('-s', '--sysroot', default='/', help='sysroot to prepend')
  53. parser.add_option('-p', '--strip-prefix', default='', help='prefix to strip')
  54. opts, args = parser.parse_args(argv[1:])
  55. for line in sys.stdin.readlines():
  56. line = RewriteLine(line.strip(), opts)
  57. print(line)
  58. return 0
  59. if __name__ == '__main__':
  60. sys.exit(main(sys.argv))