Debian Codegraph @

subprojects/fontconfig/build-aux/fetch-testfonts.py

raw
1 #!/usr/bin/env python3
2
3 import argparse
4 import os
5 import shutil
6 import subprocess
7 import sys
8 import tempfile
9 from urllib.request import urlretrieve
10 import multiprocessing
11
12 import logging
13 import sys
14
15 logging.basicConfig(level=logging.INFO)
16 logger = logging.getLogger()
17
18 if not sys.stdout.isatty():
19 logger.handlers = []
20
21 URL_TEMPLATE = (
22 "https://commondatastorage.googleapis.com/chromeos-localmirror/distfiles/%s"
23 )
24 SOURCE_FILES = (
25 "noto-cjk-20210501.tar.bz2",
26 "crosextrafonts-20130214.tar.gz",
27 "notofonts-20250214.tar.xz",
28 "robotofonts-2.132.tar.bz2",
29 "lohitfonts-cros-2.5.5.tar.bz2",
30 "ko-nanumfonts-3.20.tar.bz2",
31 )
32 SOURCES = [URL_TEMPLATE % source for source in SOURCE_FILES]
33 SOURCES += ["https://github.com/googlefonts/roboto-flex/releases/download/3.100/roboto-flex-fonts.zip"]
34
35 CONTAINER_DOWNLOAD_DIR = "/testfonts"
36
37 # If you want to update these, copy the contents of the .stamp file from the target directory here.
38 EXPECTED_HASHES = """
39 noto-cjk-20210501.tar.bz2 5c70f246c392bf15aeaee22b2fba26bb0ac54e47c00a4b9c3b556bd06fe89281
40 crosextrafonts-20130214.tar.gz c48d1c2fd613c9c06c959c34da7b8388059e2408d2bb19845dc3ed35f76e4d09
41 notofonts-20250214.tar.xz cb0f9edc030e07eca58b799c607d000dfde588911d8e228fc82d5f61b9e5b6b3
42 robotofonts-2.132.tar.bz2 087c6f0708fe71f71a056f70fdbd5a85f4d2ce916670a98bd4be10b168abe16a
43 lohitfonts-cros-2.5.5.tar.bz2 ce0ce2a5098c8ffc52327cc030576df7f5328ad9fd8a3289e2476990ad133ff1
44 ko-nanumfonts-3.20.tar.bz2 59f9b6d7fcf63ca2bea7156ad66c784a1f0601d47be1b11237e17733d7112832
45 roboto-flex-fonts.zip 02e0f5db84e69f254958434269d83aa6057b06f3c2a21042bb81b1afe1a0c8c6
46 """
47
48 STAMP_FILE = ".stamp"
49
50
51 def download_file(url, tmp_dir, target_dir):
52 filename = os.path.basename(url)
53 filepath = os.path.join(tmp_dir, filename)
54 logger.info(f"Downloading {url} to {filepath}")
55 urlretrieve(url, filepath)
56 return filepath
57
58
59 def compute_sha256(filepath):
60 """Computes the SHA-256 hash of a file."""
61 import hashlib
62
63 hasher = hashlib.sha256()
64 with open(filepath, "rb") as file:
65 while True:
66 chunk = file.read(4096)
67 if not chunk:
68 break
69 hasher.update(chunk)
70 return hasher.hexdigest()
71
72
73 def extract_archive(filepath, target_dir):
74 """Extracts an archive to the target directory."""
75 filename = os.path.basename(filepath)
76 logger.info(f"Extracting {filepath} to {target_dir}")
77 if filename.endswith((".tar.bz2", ".tar.gz", ".tar.xz")):
78 subprocess.run(["tar", "xf", filepath, "-C", target_dir], check=True)
79 elif filename.endswith(".zip"):
80 shutil.unpack_archive(filepath, target_dir)
81 else:
82 raise ValueError(f"Unsupported archive type: {filename}")
83
84
85 def download_and_extract(url, tmp_dir, target_dir):
86 archivepath = download_file(url, tmp_dir, target_dir)
87 archivehash = compute_sha256(archivepath)
88 extract_archive(archivepath, target_dir)
89 return os.path.basename(archivepath), archivehash
90
91
92 def stamp_target_dir(target_dir, downloaded_files_hashes):
93 if not downloaded_files_hashes or len(downloaded_files_hashes) == 0:
94 logger.error("No files to stamp")
95 return
96
97 stamp_path = os.path.join(target_dir, STAMP_FILE)
98 if os.path.exists(stamp_path):
99 os.remove(stamp_path)
100
101 max_filename_length = (
102 max(len(filename) for filename, _ in downloaded_files_hashes)
103 if downloaded_files_hashes
104 else 0
105 )
106
107 hash_results = "\n".join(
108 f"{filename:<{max_filename_length}} {hash}"
109 for filename, hash in downloaded_files_hashes
110 )
111 with open(stamp_path, "w") as f:
112 f.write(hash_results)
113
114 if not stamp_hashes_match(stamp_path):
115 raise ValueError("Downloaded files do not match recorded hashes!")
116
117
118 def stamp_hashes_match(stamp_path):
119 if not os.path.exists(stamp_path):
120 return False
121
122 lines = []
123 with open(stamp_path, "r") as f:
124 lines = f.readlines()
125
126 expected_hashes = {}
127 for line in EXPECTED_HASHES.strip().split("\n"):
128 filename, hash = line.split()
129 expected_hashes[filename] = hash
130
131 for line in lines:
132 filename, hash = line.split()
133 if filename not in expected_hashes:
134 logger.error(f"Unexpected file in stamp: {filename}")
135 return False
136 if expected_hashes[filename] != hash:
137 logger.error(
138 f"Hash mismatch for {filename}: expected {expected_hashes[filename]}, got {hash}"
139 )
140 return False
141 return True
142
143
144 def main():
145 """Main function to parse arguments and download/extract fonts."""
146
147 parser = argparse.ArgumentParser(description="Download and extract ChromeOS fonts.")
148
149 parser.add_argument("--target-dir", help="Target directory for extracted fonts.")
150 parser.add_argument(
151 "--try-symlink",
152 action="store_true",
153 help="Try to symlink test files previously downloaded to the container.",
154 )
155 args = parser.parse_args()
156
157 target_dir = args.target_dir
158
159 if args.try_symlink:
160 if os.path.exists(CONTAINER_DOWNLOAD_DIR) and stamp_hashes_match(
161 os.path.join(CONTAINER_DOWNLOAD_DIR, STAMP_FILE)
162 ):
163 try:
164 os.symlink(CONTAINER_DOWNLOAD_DIR, target_dir, target_is_directory=True)
165 except FileExistsError:
166 logger.debug(
167 f"Target directory {target_dir} already exists. Skipping symlink."
168 )
169 except OSError as e:
170 logger.warning(f"Failed to create symlink: {e}")
171 logger.info(
172 f"Symlinked test fonts directory from {CONTAINER_DOWNLOAD_DIR} to {target_dir}."
173 )
174 else:
175 logger.debug("Pre-downloaded test fonts not found.")
176
177 if stamp_hashes_match(os.path.join(target_dir, STAMP_FILE)):
178 logger.info("Fonts already downloaded and extracted.")
179 return 0
180
181 os.makedirs(target_dir, exist_ok=True)
182
183 with tempfile.TemporaryDirectory() as tmp_dir:
184 with multiprocessing.Pool(processes=multiprocessing.cpu_count()) as pool:
185 hashes = pool.starmap(
186 download_and_extract,
187 [(source, tmp_dir, target_dir) for source in SOURCES],
188 )
189 stamp_target_dir(target_dir, hashes)
190
191
192 if __name__ == "__main__":
193 main()