Mads Ager | 418d1ca | 2017-05-22 09:35:49 +0200 | [diff] [blame] | 1 | # Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file |
| 2 | # for details. All rights reserved. Use of this source code is governed by a |
| 3 | # BSD-style license that can be found in the LICENSE file. |
| 4 | |
| 5 | # Different utility functions used accross scripts |
| 6 | |
| 7 | import hashlib |
| 8 | import os |
| 9 | import shutil |
| 10 | import subprocess |
| 11 | import sys |
| 12 | import tempfile |
| 13 | |
| 14 | TOOLS_DIR = os.path.abspath(os.path.normpath(os.path.join(__file__, '..'))) |
| 15 | REPO_ROOT = os.path.realpath(os.path.join(TOOLS_DIR, '..')) |
| 16 | DOWNLOAD_DEPS = os.path.join(REPO_ROOT, 'scripts', 'download-deps.sh') |
| 17 | |
| 18 | def PrintCmd(s): |
| 19 | if type(s) is list: |
| 20 | s = ' '.join(s) |
| 21 | print 'Running: %s' % s |
| 22 | # I know this will hit os on windows eventually if we don't do this. |
| 23 | sys.stdout.flush() |
| 24 | |
| 25 | def DownloadFromGoogleCloudStorage(sha1_file, bucket='r8-deps'): |
| 26 | cmd = ["download_from_google_storage", "-n", "-b", bucket, "-u", "-s", |
| 27 | sha1_file] |
| 28 | PrintCmd(cmd) |
| 29 | subprocess.check_call(cmd) |
| 30 | |
| 31 | def get_sha1(filename): |
| 32 | sha1 = hashlib.sha1() |
| 33 | with open(filename, 'rb') as f: |
| 34 | while True: |
| 35 | chunk = f.read(1024*1024) |
| 36 | if not chunk: |
| 37 | break |
| 38 | sha1.update(chunk) |
| 39 | return sha1.hexdigest() |
| 40 | |
Tamas Kenez | 971eec6 | 2017-05-24 11:08:40 +0200 | [diff] [blame^] | 41 | def makedirs_if_needed(path): |
| 42 | try: |
| 43 | os.makedirs(path) |
| 44 | except OSError: |
| 45 | if not os.path.isdir(path): |
| 46 | raise |
| 47 | |
Mads Ager | 418d1ca | 2017-05-22 09:35:49 +0200 | [diff] [blame] | 48 | class TempDir(object): |
| 49 | def __init__(self, prefix=''): |
| 50 | self._temp_dir = None |
| 51 | self._prefix = prefix |
| 52 | |
| 53 | def __enter__(self): |
| 54 | self._temp_dir = tempfile.mkdtemp(self._prefix) |
| 55 | return self._temp_dir |
| 56 | |
| 57 | def __exit__(self, *_): |
| 58 | shutil.rmtree(self._temp_dir, ignore_errors=True) |
| 59 | |
| 60 | class ChangedWorkingDirectory(object): |
| 61 | def __init__(self, working_directory): |
| 62 | self._working_directory = working_directory |
| 63 | |
| 64 | def __enter__(self): |
| 65 | self._old_cwd = os.getcwd() |
| 66 | print "Enter directory = ", self._working_directory |
| 67 | os.chdir(self._working_directory) |
| 68 | |
| 69 | def __exit__(self, *_): |
| 70 | print "Enter directory = ", self._old_cwd |
| 71 | os.chdir(self._old_cwd) |