fonts/extract.py
2024-07-04 00:04:26 +08:00

81 lines
2.5 KiB
Python

"""mass font extractor"""
from pathlib import Path
from shutil import copy2
from sys import argv
from shutil import get_terminal_size
# sources: source font zip files are
# sources/ext: extracted content of source/*.zip
# pre: files that have already been extracted previously
# files: the output dir
SOURCES_DIR: Path = Path(__file__).parent.joinpath('sources')
SOURCES_EXT_DIR: Path = SOURCES_DIR.joinpath('ext')
PRE_DIR: Path = Path(__file__).parent.joinpath('pre')
FILES_DIR: Path = Path(__file__).parent.joinpath('files')
def chkdir(path: Path) -> None:
path.mkdir(parents=True, exist_ok=True)
assert path.exists()
def main():
# check
chkdir(SOURCES_DIR)
assert SOURCES_EXT_DIR.exists(), "sources/ext does not exist - extract sources/*.zip files into sources/ext/*"
chkdir(FILES_DIR)
pre_exists: bool = PRE_DIR.exists()
tracking: list[str] = []
# get terminal size, if possible
col: int = 0
lns: int = 0
try:
col, lns = get_terminal_size()
except Exception:
col, lns = 0, 0
# recursively iterate through SOURCES_EXT_DIR
for path in SOURCES_EXT_DIR.rglob('*'):
# if it is an otf or ttf file, copy just the file to FILES_DIR
if path.is_file() and path.suffix in ['.otf', '.ttf']:
# if the file starts with a dot, skip
if path.stem.startswith('.'):
if "-v" in argv:
print(f"{path.relative_to(SOURCES_DIR)} (skipped)")
continue
# if we already copied either its otf or ttf counterpart, skip
if path.stem in tracking:
continue
else:
tracking.append(path.stem)
dest = FILES_DIR.joinpath(path.name)
copy2(path, dest)
# print 'path' and 'dest' in a short format
if "-v" in argv:
print(f"{str(path.relative_to(SOURCES_DIR.parent))} -> {str(dest.relative_to(FILES_DIR.parent))}")
else:
print(f"\r{str(dest.relative_to(FILES_DIR.parent)).ljust(col)}", end="")
else:
print()
# if PRE_DIR exists, recursively iterate through it and then see
# what files in the PRE_DIR are not in PRE_DIR
if pre_exists:
for path in PRE_DIR.rglob('*'):
if path.is_file() and path.suffix in ['.otf', '.ttf']:
if path.stem not in tracking:
print(f"!!! pre file '{path}' is unique")
print(f"copied {len(tracking)} files to {FILES_DIR}")
if __name__ == "__main__":
main()