michael@0: #!/usr/bin/python michael@0: # Copyright (c) 2012 The Chromium Authors. All rights reserved. michael@0: # Use of this source code is governed by a BSD-style license that can be michael@0: # found in the LICENSE file. michael@0: michael@0: import os michael@0: import sys michael@0: michael@0: def Main(argv): michael@0: """This is like 'env -i', but it uses a whitelist of env variables to allow michael@0: through to the command being run. It attempts to strip off Xcode-added michael@0: values from PATH. michael@0: """ michael@0: # Note: An attempt was made to do something like: env -i bash -lc '[command]' michael@0: # but that fails to set the things set by login (USER, etc.), so instead michael@0: # the only approach that seems to work is to have a whitelist. michael@0: env_key_whitelist = ( michael@0: 'HOME', michael@0: 'LOGNAME', michael@0: # 'PATH' added below (but filtered). michael@0: 'PWD', michael@0: 'SHELL', michael@0: 'TEMP', michael@0: 'TMPDIR', michael@0: 'USER' michael@0: ) michael@0: michael@0: # Need something to run. michael@0: # TODO(lliabraa): Make this output a usage string and exit (here and below). michael@0: assert(len(argv) > 0) michael@0: michael@0: add_to_path = []; michael@0: first_entry = argv[0]; michael@0: if first_entry.startswith('ADD_TO_PATH='): michael@0: argv = argv[1:]; michael@0: add_to_path = first_entry.replace('ADD_TO_PATH=', '', 1).split(':') michael@0: michael@0: # Still need something to run. michael@0: assert(len(argv) > 0) michael@0: michael@0: clean_env = {} michael@0: michael@0: # Pull over the whitelisted keys. michael@0: for key in env_key_whitelist: michael@0: val = os.environ.get(key, None) michael@0: if not val is None: michael@0: clean_env[key] = val michael@0: michael@0: # Collect the developer dir as set via Xcode, defaulting it. michael@0: dev_prefix = os.environ.get('DEVELOPER_DIR', '/Developer/') michael@0: if dev_prefix[-1:] != '/': michael@0: dev_prefix += '/' michael@0: michael@0: # Now pull in PATH, but remove anything Xcode might have added. michael@0: initial_path = os.environ.get('PATH', '') michael@0: filtered_chunks = \ michael@0: [x for x in initial_path.split(':') if not x.startswith(dev_prefix)] michael@0: if filtered_chunks: michael@0: clean_env['PATH'] = ':'.join(add_to_path + filtered_chunks) michael@0: michael@0: # Add any KEY=VALUE args before the command to the cleaned environment. michael@0: args = argv[:] michael@0: while '=' in args[0]: michael@0: (key, val) = args[0].split('=', 1) michael@0: clean_env[key] = val michael@0: args = args[1:] michael@0: michael@0: # Still need something to run. michael@0: assert(len(args) > 0) michael@0: michael@0: # Off it goes... michael@0: os.execvpe(args[0], args, clean_env) michael@0: # Should never get here, so return a distinctive, non-zero status code. michael@0: return 66 michael@0: michael@0: if __name__ == '__main__': michael@0: sys.exit(Main(sys.argv[1:]))