__init__.py 13 KB

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