__init__.py 21 KB

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