blob: 67cac46b7be2067665b8a3b61079cfc11b55a32c [file] [log] [blame]
Mads Ager418d1ca2017-05-22 09:35:49 +02001# 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
7import hashlib
8import os
9import shutil
10import subprocess
11import sys
12import tempfile
13
14TOOLS_DIR = os.path.abspath(os.path.normpath(os.path.join(__file__, '..')))
15REPO_ROOT = os.path.realpath(os.path.join(TOOLS_DIR, '..'))
16DOWNLOAD_DEPS = os.path.join(REPO_ROOT, 'scripts', 'download-deps.sh')
17
18def 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
25def 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
31def 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 Kenez971eec62017-05-24 11:08:40 +020041def makedirs_if_needed(path):
42 try:
43 os.makedirs(path)
44 except OSError:
45 if not os.path.isdir(path):
46 raise
47
Mads Ager418d1ca2017-05-22 09:35:49 +020048class 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
60class 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)