util.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import atexit
  4. import contextlib
  5. import datetime
  6. import errno
  7. import json
  8. import os
  9. import platform
  10. import re
  11. import shutil
  12. import ssl
  13. import stat
  14. import subprocess
  15. import sys
  16. import tarfile
  17. import tempfile
  18. # Python 3 / 2 compat import
  19. try:
  20. from urllib.request import urlopen
  21. except ImportError:
  22. from urllib2 import urlopen
  23. import zipfile
  24. from lib.config import is_verbose_mode, PLATFORM
  25. from lib.env_util import get_vs_env
  26. ELECTRON_DIR = os.path.abspath(
  27. os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
  28. )
  29. SRC_DIR = os.path.abspath(os.path.join(__file__, '..', '..', '..', '..'))
  30. BOTO_DIR = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'vendor',
  31. 'boto'))
  32. NPM = 'npm'
  33. if sys.platform in ['win32', 'cygwin']:
  34. NPM += '.cmd'
  35. def tempdir(prefix=''):
  36. directory = tempfile.mkdtemp(prefix=prefix)
  37. atexit.register(shutil.rmtree, directory)
  38. return directory
  39. @contextlib.contextmanager
  40. def scoped_cwd(path):
  41. cwd = os.getcwd()
  42. os.chdir(path)
  43. try:
  44. yield
  45. finally:
  46. os.chdir(cwd)
  47. @contextlib.contextmanager
  48. def scoped_env(key, value):
  49. origin = ''
  50. if key in os.environ:
  51. origin = os.environ[key]
  52. os.environ[key] = value
  53. try:
  54. yield
  55. finally:
  56. os.environ[key] = origin
  57. def download(text, url, path):
  58. safe_mkdir(os.path.dirname(path))
  59. with open(path, 'wb') as local_file:
  60. if hasattr(ssl, '_create_unverified_context'):
  61. ssl._create_default_https_context = ssl._create_unverified_context
  62. print("Downloading %s to %s" % (url, path))
  63. web_file = urlopen(url)
  64. info = web_file.info()
  65. if hasattr(info, 'getheader'):
  66. file_size = int(info.getheaders("Content-Length")[0])
  67. else:
  68. file_size = int(info.get("Content-Length")[0])
  69. downloaded_size = 0
  70. block_size = 4096
  71. ci = os.environ.get('CI') is not None
  72. while True:
  73. buf = web_file.read(block_size)
  74. if not buf:
  75. break
  76. downloaded_size += len(buf)
  77. local_file.write(buf)
  78. if not ci:
  79. percent = downloaded_size * 100. / file_size
  80. status = "\r%s %10d [%3.1f%%]" % (text, downloaded_size, percent)
  81. print(status, end=' ')
  82. if ci:
  83. print("%s done." % (text))
  84. else:
  85. print()
  86. return path
  87. def extract_tarball(tarball_path, member, destination):
  88. with tarfile.open(tarball_path) as tarball:
  89. tarball.extract(member, destination)
  90. def extract_zip(zip_path, destination):
  91. if sys.platform == 'darwin':
  92. # Use unzip command on Mac to keep symbol links in zip file work.
  93. execute(['unzip', zip_path, '-d', destination])
  94. else:
  95. with zipfile.ZipFile(zip_path) as z:
  96. z.extractall(destination)
  97. def make_zip(zip_file_path, files, dirs):
  98. safe_unlink(zip_file_path)
  99. if sys.platform == 'darwin':
  100. allfiles = files + dirs
  101. execute(['zip', '-r', '-y', zip_file_path] + allfiles)
  102. else:
  103. zip_file = zipfile.ZipFile(zip_file_path, "w", zipfile.ZIP_DEFLATED,
  104. allowZip64=True)
  105. for filename in files:
  106. zip_file.write(filename, filename)
  107. for dirname in dirs:
  108. for root, _, filenames in os.walk(dirname):
  109. for f in filenames:
  110. zip_file.write(os.path.join(root, f))
  111. zip_file.close()
  112. def rm_rf(path):
  113. try:
  114. shutil.rmtree(path)
  115. except OSError:
  116. pass
  117. def safe_unlink(path):
  118. try:
  119. os.unlink(path)
  120. except OSError as e:
  121. if e.errno != errno.ENOENT:
  122. raise
  123. def safe_mkdir(path):
  124. try:
  125. os.makedirs(path)
  126. except OSError as e:
  127. if e.errno != errno.EEXIST:
  128. raise
  129. def execute(argv, env=None, cwd=None):
  130. if env is None:
  131. env = os.environ
  132. if is_verbose_mode():
  133. print(' '.join(argv))
  134. try:
  135. output = subprocess.check_output(argv, stderr=subprocess.STDOUT,
  136. env=env, cwd=cwd)
  137. if is_verbose_mode():
  138. print(output)
  139. return output
  140. except subprocess.CalledProcessError as e:
  141. print(e.output)
  142. raise e
  143. def execute_stdout(argv, env=None, cwd=None):
  144. if env is None:
  145. env = os.environ
  146. if is_verbose_mode():
  147. print(' '.join(argv))
  148. try:
  149. subprocess.check_call(argv, env=env, cwd=cwd)
  150. except subprocess.CalledProcessError as e:
  151. print(e.output)
  152. raise e
  153. else:
  154. execute(argv, env, cwd)
  155. def get_electron_branding():
  156. SOURCE_ROOT = os.path.abspath(os.path.join(__file__, '..', '..', '..'))
  157. branding_file_path = os.path.join(
  158. SOURCE_ROOT, 'shell', 'app', 'BRANDING.json')
  159. with open(branding_file_path) as f:
  160. return json.load(f)
  161. def get_electron_version():
  162. SOURCE_ROOT = os.path.abspath(os.path.join(__file__, '..', '..', '..'))
  163. version_file = os.path.join(SOURCE_ROOT, 'ELECTRON_VERSION')
  164. with open(version_file) as f:
  165. return 'v' + f.read().strip()
  166. def boto_path_dirs():
  167. return [
  168. os.path.join(BOTO_DIR, 'build', 'lib'),
  169. os.path.join(BOTO_DIR, 'build', 'lib.linux-x86_64-2.7')
  170. ]
  171. def run_boto_script(access_key, secret_key, script_name, *args):
  172. env = os.environ.copy()
  173. env['AWS_ACCESS_KEY_ID'] = access_key
  174. env['AWS_SECRET_ACCESS_KEY'] = secret_key
  175. env['PYTHONPATH'] = os.path.pathsep.join(
  176. [env.get('PYTHONPATH', '')] + boto_path_dirs())
  177. boto = os.path.join(BOTO_DIR, 'bin', script_name)
  178. execute([sys.executable, boto] + list(args), env)
  179. def s3put(bucket, access_key, secret_key, prefix, key_prefix, files):
  180. args = [
  181. '--bucket', bucket,
  182. '--prefix', prefix,
  183. '--key_prefix', key_prefix,
  184. '--grant', 'public-read'
  185. ] + files
  186. run_boto_script(access_key, secret_key, 's3put', *args)
  187. def add_exec_bit(filename):
  188. os.chmod(filename, os.stat(filename).st_mode | stat.S_IEXEC)
  189. def get_out_dir():
  190. out_dir = 'Debug'
  191. override = os.environ.get('ELECTRON_OUT_DIR')
  192. if override is not None:
  193. out_dir = override
  194. return os.path.join(SRC_DIR, 'out', out_dir)
  195. # NOTE: This path is not created by gn, it is used as a scratch zone by our
  196. # upload scripts
  197. def get_dist_dir():
  198. return os.path.join(get_out_dir(), 'gen', 'electron_dist')
  199. def get_electron_exec():
  200. out_dir = get_out_dir()
  201. if sys.platform == 'darwin':
  202. return '{0}/Electron.app/Contents/MacOS/Electron'.format(out_dir)
  203. elif sys.platform == 'win32':
  204. return '{0}/electron.exe'.format(out_dir)
  205. elif sys.platform == 'linux':
  206. return '{0}/electron'.format(out_dir)
  207. raise Exception(
  208. "get_electron_exec: unexpected platform '{0}'".format(sys.platform))
  209. def get_buildtools_executable(name):
  210. buildtools = os.path.realpath(os.path.join(ELECTRON_DIR, '..', 'buildtools'))
  211. chromium_platform = {
  212. 'darwin': 'mac',
  213. 'linux': 'linux64',
  214. 'linux2': 'linux64',
  215. 'win32': 'win',
  216. }[sys.platform]
  217. path = os.path.join(buildtools, chromium_platform, name)
  218. if sys.platform == 'win32':
  219. path += '.exe'
  220. return path
  221. def get_objcopy_path(target_cpu):
  222. if PLATFORM != 'linux':
  223. raise Exception(
  224. "get_objcopy_path: unexpected platform '{0}'".format(PLATFORM))
  225. if target_cpu != 'x64':
  226. raise Exception(
  227. "get_objcopy_path: unexpected target cpu '{0}'".format(target_cpu))
  228. return os.path.join(SRC_DIR, 'third_party', 'binutils', 'Linux_x64',
  229. 'Release', 'bin', 'objcopy')