🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

302 lines
8.7 KiB

  1. #!/usr/bin/env python3
  2. """Download test fonts used by the FreeType regression test programs. These
  3. will be copied to $FREETYPE/tests/data/ by default."""
  4. import argparse
  5. import collections
  6. import hashlib
  7. import io
  8. import os
  9. import requests
  10. import sys
  11. import zipfile
  12. from typing import Callable, List, Optional, Tuple
  13. # The list of download items describing the font files to install. Each
  14. # download item is a dictionary with one of the following schemas:
  15. #
  16. # - File item:
  17. #
  18. # file_url
  19. # Type: URL string.
  20. # Required: Yes.
  21. # Description: URL to download the file from.
  22. #
  23. # install_name
  24. # Type: file name string
  25. # Required: No
  26. # Description: Installation name for the font file, only provided if
  27. # it must be different from the original URL's basename.
  28. #
  29. # hex_digest
  30. # Type: hexadecimal string
  31. # Required: No
  32. # Description: Digest of the input font file.
  33. #
  34. # - Zip items:
  35. #
  36. # These items correspond to one or more font files that are embedded in a
  37. # remote zip archive. Each entry has the following fields:
  38. #
  39. # zip_url
  40. # Type: URL string.
  41. # Required: Yes.
  42. # Description: URL to download the zip archive from.
  43. #
  44. # zip_files
  45. # Type: List of file entries (see below)
  46. # Required: Yes
  47. # Description: A list of entries describing a single font file to be
  48. # extracted from the archive
  49. #
  50. # Apart from that, some schemas are used for dictionaries used inside
  51. # download items:
  52. #
  53. # - File entries:
  54. #
  55. # These are dictionaries describing a single font file to extract from an
  56. # archive.
  57. #
  58. # filename
  59. # Type: file path string
  60. # Required: Yes
  61. # Description: Path of source file, relative to the archive's
  62. # top-level directory.
  63. #
  64. # install_name
  65. # Type: file name string
  66. # Required: No
  67. # Description: Installation name for the font file; only provided if
  68. # it must be different from the original filename value.
  69. #
  70. # hex_digest
  71. # Type: hexadecimal string
  72. # Required: No
  73. # Description: Digest of the input source file
  74. #
  75. _DOWNLOAD_ITEMS = [
  76. {
  77. "zip_url": "https://github.com/python-pillow/Pillow/files/6622147/As.I.Lay.Dying.zip",
  78. "zip_files": [
  79. {
  80. "filename": "As I Lay Dying.ttf",
  81. "install_name": "As.I.Lay.Dying.ttf",
  82. "hex_digest": "ef146bbc2673b387",
  83. },
  84. ],
  85. },
  86. ]
  87. def digest_data(data: bytes):
  88. """Compute the digest of a given input byte string, which are the first
  89. 8 bytes of its sha256 hash."""
  90. m = hashlib.sha256()
  91. m.update(data)
  92. return m.digest()[:8]
  93. def check_existing(path: str, hex_digest: str):
  94. """Return True if |path| exists and matches |hex_digest|."""
  95. if not os.path.exists(path) or hex_digest is None:
  96. return False
  97. with open(path, "rb") as f:
  98. existing_content = f.read()
  99. return bytes.fromhex(hex_digest) == digest_data(existing_content)
  100. def install_file(content: bytes, dest_path: str):
  101. """Write a byte string to a given destination file.
  102. Args:
  103. content: Input data, as a byte string
  104. dest_path: Installation path
  105. """
  106. parent_path = os.path.dirname(dest_path)
  107. if not os.path.exists(parent_path):
  108. os.makedirs(parent_path)
  109. with open(dest_path, "wb") as f:
  110. f.write(content)
  111. def download_file(url: str, expected_digest: Optional[bytes] = None):
  112. """Download a file from a given URL.
  113. Args:
  114. url: Input URL
  115. expected_digest: Optional digest of the file
  116. as a byte string
  117. Returns:
  118. URL content as binary string.
  119. """
  120. r = requests.get(url, allow_redirects=True)
  121. content = r.content
  122. if expected_digest is not None:
  123. digest = digest_data(r.content)
  124. if digest != expected_digest:
  125. raise ValueError(
  126. "%s has invalid digest %s (expected %s)"
  127. % (url, digest.hex(), expected_digest.hex())
  128. )
  129. return content
  130. def extract_file_from_zip_archive(
  131. archive: zipfile.ZipFile,
  132. archive_name: str,
  133. filepath: str,
  134. expected_digest: Optional[bytes] = None,
  135. ):
  136. """Extract a file from a given zipfile.ZipFile archive.
  137. Args:
  138. archive: Input ZipFile objec.
  139. archive_name: Archive name or URL, only used to generate a
  140. human-readable error message.
  141. filepath: Input filepath in archive.
  142. expected_digest: Optional digest for the file.
  143. Returns:
  144. A new File instance corresponding to the extract file.
  145. Raises:
  146. ValueError if expected_digest is not None and does not match the
  147. extracted file.
  148. """
  149. file = archive.open(filepath)
  150. if expected_digest is not None:
  151. digest = digest_data(archive.open(filepath).read())
  152. if digest != expected_digest:
  153. raise ValueError(
  154. "%s in zip archive at %s has invalid digest %s (expected %s)"
  155. % (filepath, archive_name, digest.hex(), expected_digest.hex())
  156. )
  157. return file.read()
  158. def _get_and_install_file(
  159. install_path: str,
  160. hex_digest: Optional[str],
  161. force_download: bool,
  162. get_content: Callable[[], bytes],
  163. ) -> bool:
  164. if not force_download and hex_digest is not None \
  165. and os.path.exists(install_path):
  166. with open(install_path, "rb") as f:
  167. content: bytes = f.read()
  168. if bytes.fromhex(hex_digest) == digest_data(content):
  169. return False
  170. content = get_content()
  171. install_file(content, install_path)
  172. return True
  173. def download_and_install_item(
  174. item: dict, install_dir: str, force_download: bool
  175. ) -> List[Tuple[str, bool]]:
  176. """Download and install one item.
  177. Args:
  178. item: Download item as a dictionary, see above for schema.
  179. install_dir: Installation directory.
  180. force_download: Set to True to force download and installation, even
  181. if the font file is already installed with the right content.
  182. Returns:
  183. A list of (install_name, status) tuples, where 'install_name' is the
  184. file's installation name under 'install_dir', and 'status' is a
  185. boolean that is True to indicate that the file was downloaded and
  186. installed, or False to indicate that the file is already installed
  187. with the right content.
  188. """
  189. if "file_url" in item:
  190. file_url = item["file_url"]
  191. install_name = item.get("install_name", os.path.basename(file_url))
  192. install_path = os.path.join(install_dir, install_name)
  193. hex_digest = item.get("hex_digest")
  194. def get_content():
  195. return download_file(file_url, hex_digest)
  196. status = _get_and_install_file(
  197. install_path, hex_digest, force_download, get_content
  198. )
  199. return [(install_name, status)]
  200. if "zip_url" in item:
  201. # One or more files from a zip archive.
  202. archive_url = item["zip_url"]
  203. archive = zipfile.ZipFile(io.BytesIO(download_file(archive_url)))
  204. result = []
  205. for f in item["zip_files"]:
  206. filename = f["filename"]
  207. install_name = f.get("install_name", filename)
  208. hex_digest = f.get("hex_digest")
  209. def get_content():
  210. return extract_file_from_zip_archive(
  211. archive,
  212. archive_url,
  213. filename,
  214. bytes.fromhex(hex_digest) if hex_digest else None,
  215. )
  216. status = _get_and_install_file(
  217. os.path.join(install_dir, install_name),
  218. hex_digest,
  219. force_download,
  220. get_content,
  221. )
  222. result.append((install_name, status))
  223. return result
  224. else:
  225. raise ValueError("Unknown download item schema: %s" % item)
  226. def main():
  227. parser = argparse.ArgumentParser(description=__doc__)
  228. # Assume this script is under tests/scripts/ and tests/data/
  229. # is the default installation directory.
  230. install_dir = os.path.normpath(
  231. os.path.join(os.path.dirname(__file__), "..", "data")
  232. )
  233. parser.add_argument(
  234. "--force",
  235. action="store_true",
  236. default=False,
  237. help="Force download and installation of font files",
  238. )
  239. parser.add_argument(
  240. "--install-dir",
  241. default=install_dir,
  242. help="Specify installation directory [%s]" % install_dir,
  243. )
  244. args = parser.parse_args()
  245. for item in _DOWNLOAD_ITEMS:
  246. for install_name, status in download_and_install_item(
  247. item, args.install_dir, args.force
  248. ):
  249. print("%s %s" % (install_name,
  250. "INSTALLED" if status else "UP-TO-DATE"))
  251. return 0
  252. if __name__ == "__main__":
  253. sys.exit(main())
  254. # EOF