1 # Copyright 2017 The Chromium Authors. All rights reserved. 2 # Use of this source code is governed by a BSD-style license that can be 3 # found in the LICENSE file. 4 # 5 # Shell scripting helpers (created for Telemetry dependency roll scripts). 6 7 import os as _os 8 import shutil as _shutil 9 import subprocess as _subprocess 10 import tempfile as _tempfile 11 from contextlib import contextmanager as _contextmanager 12 13 @_contextmanager 14 def ScopedChangeDir(new_path): 15 old_path = _os.getcwd() 16 _os.chdir(new_path) 17 print '> cd', _os.getcwd() 18 try: 19 yield 20 finally: 21 _os.chdir(old_path) 22 print '> cd', old_path 23 24 @_contextmanager 25 def ScopedTempDir(): 26 temp_dir = _tempfile.mkdtemp() 27 try: 28 with ScopedChangeDir(temp_dir): 29 yield 30 finally: 31 _shutil.rmtree(temp_dir) 32 33 def CallProgram(path_parts, *args, **kwargs): 34 '''Call an executable os.path.join(*path_parts) with the arguments specified 35 by *args. Any keyword arguments are passed as environment variables.''' 36 args = [_os.path.join(*path_parts)] + list(args) 37 env = dict(_os.environ) 38 env.update(kwargs) 39 print '>', ' '.join(args) 40 _subprocess.check_call(args, env=env) 41