update_repo.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. # Copyright 2020 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Quick and dirty utility to download latest icon assets for github."""
  15. from absl import app
  16. from absl import flags
  17. import icons
  18. import json
  19. from pathlib import Path
  20. import re
  21. import requests
  22. import time
  23. from typing import NamedTuple, Set, Sequence, Tuple
  24. from zipfile import ZipFile
  25. FLAGS = flags.FLAGS
  26. flags.DEFINE_bool(
  27. "skip_existing",
  28. False,
  29. "Do not download if local file exists, even if an update is available.",
  30. )
  31. flags.DEFINE_bool("fetch", True, "Whether we can attempt to download assets.")
  32. flags.DEFINE_bool("explode_zip_files", True, "Whether to unzip any zip assets.")
  33. flags.DEFINE_integer("icon_limit", 0, "If > 0, the max # of icons to process.")
  34. _METADATA_URL = "http://fonts.google.com/metadata/icons?incomplete=1"
  35. class Asset(NamedTuple):
  36. src_url_pattern: str
  37. dest_dir_pattern: str
  38. class Fetch(NamedTuple):
  39. src_url: str
  40. dest_file: Path
  41. class Icon(NamedTuple):
  42. name: str
  43. category: str
  44. version: int
  45. sizes_px: Tuple[int, ...]
  46. stylistic_sets: Set[str]
  47. _ICON_ASSETS = (
  48. Asset(
  49. "https://{host}/s/i/{stylistic_set_snake}/{icon.name}/v{icon.version}/{size_px}px.svg",
  50. "src/{icon.category}/{icon.name}/{stylistic_set_snake}/{size_px}px.svg",
  51. ),
  52. Asset(
  53. "https://{host}/s/i/{stylistic_set_snake}/{icon.name}/v{icon.version}/black-android.zip",
  54. "android/{icon.category}/{icon.name}/{stylistic_set_snake}/black.zip",
  55. ),
  56. Asset(
  57. "https://{host}/s/i/{stylistic_set_snake}/{icon.name}/v{icon.version}/black-ios.zip",
  58. "ios/{icon.category}/{icon.name}/{stylistic_set_snake}/black.zip",
  59. ),
  60. Asset(
  61. "https://{host}/s/i/{stylistic_set_snake}/{icon.name}/v{icon.version}/black-18dp.zip",
  62. "png/{icon.category}/{icon.name}/{stylistic_set_snake}/18dp.zip",
  63. ),
  64. Asset(
  65. "https://{host}/s/i/{stylistic_set_snake}/{icon.name}/v{icon.version}/black-24dp.zip",
  66. "png/{icon.category}/{icon.name}/{stylistic_set_snake}/24dp.zip",
  67. ),
  68. Asset(
  69. "https://{host}/s/i/{stylistic_set_snake}/{icon.name}/v{icon.version}/black-36dp.zip",
  70. "png/{icon.category}/{icon.name}/{stylistic_set_snake}/36dp.zip",
  71. ),
  72. Asset(
  73. "https://{host}/s/i/{stylistic_set_snake}/{icon.name}/v{icon.version}/black-48dp.zip",
  74. "png/{icon.category}/{icon.name}/{stylistic_set_snake}/48dp.zip",
  75. ),
  76. )
  77. _SET_ASSETS = (
  78. # Fonts are acquired by abusing the Google Fonts web api. Nobody tell them :D
  79. Asset(
  80. "https://fonts.googleapis.com/css2?family={stylistic_set_url}",
  81. "font/{stylistic_set_font}.css",
  82. ),
  83. )
  84. def _latest_metadata():
  85. resp = requests.get(_METADATA_URL)
  86. resp.raise_for_status()
  87. raw_json = resp.text[5:]
  88. return json.loads(raw_json)
  89. def _current_versions():
  90. return Path("current_versions.json")
  91. def _version_key(icon: Icon):
  92. return f"{icon.category}::{icon.name}"
  93. def _icons(metadata):
  94. all_sets = set(metadata["families"])
  95. for raw_icon in metadata["icons"]:
  96. unsupported = set(raw_icon["unsupported_families"])
  97. yield Icon(
  98. raw_icon["name"],
  99. raw_icon["categories"][0],
  100. raw_icon["version"],
  101. tuple(raw_icon["sizes_px"]),
  102. all_sets - unsupported,
  103. )
  104. def _create_fetch(asset, args):
  105. src_url = asset.src_url_pattern.format(**args)
  106. dest_file = asset.dest_dir_pattern.format(**args)
  107. dest_file = (Path(__file__) / "../.." / dest_file).resolve()
  108. return Fetch(src_url, dest_file)
  109. def _do_fetch(fetch):
  110. resp = requests.get(fetch.src_url)
  111. resp.raise_for_status()
  112. fetch.dest_file.parent.mkdir(parents=True, exist_ok=True)
  113. fetch.dest_file.write_bytes(resp.content)
  114. def _do_fetches(fetches):
  115. print(f"Starting {len(fetches)} fetches")
  116. start_t = time.monotonic()
  117. print_t = start_t
  118. for idx, fetch in enumerate(fetches):
  119. _do_fetch(fetch)
  120. t = time.monotonic()
  121. if t - print_t > 5:
  122. print_t = t
  123. est_complete = (t - start_t) * (len(fetches) / (idx + 1))
  124. print(f"{idx}/{len(fetches)}, estimating {int(est_complete)}s left")
  125. def _unzip_target(zip_path: Path):
  126. return zip_path.parent.resolve() / zip_path.stem
  127. def _explode_zip_files(zips: Sequence[Path]):
  128. for zip_path in zips:
  129. assert zip_path.suffix == ".zip", zip_path
  130. if not zip_path.is_file():
  131. continue
  132. unzip_target = _unzip_target(zip_path)
  133. print(f"Unzip {zip_path} => {unzip_target}")
  134. with ZipFile(zip_path) as zip_file:
  135. zip_file.extractall(unzip_target)
  136. zip_path.unlink()
  137. def _fetch_fonts(css_files: Sequence[Path]):
  138. for css_file in css_files:
  139. css = css_file.read_text()
  140. url = re.search(r"src:\s+url\(([^)]+)\)", css).group(1)
  141. assert url.endswith(".otf") or url.endswith(".ttf")
  142. fetch = Fetch(url, css_file.parent / (css_file.stem + url[-4:]))
  143. _do_fetch(fetch)
  144. css_file.unlink()
  145. with open(fetch.dest_file.with_suffix(".codepoints"), "w") as f:
  146. for name, codepoint in sorted(icons.enumerate(fetch.dest_file)):
  147. f.write(f"{name} {codepoint:04x}\n")
  148. def _is_css(p: Path):
  149. return p.suffix == ".css"
  150. def _is_zip(p: Path):
  151. return p.suffix == ".zip"
  152. def _files(fetches: Sequence[Fetch], pred):
  153. return [f.dest_file for f in fetches if pred(f.dest_file)]
  154. def _should_skip(fetch: Fetch):
  155. if not FLAGS.skip_existing:
  156. return False
  157. if _is_zip(fetch.dest_file):
  158. return _unzip_target(fetch.dest_file).is_dir()
  159. return fetch.dest_file.is_file()
  160. def _pattern_args(metadata, stylistic_set):
  161. return {
  162. "host": metadata["host"],
  163. "stylistic_set_snake": stylistic_set.replace(" ", "").lower(),
  164. "stylistic_set_url": stylistic_set.replace(" ", "+"),
  165. "stylistic_set_font": stylistic_set.replace(" ", "") + "-Regular",
  166. }
  167. def main(_):
  168. current_versions = json.loads(_current_versions().read_text())
  169. metadata = _latest_metadata()
  170. stylistic_sets = tuple(metadata["families"])
  171. fetches = []
  172. skips = []
  173. num_changed = 0
  174. icons = tuple(_icons(metadata))
  175. if FLAGS.icon_limit > 0:
  176. icons = icons[: FLAGS.icon_limit]
  177. for icon in icons:
  178. ver_key = _version_key(icon)
  179. if icon.version <= current_versions.get(ver_key, 0):
  180. continue
  181. current_versions[ver_key] = icon.version
  182. num_changed += 1
  183. for size_px in icon.sizes_px:
  184. for stylistic_set in stylistic_sets:
  185. if stylistic_set not in icon.stylistic_sets:
  186. continue
  187. pattern_args = _pattern_args(metadata, stylistic_set)
  188. pattern_args["icon"] = icon
  189. pattern_args["size_px"] = size_px
  190. for asset in _ICON_ASSETS:
  191. fetch = _create_fetch(asset, pattern_args)
  192. if _should_skip(fetch):
  193. skips.append(fetch)
  194. else:
  195. fetches.append(fetch)
  196. for stylistic_set in stylistic_sets:
  197. for asset in _SET_ASSETS:
  198. pattern_args = _pattern_args(metadata, stylistic_set)
  199. fetch = _create_fetch(asset, pattern_args)
  200. fetches.append(fetch)
  201. print(f"{num_changed}/{len(icons)} icons have changed")
  202. if skips:
  203. print(f"{len(skips)} fetches skipped because assets exist")
  204. if fetches:
  205. if FLAGS.fetch:
  206. _do_fetches(fetches)
  207. else:
  208. print(f"fetch disabled; not fetching {len(fetches)} assets")
  209. if FLAGS.explode_zip_files:
  210. _explode_zip_files(_files(fetches + skips, _is_zip))
  211. _fetch_fonts(_files(fetches + skips, _is_css))
  212. with open(_current_versions(), "w") as f:
  213. json.dump(current_versions, f, indent=4, sort_keys=True)
  214. if __name__ == "__main__":
  215. app.run(main)