__init__.py 21 KB

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