blob: 21edfe633c718ed8f96bd091731fa305da654821 [file] [log] [blame]
sivachandra@chromium.orgc2878f52013-09-14 10:02:25 +09001#!/usr/bin/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
6# This script can either source a file and dump the enironment changes done by
7# it, or just simply dump the current environment as JSON into a file.
8
9import json
10import optparse
11import os
sivachandra@chromium.orgef017762013-09-18 06:59:02 +090012import pipes
sivachandra@chromium.orgc2878f52013-09-14 10:02:25 +090013import subprocess
14import sys
15
16
17def main():
18 parser = optparse.OptionParser()
19 parser.add_option('-f', '--output-json',
20 help='File to dump the environment as JSON into.')
21 parser.add_option(
22 '-d', '--dump-mode', action='store_true',
sivachandra@chromium.org449acfd2013-09-19 03:01:30 +090023 help='Dump the environment to sys.stdout and exit immediately.')
sivachandra@chromium.orgc2878f52013-09-14 10:02:25 +090024
sivachandra@chromium.orge4eb6602013-09-24 08:08:09 +090025 parser.disable_interspersed_args()
sivachandra@chromium.orgc2878f52013-09-14 10:02:25 +090026 options, args = parser.parse_args()
sivachandra@chromium.orgc2878f52013-09-14 10:02:25 +090027 if options.dump_mode:
sivachandra@chromium.org449acfd2013-09-19 03:01:30 +090028 if args or options.output_json:
29 parser.error('Cannot specify args or --output-json with --dump-mode.')
30 json.dump(dict(os.environ), sys.stdout)
sivachandra@chromium.orgc2878f52013-09-14 10:02:25 +090031 else:
sivachandra@chromium.org449acfd2013-09-19 03:01:30 +090032 if not options.output_json:
33 parser.error('Requires --output-json option.')
34
sivachandra@chromium.orgef017762013-09-18 06:59:02 +090035 envsetup_cmd = ' '.join(map(pipes.quote, args))
sivachandra@chromium.orgc2878f52013-09-14 10:02:25 +090036 full_cmd = [
37 'bash', '-c',
sivachandra@chromium.org449acfd2013-09-19 03:01:30 +090038 '. %s > /dev/null; %s -d' % (envsetup_cmd, os.path.abspath(__file__))
sivachandra@chromium.orgef017762013-09-18 06:59:02 +090039 ]
sivachandra@chromium.org449acfd2013-09-19 03:01:30 +090040 try:
41 output = subprocess.check_output(full_cmd)
42 except Exception as e:
43 sys.exit('Error running %s and dumping environment.' % envsetup_cmd)
44
45 env_diff = {}
46 new_env = json.loads(output)
47 for k, val in new_env.items():
48 if k == '_' or (k in os.environ and os.environ[k] == val):
49 continue
50 env_diff[k] = val
51 with open(options.output_json, 'w') as f:
52 json.dump(env_diff, f)
sivachandra@chromium.orgc2878f52013-09-14 10:02:25 +090053
54
55if __name__ == '__main__':
56 sys.exit(main())