Asterisk - The Open Source Telephony Project  18.5.0
transform.py
Go to the documentation of this file.
1 #
2 # Asterisk -- An open source telephony toolkit.
3 #
4 # Copyright (C) 2013, Digium, Inc.
5 #
6 # David M. Lee, II <[email protected]>
7 #
8 # See http://www.asterisk.org for more information about
9 # the Asterisk project. Please do not directly contact
10 # any of the maintainers of this project for assistance;
11 # the project provides a web site, mailing lists and IRC
12 # channels for your use.
13 #
14 # This program is free software, distributed under the terms of
15 # the GNU General Public License Version 2. See the LICENSE file
16 # at the top of the source tree.
17 #
18 
19 import filecmp
20 import os.path
21 import pystache
22 import shutil
23 import tempfile
24 import sys
25 
26 if sys.version_info[0] == 3:
27  def unicode(v):
28  return str(v)
29 
30 
31 class Transform(object):
32  """Transformation for template to code.
33  """
34  def __init__(self, template_file, dest_file_template_str, overwrite=True):
35  """Ctor.
36 
37  @param template_file: Filename of the mustache template.
38  @param dest_file_template_str: Destination file name. This is a
39  mustache template, so each resource can write to a unique file.
40  @param overwrite: If True, destination file is ovewritten if it exists.
41  """
42  template_str = unicode(open(template_file, "r").read())
43  self.template = pystache.parse(template_str)
44  dest_file_template_str = unicode(dest_file_template_str)
45  self.dest_file_template = pystache.parse(dest_file_template_str)
46  self.overwrite = overwrite
47 
48  def render(self, renderer, model, dest_dir):
49  """Render a model according to this transformation.
50 
51  @param render: Pystache renderer.
52  @param model: Model object to render.
53  @param dest_dir: Destination directory to write generated code.
54  """
55  dest_file = pystache.render(self.dest_file_template, model)
56  dest_file = os.path.join(dest_dir, dest_file)
57  dest_exists = os.path.exists(dest_file)
58  if dest_exists and not self.overwrite:
59  return
60  with tempfile.NamedTemporaryFile(mode='w+') as out:
61  out.write(renderer.render(self.template, model))
62  out.flush()
63 
64  if not dest_exists or not filecmp.cmp(out.name, dest_file):
65  print("Writing %s" % dest_file)
66  shutil.copyfile(out.name, dest_file)
const char * str
Definition: app_jack.c:147
def __init__(self, template_file, dest_file_template_str, overwrite=True)
Definition: transform.py:34
def render(self, renderer, model, dest_dir)
Definition: transform.py:48
def unicode(v)
Definition: transform.py:27