|
28 | 28 | import sys
|
29 | 29 |
|
30 | 30 | from collections import defaultdict
|
31 |
| -from glob import glob |
32 | 31 | from hashlib import md5
|
33 | 32 | from io import BytesIO
|
34 | 33 | from mkdocs.commands.build import DuplicateFilter
|
@@ -449,19 +448,31 @@ def _load_font(self, config):
|
449 | 448 | else:
|
450 | 449 | name = "Roboto"
|
451 | 450 |
|
452 |
| - # Retrieve font files, if not already done |
453 |
| - files = glob(f"{self.cache}/**/*.[ot]tf") |
454 |
| - files = [os.path.relpath(file, self.cache) for file in files] |
455 |
| - files = [file for file in files if file.endswith(".ttf") or file.endswith(".otf")] or ( |
456 |
| - self._load_font_from_google(name) |
457 |
| - ) |
| 451 | + # Google fonts can return varients like OpenSans_Condensed-Regular.ttf so |
| 452 | + # we only use the font requested e.g. OpenSans-Regular.ttf |
| 453 | + font_filename_base = name.replace(' ', '') |
| 454 | + filename_regex = re.escape(font_filename_base)+r"-(\w+)\.[ot]tf$" |
458 | 455 |
|
459 |
| - # Map available font weights to file paths |
460 | 456 | font = dict()
|
461 |
| - for file in files: |
462 |
| - match = re.search(r"-(\w+)\.[ot]tf$", file) |
463 |
| - if match: |
464 |
| - font[match.group(1)] = os.path.join(self.cache, file) |
| 457 | + # Check for cached files - note these may be in subfolders |
| 458 | + for currentpath, folders, files in os.walk(self.cache): |
| 459 | + for file in files: |
| 460 | + # Map available font weights to file paths |
| 461 | + fname = os.path.join(currentpath, file) |
| 462 | + match = re.search(filename_regex, fname) |
| 463 | + if match: |
| 464 | + font[match.group(1)] = fname |
| 465 | + |
| 466 | + # If none found, fetch from Google and try again |
| 467 | + if len(font) == 0: |
| 468 | + self._load_font_from_google(name) |
| 469 | + for currentpath, folders, files in os.walk(self.cache): |
| 470 | + for file in files: |
| 471 | + # Map available font weights to file paths |
| 472 | + fname = os.path.join(currentpath, file) |
| 473 | + match = re.search(filename_regex, fname) |
| 474 | + if match: |
| 475 | + font[match.group(1)] = fname |
465 | 476 |
|
466 | 477 | # Return available font weights with fallback
|
467 | 478 | return defaultdict(lambda: font["Regular"], font)
|
|
0 commit comments