tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

gen_from_jinja.py (1632B)


      1 # -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
      2 # vim: set filetype=python:
      3 # This Source Code Form is subject to the terms of the Mozilla Public
      4 # License, v. 2.0. If a copy of the MPL was not distributed with this
      5 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
      6 
      7 import os
      8 
      9 from jinja2 import Environment, FileSystemLoader, StrictUndefined
     10 
     11 
     12 def main(output_fd, input_filename, *args):
     13    # FileSystemLoader requires the path to the directory containing templates,
     14    # not the file name of the template itself. We hang onto the leaf name
     15    # which will shortly be passed to Environment.get_template.
     16    (path, leaf) = os.path.split(input_filename)
     17 
     18    # Jinja's default value for undefined is too permissive and would allow
     19    # omissions to slip into the generated output. We set undefined to
     20    # StrictUndefined to force Jinja to raise an exception any time a required
     21    # value is missing.
     22    env = Environment(
     23        loader=FileSystemLoader(path, encoding="utf-8"),
     24        autoescape=True,
     25        undefined=StrictUndefined,
     26    )
     27    tpl = env.get_template(leaf)
     28 
     29    context = dict()
     30 
     31    # args should all be key=value pairs that will be added to the context.
     32    # Note that all values are *strings*, so the Jinja template may need to
     33    # convert them to other types during processing.
     34    # (As in Python, the empty string is falsy, so simple boolean checks are possible)
     35    for arg in args:
     36        (k, v) = arg.split("=", 1)
     37        context[k] = v
     38 
     39    # Now run the template and send its output directly to output_fd
     40    tpl.stream(context).dump(output_fd, encoding="utf-8")