Fix cache dir being passed relatively to typst and add typing to args

This commit is contained in:
Skye 2023-12-02 18:37:38 -05:00
parent 3ddd3dec8e
commit 1f04a61598

View file

@ -5,7 +5,6 @@ import csv
import hashlib import hashlib
import json import json
import os import os
import pathlib
import string import string
import typing import typing
import urllib.parse import urllib.parse
@ -14,25 +13,44 @@ import requests
import imb import imb
from pathlib import Path from pathlib import Path
from typing import TypedDict from typing import NewType, TypedDict
# A lot of stuff needs to be in the same directory, just chdir # A lot of stuff needs to be in the same directory, just chdir
os.chdir(os.path.dirname(os.path.realpath(__file__))) # os.chdir(os.path.dirname(os.path.realpath(__file__)))
_cache: Path | None = None
def cache_dir() -> Path: def cache_dir() -> Path:
cache = Path("cache") global _cache
cache.mkdir(exist_ok=True) if _cache is None:
return cache _cache = root_dir() / "cache"
_cache.mkdir(exist_ok=True)
return _cache
def iso_code(s: str) -> str: _root: Path | None = None
def root_dir() -> Path:
global _root
if _root is None:
_root = Path(os.path.realpath(__file__)).parent
_root.mkdir(exist_ok=True)
return _root
IsoCode = NewType("IsoCode", str)
def iso_code(s: str) -> IsoCode:
if len(s) != 2: if len(s) != 2:
raise ValueError("must be 2 characters long") raise ValueError("must be 2 characters long")
s = s.lower() s = s.lower()
if not (s[0] in string.ascii_lowercase and s[1] in string.ascii_lowercase): if not (s[0] in string.ascii_lowercase and s[1] in string.ascii_lowercase):
raise ValueError("must be ascii letters") raise ValueError("must be ascii letters")
return s return IsoCode(s)
def get_discord_avatar( def get_discord_avatar(
@ -95,8 +113,7 @@ def get_orig_avatar(
def get_avatar(url: str, secrets: dict[str, str]) -> str | None: def get_avatar(url: str, secrets: dict[str, str]) -> str | None:
basename = hashlib.sha256(url.encode("utf-8")).hexdigest() basename = hashlib.sha256(url.encode("utf-8")).hexdigest()
file_path = cache_dir() / f"{basename}.svg" file_path = cache_dir() / f"{basename}.svg"
if file_path.exists(): if not file_path.exists():
return str(file_path)
avatar_raster = get_orig_avatar(url, basename, secrets) avatar_raster = get_orig_avatar(url, basename, secrets)
if avatar_raster is None: if avatar_raster is None:
return None return None
@ -111,7 +128,7 @@ def get_avatar(url: str, secrets: dict[str, str]) -> str | None:
with open(file_path, "w") as svgfile: with open(file_path, "w") as svgfile:
svgfile.write(svg_text) svgfile.write(svg_text)
return str(file_path) return str(file_path.relative_to(root_dir()))
def get_country_name( def get_country_name(
@ -187,7 +204,20 @@ parser.add_argument(
parser.add_argument("-w", "--watch", action="store_true", help="Watch input files") parser.add_argument("-w", "--watch", action="store_true", help="Watch input files")
args = parser.parse_args()
class Args(argparse.Namespace):
template: str
origin: IsoCode
language: IsoCode
count: int
skip: int
address_file: str
content_path: str
no_content: bool
dont_compile: bool
args = parser.parse_args(args=None, namespace=Args())
cldr_root = ET.parse( cldr_root = ET.parse(
f"{os.getenv('CLDR_ROOT')}/share/unicode/cldr/common/main/{args.language}.xml" f"{os.getenv('CLDR_ROOT')}/share/unicode/cldr/common/main/{args.language}.xml"
@ -239,11 +269,10 @@ for row in rows:
# Typst can't access files outside the project root, except through a symlink # Typst can't access files outside the project root, except through a symlink
# Create one in cache to use here # Create one in cache to use here
if not os.path.exists("cache"): p = cache_dir() / "content"
os.mkdir("cache")
p = pathlib.Path("cache/content")
p.unlink(missing_ok=True) p.unlink(missing_ok=True)
p.symlink_to(args.content_path) content_full_path = Path(os.getcwd()).joinpath(args.content_path)
p.symlink_to(content_full_path)
cards = cards * args.count cards = cards * args.count
@ -258,7 +287,7 @@ if args.origin == "us":
serial += 1 serial += 1
imb.write_current_serial(serial) imb.write_current_serial(serial)
with open("options.json", "w") as options: with (root_dir() / "options.json").open("w") as options:
json.dump( json.dump(
fp=options, fp=options,
obj={ obj={
@ -273,14 +302,22 @@ if args.dont_compile:
font_paths = os.getenv("TYPST_FONT_PATHS") font_paths = os.getenv("TYPST_FONT_PATHS")
assert font_paths is not None assert font_paths is not None
os.execlp( typst_args = [
"typst",
"typst", "typst",
"watch" if args.watch else "compile", "watch" if args.watch else "compile",
"--root",
root_dir(),
"--font-path", "--font-path",
args.content_path, cache_dir() / "content",
"--font-path", "--font-path",
font_paths, font_paths,
args.template, args.template,
"output.pdf", "output.pdf",
]
# print(*typst_args)
os.execlp(
"typst",
*typst_args,
) )