__init__.py 18 KB

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