aboutsummarylogtreecommitdiffstats
path: root/iosevka-generate
blob: b951506855637fc9a0ef0d30548acf898b6175c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#!/usr/bin/env python3
# pylint: disable=C0103,C0111

import configparser
import shutil
import subprocess
import sys
from pathlib import Path
from textwrap import dedent
from typing import Dict, Iterable, List, Optional, Set, Tuple

import inflection
from git import Repo
from xdg.BaseDirectory import xdg_cache_home, xdg_config_home, xdg_data_home

IOSEVKA_REPO = "https://github.com/be5invis/iosevka"
NERDFONT_REPO = "https://github.com/ryanoasis/nerd-fonts"


def get_repo(repo_dir: Path, remote_url: str) -> Repo:
    if repo_dir.exists():
        print(f"Updating {IOSEVKA_REPO} ...", file=sys.stderr)
        repo = Repo(repo_dir)
        repo.remote().pull()
    else:
        print(f"Cloning {remote_url} ...", file=sys.stderr)
        repo = Repo.clone_from(remote_url, repo_dir, depth=1)
    return repo


def install_iosevka(repo_dir: Path):
    get_repo(repo_dir, IOSEVKA_REPO)

    print("Installing iosevka...", file=sys.stderr)
    try:
        subprocess.run(["npm", "install"], cwd=repo_dir).check_returncode()
        subprocess.run(
            ["npm", "install", "--package-lock-only"],
            cwd=repo_dir,
        ).check_returncode()
        subprocess.run(["npm", "audit", "fix"], cwd=repo_dir).check_returncode()
    except subprocess.CalledProcessError:
        print("Failed to install iosevka", file=sys.stderr)
        sys.exit(1)
    else:
        print("Iosevka installed.", file=sys.stderr)


def generate_font_plan(
    iosevka_dir: Path,
    font_name: str,
    font_styles: Dict[str, Set[str]],
):
    family_name = f"Iosevka {inflection.titleize(font_name)}"
    print(f"Building font with family name: {family_name}")

    with open(iosevka_dir / "private-build-plans.toml", "w") as fp:
        sep = """
            """
        conf = f"""
            [buildPlans.{font_name}]
            family = "{font_name}"
            {sep.join(font_styles["options"])}

            [buildPlans.{font_name}.variants.design]
            {sep.join(font_styles["common"])}

            [buildPlans.{font_name}.variants.upright]
            {sep.join(font_styles["upright"])}

            [buildPlans.{font_name}.variants.italic]
            {sep.join(font_styles["italic"])}

            [buildPlans.{font_name}.variants.oblique]
            {sep.join(font_styles["oblique"])}

            [buildPlans.{font_name}.ligations]
            inherits = "{" ".join(font_styles["ligations"])}"
        """

        print(f"Building iosevka conf:\n{conf}", file=sys.stderr)
        fp.write(dedent(conf))


def generate_font(iosevka_dir: Path, font_name: str) -> None:
    subprocess.run(
        ["npm", "run", "build", "--", f"ttf::{font_name}"], cwd=iosevka_dir
    ).check_returncode()


def nerdfont_patch(
    font_dir: Path,
    repo_dir: Path,
    options: Iterable[str] = [],
    mono: bool = True,
) -> None:
    get_repo(repo_dir, NERDFONT_REPO)

    for font in filter(Path.is_file, font_dir.glob("*")):
        print(f"Patching {font} with nerdfont ...", file=sys.stderr)
        subprocess.run(
            [
                f"{repo_dir}/font-patcher",
                "--careful",
                "--progressbars",
                *(["--mono"] if mono else []),
                *map(lambda o: f"--{o}", options),
                font,
            ],
            cwd=font_dir,
        ).check_returncode()
        font.rename(f"{font}.unpatched")


def parse_config(config_file: Path) -> Tuple[str, Dict[str, Set[str]], Optional[List]]:
    print(f"Parsing iosevka-generate conf: {config_file} ...", file=sys.stderr)

    config = configparser.ConfigParser(
        allow_no_value=True, inline_comment_prefixes=(";")
    )
    config.read_dict({"options": {"name": "myosevka"}})

    sections = {"common", "upright", "italic", "oblique", "ligations", "options"}
    config.read_dict({s: {} for s in sections})
    config.read(config_file)

    font_styles = {
        section: {f'{char} = "{style}"' for char, style in config[section].items()}
        if section != "options"
        else set()
        for section in sections
    }

    nerdfont: Optional[List] = None
    for option, value in config["options"].items():
        if option == "name":
            font_name = value
        elif option == "nerdfont":
            nerdfont = value.split(" ")
        elif option == "ligset":
            font_styles["ligations"].add(value)
        else:
            font_styles["options"].add(f'{option} = "{value}"')

    return (font_name, font_styles, nerdfont)


def store_fonts(dest: Path, source: Path):
    dest.mkdir(parents=True, exist_ok=True)
    for font in filter(lambda f: f.is_file(), source.glob("*.ttf")):
        shutil.move(str(source / font), dest / font.name)
    print(f"Fonts installed to {dest}", file=sys.stderr)

    subprocess.run(["fc-cache", "--force"]).check_returncode()
    print("Fonts re-cached", file=sys.stderr)


if __name__ == "__main__":
    config_dir = Path(xdg_config_home) / "iosevka"
    cache_dir = Path(xdg_cache_home)
    install_dir = cache_dir / "iosevka"
    font_dir = Path(xdg_data_home) / "fonts"

    install_iosevka(install_dir)
    print(f"Loading font configurations in {config_dir}", file=sys.stderr)
    for conf in filter(
        lambda p: p.suffix in {".ini", ".toml"},
        Path(config_dir).glob("*"),
    ):
        print(f"Found {conf.stem}", file=sys.stderr)

        if conf.suffix == ".ini":
            name, styles, nerdfont_opts = parse_config(conf)
            generate_font_plan(install_dir, name, styles)
        else:
            name, styles, nerdfont_opts = conf.stem, {}, None
            shutil.copy(conf, install_dir / "private-build-plans.toml")

        generate_font(install_dir, name)
        gen_dir = install_dir / "dist" / name / "ttf"

        if nerdfont_opts is not None:
            mono = any(filter(lambda o: o in styles["common"], ("sp-term", "sp-fixed")))

            nerdfont_patch(
                gen_dir, cache_dir / "nerdfont", options=nerdfont_opts, mono=mono
            )

        store_fonts(font_dir, gen_dir)