PageRenderTime 65ms CodeModel.GetById 43ms RepoModel.GetById 1ms app.codeStats 0ms

/download-deps.py

https://github.com/dumganhar/cocos2d-x
Python | 344 lines | 320 code | 4 blank | 20 comment | 0 complexity | 9e8641dccaae753da857adb5e6e4d05a MD5 | raw file
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. #
  4. # ./download-deps.py
  5. #
  6. # Downloads Cocos2D-x 3rd party dependencies from github:
  7. # https://github.com/cocos2d/cocos2d-x-3rd-party-libs-bin) and extracts the zip
  8. # file
  9. #
  10. # Having the dependencies outside the official cocos2d-x repo helps prevent
  11. # bloating the repo.
  12. #
  13. """****************************************************************************
  14. Copyright (c) 2014 cocos2d-x.org
  15. Copyright (c) 2014-2017 Chukong Technologies Inc.
  16. http://www.cocos2d-x.org
  17. Permission is hereby granted, free of charge, to any person obtaining a copy
  18. of this software and associated documentation files (the "Software"), to deal
  19. in the Software without restriction, including without limitation the rights
  20. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21. copies of the Software, and to permit persons to whom the Software is
  22. furnished to do so, subject to the following conditions:
  23. The above copyright notice and this permission notice shall be included in
  24. all copies or substantial portions of the Software.
  25. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  26. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  27. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  28. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  29. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  30. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  31. THE SOFTWARE.
  32. ****************************************************************************"""
  33. import os.path
  34. import zipfile
  35. import shutil
  36. import sys
  37. import traceback
  38. import distutils
  39. import fileinput
  40. import json
  41. from optparse import OptionParser
  42. from time import time
  43. from sys import stdout
  44. from distutils.errors import DistutilsError
  45. from distutils.dir_util import copy_tree, remove_tree
  46. def delete_folder_except(folder_path, excepts):
  47. """
  48. Delete a folder excepts some files/subfolders, `excepts` doesn't recursively which means it can not include
  49. `subfoler/file1`. `excepts` is an array.
  50. """
  51. for file in os.listdir(folder_path):
  52. if (file in excepts):
  53. continue
  54. full_path = os.path.join(folder_path, file)
  55. if os.path.isdir(full_path):
  56. shutil.rmtree(full_path)
  57. else:
  58. os.remove(full_path)
  59. class UnrecognizedFormat:
  60. def __init__(self, prompt):
  61. self._prompt = prompt
  62. def __str__(self):
  63. return self._prompt
  64. class CocosZipInstaller(object):
  65. def __init__(self, workpath, config_path, version_path, remote_version_key=None):
  66. self._workpath = workpath
  67. self._config_path = config_path
  68. self._version_path = version_path
  69. data = self.load_json_file(config_path)
  70. self._current_version = data["version"]
  71. self._repo_name = data["repo_name"]
  72. try:
  73. self._move_dirs = data["move_dirs"]
  74. except:
  75. self._move_dirs = None
  76. self._filename = self._current_version + '.zip'
  77. self._url = data["repo_parent"] + self._repo_name + '/archive/' + self._filename
  78. self._zip_file_size = int(data["zip_file_size"])
  79. # 'v' letter was swallowed by github, so we need to substring it from the 2nd letter
  80. self._extracted_folder_name = os.path.join(self._workpath, self._repo_name + '-' + self._current_version[1:])
  81. try:
  82. data = self.load_json_file(version_path)
  83. if remote_version_key is None:
  84. self._remote_version = data["version"]
  85. else:
  86. self._remote_version = data[remote_version_key]
  87. except:
  88. print("==> version file doesn't exist")
  89. def get_input_value(self, prompt):
  90. ret = raw_input(prompt)
  91. ret.rstrip(" \t")
  92. return ret
  93. def download_file(self):
  94. print("==> Ready to download '%s' from '%s'" % (self._filename, self._url))
  95. import urllib2
  96. try:
  97. u = urllib2.urlopen(self._url)
  98. except urllib2.HTTPError as e:
  99. if e.code == 404:
  100. print("==> Error: Could not find the file from url: '%s'" % (self._url))
  101. print("==> Http request failed, error code: " + str(e.code) + ", reason: " + e.read())
  102. sys.exit(1)
  103. f = open(self._filename, 'wb')
  104. meta = u.info()
  105. content_len = meta.getheaders("Content-Length")
  106. file_size = 0
  107. if content_len and len(content_len) > 0:
  108. file_size = int(content_len[0])
  109. else:
  110. # github server may not reponse a header information which contains `Content-Length`,
  111. # therefore, the size needs to be written hardcode here. While server doesn't return
  112. # `Content-Length`, use it instead
  113. print("==> WARNING: Couldn't grab the file size from remote, use 'zip_file_size' section in '%s'" % self._config_path)
  114. file_size = self._zip_file_size
  115. print("==> Start to download, please wait ...")
  116. file_size_dl = 0
  117. block_sz = 8192
  118. block_size_per_second = 0
  119. old_time = time()
  120. status = ""
  121. while True:
  122. buffer = u.read(block_sz)
  123. if not buffer:
  124. print("%s%s" % (" " * len(status), "\r")),
  125. break
  126. file_size_dl += len(buffer)
  127. block_size_per_second += len(buffer)
  128. f.write(buffer)
  129. new_time = time()
  130. if (new_time - old_time) > 1:
  131. speed = block_size_per_second / (new_time - old_time) / 1000.0
  132. if file_size != 0:
  133. percent = file_size_dl * 100. / file_size
  134. status = r"Downloaded: %6dK / Total: %dK, Percent: %3.2f%%, Speed: %6.2f KB/S " % (file_size_dl / 1000, file_size / 1000, percent, speed)
  135. else:
  136. status = r"Downloaded: %6dK, Speed: %6.2f KB/S " % (file_size_dl / 1000, speed)
  137. print(status),
  138. sys.stdout.flush()
  139. print("\r"),
  140. block_size_per_second = 0
  141. old_time = new_time
  142. print("==> Downloading finished!")
  143. f.close()
  144. def ensure_directory(self, target):
  145. if not os.path.exists(target):
  146. os.mkdir(target)
  147. def unpack_zipfile(self, extract_dir):
  148. """Unpack zip `filename` to `extract_dir`
  149. Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
  150. by ``zipfile.is_zipfile()``).
  151. """
  152. if not zipfile.is_zipfile(self._filename):
  153. raise UnrecognizedFormat("%s is not a zip file" % (self._filename))
  154. print("==> Extracting files, please wait ...")
  155. z = zipfile.ZipFile(self._filename)
  156. try:
  157. for info in z.infolist():
  158. name = info.filename
  159. # don't extract absolute paths or ones with .. in them
  160. if name.startswith('/') or '..' in name:
  161. continue
  162. target = os.path.join(extract_dir, *name.split('/'))
  163. if not target:
  164. continue
  165. if name.endswith('/'):
  166. # directory
  167. self.ensure_directory(target)
  168. else:
  169. # file
  170. data = z.read(info.filename)
  171. f = open(target, 'wb')
  172. try:
  173. f.write(data)
  174. finally:
  175. f.close()
  176. del data
  177. unix_attributes = info.external_attr >> 16
  178. if unix_attributes:
  179. os.chmod(target, unix_attributes)
  180. finally:
  181. z.close()
  182. print("==> Extraction done!")
  183. def ask_to_delete_downloaded_zip_file(self):
  184. ret = self.get_input_value("==> Would you like to save '%s'? So you don't have to download it later. [Yes/no]: " % self._filename)
  185. ret = ret.strip()
  186. if ret != 'yes' and ret != 'y' and ret != 'no' and ret != 'n':
  187. print("==> Saving the dependency libraries by default")
  188. return False
  189. else:
  190. return True if ret == 'no' or ret == 'n' else False
  191. def download_zip_file(self):
  192. if not os.path.isfile(self._filename):
  193. self.download_file()
  194. try:
  195. if not zipfile.is_zipfile(self._filename):
  196. raise UnrecognizedFormat("%s is not a zip file" % (self._filename))
  197. except UnrecognizedFormat as e:
  198. print("==> Unrecognized zip format from your local '%s' file!" % (self._filename))
  199. if os.path.isfile(self._filename):
  200. os.remove(self._filename)
  201. print("==> Download it from internet again, please wait...")
  202. self.download_zip_file()
  203. def need_to_update(self):
  204. if not os.path.isfile(self._version_path):
  205. return True
  206. with open(self._version_path) as data_file:
  207. data = json.load(data_file)
  208. if self._remote_version == self._current_version:
  209. return False
  210. return True
  211. def load_json_file(self, file_path):
  212. if not os.path.isfile(file_path):
  213. raise Exception("Could not find (%s)" % (file_path))
  214. with open(file_path) as data_file:
  215. data = json.load(data_file)
  216. return data
  217. def clean_external_folder(self, external_folder):
  218. print('==> Cleaning cocos2d-x/external folder ...')
  219. # remove external except 'config.json'
  220. delete_folder_except(external_folder, ['config.json'])
  221. def run(self, workpath, folder_for_extracting, remove_downloaded, force_update, download_only):
  222. if not force_update and not self.need_to_update():
  223. print("==> Not need to update!")
  224. return
  225. if os.path.exists(self._extracted_folder_name):
  226. shutil.rmtree(self._extracted_folder_name)
  227. self.download_zip_file()
  228. if not download_only:
  229. self.unpack_zipfile(self._workpath)
  230. if not os.path.exists(folder_for_extracting):
  231. os.mkdir(folder_for_extracting)
  232. self.clean_external_folder(folder_for_extracting)
  233. print("==> Copying files...")
  234. distutils.dir_util.copy_tree(self._extracted_folder_name, folder_for_extracting)
  235. if self._move_dirs is not None:
  236. for srcDir in self._move_dirs.keys():
  237. distDir = os.path.join( os.path.join(workpath, self._move_dirs[srcDir]), srcDir)
  238. if os.path.exists(distDir):
  239. shutil.rmtree(distDir)
  240. shutil.move( os.path.join(folder_for_extracting, srcDir), distDir)
  241. print("==> Cleaning...")
  242. if os.path.exists(self._extracted_folder_name):
  243. shutil.rmtree(self._extracted_folder_name)
  244. if os.path.isfile(self._filename):
  245. if remove_downloaded is not None:
  246. if remove_downloaded == 'yes':
  247. os.remove(self._filename)
  248. elif self.ask_to_delete_downloaded_zip_file():
  249. os.remove(self._filename)
  250. else:
  251. print("==> Download (%s) finish!" % self._filename)
  252. def _check_python_version():
  253. major_ver = sys.version_info[0]
  254. if major_ver > 2:
  255. print ("The python version is %d.%d. But python 2.x is required. (Version 2.7 is well tested)\n"
  256. "Download it here: https://www.python.org/" % (major_ver, sys.version_info[1]))
  257. return False
  258. return True
  259. def main():
  260. workpath = os.path.dirname(os.path.realpath(__file__))
  261. if not _check_python_version():
  262. exit()
  263. parser = OptionParser()
  264. parser.add_option('-r', '--remove-download',
  265. action="store", type="string", dest='remove_downloaded', default=None,
  266. help="Whether to remove downloaded zip file, 'yes' or 'no'")
  267. parser.add_option("-f", "--force-update",
  268. action="store_true", dest="force_update", default=False,
  269. help="Whether to force update the third party libraries")
  270. parser.add_option("-d", "--download-only",
  271. action="store_true", dest="download_only", default=False,
  272. help="Only download zip file of the third party libraries, will not extract it")
  273. (opts, args) = parser.parse_args()
  274. print("=======================================================")
  275. print("==> Prepare to download external libraries!")
  276. external_path = os.path.join(workpath, 'external')
  277. installer = CocosZipInstaller(workpath, os.path.join(workpath, 'external', 'config.json'), os.path.join(workpath, 'external', 'version.json'), "prebuilt_libs_version")
  278. installer.run(workpath, external_path, opts.remove_downloaded, opts.force_update, opts.download_only)
  279. # -------------- main --------------
  280. if __name__ == '__main__':
  281. try:
  282. main()
  283. except Exception as e:
  284. traceback.print_exc()
  285. sys.exit(1)