nsiswriter.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import itertools
  2. import operator
  3. import os
  4. import ntpath
  5. import re
  6. import sys
  7. import jinja2
  8. _PKGDIR = os.path.abspath(os.path.dirname(__file__))
  9. PY2 = sys.version_info[0] == 2
  10. class NSISFileWriter(object):
  11. """Write an .nsi script file by filling in a template.
  12. """
  13. def __init__(self, template_file, installerbuilder, definitions=None):
  14. """Instantiate an NSISFileWriter
  15. :param str template_file: Path to the .nsi template
  16. :param dict definitions: Mapping of name to value (values will be quoted)
  17. """
  18. env = jinja2.Environment(loader=jinja2.FileSystemLoader([
  19. _PKGDIR,
  20. os.getcwd()
  21. ]),
  22. # Change template markers from {}, which NSIS uses, to [], which it
  23. # doesn't much, so it's easier to distinguishing our templating from
  24. # NSIS preprocessor variables.
  25. block_start_string="[%",
  26. block_end_string="%]",
  27. variable_start_string="[[",
  28. variable_end_string="]]",
  29. comment_start_string="[#",
  30. comment_end_string="#]",
  31. )
  32. self.template = env.get_template(template_file)
  33. self.installerbuilder = installerbuilder
  34. self.namespace = {
  35. 'ib': installerbuilder,
  36. 'grouped_files': list(itertools.groupby(self.installerbuilder.install_files,
  37. operator.itemgetter(1))),
  38. 'icon': os.path.basename(installerbuilder.icon),
  39. 'arch_tag': '.amd64' if (installerbuilder.py_bitness==64) else '',
  40. 'pjoin': ntpath.join,
  41. 'single_shortcut': len(installerbuilder.shortcuts) == 1,
  42. }
  43. def write(self, target):
  44. """Fill out the template and write the result to 'target'.
  45. :param str target: Path to the file to be written
  46. """
  47. with open(target, 'w') as fout:
  48. fout.write(self.template.render(self.namespace))