transform.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #
  2. # Asterisk -- An open source telephony toolkit.
  3. #
  4. # Copyright (C) 2013, Digium, Inc.
  5. #
  6. # David M. Lee, II <dlee@digium.com>
  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. import filecmp
  19. import os.path
  20. import pystache
  21. import shutil
  22. import tempfile
  23. import sys
  24. if sys.version_info[0] == 3:
  25. def unicode(v):
  26. return str(v)
  27. class Transform(object):
  28. """Transformation for template to code.
  29. """
  30. def __init__(self, template_file, dest_file_template_str, overwrite=True):
  31. """Ctor.
  32. @param template_file: Filename of the mustache template.
  33. @param dest_file_template_str: Destination file name. This is a
  34. mustache template, so each resource can write to a unique file.
  35. @param overwrite: If True, destination file is ovewritten if it exists.
  36. """
  37. template_str = unicode(open(template_file, "r").read())
  38. self.template = pystache.parse(template_str)
  39. dest_file_template_str = unicode(dest_file_template_str)
  40. self.dest_file_template = pystache.parse(dest_file_template_str)
  41. self.overwrite = overwrite
  42. def render(self, renderer, model, dest_dir):
  43. """Render a model according to this transformation.
  44. @param render: Pystache renderer.
  45. @param model: Model object to render.
  46. @param dest_dir: Destination directory to write generated code.
  47. """
  48. dest_file = pystache.render(self.dest_file_template, model)
  49. dest_file = os.path.join(dest_dir, dest_file)
  50. dest_exists = os.path.exists(dest_file)
  51. if dest_exists and not self.overwrite:
  52. return
  53. with tempfile.NamedTemporaryFile(mode='w+') as out:
  54. out.write(renderer.render(self.template, model))
  55. out.flush()
  56. if not dest_exists or not filecmp.cmp(out.name, dest_file):
  57. print("Writing %s" % dest_file)
  58. shutil.copyfile(out.name, dest_file)