__init__.py 20 KB

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