paivana

HTTP paywall reverse proxy
Log | Files | Refs | Submodules | README | LICENSE

generate-paywall.py (2079B)


      1 #!/usr/bin/env python3
      2 import sys
      3 import os
      4 import jinja2
      5 
      6 
      7 def main():
      8     if len(sys.argv) < 3:
      9         print(f"Usage: {sys.argv[0]} <input_template> <output_file>", file=sys.stderr)
     10         sys.exit(1)
     11 
     12     input_template = sys.argv[1]
     13     output_file = sys.argv[2]
     14 
     15     # We resolve included files relative to the input template's directory.
     16     search_dir = os.path.dirname(os.path.abspath(input_template))
     17 
     18     # Set up jinja2 environment with custom delimiters.
     19     #
     20     # Delimiters are changed to avoid conflict with Mustache tags like
     21     # {{ merchant_backend }}: the output of this step is a Mustache
     22     # template rendered later by libtalertemplating, so {{ ... }} has to
     23     # survive verbatim.  The replacements have to be sequences that do
     24     # not occur in HTML, CSS or JavaScript; '@<' and '@#' are safe, and
     25     # note that CSS at-rules ('@media', '@keyframes') are not, so the
     26     # single-character '@' can never become a delimiter here.
     27     #
     28     # StrictUndefined makes a mistyped '@@ name @@' an error rather than
     29     # an empty string, and keep_trailing_newline keeps the file ending
     30     # in a newline the way the source template does.
     31     env = jinja2.Environment(
     32         loader=jinja2.FileSystemLoader(search_dir),
     33         variable_start_string="@@",
     34         variable_end_string="@@",
     35         block_start_string="@<",
     36         block_end_string=">@",
     37         comment_start_string="@#",
     38         comment_end_string="#@",
     39         undefined=jinja2.StrictUndefined,
     40         keep_trailing_newline=True,
     41     )
     42 
     43     template_name = os.path.basename(input_template)
     44     template = env.get_template(template_name)
     45 
     46     rendered = template.render()
     47 
     48     if not rendered.strip():
     49         print(f"{input_template} rendered to nothing", file=sys.stderr)
     50         sys.exit(1)
     51 
     52     # Ensure parent directory of output_file exists (especially in build directories).
     53     os.makedirs(os.path.dirname(os.path.abspath(output_file)), exist_ok=True)
     54 
     55     with open(output_file, "w", encoding="utf-8") as f:
     56         f.write(rendered)
     57 
     58 
     59 if __name__ == "__main__":
     60     main()