__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. """Build NSIS installers for Python applications.
  2. """
  3. import errno
  4. import logging
  5. import ntpath
  6. import operator
  7. import os
  8. import re
  9. import shutil
  10. from subprocess import call
  11. import sys
  12. PY2 = sys.version_info[0] == 2
  13. if os.name == 'nt':
  14. if PY2:
  15. import _winreg as winreg
  16. else:
  17. import winreg
  18. else:
  19. winreg = None
  20. from .copymodules import copy_modules
  21. from .nsiswriter import NSISFileWriter
  22. from .util import download
  23. __version__ = '0.3'
  24. pjoin = os.path.join
  25. logger = logging.getLogger(__name__)
  26. _PKGDIR = os.path.abspath(os.path.dirname(__file__))
  27. DEFAULT_PY_VERSION = '2.7.6' if PY2 else '3.4.0'
  28. DEFAULT_BUILD_DIR = pjoin('build', 'nsis')
  29. DEFAULT_NSI_TEMPLATE = pjoin(_PKGDIR, 'template.nsi')
  30. DEFAULT_ICON = pjoin(_PKGDIR, 'glossyorb.ico')
  31. if os.name == 'nt' and sys.maxsize == (2**63)-1:
  32. DEFAULT_BITNESS = 64
  33. else:
  34. DEFAULT_BITNESS = 32
  35. class InputError(ValueError):
  36. def __init__(self, param, value, expected):
  37. self.param = param
  38. self.value = value
  39. self.expected = expected
  40. def __str__(self):
  41. return "{e.value!r} is not valid for {e.param}, expected {e.expected}".format(e=self)
  42. class InstallerBuilder(object):
  43. """Controls building an installer. This includes three main steps:
  44. 1. Arranging the necessary files in the build directory.
  45. 2. Filling out the template NSI file to control NSIS.
  46. 3. Running ``makensis`` to build the installer.
  47. :param str appname: Application name
  48. :param str version: Application version
  49. :param list shortcuts: List of dictionaries, with keys matching
  50. :ref:`shortcut_config` in the config file
  51. :param str icon: Path to an icon for the application
  52. :param list packages: List of strings for importable packages to include
  53. :param list extra_files: List of 2-tuples (file, destination) of files to include
  54. :param str py_version: Full version of Python to bundle
  55. :param int py_bitness: Bitness of bundled Python (32 or 64)
  56. :param str build_dir: Directory to run the build in
  57. :param str installer_name: Filename of the installer to produce
  58. :param str nsi_template: Path to a template NSI file to use
  59. """
  60. def __init__(self, appname, version, shortcuts, icon=DEFAULT_ICON,
  61. packages=None, extra_files=None, py_version=DEFAULT_PY_VERSION,
  62. py_bitness=DEFAULT_BITNESS, build_dir=DEFAULT_BUILD_DIR,
  63. installer_name=None, nsi_template=DEFAULT_NSI_TEMPLATE):
  64. self.appname = appname
  65. self.version = version
  66. self.shortcuts = shortcuts
  67. self.icon = icon
  68. self.packages = packages or []
  69. self.extra_files = extra_files or []
  70. self.py_version = py_version
  71. if not self._py_version_pattern.match(py_version):
  72. raise InputError('py_version', py_version, "a full Python version like '3.4.0'")
  73. self.py_bitness = py_bitness
  74. if py_bitness not in {32, 64}:
  75. raise InputError('py_bitness', py_bitness, "32 or 64")
  76. self.build_dir = build_dir
  77. self.installer_name = installer_name or self.make_installer_name()
  78. self.nsi_template = nsi_template
  79. self.nsi_file = pjoin(self.build_dir, 'installer.nsi')
  80. self.py_qualifier = '.'.join(self.py_version.split('.')[:2])
  81. if self.py_bitness == 32:
  82. self.py_qualifier += '-32'
  83. # To be filled later
  84. self.install_files = []
  85. self.install_dirs = []
  86. _py_version_pattern = re.compile(r'\d\.\d+\.\d+$')
  87. def make_installer_name(self):
  88. """Generate the filename of the installer exe
  89. e.g. My_App_1.0.exe
  90. """
  91. s = self.appname + '_' + self.version + '.exe'
  92. return s.replace(' ', '_')
  93. def fetch_python(self):
  94. """Fetch the MSI for the specified version of Python.
  95. It will be placed in the build directory.
  96. if possible.
  97. """
  98. version = self.py_version
  99. arch_tag = '.amd64' if (self.py_bitness==64) else ''
  100. url = 'https://python.org/ftp/python/{0}/python-{0}{1}.msi'.format(version, arch_tag)
  101. target = pjoin(self.build_dir, 'python-{0}{1}.msi'.format(version, arch_tag))
  102. if os.path.isfile(target):
  103. logger.info('Python MSI already in build directory.')
  104. return
  105. logger.info('Downloading Python MSI...')
  106. download(url, target)
  107. def fetch_pylauncher(self):
  108. """Fetch the MSI for PyLauncher (required for Python2.x).
  109. It will be placed in the build directory.
  110. """
  111. arch_tag = '.amd64' if (self.py_bitness == 64) else ''
  112. url = ("https://bitbucket.org/vinay.sajip/pylauncher/downloads/"
  113. "launchwin{0}.msi".format(arch_tag))
  114. target = pjoin(self.build_dir, 'launchwin{0}.msi'.format(arch_tag))
  115. if os.path.isfile(target):
  116. logger.info('PyLauncher MSI already in build directory.')
  117. return
  118. logger.info('Downloading PyLauncher MSI...')
  119. download(url, target)
  120. SCRIPT_TEMPLATE = """#!python{qualifier}
  121. import sys, os
  122. scriptdir, script = os.path.split(__file__)
  123. pkgdir = os.path.join(scriptdir, 'pkgs')
  124. sys.path.insert(0, pkgdir)
  125. os.environ['PYTHONPATH'] = pkgdir + os.pathsep + os.environ.get('PYTHONPATH', '')
  126. def excepthook(etype, value, tb):
  127. "Write unhandled exceptions to a file rather than exiting silently."
  128. import traceback
  129. with open(os.path.join(scriptdir, script+'.log'), 'w') as f:
  130. traceback.print_exception(etype, value, tb, file=f)
  131. sys.excepthook = excepthook
  132. from {module} import {func}
  133. {func}()
  134. """
  135. def write_script(self, entrypt, target):
  136. """Write a launcher script from a 'module:function' entry point
  137. python_version and bitness are used to write an appropriate shebang line
  138. for the PEP 397 Windows launcher.
  139. """
  140. module, func = entrypt.split(":")
  141. with open(target, 'w') as f:
  142. f.write(self.SCRIPT_TEMPLATE.format(qualifier=self.py_qualifier,
  143. module=module, func=func))
  144. pkg = module.split('.')[0]
  145. if pkg not in self.packages:
  146. self.packages.append(pkg)
  147. def prepare_shortcuts(self):
  148. """Prepare shortcut files in the build directory.
  149. If entry_point is specified, write the script. If script is specified,
  150. copy to the build directory. Prepare target and parameters for these
  151. shortcuts.
  152. Also copies shortcut icons
  153. """
  154. files = set()
  155. for scname, sc in self.shortcuts.items():
  156. if not sc.get('target'):
  157. if sc.get('entry_point'):
  158. sc['script'] = script = scname.replace(' ', '_') + '.launch.py' \
  159. + ('' if sc['console'] else 'w')
  160. self.write_script(sc['entry_point'], pjoin(self.build_dir, script))
  161. else:
  162. shutil.copy2(sc['script'], self.build_dir)
  163. sc['target'] = 'py' if sc['console'] else 'pyw'
  164. sc['parameters'] = '"%s"' % ntpath.join('$INSTDIR', sc['script'])
  165. files.add(os.path.basename(sc['script']))
  166. shutil.copy2(sc['icon'], self.build_dir)
  167. sc['icon'] = os.path.basename(sc['icon'])
  168. files.add(sc['icon'])
  169. self.install_files.extend([(f, '$INSTDIR') for f in files])
  170. def prepare_packages(self):
  171. """Move requested packages into the build directory.
  172. If a pynsist_pkgs directory exists, it is copied into the build
  173. directory as pkgs/ . Any packages not already there are found on
  174. sys.path and copied in.
  175. """
  176. logger.info("Copying packages into build directory...")
  177. build_pkg_dir = pjoin(self.build_dir, 'pkgs')
  178. if os.path.isdir(build_pkg_dir):
  179. shutil.rmtree(build_pkg_dir)
  180. if os.path.isdir('pynsist_pkgs'):
  181. shutil.copytree('pynsist_pkgs', build_pkg_dir)
  182. else:
  183. os.mkdir(build_pkg_dir)
  184. copy_modules(self.packages, build_pkg_dir, py_version=self.py_version)
  185. def copy_extra_files(self):
  186. """Copy a list of files into the build directory, and add them to
  187. install_files or install_dirs as appropriate.
  188. """
  189. for file, destination in self.extra_files:
  190. file = file.rstrip('/\\')
  191. basename = os.path.basename(file)
  192. if not destination:
  193. destination = '$INSTDIR'
  194. if os.path.isdir(file):
  195. target_name = pjoin(self.build_dir, basename)
  196. if os.path.isdir(target_name):
  197. shutil.rmtree(target_name)
  198. elif os.path.exists(target_name):
  199. os.unlink(target_name)
  200. shutil.copytree(file, target_name)
  201. self.install_dirs.append((basename, destination))
  202. else:
  203. shutil.copy2(file, self.build_dir)
  204. self.install_files.append((basename, destination))
  205. def write_nsi(self):
  206. """Write the NSI file to define the NSIS installer.
  207. Most of the details of this are in the template and the
  208. :class:`nsist.nsiswriter.NSISFileWriter` class.
  209. """
  210. nsis_writer = NSISFileWriter(self.nsi_template, installerbuilder=self,
  211. definitions = {'PRODUCT_NAME': self.appname,
  212. 'PRODUCT_VERSION': self.version,
  213. 'PY_VERSION': self.py_version,
  214. 'PY_QUALIFIER': self.py_qualifier,
  215. 'PRODUCT_ICON': os.path.basename(self.icon),
  216. 'INSTALLER_NAME': self.installer_name,
  217. 'ARCH_TAG': '.amd64' if (self.py_bitness==64) else '',
  218. },
  219. )
  220. logger.info('Writing NSI file to %s', self.nsi_file)
  221. # Sort by destination directory, so we can group them effectively
  222. self.install_files.sort(key=operator.itemgetter(1))
  223. nsis_writer.write(self.nsi_file)
  224. def run_nsis(self):
  225. """Runs makensis using the specified .nsi file
  226. Returns the exit code.
  227. """
  228. try:
  229. if os.name == 'nt':
  230. makensis = pjoin(winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\NSIS'),
  231. 'makensis.exe')
  232. else:
  233. makensis = 'makensis'
  234. return call([makensis, self.nsi_file])
  235. except OSError as e:
  236. # This should catch either the registry key or makensis being absent
  237. if e.errno == errno.ENOENT:
  238. print("makensis was not found. Install NSIS and try again.")
  239. print("http://nsis.sourceforge.net/Download")
  240. return 1
  241. def run(self):
  242. """Run all the steps to build an installer.
  243. """
  244. try:
  245. os.makedirs(self.build_dir)
  246. except OSError as e:
  247. if e.errno != errno.EEXIST:
  248. raise e
  249. self.fetch_python()
  250. if self.py_version < '3.3':
  251. self.fetch_pylauncher()
  252. self.prepare_shortcuts()
  253. # Packages
  254. self.prepare_packages()
  255. # Extra files
  256. self.copy_extra_files()
  257. self.write_nsi()
  258. exitcode = self.run_nsis()
  259. if not exitcode:
  260. logger.info('Installer written to %s', pjoin(self.build_dir, self.installer_name))
  261. def main(argv=None):
  262. """Make an installer from the command line.
  263. This parses command line arguments and a config file, and calls
  264. :func:`all_steps` with the extracted information.
  265. """
  266. logger.setLevel(logging.INFO)
  267. logger.handlers = [logging.StreamHandler()]
  268. import argparse
  269. argp = argparse.ArgumentParser(prog='pynsist')
  270. argp.add_argument('config_file')
  271. options = argp.parse_args(argv)
  272. dirname, config_file = os.path.split(options.config_file)
  273. if dirname:
  274. os.chdir(dirname)
  275. try:
  276. from . import configreader
  277. cfg = configreader.read_and_validate(config_file)
  278. shortcuts = configreader.read_shortcuts_config(cfg)
  279. except configreader.InvalidConfig as e:
  280. logger.error('Error parsing configuration file:')
  281. logger.error(str(e))
  282. sys.exit(1)
  283. appcfg = cfg['Application']
  284. try:
  285. InstallerBuilder(
  286. appname = appcfg['name'],
  287. version = appcfg['version'],
  288. icon = appcfg.get('icon', DEFAULT_ICON),
  289. shortcuts = shortcuts,
  290. packages = cfg.get('Include', 'packages', fallback='').splitlines(),
  291. extra_files = configreader.read_extra_files(cfg),
  292. py_version = cfg.get('Python', 'version', fallback=DEFAULT_PY_VERSION),
  293. py_bitness = cfg.getint('Python', 'bitness', fallback=DEFAULT_BITNESS),
  294. build_dir = cfg.get('Build', 'directory', fallback=DEFAULT_BUILD_DIR),
  295. installer_name = cfg.get('Build', 'installer_name', fallback=None),
  296. nsi_template = cfg.get('Build', 'nsi_template', fallback=DEFAULT_NSI_TEMPLATE),
  297. ).run()
  298. except InputError as e:
  299. logger.error("Error in config values:")
  300. logger.error(str(e))
  301. sys.exit(1)