__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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, license_file=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. self.license_file = license_file
  100. # Python options
  101. self.py_version = py_version
  102. if not self._py_version_pattern.match(py_version):
  103. if not os.environ.get('PYNSIST_PY_PRERELEASE'):
  104. raise InputError('py_version', py_version,
  105. "a full Python version like '3.4.0'")
  106. if self.py_version_tuple < (3, 5):
  107. raise InputError('py_version', py_version,
  108. "Python >= 3.5.0 (use Pynsist 1.x for older Python.")
  109. self.py_bitness = py_bitness
  110. if py_bitness not in {32, 64}:
  111. raise InputError('py_bitness', py_bitness, "32 or 64")
  112. self.py_major_version = self.py_qualifier = '.'.join(self.py_version.split('.')[:2])
  113. if self.py_bitness == 32:
  114. self.py_qualifier += '-32'
  115. if py_format == 'installer':
  116. raise InputError('py_format', py_format, "'bundled' (use Pynsist 1.x for 'installer')")
  117. elif py_format != 'bundled':
  118. raise InputError('py_format', py_format, "'bundled'")
  119. self.inc_msvcrt = inc_msvcrt
  120. # Build details
  121. self.build_dir = build_dir
  122. self.installer_name = installer_name or self.make_installer_name()
  123. self.nsi_template = nsi_template
  124. if self.nsi_template is None:
  125. if self.inc_msvcrt:
  126. self.nsi_template = 'pyapp_msvcrt.nsi'
  127. else:
  128. self.nsi_template = 'pyapp.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. filename = 'python-{}-embed-{}.zip'.format(version,
  149. 'amd64' if bitness==64 else 'win32')
  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_embeddable(self):
  154. """Fetch the embeddable Windows build for the specified Python version
  155. It will be unpacked into the build directory.
  156. In addition, any ``*._pth`` files found therein will have the pkgs path
  157. appended to them.
  158. """
  159. url, filename = self._python_download_url_filename()
  160. cache_file = get_cache_dir(ensure_existence=True) / filename
  161. if not cache_file.is_file():
  162. logger.info('Downloading embeddable Python build...')
  163. logger.info('Getting %s', url)
  164. download(url, cache_file)
  165. logger.info('Unpacking Python...')
  166. python_dir = pjoin(self.build_dir, 'Python')
  167. try:
  168. shutil.rmtree(python_dir)
  169. except OSError as e:
  170. if e.errno != errno.ENOENT:
  171. raise
  172. with zipfile.ZipFile(str(cache_file)) as z:
  173. z.extractall(python_dir)
  174. # Manipulate any *._pth files so the default paths AND pkgs directory
  175. # ends up in sys.path. Please see:
  176. # https://docs.python.org/3/using/windows.html#finding-modules
  177. # for more information.
  178. pth_files = [f for f in os.listdir(python_dir)
  179. if os.path.isfile(pjoin(python_dir, f))
  180. and f.endswith('._pth')]
  181. for pth in pth_files:
  182. with open(pjoin(python_dir, pth), 'a+b') as f:
  183. f.write(b'\r\n..\\pkgs\r\nimport site\r\n')
  184. self.install_dirs.append(('Python', '$INSTDIR'))
  185. def prepare_msvcrt(self):
  186. arch = 'x64' if self.py_bitness == 64 else 'x86'
  187. src = pjoin(_PKGDIR, 'msvcrt', arch)
  188. dst = pjoin(self.build_dir, 'msvcrt')
  189. self.msvcrt_files = sorted(os.listdir(src))
  190. try:
  191. shutil.rmtree(dst)
  192. except OSError as e:
  193. if e.errno != errno.ENOENT:
  194. raise
  195. shutil.copytree(src, dst)
  196. SCRIPT_TEMPLATE = """#!python{qualifier}
  197. import sys, os
  198. scriptdir, script = os.path.split(__file__)
  199. installdir = scriptdir # for compatibility with commands
  200. pkgdir = os.path.join(scriptdir, 'pkgs')
  201. sys.path.insert(0, pkgdir)
  202. os.environ['PYTHONPATH'] = pkgdir + os.pathsep + os.environ.get('PYTHONPATH', '')
  203. # APPDATA should always be set, but in case it isn't, try user home
  204. # If none of APPDATA, HOME, USERPROFILE or HOMEPATH are set, this will fail.
  205. appdata = os.environ.get('APPDATA', None) or os.path.expanduser('~')
  206. if 'pythonw' in sys.executable:
  207. # Running with no console - send all stdstream output to a file.
  208. kw = {{'errors': 'replace'}} if (sys.version_info[0] >= 3) else {{}}
  209. sys.stdout = sys.stderr = open(os.path.join(appdata, script+'.log'), 'w', **kw)
  210. else:
  211. # In a console. But if the console was started just for this program, it
  212. # will close as soon as we exit, so write the traceback to a file as well.
  213. def excepthook(etype, value, tb):
  214. "Write unhandled exceptions to a file and to stderr."
  215. import traceback
  216. traceback.print_exception(etype, value, tb)
  217. with open(os.path.join(appdata, script+'.log'), 'w') as f:
  218. traceback.print_exception(etype, value, tb, file=f)
  219. sys.excepthook = excepthook
  220. {extra_preamble}
  221. if __name__ == '__main__':
  222. from {module} import {func}
  223. {func}()
  224. """
  225. def write_script(self, entrypt, target, extra_preamble=''):
  226. """Write a launcher script from a 'module:function' entry point
  227. py_version and py_bitness are used to write an appropriate shebang line
  228. for the PEP 397 Windows launcher.
  229. """
  230. module, func = entrypt.split(":")
  231. with open(target, 'w') as f:
  232. f.write(self.SCRIPT_TEMPLATE.format(qualifier=self.py_qualifier,
  233. module=module, func=func, extra_preamble=extra_preamble))
  234. pkg = module.split('.')[0]
  235. if pkg not in self.packages:
  236. self.packages.append(pkg)
  237. def prepare_shortcuts(self):
  238. """Prepare shortcut files in the build directory.
  239. If entry_point is specified, write the script. If script is specified,
  240. copy to the build directory. Prepare target and parameters for these
  241. shortcuts.
  242. Also copies shortcut icons.
  243. """
  244. files = set()
  245. for scname, sc in self.shortcuts.items():
  246. if not sc.get('target'):
  247. if sc.get('entry_point'):
  248. sc['script'] = script = scname.replace(' ', '_') + '.launch.py' \
  249. + ('' if sc['console'] else 'w')
  250. specified_preamble = sc.get('extra_preamble', None)
  251. if isinstance(specified_preamble, text_types):
  252. # Filename
  253. extra_preamble = io.open(specified_preamble, encoding='utf-8')
  254. elif specified_preamble is None:
  255. extra_preamble = io.StringIO() # Empty
  256. else:
  257. # Passed a StringIO or similar object
  258. extra_preamble = specified_preamble
  259. self.write_script(sc['entry_point'], pjoin(self.build_dir, script),
  260. extra_preamble.read().rstrip())
  261. else:
  262. shutil.copy2(sc['script'], self.build_dir)
  263. target = '$INSTDIR\Python\python{}.exe'
  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 copy_license(self):
  272. """
  273. If a license file has been specified, ensure it's copied into the
  274. install directory and added to the install_files list.
  275. """
  276. if self.license_file:
  277. shutil.copy2(self.license_file, self.build_dir)
  278. license_file_name = os.path.basename(self.license_file)
  279. self.install_files.append((license_file_name, '$INSTDIR'))
  280. def prepare_packages(self):
  281. """Move requested packages into the build directory.
  282. If a pynsist_pkgs directory exists, it is copied into the build
  283. directory as pkgs/ . Any packages not already there are found on
  284. sys.path and copied in.
  285. """
  286. logger.info("Copying packages into build directory...")
  287. build_pkg_dir = pjoin(self.build_dir, 'pkgs')
  288. if os.path.isdir(build_pkg_dir):
  289. shutil.rmtree(build_pkg_dir)
  290. # 1. Manually prepared packages
  291. if os.path.isdir('pynsist_pkgs'):
  292. shutil.copytree('pynsist_pkgs', build_pkg_dir)
  293. else:
  294. os.mkdir(build_pkg_dir)
  295. # 2. Wheels from PyPI
  296. fetch_pypi_wheels(self.pypi_wheel_reqs, build_pkg_dir,
  297. py_version=self.py_version, bitness=self.py_bitness,
  298. extra_sources=self.extra_wheel_sources,
  299. exclude=self.exclude)
  300. # 3. Copy importable modules
  301. copy_modules(self.packages, build_pkg_dir,
  302. py_version=self.py_version, exclude=self.exclude)
  303. def prepare_commands(self):
  304. command_dir = Path(self.build_dir) / 'bin'
  305. if command_dir.is_dir():
  306. shutil.rmtree(str(command_dir))
  307. command_dir.mkdir()
  308. prepare_bin_directory(command_dir, self.commands, bitness=self.py_bitness)
  309. self.install_dirs.append((command_dir.name, '$INSTDIR'))
  310. self.extra_files.append((pjoin(_PKGDIR, '_system_path.py'), '$INSTDIR'))
  311. self.extra_files.append((pjoin(_PKGDIR, '_rewrite_shebangs.py'), '$INSTDIR'))
  312. def copytree_ignore_callback(self, directory, files):
  313. """This is being called back by our shutil.copytree call to implement the
  314. 'exclude' feature.
  315. """
  316. ignored = set()
  317. # Filter by file names relative to the build directory
  318. directory = os.path.normpath(directory)
  319. files = [os.path.join(directory, fname) for fname in files]
  320. # Execute all patterns
  321. for pattern in self.exclude:
  322. ignored.update([
  323. os.path.basename(fname)
  324. for fname in fnmatch.filter(files, pattern)
  325. ])
  326. return ignored
  327. def copy_extra_files(self):
  328. """Copy a list of files into the build directory, and add them to
  329. install_files or install_dirs as appropriate.
  330. """
  331. for file, destination in self.extra_files:
  332. file = file.rstrip('/\\')
  333. basename = os.path.basename(file)
  334. if not destination:
  335. destination = '$INSTDIR'
  336. if os.path.isdir(file):
  337. target_name = pjoin(self.build_dir, basename)
  338. if os.path.isdir(target_name):
  339. shutil.rmtree(target_name)
  340. elif os.path.exists(target_name):
  341. os.unlink(target_name)
  342. if self.exclude:
  343. shutil.copytree(file, target_name,
  344. ignore=self.copytree_ignore_callback)
  345. else:
  346. # Don't use our exclude callback if we don't need to,
  347. # as it slows things down.
  348. shutil.copytree(file, target_name)
  349. self.install_dirs.append((basename, destination))
  350. else:
  351. shutil.copy2(file, self.build_dir)
  352. self.install_files.append((basename, destination))
  353. def write_nsi(self):
  354. """Write the NSI file to define the NSIS installer.
  355. Most of the details of this are in the template and the
  356. :class:`nsist.nsiswriter.NSISFileWriter` class.
  357. """
  358. nsis_writer = NSISFileWriter(self.nsi_template, installerbuilder=self)
  359. logger.info('Writing NSI file to %s', self.nsi_file)
  360. # Sort by destination directory, so we can group them effectively
  361. self.install_files.sort(key=operator.itemgetter(1))
  362. nsis_writer.write(self.nsi_file)
  363. def run_nsis(self):
  364. """Runs makensis using the specified .nsi file
  365. Returns the exit code.
  366. """
  367. try:
  368. if os.name == 'nt':
  369. makensis = find_makensis_win()
  370. else:
  371. makensis = 'makensis'
  372. logger.info('\n~~~ Running makensis ~~~')
  373. return call([makensis, self.nsi_file])
  374. except OSError as e:
  375. # This should catch either the registry key or makensis being absent
  376. if e.errno == errno.ENOENT:
  377. print("makensis was not found. Install NSIS and try again.")
  378. print("http://nsis.sourceforge.net/Download")
  379. return 1
  380. def run(self, makensis=True):
  381. """Run all the steps to build an installer.
  382. """
  383. try:
  384. os.makedirs(self.build_dir)
  385. except OSError as e:
  386. if e.errno != errno.EEXIST:
  387. raise e
  388. self.fetch_python_embeddable()
  389. if self.inc_msvcrt:
  390. self.prepare_msvcrt()
  391. self.prepare_shortcuts()
  392. self.copy_license()
  393. if self.commands:
  394. self.prepare_commands()
  395. # Packages
  396. self.prepare_packages()
  397. # Extra files
  398. self.copy_extra_files()
  399. self.write_nsi()
  400. if makensis:
  401. exitcode = self.run_nsis()
  402. if not exitcode:
  403. logger.info('Installer written to %s', pjoin(self.build_dir, self.installer_name))
  404. def main(argv=None):
  405. """Make an installer from the command line.
  406. This parses command line arguments and a config file, and calls
  407. :func:`all_steps` with the extracted information.
  408. """
  409. logger.setLevel(logging.INFO)
  410. logger.handlers = [logging.StreamHandler()]
  411. import argparse
  412. argp = argparse.ArgumentParser(prog='pynsist')
  413. argp.add_argument('config_file')
  414. argp.add_argument('--no-makensis', action='store_true',
  415. help='Prepare files and folders, stop before calling makensis. For debugging.'
  416. )
  417. options = argp.parse_args(argv)
  418. dirname, config_file = os.path.split(options.config_file)
  419. if dirname:
  420. os.chdir(dirname)
  421. from . import configreader
  422. try:
  423. cfg = configreader.read_and_validate(config_file)
  424. except configreader.InvalidConfig as e:
  425. logger.error('Error parsing configuration file:')
  426. logger.error(str(e))
  427. sys.exit(1)
  428. args = get_installer_builder_args(cfg)
  429. try:
  430. InstallerBuilder(**args).run(makensis=(not options.no_makensis))
  431. except InputError as e:
  432. logger.error("Error in config values:")
  433. logger.error(str(e))
  434. sys.exit(1)