Debian Codegraph @

setupbase.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 import os
3 import re
4 import io
5 import sys
6 import json
7 import hashlib
8 import zipfile
9
10 try:
11 from fontTools import ttLib
12 except ImportError:
13 ttLib = None
14
15 from urllib.request import urlopen
16
17 import setuptools
18
19 LOG_INFO = 20
20
21 HERE = os.path.abspath(os.path.dirname(__file__))
22 INIT_PY_PATH = os.path.join(HERE, "qtawesome", "__init__.py")
23
24
25 def rename_font(font_path, font_name):
26 """
27 Font renaming code originally from:
28 https://github.com/chrissimpkins/fontname.py/blob/master/fontname.py
29 """
30 tt = ttLib.TTFont(font_path, recalcBBoxes=False, recalcTimestamp=False)
31 namerecord_list = tt["name"].names
32 variant = ""
33
34 # determine font variant for this file path from name record nameID 2
35 for record in namerecord_list:
36 if record.nameID == 2:
37 variant = str(record)
38 break
39
40 # test that a variant name was found in the OpenType tables of the font
41 if len(variant) == 0:
42 raise ValueError(
43 "Unable to detect the font variant from the OpenType name table in: %s"
44 % font_path
45 )
46
47 # Here are some sample name records to give you an idea of the name tables:
48 # ID 0: 'Copyright (c) Font Awesome'
49 # ID 1: 'Font Awesome 5 Free Regular'
50 # ID 2: 'Regular'
51 # ID 3: 'Font Awesome 5 Free Regular-5.14.0'
52 # ID 4: 'Font Awesome 5 Free Regular'
53 # ID 5: '331.264 (Font Awesome version: 5.14.0)'
54 # ID 6: 'FontAwesome5Free-Regular'
55 # ID 10: "The web's most popular icon set and toolkit."
56 # ID 11: 'https://fontawesome.com'
57 # ID 16: 'Font Awesome 5 Free'
58 # ID 17: 'Regular'
59 # ID 18: 'Font Awesome 5 Free Regular'
60 # ID 21: 'Font Awesome 5 Free'
61 # ID 22: 'Regular'
62
63 # modify the opentype table data in memory with updated values
64 for record in namerecord_list:
65 if record.nameID in (1, 4, 16, 21):
66 print(
67 f"Renaming font name record at ID {record.nameID}: {record.string} --> {font_name}"
68 )
69 record.string = font_name
70
71 # write changes to the font file
72 try:
73 tt.save(font_path, reorderTables=False)
74 except Exception:
75 raise RuntimeError(
76 f"ERROR: unable to write new name to OpenType tables for: {font_path}"
77 )
78
79
80 class UpdateFA6Command(setuptools.Command):
81 """A custom command to make updating FontAwesome 6.x easy!"""
82
83 description = "Try to update the FontAwesome 6.x data in the project."
84 user_options = [
85 ("fa-version=", None, "FA version."),
86 ("zip-path=", None, "Read from local zip file path."),
87 ]
88
89 # Update these below if the FontAwesome changes their structure:
90 FA_STYLES = ("regular", "solid", "brands")
91 CHARMAP_PATH_TEMPLATE = os.path.join(
92 HERE,
93 "qtawesome",
94 "fonts",
95 "fontawesome6-{style}-webfont-charmap-{version}.json",
96 )
97 TTF_PATH_TEMPLATE = os.path.join(
98 HERE, "qtawesome", "fonts", "fontawesome6-{style}-webfont-{version}.ttf"
99 )
100 URL_TEMPLATE = (
101 "https://github.com/FortAwesome/Font-Awesome/"
102 "releases/download/{version}/fontawesome-free-{version}-web.zip"
103 )
104
105 def initialize_options(self):
106 """Set default values for the command options."""
107 self.fa_version = ""
108 self.zip_path = ""
109
110 def finalize_options(self):
111 """Validate the command options."""
112 assert bool(self.fa_version), "FA version is mandatory for this command."
113 if self.zip_path:
114 assert os.path.exists(self.zip_path), (
115 "Local zipfile does not exist: %s" % self.zip_path
116 )
117
118 def __print(self, msg):
119 """Shortcut for printing with the setuptools logger."""
120 self.announce(msg, level=LOG_INFO)
121
122 def __get_charmap_path(self, style):
123 """Get the project FA charmap path for a given style."""
124 return self.CHARMAP_PATH_TEMPLATE.format(style=style, version=self.fa_version)
125
126 def __get_ttf_path(self, style):
127 """Get the project FA font path for a given style."""
128 return self.TTF_PATH_TEMPLATE.format(style=style, version=self.fa_version)
129
130 @property
131 def __release_url(self):
132 """Get the release URL."""
133 return self.URL_TEMPLATE.format(version=self.fa_version)
134
135 @property
136 def __zip_file(self):
137 """Get a file object of the FA zip file."""
138 if self.zip_path:
139 # If using a local file, just open it:
140 self.__print("Opening local zipfile: %s" % self.zip_path)
141 return open(self.zip_path, "rb")
142
143 # Otherwise, download it and make a file object in-memory:
144 url = self.__release_url
145 self.__print("Downloading from URL: %s" % url)
146 response = urlopen(url)
147 return io.BytesIO(response.read())
148
149 @property
150 def __zipped_files_data(self):
151 """Get a dict of all files of interest from the FA release zipfile."""
152 files = {}
153 with zipfile.ZipFile(self.__zip_file) as thezip:
154 for zipinfo in thezip.infolist():
155 if zipinfo.filename.endswith("metadata/icons.json"):
156 with thezip.open(zipinfo) as compressed_file:
157 files["icons.json"] = compressed_file.read()
158 elif zipinfo.filename.endswith(".ttf"):
159 # For the record, the paths usually look like this:
160 # webfonts/fa-brands-400.ttf
161 # webfonts/fa-regular-400.ttf
162 # webfonts/fa-solid-900.ttf
163 name = os.path.basename(zipinfo.filename)
164 tokens = name.split("-")
165 style = tokens[1]
166 if style in self.FA_STYLES:
167 with thezip.open(zipinfo) as compressed_file:
168 files[style] = compressed_file.read()
169
170 # Safety checks:
171 assert all(style in files for style in self.FA_STYLES), (
172 "Not all FA styles found! Update code is broken."
173 )
174 assert "icons.json" in files, "icons.json not found! Update code is broken."
175
176 return files
177
178 def run(self):
179 """Run command."""
180 files = self.__zipped_files_data
181 hashes = {}
182 icons = {}
183
184 # Read icons.json (from the webfont zip download)
185 data = json.loads(files["icons.json"])
186
187 # Group icons by style, since not all icons exist for all styles:
188 for icon, info in data.items():
189 for style in info["styles"]:
190 icons.setdefault(str(style), {})
191 icons[str(style)][icon] = str(info["unicode"])
192
193 # For every FA "style":
194 for style, details in icons.items():
195 # Dump a .json charmap file:
196 charmapPath = self.__get_charmap_path(style)
197 self.__print('Dumping updated "%s" charmap: %s' % (style, charmapPath))
198 with open(charmapPath, "w+") as f:
199 json.dump(details, f, indent=4, sort_keys=True)
200
201 # Dump a .ttf font file:
202 font_path = self.__get_ttf_path(style)
203 data = files[style]
204 self.__print('Dumping updated "%s" font: %s' % (style, font_path))
205 with open(font_path, "wb+") as f:
206 f.write(data)
207
208 # Fix to prevent repeated font names:
209 if style in ("regular", "solid"):
210 new_name = str("Font Awesome 6 Free %s") % style.title()
211 self.__print('Renaming font to "%s" in: %s' % (new_name, font_path))
212 if ttLib is not None:
213 rename_font(font_path, new_name)
214 else:
215 sys.exit(
216 "This special command requires the module 'fonttools': "
217 "https://github.com/fonttools/fonttools/"
218 )
219
220 # Reread the data since we just edited the font file:
221 with open(font_path, "rb") as f:
222 data = f.read()
223 files[style] = data
224 # Store hashes for later:
225 hashes[style] = hashlib.md5(data).hexdigest()
226
227 # Now it's time to patch "__init__.py":
228 init_path = INIT_PY_PATH
229 self.__print("Patching new MD5 hashes in: %s" % init_path)
230 with open(init_path, "r") as init_file:
231 contents = init_file.read()
232 # We read it in full, then use regex substitution:
233 for style, md5 in hashes.items():
234 self.__print('New "%s" hash is: %s' % (style, md5))
235 regex = r'("fontawesome6-%s-webfont-%s.ttf":\s+)"(\w+)"' % (
236 style,
237 self.fa_version,
238 )
239 subst = r'\g<1>"' + md5 + '"'
240 contents = re.sub(regex, subst, contents, 1)
241 # and finally overwrite with the modified file:
242 self.__print("Dumping updated file: %s" % init_path)
243 with open(init_path, "w") as init_file:
244 init_file.write(contents)
245
246 self.__print(
247 "\nFinished!\n"
248 "Please check the git diff to make sure everything went okay.\n"
249 "You should also edit README.md and "
250 "qtawesome/docs/source/usage.rst to reflect the changes."
251 )
252
253
254 class UpdateCodiconCommand(setuptools.Command):
255 """A custom command to make updating Microsoft's Codicons easy!"""
256
257 description = "Try to update the Codicon font data in the project."
258 user_options = [("msc-version=", None, "Codicon version.")]
259
260 CHARMAP_PATH = os.path.join(
261 HERE, "qtawesome", "fonts", "codicon-charmap-{version}.json"
262 )
263 TTF_PATH = os.path.join(HERE, "qtawesome", "fonts", "codicon-{version}.ttf")
264 DOWNLOAD_URL_TTF = "https://github.com/microsoft/vscode-codicons/releases/download/{version}/codicon.ttf"
265 DOWNLOAD_URL_MAPPING = "https://raw.githubusercontent.com/microsoft/vscode-codicons/refs/tags/{version}/src/template/mapping.json"
266 DOWNLOAD_URL_JSON = "https://raw.githubusercontent.com/microsoft/vscode-codicons/{version}/package.json"
267
268 def initialize_options(self):
269 """Set default values for the command options."""
270 self.msc_version = ""
271
272 def finalize_options(self):
273 """Validate the command options."""
274 assert bool(self.msc_version), "Codicons version is mandatory for this command."
275
276 def __print(self, msg):
277 """Shortcut for printing with the setuptools logger."""
278 self.announce(msg, level=LOG_INFO)
279
280 def run(self):
281 """Run command."""
282
283 # Download .json to a temporary path:
284 download_url_json = self.DOWNLOAD_URL_JSON.format(version=self.msc_version)
285 package_json = urlopen(download_url_json)
286 package_info = json.load(package_json)
287 package_version = package_info["version"]
288 assert self.msc_version == package_version, (
289 "Codicons version does not match with `package.json` info. %s and %s"
290 % (
291 self.msc_version,
292 package_version,
293 )
294 )
295 self.__print("Will download codicons version: %s" % package_version)
296
297 # Download mapping.json:
298 donwload_url_mapping = self.DOWNLOAD_URL_MAPPING.format(
299 version=self.msc_version
300 )
301 req = urlopen(donwload_url_mapping)
302 if req.status != 200:
303 raise Exception("Failed to download JSON mapping")
304
305 data = json.loads(req.read().decode())
306 req.close()
307
308 # Interpret the mapping.json file:
309 charmap = {}
310 for name, key in data.items():
311 key = hex(key)
312 name = name.lower()
313 charmap[name] = key
314 self.__print("Identified %s icons in the JSON." % len(charmap))
315
316 # Dump a .json charmap file the way we like it:
317 charmap_path = self.CHARMAP_PATH.format(version=package_version)
318 self.__print("Dumping updated charmap: %s" % charmap_path)
319 with open(charmap_path, "w+") as f:
320 json.dump(charmap, f, indent=4, sort_keys=True)
321
322 # Dump a .ttf font file:
323 download_url_ttf = self.DOWNLOAD_URL_TTF.format(version=self.msc_version)
324 ttf_path = self.TTF_PATH.format(version=package_version)
325 with open(ttf_path, "wb+") as ttfFile:
326 self.__print("Downloading %s --> %s" % (download_url_ttf, ttf_path))
327 response = urlopen(download_url_ttf)
328 data = response.read()
329 ttfFile.write(data)
330 md5 = hashlib.md5(data).hexdigest()
331 self.__print("New hash is: %s" % md5)
332
333 # Now it's time to patch "__init__.py":
334 self.__print("Patching new MD5 hashes in: %s" % INIT_PY_PATH)
335 with open(INIT_PY_PATH, "r") as init_file:
336 contents = init_file.read()
337 regex = r'("codicon-%s.ttf":\s+)"(\w+)"' % self.msc_version
338 subst = r'\g<1>"' + md5 + '"'
339 contents = re.sub(regex, subst, contents, 1)
340 self.__print("Dumping updated file: %s" % INIT_PY_PATH)
341 with open(INIT_PY_PATH, "w") as init_file:
342 init_file.write(contents)
343
344 self.__print(
345 "\nFinished!\n"
346 "Please check the git diff to make sure everything went okay.\n"
347 "You should also edit README.md and "
348 "qtawesome/docs/source/usage.rst to reflect the changes."
349 )