__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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.1'
  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 extra_wheel_sources: Directory paths to find wheels in.
  68. :type extra_wheel_sources: list of Path objects
  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: (deprecated) 'bundled'. Use Pynsist 1.x for
  74. 'installer' option.
  75. :param bool inc_msvcrt: True to include the Microsoft C runtime with 'bundled'
  76. Python.
  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='bundled', inc_msvcrt=True, build_dir=DEFAULT_BUILD_DIR,
  85. installer_name=None, nsi_template=None,
  86. exclude=None, pypi_wheel_reqs=None, extra_wheel_sources=None,
  87. commands=None):
  88. self.appname = appname
  89. self.version = version
  90. self.publisher = publisher
  91. self.shortcuts = shortcuts
  92. self.icon = icon
  93. self.packages = packages or []
  94. self.exclude = [os.path.normpath(p) for p in (exclude or [])]
  95. self.extra_files = extra_files or []
  96. self.pypi_wheel_reqs = pypi_wheel_reqs or []
  97. self.extra_wheel_sources = extra_wheel_sources or []
  98. self.commands = commands or {}
  99. # Python options
  100. self.py_version = py_version
  101. if not self._py_version_pattern.match(py_version):
  102. if not os.environ.get('PYNSIST_PY_PRERELEASE'):
  103. raise InputError('py_version', py_version,
  104. "a full Python version like '3.4.0'")
  105. if self.py_version_tuple < (3, 5):
  106. raise InputError('py_version', py_version,
  107. "Python >= 3.5.0 (use Pynsist 1.x for older Python.")
  108. self.py_bitness = py_bitness
  109. if py_bitness not in {32, 64}:
  110. raise InputError('py_bitness', py_bitness, "32 or 64")
  111. self.py_major_version = self.py_qualifier = '.'.join(self.py_version.split('.')[:2])
  112. if self.py_bitness == 32:
  113. self.py_qualifier += '-32'
  114. if py_format == 'installer':
  115. raise InputError('py_format', py_format, "'bundled' (use Pynsist 1.x for 'installer')")
  116. elif py_format != 'bundled':
  117. raise InputError('py_format', py_format, "'bundled'")
  118. self.inc_msvcrt = inc_msvcrt
  119. # Build details
  120. self.build_dir = build_dir
  121. self.installer_name = installer_name or self.make_installer_name()
  122. self.nsi_template = nsi_template
  123. if self.nsi_template is None:
  124. if self.inc_msvcrt:
  125. self.nsi_template = 'pyapp_msvcrt.nsi'
  126. else:
  127. self.nsi_template = 'pyapp.nsi'
  128. self.nsi_file = pjoin(self.build_dir, 'installer.nsi')
  129. # To be filled later
  130. self.install_files = []
  131. self.install_dirs = []
  132. self.msvcrt_files = []
  133. _py_version_pattern = re.compile(r'\d\.\d+\.\d+$')
  134. @property
  135. def py_version_tuple(self):
  136. parts = self.py_version.split('.')
  137. return int(parts[0]), int(parts[1])
  138. def make_installer_name(self):
  139. """Generate the filename of the installer exe
  140. e.g. My_App_1.0.exe
  141. """
  142. s = self.appname + '_' + self.version + '.exe'
  143. return s.replace(' ', '_')
  144. def _python_download_url_filename(self):
  145. version = self.py_version
  146. bitness = self.py_bitness
  147. filename = 'python-{}-embed-{}.zip'.format(version,
  148. 'amd64' if bitness==64 else 'win32')
  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_embeddable(self):
  153. """Fetch the embeddable Windows build for the specified Python version
  154. It will be unpacked into the build directory.
  155. In addition, any *._pth files found therein will have the pkgs path
  156. appended to them.
  157. """
  158. url, filename = self._python_download_url_filename()
  159. cache_file = get_cache_dir(ensure_existence=True) / filename
  160. if not cache_file.is_file():
  161. logger.info('Downloading embeddable Python build...')
  162. logger.info('Getting %s', url)
  163. download(url, cache_file)
  164. logger.info('Unpacking Python...')
  165. python_dir = pjoin(self.build_dir, 'Python')
  166. try:
  167. shutil.rmtree(python_dir)
  168. except OSError as e:
  169. if e.errno != errno.ENOENT:
  170. raise
  171. with zipfile.ZipFile(str(cache_file)) as z:
  172. z.extractall(python_dir)
  173. # Manipulate any *._pth files so the default paths AND pkgs directory
  174. # ends up in sys.path. Please see:
  175. # https://docs.python.org/3/using/windows.html#finding-modules
  176. # for more information.
  177. pth_files = [f for f in os.listdir(python_dir)
  178. if os.path.isfile(pjoin(python_dir, f))
  179. and f.endswith('._pth')]
  180. for pth in pth_files:
  181. with open(pjoin(python_dir, pth), 'a+b') as f:
  182. f.write(b'\r\n..\\pkgs\r\n')
  183. self.install_dirs.append(('Python', '$INSTDIR'))
  184. def prepare_msvcrt(self):
  185. arch = 'x64' if self.py_bitness == 64 else 'x86'
  186. src = pjoin(_PKGDIR, 'msvcrt', arch)
  187. dst = pjoin(self.build_dir, 'msvcrt')
  188. self.msvcrt_files = sorted(os.listdir(src))
  189. try:
  190. shutil.rmtree(dst)
  191. except OSError as e:
  192. if e.errno != errno.ENOENT:
  193. raise
  194. shutil.copytree(src, dst)
  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. target = '$INSTDIR\Python\python{}.exe'
  262. sc['target'] = target.format('' if sc['console'] else 'w')
  263. sc['parameters'] = '"%s"' % ntpath.join('$INSTDIR', sc['script'])
  264. files.add(os.path.basename(sc['script']))
  265. shutil.copy2(sc['icon'], self.build_dir)
  266. sc['icon'] = os.path.basename(sc['icon'])
  267. files.add(sc['icon'])
  268. self.install_files.extend([(f, '$INSTDIR') for f in files])
  269. def prepare_packages(self):
  270. """Move requested packages into the build directory.
  271. If a pynsist_pkgs directory exists, it is copied into the build
  272. directory as pkgs/ . Any packages not already there are found on
  273. sys.path and copied in.
  274. """
  275. logger.info("Copying packages into build directory...")
  276. build_pkg_dir = pjoin(self.build_dir, 'pkgs')
  277. if os.path.isdir(build_pkg_dir):
  278. shutil.rmtree(build_pkg_dir)
  279. # 1. Manually prepared packages
  280. if os.path.isdir('pynsist_pkgs'):
  281. shutil.copytree('pynsist_pkgs', build_pkg_dir)
  282. else:
  283. os.mkdir(build_pkg_dir)
  284. # 2. Wheels from PyPI
  285. fetch_pypi_wheels(self.pypi_wheel_reqs, build_pkg_dir,
  286. py_version=self.py_version, bitness=self.py_bitness,
  287. extra_sources=self.extra_wheel_sources)
  288. # 3. Copy importable modules
  289. copy_modules(self.packages, build_pkg_dir,
  290. py_version=self.py_version, exclude=self.exclude)
  291. def prepare_commands(self):
  292. command_dir = Path(self.build_dir) / 'bin'
  293. if command_dir.is_dir():
  294. shutil.rmtree(str(command_dir))
  295. command_dir.mkdir()
  296. prepare_bin_directory(command_dir, self.commands, bitness=self.py_bitness)
  297. self.install_dirs.append((command_dir.name, '$INSTDIR'))
  298. self.extra_files.append((pjoin(_PKGDIR, '_system_path.py'), '$INSTDIR'))
  299. self.extra_files.append((pjoin(_PKGDIR, '_rewrite_shebangs.py'), '$INSTDIR'))
  300. def copytree_ignore_callback(self, directory, files):
  301. """This is being called back by our shutil.copytree call to implement the
  302. 'exclude' feature.
  303. """
  304. ignored = set()
  305. # Filter by file names relative to the build directory
  306. directory = os.path.normpath(directory)
  307. files = [os.path.join(directory, fname) for fname in files]
  308. # Execute all patterns
  309. for pattern in self.exclude:
  310. ignored.update([
  311. os.path.basename(fname)
  312. for fname in fnmatch.filter(files, pattern)
  313. ])
  314. return ignored
  315. def copy_extra_files(self):
  316. """Copy a list of files into the build directory, and add them to
  317. install_files or install_dirs as appropriate.
  318. """
  319. for file, destination in self.extra_files:
  320. file = file.rstrip('/\\')
  321. basename = os.path.basename(file)
  322. if not destination:
  323. destination = '$INSTDIR'
  324. if os.path.isdir(file):
  325. target_name = pjoin(self.build_dir, basename)
  326. if os.path.isdir(target_name):
  327. shutil.rmtree(target_name)
  328. elif os.path.exists(target_name):
  329. os.unlink(target_name)
  330. if self.exclude:
  331. shutil.copytree(file, target_name,
  332. ignore=self.copytree_ignore_callback)
  333. else:
  334. # Don't use our exclude callback if we don't need to,
  335. # as it slows things down.
  336. shutil.copytree(file, target_name)
  337. self.install_dirs.append((basename, destination))
  338. else:
  339. shutil.copy2(file, self.build_dir)
  340. self.install_files.append((basename, destination))
  341. def write_nsi(self):
  342. """Write the NSI file to define the NSIS installer.
  343. Most of the details of this are in the template and the
  344. :class:`nsist.nsiswriter.NSISFileWriter` class.
  345. """
  346. nsis_writer = NSISFileWriter(self.nsi_template, installerbuilder=self)
  347. logger.info('Writing NSI file to %s', self.nsi_file)
  348. # Sort by destination directory, so we can group them effectively
  349. self.install_files.sort(key=operator.itemgetter(1))
  350. nsis_writer.write(self.nsi_file)
  351. def run_nsis(self):
  352. """Runs makensis using the specified .nsi file
  353. Returns the exit code.
  354. """
  355. try:
  356. if os.name == 'nt':
  357. makensis = find_makensis_win()
  358. else:
  359. makensis = 'makensis'
  360. logger.info('\n~~~ Running makensis ~~~')
  361. return call([makensis, self.nsi_file])
  362. except OSError as e:
  363. # This should catch either the registry key or makensis being absent
  364. if e.errno == errno.ENOENT:
  365. print("makensis was not found. Install NSIS and try again.")
  366. print("http://nsis.sourceforge.net/Download")
  367. return 1
  368. def run(self, makensis=True):
  369. """Run all the steps to build an installer.
  370. """
  371. try:
  372. os.makedirs(self.build_dir)
  373. except OSError as e:
  374. if e.errno != errno.EEXIST:
  375. raise e
  376. self.fetch_python_embeddable()
  377. if self.inc_msvcrt:
  378. self.prepare_msvcrt()
  379. self.prepare_shortcuts()
  380. if self.commands:
  381. self.prepare_commands()
  382. # Packages
  383. self.prepare_packages()
  384. # Extra files
  385. self.copy_extra_files()
  386. self.write_nsi()
  387. if makensis:
  388. exitcode = self.run_nsis()
  389. if not exitcode:
  390. logger.info('Installer written to %s', pjoin(self.build_dir, self.installer_name))
  391. def main(argv=None):
  392. """Make an installer from the command line.
  393. This parses command line arguments and a config file, and calls
  394. :func:`all_steps` with the extracted information.
  395. """
  396. logger.setLevel(logging.INFO)
  397. logger.handlers = [logging.StreamHandler()]
  398. import argparse
  399. argp = argparse.ArgumentParser(prog='pynsist')
  400. argp.add_argument('config_file')
  401. argp.add_argument('--no-makensis', action='store_true',
  402. help='Prepare files and folders, stop before calling makensis. For debugging.'
  403. )
  404. options = argp.parse_args(argv)
  405. dirname, config_file = os.path.split(options.config_file)
  406. if dirname:
  407. os.chdir(dirname)
  408. from . import configreader
  409. try:
  410. cfg = configreader.read_and_validate(config_file)
  411. except configreader.InvalidConfig as e:
  412. logger.error('Error parsing configuration file:')
  413. logger.error(str(e))
  414. sys.exit(1)
  415. args = get_installer_builder_args(cfg)
  416. try:
  417. InstallerBuilder(**args).run(makensis=(not options.no_makensis))
  418. except InputError as e:
  419. logger.error("Error in config values:")
  420. logger.error(str(e))
  421. sys.exit(1)