__init__.py 15 KB

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