clean_env.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/python
  2. # Copyright (c) 2012 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. import os
  6. import sys
  7. def Main(argv):
  8. """This is like 'env -i', but it uses a whitelist of env variables to allow
  9. through to the command being run. It attempts to strip off Xcode-added
  10. values from PATH.
  11. """
  12. # Note: An attempt was made to do something like: env -i bash -lc '[command]'
  13. # but that fails to set the things set by login (USER, etc.), so instead
  14. # the only approach that seems to work is to have a whitelist.
  15. env_key_whitelist = (
  16. 'HOME',
  17. 'LOGNAME',
  18. # 'PATH' added below (but filtered).
  19. 'PWD',
  20. 'SHELL',
  21. 'TEMP',
  22. 'TMPDIR',
  23. 'USER'
  24. )
  25. # Need something to run.
  26. # TODO(lliabraa): Make this output a usage string and exit (here and below).
  27. assert(len(argv) > 0)
  28. add_to_path = [];
  29. first_entry = argv[0];
  30. if first_entry.startswith('ADD_TO_PATH='):
  31. argv = argv[1:];
  32. add_to_path = first_entry.replace('ADD_TO_PATH=', '', 1).split(':')
  33. # Still need something to run.
  34. assert(len(argv) > 0)
  35. clean_env = {}
  36. # Pull over the whitelisted keys.
  37. for key in env_key_whitelist:
  38. val = os.environ.get(key, None)
  39. if not val is None:
  40. clean_env[key] = val
  41. # Collect the developer dir as set via Xcode, defaulting it.
  42. dev_prefix = os.environ.get('DEVELOPER_DIR', '/Developer/')
  43. if dev_prefix[-1:] != '/':
  44. dev_prefix += '/'
  45. # Now pull in PATH, but remove anything Xcode might have added.
  46. initial_path = os.environ.get('PATH', '')
  47. filtered_chunks = \
  48. [x for x in initial_path.split(':') if not x.startswith(dev_prefix)]
  49. if filtered_chunks:
  50. clean_env['PATH'] = ':'.join(add_to_path + filtered_chunks)
  51. # Add any KEY=VALUE args before the command to the cleaned environment.
  52. args = argv[:]
  53. while '=' in args[0]:
  54. (key, val) = args[0].split('=', 1)
  55. clean_env[key] = val
  56. args = args[1:]
  57. # Still need something to run.
  58. assert(len(args) > 0)
  59. # Off it goes...
  60. os.execvpe(args[0], args, clean_env)
  61. # Should never get here, so return a distinctive, non-zero status code.
  62. return 66
  63. if __name__ == '__main__':
  64. sys.exit(Main(sys.argv[1:]))