nsiswriter.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import itertools
  2. from operator import itemgetter
  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. # Trim whitespace around block tags, so formatting works as I expect
  32. trim_blocks=True,
  33. lstrip_blocks=True,
  34. )
  35. self.template = env.get_template(template_file)
  36. self.installerbuilder = installerbuilder
  37. # Group files by their destination directory
  38. grouped_files = [(dest, [x[0] for x in group]) for (dest, group) in
  39. itertools.groupby(self.installerbuilder.install_files, itemgetter(1))
  40. ]
  41. self.namespace = {
  42. 'ib': installerbuilder,
  43. 'grouped_files': grouped_files,
  44. 'icon': os.path.basename(installerbuilder.icon),
  45. 'arch_tag': '.amd64' if (installerbuilder.py_bitness==64) else '',
  46. 'pjoin': ntpath.join,
  47. 'single_shortcut': len(installerbuilder.shortcuts) == 1,
  48. 'pynsist_pkg_dir': _PKGDIR,
  49. 'has_commands': len(installerbuilder.commands) > 0,
  50. 'python': '"$INSTDIR\\Python\\python"'
  51. }
  52. def write(self, target):
  53. """Fill out the template and write the result to 'target'.
  54. :param str target: Path to the file to be written
  55. """
  56. with open(target, 'w') as fout:
  57. fout.write(self.template.render(self.namespace))