|
| 1 | +""" |
| 2 | +Author: RedFantom |
| 3 | +License: GNU GPLv3 |
| 4 | +Copyright (c) 2021 RedFantom |
| 5 | +
|
| 6 | +Modify generated wheels such that they load the sytem-version of the |
| 7 | +libfontconfig binary rather than the manylinux provided one. |
| 8 | +""" |
| 9 | +import shutil |
| 10 | +from typing import Any, List, Optional |
| 11 | +import os |
| 12 | +import zipfile # Wheels are actually zip files |
| 13 | + |
| 14 | +LIB = b"libfontconfig.so.1" |
| 15 | + |
| 16 | + |
| 17 | +def get_whl_files() -> List[str]: |
| 18 | + return list(map(lambda s: os.path.join("dist", s), filter(lambda s: s.endswith(".whl"), os.listdir("dist")))) |
| 19 | + |
| 20 | + |
| 21 | +def printf(string, **kwargs): |
| 22 | + kwargs.update({"end": "", "flush": True}) |
| 23 | + print(string, **kwargs) |
| 24 | + |
| 25 | + |
| 26 | +def first(lst: List[Any]) -> Optional[Any]: |
| 27 | + return lst[0] if len(lst) > 0 else None |
| 28 | + |
| 29 | + |
| 30 | +for whl in get_whl_files(): |
| 31 | + # Step one: Open the wheel as a zip file |
| 32 | + printf(f"Processing {whl}...") |
| 33 | + source = zipfile.ZipFile(whl) |
| 34 | + target = zipfile.ZipFile(os.path.basename(whl), "w") |
| 35 | + printf(".") |
| 36 | + |
| 37 | + # Step two: Find the fontconfig file |
| 38 | + members: List[str] = source.namelist() |
| 39 | + wo_fontconfig = [member for member in members if "libfontconfig" not in member] |
| 40 | + fontconfig = first(list(set(members) - set(wo_fontconfig))) |
| 41 | + if fontconfig is None: |
| 42 | + printf("notfound\n") |
| 43 | + continue |
| 44 | + fontconfig = os.path.basename(fontconfig) |
| 45 | + printf(fontconfig) |
| 46 | + printf(".") |
| 47 | + fontconfig = fontconfig.encode() |
| 48 | + |
| 49 | + # Step three: Copy the modified contents to the target wheel file |
| 50 | + for member in wo_fontconfig: |
| 51 | + buffer: bytes = source.read(member) |
| 52 | + if "extrafont.so" in member: # We found our compiled binary! |
| 53 | + # Step four: Modify extrafont.so to no longer load the old fontconfig |
| 54 | + printf(buffer.index(fontconfig)) |
| 55 | + buffer = buffer.replace(fontconfig, LIB + b"\x00" * (len(fontconfig) - len(LIB))) |
| 56 | + |
| 57 | + # Step five: Write the new zipfile |
| 58 | + target.writestr(member, buffer) |
| 59 | + source.close() |
| 60 | + target.close() |
| 61 | + |
| 62 | + # Step six: Replace the original wheel file with the new file |
| 63 | + os.remove(whl) |
| 64 | + shutil.copyfile(os.path.basename(whl), whl) |
| 65 | + os.remove(os.path.basename(whl)) |
| 66 | + printf(" Done.\n") |
0 commit comments