__init__.py 20 KB

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