env_dump.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python
  2. # Copyright 2013 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. # This script can either source a file and dump the enironment changes done by
  6. # it, or just simply dump the current environment as JSON into a file.
  7. import json
  8. import optparse
  9. import os
  10. import pipes
  11. import subprocess
  12. import sys
  13. def main():
  14. parser = optparse.OptionParser()
  15. parser.add_option('-f', '--output-json',
  16. help='File to dump the environment as JSON into.')
  17. parser.add_option(
  18. '-d', '--dump-mode', action='store_true',
  19. help='Dump the environment to sys.stdout and exit immediately.')
  20. parser.disable_interspersed_args()
  21. options, args = parser.parse_args()
  22. if options.dump_mode:
  23. if args or options.output_json:
  24. parser.error('Cannot specify args or --output-json with --dump-mode.')
  25. json.dump(dict(os.environ), sys.stdout)
  26. else:
  27. if not options.output_json:
  28. parser.error('Requires --output-json option.')
  29. envsetup_cmd = ' '.join(map(pipes.quote, args))
  30. full_cmd = [
  31. 'bash', '-c',
  32. '. %s > /dev/null; %s -d' % (envsetup_cmd, os.path.abspath(__file__))
  33. ]
  34. try:
  35. output = subprocess.check_output(full_cmd)
  36. except Exception as e:
  37. sys.exit('Error running %s and dumping environment.' % envsetup_cmd)
  38. env_diff = {}
  39. new_env = json.loads(output)
  40. for k, val in new_env.items():
  41. if k == '_' or (k in os.environ and os.environ[k] == val):
  42. continue
  43. env_diff[k] = val
  44. with open(options.output_json, 'w') as f:
  45. json.dump(env_diff, f)
  46. if __name__ == '__main__':
  47. sys.exit(main())