blob: 1eaf8dc92125620c2b12f3b798116e4e9b09b877 [file] [log] [blame]
Takuto Ikuta3dab32e02023-01-12 18:52:001#!/usr/bin/env python3
Avi Drissman73a09d12022-09-08 20:33:382# Copyright 2013 The Chromium Authors
[email protected]bbc811f2013-09-14 01:02:253# 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
[email protected]85de4ba2013-09-17 21:59:0212import pipes
[email protected]bbc811f2013-09-14 01:02:2513import 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',
[email protected]fa725ad2013-09-18 18:01:3023 help='Dump the environment to sys.stdout and exit immediately.')
[email protected]bbc811f2013-09-14 01:02:2524
[email protected]2b0ee8e2013-09-23 23:08:0925 parser.disable_interspersed_args()
[email protected]bbc811f2013-09-14 01:02:2526 options, args = parser.parse_args()
[email protected]bbc811f2013-09-14 01:02:2527 if options.dump_mode:
[email protected]fa725ad2013-09-18 18:01:3028 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)
[email protected]bbc811f2013-09-14 01:02:2531 else:
[email protected]fa725ad2013-09-18 18:01:3032 if not options.output_json:
33 parser.error('Requires --output-json option.')
34
[email protected]85de4ba2013-09-17 21:59:0235 envsetup_cmd = ' '.join(map(pipes.quote, args))
[email protected]bbc811f2013-09-14 01:02:2536 full_cmd = [
37 'bash', '-c',
[email protected]fa725ad2013-09-18 18:01:3038 '. %s > /dev/null; %s -d' % (envsetup_cmd, os.path.abspath(__file__))
[email protected]85de4ba2013-09-17 21:59:0239 ]
[email protected]fa725ad2013-09-18 18:01:3040 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)
[email protected]bbc811f2013-09-14 01:02:2553
54
55if __name__ == '__main__':
56 sys.exit(main())