|
8 | 8 | from pathlib import Path |
9 | 9 |
|
10 | 10 | import fsutil |
| 11 | +import ots |
11 | 12 | from fontTools import unicodedata |
12 | 13 | from fontTools.subset import Options as SubsetterOptions |
13 | 14 | from fontTools.subset import Subsetter |
@@ -549,6 +550,8 @@ def get_format(self, *, ignore_flavor=False): |
549 | 550 | format = self.FORMAT_WOFF |
550 | 551 | elif version == "wOF2": |
551 | 552 | format = self.FORMAT_WOFF2 |
| 553 | + if format is None: |
| 554 | + raise TypeError("Unable to get the font format.") |
552 | 555 | return format |
553 | 556 |
|
554 | 557 | def get_glyphs(self): |
@@ -1133,6 +1136,47 @@ def rename(self, *, family_name="", style_name="", update_style_flags=True): |
1133 | 1136 | if update_style_flags: |
1134 | 1137 | self.set_style_flags_by_subfamily_name() |
1135 | 1138 |
|
| 1139 | + def sanitize(self, *, strict=True): |
| 1140 | + """ |
| 1141 | + Sanitize the font file using OpenType Sanitizer. |
| 1142 | + https://github.com/googlefonts/ots-python |
| 1143 | +
|
| 1144 | + :param strict: If True (default), raises an exception even on sanitizer warnings. |
| 1145 | + If False, only raises an exception on sanitizer failure (non-zero exit code). |
| 1146 | + :type strict: bool |
| 1147 | +
|
| 1148 | + :raises Exception: If the OpenType Sanitizer reports an error during the sanitization process. |
| 1149 | + :return: None |
| 1150 | +
|
| 1151 | + :note: Uses OpenType Sanitizer (ots) to sanitize the font file. |
| 1152 | + Saves the font to a temporary directory and invokes the sanitizer on the saved file. |
| 1153 | + If `strict` is True (default), treats sanitizer warnings as errors. |
| 1154 | + If `strict` is False, only checks for sanitizer errors. |
| 1155 | + """ |
| 1156 | + with tempfile.TemporaryDirectory() as dest: |
| 1157 | + filename = self.get_filename() |
| 1158 | + filepath = fsutil.join_path(dest, filename) |
| 1159 | + filepath = self.save(filepath) |
| 1160 | + result = ots.sanitize( |
| 1161 | + filepath, |
| 1162 | + capture_output=True, |
| 1163 | + encoding="utf-8", |
| 1164 | + ) |
| 1165 | + error_code = result.returncode |
| 1166 | + errors = result.stderr |
| 1167 | + if error_code: |
| 1168 | + exc = Exception( |
| 1169 | + f"OpenType Sanitizer returned non-zero exit code ({error_code}): \n{errors}" |
| 1170 | + ) |
| 1171 | + print(exc) |
| 1172 | + raise exc |
| 1173 | + elif strict: |
| 1174 | + warnings = result.stdout |
| 1175 | + success_message = "File sanitized successfully!\n" |
| 1176 | + if warnings != success_message: |
| 1177 | + warnings = warnings.rstrip(success_message) |
| 1178 | + raise Exception(f"OpenType Sanitizer warnings: \n{warnings}") |
| 1179 | + |
1136 | 1180 | def save(self, filepath=None, *, overwrite=False): |
1137 | 1181 | """ |
1138 | 1182 | Saves the font at filepath. |
|
0 commit comments