__init__.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. from pathlib import Path
  10. import re
  11. import shutil
  12. from subprocess import call
  13. import sys
  14. import fnmatch
  15. import zipfile
  16. PY2 = sys.version_info[0] == 2
  17. if os.name == 'nt':
  18. if PY2:
  19. import _winreg as winreg
  20. else:
  21. import winreg
  22. else:
  23. winreg = None
  24. from .configreader import get_installer_builder_args
  25. from .commands import prepare_bin_directory
  26. from .copymodules import copy_modules
  27. from .nsiswriter import NSISFileWriter
  28. from .pypi import fetch_pypi_wheels
  29. from .util import download, text_types, get_cache_dir
  30. __version__ = '1.10'
  31. pjoin = os.path.join
  32. logger = logging.getLogger(__name__)
  33. _PKGDIR = os.path.abspath(os.path.dirname(__file__))
  34. DEFAULT_PY_VERSION = '2.7.13' if PY2 else '3.6.0'
  35. DEFAULT_BUILD_DIR = pjoin('build', 'nsis')
  36. DEFAULT_ICON = pjoin(_PKGDIR, 'glossyorb.ico')
  37. if os.name == 'nt' and sys.maxsize == (2**63)-1:
  38. DEFAULT_BITNESS = 64
  39. else:
  40. DEFAULT_BITNESS = 32
  41. def find_makensis_win():
  42. """Locate makensis.exe on Windows by querying the registry"""
  43. try:
  44. nsis_install_dir = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\NSIS')
  45. except OSError:
  46. nsis_install_dir = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432Node\\NSIS')
  47. return pjoin(nsis_install_dir, 'makensis.exe')
  48. class InputError(ValueError):
  49. def __init__(self, param, value, expected):
  50. self.param = param
  51. self.value = value
  52. self.expected = expected
  53. def __str__(self):
  54. return "{e.value!r} is not valid for {e.param}, expected {e.expected}".format(e=self)
  55. class InstallerBuilder(object):
  56. """Controls building an installer. This includes three main steps:
  57. 1. Arranging the necessary files in the build directory.
  58. 2. Filling out the template NSI file to control NSIS.
  59. 3. Running ``makensis`` to build the installer.
  60. :param str appname: Application name
  61. :param str version: Application version
  62. :param dict shortcuts: Dictionary keyed by shortcut name, containing
  63. dictionaries whose keys match the fields of :ref:`shortcut_config`
  64. in the config file
  65. :param str icon: Path to an icon for the application
  66. :param list packages: List of strings for importable packages to include
  67. :param dict commands: Dictionary keyed by command name, containing dicts
  68. defining the commands, as in the config file.
  69. :param list pypi_wheel_reqs: Package specifications to fetch from PyPI as wheels
  70. :param list extra_files: List of 2-tuples (file, destination) of files to include
  71. :param list exclude: Paths of files to exclude that would otherwise be included
  72. :param str py_version: Full version of Python to bundle
  73. :param int py_bitness: Bitness of bundled Python (32 or 64)
  74. :param str py_format: 'installer' or 'bundled'. Default 'bundled' for Python
  75. >= 3.6, 'installer' for older versions.
  76. :param bool inc_msvcrt: True to include the Microsoft C runtime with 'bundled'
  77. Python. Ignored when py_format='installer'.
  78. :param str build_dir: Directory to run the build in
  79. :param str installer_name: Filename of the installer to produce
  80. :param str nsi_template: Path to a template NSI file to use
  81. """
  82. def __init__(self, appname, version, shortcuts, publisher=None,
  83. icon=DEFAULT_ICON, packages=None, extra_files=None,
  84. py_version=DEFAULT_PY_VERSION, py_bitness=DEFAULT_BITNESS,
  85. py_format=None, inc_msvcrt=True, build_dir=DEFAULT_BUILD_DIR,
  86. installer_name=None, nsi_template=None,
  87. exclude=None, pypi_wheel_reqs=None, commands=None):
  88. self.appname = appname
  89. self.version = version
  90. self.publisher = publisher
  91. self.shortcuts = shortcuts
  92. self.icon = icon
  93. self.packages = packages or []
  94. self.exclude = [os.path.normpath(p) for p in (exclude or [])]
  95. self.extra_files = extra_files or []
  96. self.pypi_wheel_reqs = pypi_wheel_reqs or []
  97. self.commands = commands or {}
  98. # Python options
  99. self.py_version = py_version
  100. if not self._py_version_pattern.match(py_version):
  101. if not os.environ.get('PYNSIST_PY_PRERELEASE'):
  102. raise InputError('py_version', py_version,
  103. "a full Python version like '3.4.0'")
  104. self.py_bitness = py_bitness
  105. if py_bitness not in {32, 64}:
  106. raise InputError('py_bitness', py_bitness, "32 or 64")
  107. self.py_major_version = self.py_qualifier = '.'.join(self.py_version.split('.')[:2])
  108. if self.py_bitness == 32:
  109. self.py_qualifier += '-32'
  110. if py_format is not None:
  111. self.py_format = py_format
  112. elif self.py_version_tuple >= (3, 6):
  113. self.py_format = 'bundled'
  114. else:
  115. self.py_format = 'installer'
  116. if self.py_version_tuple >= (3, 5):
  117. if self.py_format not in {'installer', 'bundled'}:
  118. raise InputError('py_format', self.py_format, "installer or bundled")
  119. else:
  120. if self.py_format != 'installer':
  121. raise InputError('py_format', self.py_format, "installer (for Python < 3.5)")
  122. self.inc_msvcrt = inc_msvcrt
  123. # Build details
  124. self.build_dir = build_dir
  125. self.installer_name = installer_name or self.make_installer_name()
  126. self.nsi_template = nsi_template
  127. if self.nsi_template is None:
  128. if self.py_format == 'bundled':
  129. if self.inc_msvcrt:
  130. self.nsi_template = 'pyapp_msvcrt.nsi'
  131. else:
  132. self.nsi_template = 'pyapp.nsi'
  133. elif self.py_version_tuple < (3, 3):
  134. self.nsi_template = 'pyapp_w_pylauncher.nsi'
  135. else:
  136. self.nsi_template = 'pyapp_installpy.nsi'
  137. self.nsi_file = pjoin(self.build_dir, 'installer.nsi')
  138. # To be filled later
  139. self.install_files = []
  140. self.install_dirs = []
  141. self.msvcrt_files = []
  142. _py_version_pattern = re.compile(r'\d\.\d+\.\d+$')
  143. @property
  144. def py_version_tuple(self):
  145. parts = self.py_version.split('.')
  146. return int(parts[0]), int(parts[1])
  147. def make_installer_name(self):
  148. """Generate the filename of the installer exe
  149. e.g. My_App_1.0.exe
  150. """
  151. s = self.appname + '_' + self.version + '.exe'
  152. return s.replace(' ', '_')
  153. def _python_download_url_filename(self):
  154. version = self.py_version
  155. bitness = self.py_bitness
  156. if self.py_version_tuple >= (3, 5):
  157. if self.py_format == 'bundled':
  158. filename = 'python-{}-embed-{}.zip'.format(version,
  159. 'amd64' if bitness==64 else 'win32')
  160. else:
  161. filename = 'python-{}{}.exe'.format(version,
  162. '-amd64' if bitness==64 else '')
  163. else:
  164. filename = 'python-{0}{1}.msi'.format(version,
  165. '.amd64' if bitness==64 else '')
  166. version_minus_prerelease = re.sub(r'(a|b|rc)\d+$', '', self.py_version)
  167. return 'https://www.python.org/ftp/python/{0}/{1}'.format(
  168. version_minus_prerelease, filename), filename
  169. def fetch_python(self):
  170. """Fetch the MSI for the specified version of Python.
  171. It will be placed in the build directory.
  172. """
  173. url, filename = self._python_download_url_filename()
  174. cache_file = get_cache_dir(ensure_existence=True) / filename
  175. if not cache_file.is_file():
  176. logger.info('Downloading Python installer...')
  177. logger.info('Getting %s', url)
  178. download(url, cache_file)
  179. logger.info('Copying Python installer to build directory')
  180. shutil.copy2(str(cache_file), self.build_dir)
  181. def fetch_python_embeddable(self):
  182. url, filename = self._python_download_url_filename()
  183. cache_file = get_cache_dir(ensure_existence=True) / filename
  184. if not cache_file.is_file():
  185. logger.info('Downloading embeddable Python build...')
  186. logger.info('Getting %s', url)
  187. download(url, cache_file)
  188. logger.info('Unpacking Python...')
  189. python_dir = pjoin(self.build_dir, 'Python')
  190. try:
  191. shutil.rmtree(python_dir)
  192. except OSError as e:
  193. if e.errno != errno.ENOENT:
  194. raise
  195. with zipfile.ZipFile(str(cache_file)) as z:
  196. z.extractall(python_dir)
  197. self.install_dirs.append(('Python', '$INSTDIR'))
  198. def prepare_msvcrt(self):
  199. arch = 'x64' if self.py_bitness == 64 else 'x86'
  200. src = pjoin(_PKGDIR, 'msvcrt', arch)
  201. dst = pjoin(self.build_dir, 'msvcrt')
  202. self.msvcrt_files = sorted(os.listdir(src))
  203. try:
  204. shutil.rmtree(dst)
  205. except OSError as e:
  206. if e.errno != errno.ENOENT:
  207. raise
  208. shutil.copytree(src, dst)
  209. def fetch_pylauncher(self):
  210. """Fetch the MSI for PyLauncher (required for Python2.x).
  211. It will be placed in the build directory.
  212. """
  213. arch_tag = '.amd64' if (self.py_bitness == 64) else ''
  214. url = ("https://bitbucket.org/vinay.sajip/pylauncher/downloads/"
  215. "launchwin{0}.msi".format(arch_tag))
  216. target = pjoin(self.build_dir, 'launchwin{0}.msi'.format(arch_tag))
  217. if os.path.isfile(target):
  218. logger.info('PyLauncher MSI already in build directory.')
  219. return
  220. logger.info('Downloading PyLauncher MSI...')
  221. download(url, target)
  222. SCRIPT_TEMPLATE = """#!python{qualifier}
  223. import sys, os
  224. scriptdir, script = os.path.split(__file__)
  225. pkgdir = os.path.join(scriptdir, 'pkgs')
  226. sys.path.insert(0, pkgdir)
  227. os.environ['PYTHONPATH'] = pkgdir + os.pathsep + os.environ.get('PYTHONPATH', '')
  228. # APPDATA should always be set, but in case it isn't, try user home
  229. # If none of APPDATA, HOME, USERPROFILE or HOMEPATH are set, this will fail.
  230. appdata = os.environ.get('APPDATA', None) or os.path.expanduser('~')
  231. if 'pythonw' in sys.executable:
  232. # Running with no console - send all stdstream output to a file.
  233. kw = {{'errors': 'replace'}} if (sys.version_info[0] >= 3) else {{}}
  234. sys.stdout = sys.stderr = open(os.path.join(appdata, script+'.log'), 'w', **kw)
  235. else:
  236. # In a console. But if the console was started just for this program, it
  237. # will close as soon as we exit, so write the traceback to a file as well.
  238. def excepthook(etype, value, tb):
  239. "Write unhandled exceptions to a file and to stderr."
  240. import traceback
  241. traceback.print_exception(etype, value, tb)
  242. with open(os.path.join(appdata, script+'.log'), 'w') as f:
  243. traceback.print_exception(etype, value, tb, file=f)
  244. sys.excepthook = excepthook
  245. {extra_preamble}
  246. if __name__ == '__main__':
  247. from {module} import {func}
  248. {func}()
  249. """
  250. def write_script(self, entrypt, target, extra_preamble=''):
  251. """Write a launcher script from a 'module:function' entry point
  252. py_version and py_bitness are used to write an appropriate shebang line
  253. for the PEP 397 Windows launcher.
  254. """
  255. module, func = entrypt.split(":")
  256. with open(target, 'w') as f:
  257. f.write(self.SCRIPT_TEMPLATE.format(qualifier=self.py_qualifier,
  258. module=module, func=func, extra_preamble=extra_preamble))
  259. pkg = module.split('.')[0]
  260. if pkg not in self.packages:
  261. self.packages.append(pkg)
  262. def prepare_shortcuts(self):
  263. """Prepare shortcut files in the build directory.
  264. If entry_point is specified, write the script. If script is specified,
  265. copy to the build directory. Prepare target and parameters for these
  266. shortcuts.
  267. Also copies shortcut icons
  268. """
  269. files = set()
  270. for scname, sc in self.shortcuts.items():
  271. if not sc.get('target'):
  272. if sc.get('entry_point'):
  273. sc['script'] = script = scname.replace(' ', '_') + '.launch.py' \
  274. + ('' if sc['console'] else 'w')
  275. specified_preamble = sc.get('extra_preamble', None)
  276. if isinstance(specified_preamble, text_types):
  277. # Filename
  278. extra_preamble = io.open(specified_preamble, encoding='utf-8')
  279. elif specified_preamble is None:
  280. extra_preamble = io.StringIO() # Empty
  281. else:
  282. # Passed a StringIO or similar object
  283. extra_preamble = specified_preamble
  284. self.write_script(sc['entry_point'], pjoin(self.build_dir, script),
  285. extra_preamble.read().rstrip())
  286. else:
  287. shutil.copy2(sc['script'], self.build_dir)
  288. if self.py_format == 'bundled':
  289. target = '$INSTDIR\Python\python{}.exe'
  290. else:
  291. target = 'py{}'
  292. sc['target'] = target.format('' if sc['console'] else 'w')
  293. sc['parameters'] = '"%s"' % ntpath.join('$INSTDIR', sc['script'])
  294. files.add(os.path.basename(sc['script']))
  295. shutil.copy2(sc['icon'], self.build_dir)
  296. sc['icon'] = os.path.basename(sc['icon'])
  297. files.add(sc['icon'])
  298. self.install_files.extend([(f, '$INSTDIR') for f in files])
  299. def prepare_packages(self):
  300. """Move requested packages into the build directory.
  301. If a pynsist_pkgs directory exists, it is copied into the build
  302. directory as pkgs/ . Any packages not already there are found on
  303. sys.path and copied in.
  304. """
  305. logger.info("Copying packages into build directory...")
  306. build_pkg_dir = pjoin(self.build_dir, 'pkgs')
  307. if os.path.isdir(build_pkg_dir):
  308. shutil.rmtree(build_pkg_dir)
  309. # 1. Manually prepared packages
  310. if os.path.isdir('pynsist_pkgs'):
  311. shutil.copytree('pynsist_pkgs', build_pkg_dir)
  312. else:
  313. os.mkdir(build_pkg_dir)
  314. # 2. Wheels from PyPI
  315. fetch_pypi_wheels(self.pypi_wheel_reqs, build_pkg_dir,
  316. py_version=self.py_version, bitness=self.py_bitness)
  317. # 3. Copy importable modules
  318. copy_modules(self.packages, build_pkg_dir,
  319. py_version=self.py_version, exclude=self.exclude)
  320. def prepare_commands(self):
  321. command_dir = Path(self.build_dir) / 'bin'
  322. if command_dir.is_dir():
  323. shutil.rmtree(str(command_dir))
  324. command_dir.mkdir()
  325. prepare_bin_directory(command_dir, self.commands, bitness=self.py_bitness)
  326. self.install_dirs.append((command_dir.name, '$INSTDIR'))
  327. self.extra_files.append((pjoin(_PKGDIR, '_system_path.py'), '$INSTDIR'))
  328. self.extra_files.append((pjoin(_PKGDIR, '_rewrite_shebangs.py'), '$INSTDIR'))
  329. def copytree_ignore_callback(self, directory, files):
  330. """This is being called back by our shutil.copytree call to implement the
  331. 'exclude' feature.
  332. """
  333. ignored = set()
  334. # Filter by file names relative to the build directory
  335. directory = os.path.normpath(directory)
  336. files = [os.path.join(directory, fname) for fname in files]
  337. # Execute all patterns
  338. for pattern in self.exclude:
  339. ignored.update([
  340. os.path.basename(fname)
  341. for fname in fnmatch.filter(files, pattern)
  342. ])
  343. return ignored
  344. def copy_extra_files(self):
  345. """Copy a list of files into the build directory, and add them to
  346. install_files or install_dirs as appropriate.
  347. """
  348. for file, destination in self.extra_files:
  349. file = file.rstrip('/\\')
  350. basename = os.path.basename(file)
  351. if not destination:
  352. destination = '$INSTDIR'
  353. if os.path.isdir(file):
  354. target_name = pjoin(self.build_dir, basename)
  355. if os.path.isdir(target_name):
  356. shutil.rmtree(target_name)
  357. elif os.path.exists(target_name):
  358. os.unlink(target_name)
  359. if self.exclude:
  360. shutil.copytree(file, target_name,
  361. ignore=self.copytree_ignore_callback)
  362. else:
  363. # Don't use our exclude callback if we don't need to,
  364. # as it slows things down.
  365. shutil.copytree(file, target_name)
  366. self.install_dirs.append((basename, destination))
  367. else:
  368. shutil.copy2(file, self.build_dir)
  369. self.install_files.append((basename, destination))
  370. def write_nsi(self):
  371. """Write the NSI file to define the NSIS installer.
  372. Most of the details of this are in the template and the
  373. :class:`nsist.nsiswriter.NSISFileWriter` class.
  374. """
  375. nsis_writer = NSISFileWriter(self.nsi_template, installerbuilder=self)
  376. logger.info('Writing NSI file to %s', self.nsi_file)
  377. # Sort by destination directory, so we can group them effectively
  378. self.install_files.sort(key=operator.itemgetter(1))
  379. nsis_writer.write(self.nsi_file)
  380. def run_nsis(self):
  381. """Runs makensis using the specified .nsi file
  382. Returns the exit code.
  383. """
  384. try:
  385. if os.name == 'nt':
  386. makensis = find_makensis_win()
  387. else:
  388. makensis = 'makensis'
  389. return call([makensis, self.nsi_file])
  390. except OSError as e:
  391. # This should catch either the registry key or makensis being absent
  392. if e.errno == errno.ENOENT:
  393. print("makensis was not found. Install NSIS and try again.")
  394. print("http://nsis.sourceforge.net/Download")
  395. return 1
  396. def run(self, makensis=True):
  397. """Run all the steps to build an installer.
  398. """
  399. try:
  400. os.makedirs(self.build_dir)
  401. except OSError as e:
  402. if e.errno != errno.EEXIST:
  403. raise e
  404. if self.py_format == 'bundled':
  405. self.fetch_python_embeddable()
  406. if self.inc_msvcrt:
  407. self.prepare_msvcrt()
  408. else:
  409. self.fetch_python()
  410. if self.py_version < '3.3':
  411. self.fetch_pylauncher()
  412. self.prepare_shortcuts()
  413. if self.commands:
  414. self.prepare_commands()
  415. # Packages
  416. self.prepare_packages()
  417. # Extra files
  418. self.copy_extra_files()
  419. self.write_nsi()
  420. if makensis:
  421. exitcode = self.run_nsis()
  422. if not exitcode:
  423. logger.info('Installer written to %s', pjoin(self.build_dir, self.installer_name))
  424. def main(argv=None):
  425. """Make an installer from the command line.
  426. This parses command line arguments and a config file, and calls
  427. :func:`all_steps` with the extracted information.
  428. """
  429. logger.setLevel(logging.INFO)
  430. logger.handlers = [logging.StreamHandler()]
  431. import argparse
  432. argp = argparse.ArgumentParser(prog='pynsist')
  433. argp.add_argument('config_file')
  434. argp.add_argument('--no-makensis', action='store_true',
  435. help='Prepare files and folders, stop before calling makensis. For debugging.'
  436. )
  437. options = argp.parse_args(argv)
  438. dirname, config_file = os.path.split(options.config_file)
  439. if dirname:
  440. os.chdir(dirname)
  441. from . import configreader
  442. try:
  443. cfg = configreader.read_and_validate(config_file)
  444. except configreader.InvalidConfig as e:
  445. logger.error('Error parsing configuration file:')
  446. logger.error(str(e))
  447. sys.exit(1)
  448. args = get_installer_builder_args(cfg)
  449. try:
  450. InstallerBuilder(**args).run(makensis=(not options.no_makensis))
  451. except InputError as e:
  452. logger.error("Error in config values:")
  453. logger.error(str(e))
  454. sys.exit(1)