Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

tools: the card scripts say where the font comes from

xbshengea6dd3fe0272
diff --git a/docs/workflows/press.md b/docs/workflows/press.md
index abe7248de..7cfe240ca 100644
--- a/docs/workflows/press.md
+++ b/docs/workflows/press.md
@@ -11,6 +11,8 @@
performance requirements install:
`tools/venv/bin/pip install -r tools/requirements-perf.txt`, then
`tools/readme_featured.py Fredoka.ttf docs/featured.png` and
- `tools/readme_card.py Fredoka.ttf docs/card.jpg`. If you cannot redraw them, say so in the PR.
+ `tools/readme_card.py Fredoka.ttf docs/card.jpg`. Fredoka is the variable TTF from Google Fonts and its
+ file is not in the repo, so that first argument is the path of the copy you downloaded; each script says
+ so when the path is wrong. If you cannot redraw them, say so in the PR.
Then run the tests: `python3 -m unittest discover -s tests -v`.
diff --git a/tests/test_card_font_argument.py b/tests/test_card_font_argument.py
new file mode 100644
index 000000000..e2eabe2d6
--- /dev/null
+++ b/tests/test_card_font_argument.py
@@ -0,0 +1,187 @@
+"""The font the README card scripts take is not in this repo, and nothing said so.
+
+`docs/workflows/press.md` step 2 is where a contributor redraws `docs/featured.png` and `docs/card.jpg`, and
+it prints two commands that pass `Fredoka.ttf` as the first argument. No folder of this repo holds that file -
+Fredoka is the variable TTF from Google Fonts, which only `tools/readme_stats.py`'s docstring ever said - so
+a contributor who installed Pillow as the page asks and then ran the command the page prints got:
+
+ OSError: cannot open resource
+
+with no file name in it and no way to tell whether the font, the argument order or the draw call was wrong.
+Before that, running any of the three with no arguments at all died on `IndexError: list index out of range`,
+because each one read `sys.argv[1], sys.argv[2]` at the top of the module.
+
+The three scripts now take the font through one guard: it names the path it could not open, says where the
+font comes from, and prints the two arguments when there are not two. It runs before the Pillow import, since
+the font is the argument the reader brings themselves and a missing one is the likelier failure - so a run
+with no Pillow still reports the font first, which is what makes this testable in CI, where Pillow is absent.
+
+`tools/gen_tables.py --font` hands the font to two of these scripts with `check=True`, so a wrong path there
+became a `CalledProcessError` traceback around their message; it now refuses the path itself.
+
+Run from the repository root: python3 -m unittest discover -s tests -v
+"""
+import os
+import re
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+TOOLS = ROOT / "tools"
+PRESS = ROOT / "docs" / "workflows" / "press.md"
+
+# The three scripts that draw the card, with the picture each one writes.
+CARD_SCRIPTS = {
+ "readme_stats.py": "stats.png",
+ "readme_featured.py": "featured.png",
+ "readme_card.py": "card.jpg",
+}
+
+# What the guard says the reader cannot use, and what a wrong path must not be mistaken for.
+NOT_THE_FONT = "requirements-perf.txt"
+
+
+def shadow_dir(tmp):
+ """A PIL package that cannot be imported, so a script behaves as on a venv without Pillow."""
+ pkg = Path(tmp) / "PIL"
+ pkg.mkdir(exist_ok=True)
+ (pkg / "__init__.py").write_text('raise ImportError("No module named \'PIL\'")\n', encoding="utf-8")
+ return str(tmp)
+
+
+def run(argv, tmp):
+ env = dict(os.environ)
+ env["PYTHONPATH"] = shadow_dir(tmp)
+ return subprocess.run([sys.executable, *argv], cwd=ROOT, env=env, capture_output=True, text=True)
+
+
+class FontArgumentTest(unittest.TestCase):
+ def test_the_shadow_really_hides_pillow(self):
+ # Without this every check below could be reading the Pillow line and proving nothing.
+ with tempfile.TemporaryDirectory() as tmp:
+ done = run(["-c", "import PIL"], tmp)
+ self.assertNotEqual(done.returncode, 0, "the PIL shadow did not take effect")
+
+ def test_a_font_that_is_not_there_is_reported_by_name(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ for name, picture in CARD_SCRIPTS.items():
+ with self.subTest(script=name):
+ out = Path(tmp) / picture
+ done = run([str(TOOLS / name), "Fredoka.ttf", str(out)], tmp)
+ self.assertNotEqual(done.returncode, 0, f"{name} accepted a font that does not exist")
+ self.assertIn("Fredoka.ttf", done.stderr, f"{name} does not name the font it could not open")
+ self.assertNotIn("Traceback", done.stderr, f"{name} still dies on a bare traceback")
+ self.assertNotIn(NOT_THE_FONT, done.stderr,
+ f"{name} reports the font only after the Pillow import, so a reader without "
+ "Pillow never sees it")
+ self.assertFalse(out.exists(), f"{name} wrote {out} before it had a font")
+
+ def test_the_font_is_checked_before_the_pillow_import(self):
+ # A path in the message plus no Pillow line in it is only possible if the guard sits first: this
+ # reads the two apart in the source, in each script.
+ for name in CARD_SCRIPTS:
+ with self.subTest(script=name):
+ text = (TOOLS / name).read_text(encoding="utf-8")
+ guard = text.find("font_and_out(sys.argv)")
+ pillow = text.find("from PIL import")
+ self.assertGreater(guard, 0, f"{name} does not call the font guard")
+ self.assertGreater(pillow, 0, f"{name} no longer imports Pillow, so this check would prove nothing")
+ self.assertLess(guard, pillow, f"{name} checks the font after importing Pillow")
+
+ def test_no_arguments_prints_the_two_it_takes(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ for name in CARD_SCRIPTS:
+ with self.subTest(script=name):
+ done = run([str(TOOLS / name)], tmp)
+ self.assertNotEqual(done.returncode, 0, f"{name} ran with no arguments")
+ self.assertIn("usage:", done.stderr, f"{name} does not print how it is called")
+ self.assertIn(name, done.stderr, f"{name}'s usage line does not name the script")
+ self.assertNotIn("Traceback", done.stderr, f"{name} still dies on a bare traceback")
+
+ def test_one_argument_is_not_enough(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ for name in CARD_SCRIPTS:
+ with self.subTest(script=name):
+ done = run([str(TOOLS / name), "Fredoka.ttf"], tmp)
+ self.assertIn("usage:", done.stderr, f"{name} took one argument as a full command")
+
+ def test_a_font_that_exists_gets_past_the_guard(self):
+ # The guard must not swallow a path that is there: the next thing that goes wrong is Pillow.
+ with tempfile.TemporaryDirectory() as tmp:
+ font = Path(tmp) / "Fredoka.ttf"
+ font.write_bytes(b"")
+ for name, picture in CARD_SCRIPTS.items():
+ with self.subTest(script=name):
+ done = run([str(TOOLS / name), str(font), str(Path(tmp) / picture)], tmp)
+ self.assertIn(NOT_THE_FONT, done.stderr, f"{name} rejected a font path that exists")
+ self.assertNotIn("cannot open the font at", done.stderr,
+ f"{name} still reports the font it was given")
+
+
+class GenTablesFontTest(unittest.TestCase):
+ """gen_tables.py --font runs two of those scripts, so it has to refuse a wrong path itself."""
+
+ def check(self, *args):
+ """`gen_tables.py <args> --check` on this tree."""
+ return subprocess.run([sys.executable, str(TOOLS / "gen_tables.py"), *args, "--check"],
+ cwd=ROOT, capture_output=True, text=True)
+
+ def test_a_font_that_is_not_there_is_refused_before_anything_is_written(self):
+ done = self.check("--font", "Fredoka.ttf")
+ self.assertEqual(done.returncode, 2, "gen_tables.py --font accepted a font that does not exist")
+ self.assertIn("Fredoka.ttf", done.stderr, "gen_tables.py does not name the font it could not open")
+ self.assertNotIn("Traceback", done.stderr, "gen_tables.py died with a traceback")
+
+ def test_an_existing_font_leaves_the_check_verdict_alone(self):
+ # The verdict itself is the branch's business, not this suite's: --check exits 0 where the tables
+ # are current (main, whose CI job runs it after merging) and 1 on any branch that adds a list
+ # folder, which is exactly what docs/workflows/tv-list.md tells a list PR to do - "a maintainer
+ # runs tools/gen_tables.py after merging". So what is held here is that handing --font does not
+ # change that verdict, and that neither run turns into a refusal or a traceback.
+ with tempfile.TemporaryDirectory() as tmp:
+ font = Path(tmp) / "Fredoka.ttf"
+ font.write_bytes(b"")
+ plain = self.check()
+ with_font = self.check("--font", str(font))
+ self.assertIn(plain.returncode, (0, 1),
+ f"gen_tables.py --check exited {plain.returncode}: {plain.stdout}{plain.stderr}")
+ self.assertNotIn("Traceback", plain.stdout + plain.stderr, "gen_tables.py --check died with a traceback")
+ self.assertEqual(with_font.returncode, plain.returncode,
+ "handing --font changed what --check says about the tables")
+
+
+COMMAND = re.compile(r"`(tools/readme_[\w]+\.py [^`]*)`") # a command: the script and what it is given
+
+
+class PressRecipeShapeTest(unittest.TestCase):
+ """The commands the page prints have to be the two-argument shape the scripts now insist on."""
+
+ def commands(self):
+ return COMMAND.findall(PRESS.read_text(encoding="utf-8"))
+
+ def test_the_page_prints_the_redraw_commands(self):
+ named = {cmd.split()[0] for cmd in self.commands()}
+ self.assertEqual({"tools/readme_featured.py", "tools/readme_card.py"}, named,
+ "press.md no longer prints both redraw commands, so this check would prove nothing")
+
+ def test_each_command_passes_two_arguments_and_writes_a_picture_the_repo_has(self):
+ for cmd in self.commands():
+ with self.subTest(command=cmd):
+ parts = cmd.split()
+ self.assertEqual(3, len(parts), f"press.md prints '{cmd}', which is not <script> <font> <picture>")
+ self.assertTrue((ROOT / parts[0]).is_file(), f"press.md names {parts[0]}, which is not in the repo")
+ self.assertTrue((ROOT / parts[2]).is_file(),
+ f"press.md writes {parts[2]}, which the repo does not ship")
+
+ def test_the_page_says_the_font_is_not_in_the_repo(self):
+ # The one fact a reader cannot get from the commands themselves: the font path is theirs to supply.
+ text = PRESS.read_text(encoding="utf-8")
+ self.assertIn("Google Fonts", text, "press.md prints a font path without saying where the font comes from")
+ self.assertIn("not in the repo", text, "press.md prints a font path without saying it is not in the repo")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_card_scripts.py b/tests/test_card_scripts.py
index 6ed3f7b9d..3e3d5eab1 100644
--- a/tests/test_card_scripts.py
+++ b/tests/test_card_scripts.py
@@ -30,11 +30,12 @@ TOOLS = ROOT / "tools"
PRESS = ROOT / "docs" / "workflows" / "press.md"
PERF = TOOLS / "requirements-perf.txt"
-# The scripts press.md sends a reader to, with the two arguments each takes: the font, then the file.
+# The scripts press.md sends a reader to, with the picture each one draws. The font they take is not in
+# the repo; the tests below pass a file that exists so the Pillow check is the one they reach.
CARD_SCRIPTS = {
- "readme_stats.py": ["Fredoka.ttf", "stats.png"],
- "readme_featured.py": ["Fredoka.ttf", "featured.png"],
- "readme_card.py": ["Fredoka.ttf", "card.jpg"],
+ "readme_stats.py": "stats.png",
+ "readme_featured.py": "featured.png",
+ "readme_card.py": "card.jpg",
}
@@ -60,10 +61,12 @@ class CardScriptsPillowTest(unittest.TestCase):
def test_each_card_script_is_importable_without_pillow_and_names_the_file(self):
with tempfile.TemporaryDirectory() as tmp:
- for name, args in CARD_SCRIPTS.items():
+ font = Path(tmp) / "Fredoka.ttf"
+ font.write_bytes(b"") # any font path that exists: the scripts check the font before Pillow
+ for name, picture in CARD_SCRIPTS.items():
with self.subTest(script=name):
self.assertTrue((TOOLS / name).is_file(), f"press.md names {name}, which is not in tools/")
- done = run_without_pillow([str(TOOLS / name), *args], tmp)
+ done = run_without_pillow([str(TOOLS / name), str(font), picture], tmp)
self.assertNotEqual(done.returncode, 0, f"{name} ran without Pillow, so the shadow missed it")
self.assertIn("requirements-perf.txt", done.stderr, f"{name} does not say where Pillow comes from")
self.assertNotIn("Traceback", done.stderr, f"{name} still dies on a bare traceback")
diff --git a/tools/gen_tables.py b/tools/gen_tables.py
index c97c390a1..dd28a27c3 100644
--- a/tools/gen_tables.py
+++ b/tools/gen_tables.py
@@ -281,9 +281,14 @@ def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--root", default=str(Path(__file__).resolve().parents[1]))
ap.add_argument("--check", action="store_true", help="write nothing; exit 1 when a file is out of date")
- ap.add_argument("--font", help="Fredoka TTF: redraw docs/stats.png and docs/card.jpg when a count changed")
+ ap.add_argument("--font", help="Fredoka TTF (variable, from Google Fonts; not in this repo): redraw "
+ "docs/stats.png and docs/card.jpg when a count changed")
ap.add_argument("--adopt", metavar="PATCH", help="write missing tv.json files from the rows in PATCH first")
a = ap.parse_args(argv)
+ if a.font and not Path(a.font).is_file():
+ # The scripts this hands the font to exit with their own line, but subprocess.run(check=True) would
+ # then turn that into a CalledProcessError traceback, which names neither the file nor where it is.
+ ap.error(f"cannot open the font at {a.font}: Fredoka (variable TTF, Google Fonts) is not in this repo")
root = Path(a.root)
try:
if a.adopt:
diff --git a/tools/readme_card.py b/tools/readme_card.py
index e1b850afa..956cd889e 100644
--- a/tools/readme_card.py
+++ b/tools/readme_card.py
@@ -3,16 +3,41 @@ the file the front page displays.
Run tools/readme_stats.py and tools/readme_featured.py first, then:
python3 tools/readme_card.py Fredoka.ttf docs/card.jpg
+Fredoka is the variable TTF from Google Fonts, and its file is not in this repo: pass the path of the
+copy you downloaded.
"""
+import os
import sys
+USAGE = ("usage: readme_card.py <font.ttf> <out.jpg>\n"
+ " Fredoka, the variable TTF from Google Fonts, is not in this repo: download it and pass the\n"
+ " path of the file you saved.")
+
+
+def font_and_out(argv):
+ """The font and the picture, or a usage line that says where the font comes from.
+
+ The font is the one argument a reader brings themselves: it is not in this repo, so a wrong path is
+ the first thing that fails here, and Pillow's `OSError: cannot open resource` names neither the file
+ it wanted nor where to get it.
+ """
+ if len(argv) != 3:
+ sys.exit(USAGE)
+ font, out = argv[1], argv[2]
+ if not os.path.isfile(font):
+ sys.exit(f"cannot open the font at {font}: Fredoka, the variable TTF from Google Fonts, is not in\n"
+ "this repo, so pass the path of the copy you downloaded")
+ return font, out
+
+
+FONT, OUT = font_and_out(sys.argv)
+
# See readme_stats.py: Pillow lives in the optional requirements file, so name it rather than crash.
try:
from PIL import Image, ImageDraw, ImageFilter, ImageFont
except ImportError:
sys.exit("readme_card.py needs Pillow: tools/venv/bin/pip install -r tools/requirements-perf.txt")
-FONT, OUT = sys.argv[1], sys.argv[2]
BG, LINE, DIM, GREEN = "#15181e", "#2c313a", "#aab3bd", "#cfffcf"
W = 1600
def f(size, wt):
diff --git a/tools/readme_featured.py b/tools/readme_featured.py
index 87d689fb3..ed267575c 100644
--- a/tools/readme_featured.py
+++ b/tools/readme_featured.py
@@ -1,16 +1,41 @@
"""Renders the Featured in panel (docs/featured.png), the middle part of the README card.
Update LOGOS / MORE, then: python3 tools/readme_featured.py Fredoka.ttf docs/featured.png
-and rebuild the card with tools/readme_card.py. Logos come from docs/press/."""
+and rebuild the card with tools/readme_card.py. Logos come from docs/press/. Fredoka is the variable TTF
+from Google Fonts, and its file is not in this repo: pass the path of the copy you downloaded.
+"""
+import os
import sys
+USAGE = ("usage: readme_featured.py <font.ttf> <out.png>\n"
+ " Fredoka, the variable TTF from Google Fonts, is not in this repo: download it and pass the\n"
+ " path of the file you saved.")
+
+
+def font_and_out(argv):
+ """The font and the picture, or a usage line that says where the font comes from.
+
+ The font is the one argument a reader brings themselves: it is not in this repo, so a wrong path is
+ the first thing that fails here, and Pillow's `OSError: cannot open resource` names neither the file
+ it wanted nor where to get it.
+ """
+ if len(argv) != 3:
+ sys.exit(USAGE)
+ font, out = argv[1], argv[2]
+ if not os.path.isfile(font):
+ sys.exit(f"cannot open the font at {font}: Fredoka, the variable TTF from Google Fonts, is not in\n"
+ "this repo, so pass the path of the copy you downloaded")
+ return font, out
+
+
+FONT, OUT = font_and_out(sys.argv)
+
# See readme_stats.py: Pillow lives in the optional requirements file, so name it rather than crash.
try:
from PIL import Image, ImageDraw, ImageFont
except ImportError:
sys.exit("readme_featured.py needs Pillow: tools/venv/bin/pip install -r tools/requirements-perf.txt")
-FONT, OUT = sys.argv[1], sys.argv[2]
LOGOS = ["techcrunch", "techradar", "tomsguide", "mashable", "androidauthority", "xda", "flatpanelshd", "itsfoss",
"phandroid", "gigazine", "xataka", "winfuture", "frandroid", "macitynet", "techaeris", "techpp"]
MORE = "+180 more · 196 articles from 32 countries"
diff --git a/tools/readme_stats.py b/tools/readme_stats.py
index 69302ddc3..dea59c0e6 100644
--- a/tools/readme_stats.py
+++ b/tools/readme_stats.py
@@ -1,9 +1,35 @@
"""Renders the stat strip (docs/stats.png), the top part of the README card.
Update STATS, then: python3 tools/readme_stats.py Fredoka.ttf docs/stats.png
-and rebuild the card with tools/readme_card.py. Fredoka is the variable TTF from Google Fonts."""
+and rebuild the card with tools/readme_card.py. Fredoka is the variable TTF from Google Fonts, and its
+file is not in this repo: download it and pass the path of the copy you saved.
+"""
+import os
import sys
+USAGE = ("usage: readme_stats.py <font.ttf> <out.png>\n"
+ " Fredoka, the variable TTF from Google Fonts, is not in this repo: download it and pass the\n"
+ " path of the file you saved.")
+
+
+def font_and_out(argv):
+ """The font and the picture, or a usage line that says where the font comes from.
+
+ The font is the one argument a reader brings themselves: it is not in this repo, so a wrong path is
+ the first thing that fails here, and Pillow's `OSError: cannot open resource` names neither the file
+ it wanted nor where to get it.
+ """
+ if len(argv) != 3:
+ sys.exit(USAGE)
+ font, out = argv[1], argv[2]
+ if not os.path.isfile(font):
+ sys.exit(f"cannot open the font at {font}: Fredoka, the variable TTF from Google Fonts, is not in\n"
+ "this repo, so pass the path of the copy you downloaded")
+ return font, out
+
+
+FONT, OUT = font_and_out(sys.argv)
+
# Pillow is not in tools/requirements.txt: it is only needed to redraw the README card, so point at the
# optional file the way tools/flamechart.py does, instead of ending in a bare traceback.
try:
@@ -11,7 +37,6 @@ try:
except ImportError:
sys.exit("readme_stats.py needs Pillow: tools/venv/bin/pip install -r tools/requirements-perf.txt")
-FONT, OUT = sys.argv[1], sys.argv[2]
STATS = [("280", "TV MODELS"), ("81", "BRANDS"), ("25", "LANGUAGES"), ("500 KB", "LAUNCHER")]
W, H = 1600, 240
img = Image.new("RGB", (W, H), "#15181e"); d = ImageDraw.Draw(img)