__init__.py 20 KB

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