Coverage for app/backend/src/couchers/email/dump_emails.py: 86%
78 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-27 22:43 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-27 22:43 +0000
1"""
2Dumps emails subjects and html/plaintext bodies with dummy data in every supported
3locale, plus a browsable HTML index with a locale selector and expandable previews.
5All bodies are gzipped and inlined, so the index is a single self-contained page.
6"""
8import base64
9import gzip
10import inspect
11import json
12import re
13import shutil
14import sys
15from argparse import ArgumentParser
16from dataclasses import dataclass
17from datetime import UTC
18from pathlib import Path
20from markupsafe import Markup
22import couchers.email.emails
23from couchers.email.blocks import (
24 EmailBase,
25 EmailFooter,
26 UnsubscribeInfo,
27 UnsubscribeLink,
28)
29from couchers.email.rendering import render_email, template_folder
30from couchers.i18n import LocalizationContext
31from couchers.i18n.locales import DEFAULT_LOCALE, get_locales_with_translations
32from couchers.templating import Jinja2Template
35@dataclass
36class CommandLineArgs:
37 filter: str
38 outdir: Path
39 locales: str
41 @staticmethod
42 def parse(args: list[str]) -> CommandLineArgs:
43 parser = ArgumentParser(description=__doc__)
44 parser.add_argument("--filter", type=str, default="*", help="A filter for email classes to dump.")
45 parser.add_argument(
46 "--outdir", type=Path, default=template_folder, help="The directory to write email bodies to."
47 )
48 parser.add_argument(
49 "--locales",
50 type=str,
51 default="all",
52 help='Comma-separated locales to render, or "all" for every supported locale.',
53 )
54 parsed_args = parser.parse_args(args)
55 return CommandLineArgs(**parsed_args.__dict__)
58@dataclass
59class RenderedVariation:
60 email_class: str
61 variation: int
62 variation_count: int
63 subjects: dict[str, str] # locale -> subject line
64 name: str
67def _ordered_locales(locales: list[str] | None) -> list[str]:
68 if locales is None:
69 locales = get_locales_with_translations()
70 return sorted(locales, key=lambda locale: (locale != DEFAULT_LOCALE, locale))
73def dump_all(outdir: Path, *, filter_glob: str = "*", locales: list[str] | None = None) -> list[RenderedVariation]:
74 """Dumps all emails matching the filter into a single self-contained outdir/index.html,
75 a browsable index with a locale selector and expandable previews.
77 Requires the relevant config (e.g. BASE_URL) to be available, as when run inside the
78 test harness or with the deployment environment loaded.
79 """
80 locales = _ordered_locales(locales)
81 footer = EmailFooter(
82 unsubscribe_info=UnsubscribeInfo(
83 manage_notifications_url="https://example.com/manage-notifications",
84 do_not_email_url="https://example.com/do-not-email",
85 topic_action_link=UnsubscribeLink(text="topic-action", url="https://example.com/unsubscribe"),
86 ),
87 )
88 filter_regex = re.compile(re.escape(filter_glob).replace(r"\*", ".*?"))
90 rendered: list[RenderedVariation] = []
91 bodies: dict[str, dict[str, dict[str, str]]] = {locale: {} for locale in locales}
92 # Iterate over all email classes and dump their test instances if they match the filter
93 for _, klass in inspect.getmembers(couchers.email.emails, lambda o: inspect.isclass(o) and o.__base__ == EmailBase):
94 email_class: type[EmailBase] = klass
95 if filter_regex.fullmatch(email_class.__name__): 95 ↛ 93line 95 didn't jump to line 93 because the condition on line 95 was always true
96 test_instances = email_class.test_instances()
97 for i in range(len(test_instances)):
98 name = email_class.__name__
99 if len(test_instances) > 1:
100 name += f"_{i}"
101 print(f"Dumping email class {email_class.__name__} ({len(locales)} locale(s))")
102 subjects = {}
103 for locale in locales:
104 loc_context = LocalizationContext(locale=locale, timezone=UTC)
105 email = render_email(test_instances[i], footer, loc_context, embed_images=False)
106 subjects[locale] = email.subject
107 bodies[locale][name] = {"html": email.body_html, "txt": email.body_plaintext}
108 rendered.append(
109 RenderedVariation(
110 email_class=email_class.__name__,
111 variation=i,
112 variation_count=len(test_instances),
113 subjects=subjects,
114 name=name,
115 )
116 )
118 outdir.mkdir(parents=True, exist_ok=True)
119 if rendered: 119 ↛ 122line 119 didn't jump to line 122 because the condition on line 119 was always true
120 shutil.copytree(template_folder / "attachment_imgs", outdir / "attachment_imgs", dirs_exist_ok=True)
122 write_index(outdir / "index.html", rendered, locales, bodies)
123 return rendered
126def compress_bodies(bodies: dict[str, dict[str, str]]) -> str:
127 return base64.b64encode(gzip.compress(json.dumps(bodies, ensure_ascii=False).encode())).decode()
130def write_index(
131 index_path: Path,
132 rendered: list[RenderedVariation],
133 locales: list[str],
134 bodies: dict[str, dict[str, dict[str, str]]],
135) -> None:
136 """Writes a self-contained HTML index with a locale selector and an accordion entry per
137 rendered email variation, expanding to side-by-side HTML and plaintext previews."""
138 rendered = sorted(rendered, key=lambda r: (r.email_class, r.variation))
140 def embed(value: object) -> Markup:
141 # Guard against a literal "</script>" in the data breaking out of the script tag
142 return Markup(json.dumps(value, ensure_ascii=False).replace("</", "<\\/"))
144 template = Jinja2Template(
145 source=(Path(__file__).parent / "dump_emails_index.html.jinja2").read_text(encoding="utf-8"), html=True
146 )
147 index_html = template.render(
148 {
149 "rendered": rendered,
150 "locales": locales,
151 "class_count": len({r.email_class for r in rendered}),
152 "subjects_json": embed({r.name: r.subjects for r in rendered}),
153 "payloads_json": embed({locale: compress_bodies(bodies[locale]) for locale in locales}),
154 }
155 )
156 index_path.parent.mkdir(parents=True, exist_ok=True)
157 index_path.write_text(index_html, encoding="utf-8")
158 print(f"Wrote index of {len(rendered)} variation(s) in {len(locales)} locale(s) to {index_path}")
161def main() -> None:
162 args = CommandLineArgs.parse(sys.argv[1:])
163 locales = None if args.locales == "all" else args.locales.split(",")
164 dump_all(args.outdir, filter_glob=args.filter, locales=locales)
167if __name__ == "__main__": 167 ↛ 168line 167 didn't jump to line 168 because the condition on line 167 was never true
168 main()