__init__.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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, 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. with zipfile.ZipFile(str(cache_file)) as z:
  171. z.extractall(python_dir)
  172. # Manipulate any *._pth files so the default paths AND pkgs directory
  173. # ends up in sys.path. Please see:
  174. # https://docs.python.org/3/using/windows.html#finding-modules
  175. # for more information.
  176. pth_files = [f for f in os.listdir(python_dir)
  177. if os.path.isfile(pjoin(python_dir, f))
  178. and f.endswith('._pth')]
  179. for pth in pth_files:
  180. with open(pjoin(python_dir, pth), 'a+b') as f:
  181. f.write(b'\r\n..\\pkgs\r\nimport site\r\n')
  182. self.install_dirs.append(('Python', '$INSTDIR'))
  183. def prepare_msvcrt(self):
  184. arch = 'x64' if self.py_bitness == 64 else 'x86'
  185. src = pjoin(_PKGDIR, 'msvcrt', arch)
  186. dst = pjoin(self.build_dir, 'msvcrt')
  187. self.msvcrt_files = sorted(os.listdir(src))
  188. shutil.copytree(src, dst)
  189. SCRIPT_TEMPLATE = """#!python{qualifier}
  190. import sys, os
  191. scriptdir, script = os.path.split(__file__)
  192. installdir = scriptdir # for compatibility with commands
  193. pkgdir = os.path.join(scriptdir, 'pkgs')
  194. sys.path.insert(0, pkgdir)
  195. os.environ['PYTHONPATH'] = pkgdir + os.pathsep + os.environ.get('PYTHONPATH', '')
  196. # APPDATA should always be set, but in case it isn't, try user home
  197. # If none of APPDATA, HOME, USERPROFILE or HOMEPATH are set, this will fail.
  198. appdata = os.environ.get('APPDATA', None) or os.path.expanduser('~')
  199. if 'pythonw' in sys.executable:
  200. # Running with no console - send all stdstream output to a file.
  201. kw = {{'errors': 'replace'}} if (sys.version_info[0] >= 3) else {{}}
  202. sys.stdout = sys.stderr = open(os.path.join(appdata, script+'.log'), 'w', **kw)
  203. else:
  204. # In a console. But if the console was started just for this program, it
  205. # will close as soon as we exit, so write the traceback to a file as well.
  206. def excepthook(etype, value, tb):
  207. "Write unhandled exceptions to a file and to stderr."
  208. import traceback
  209. traceback.print_exception(etype, value, tb)
  210. with open(os.path.join(appdata, script+'.log'), 'w') as f:
  211. traceback.print_exception(etype, value, tb, file=f)
  212. sys.excepthook = excepthook
  213. {extra_preamble}
  214. if __name__ == '__main__':
  215. from {module} import {func}
  216. {func}()
  217. """
  218. def write_script(self, entrypt, target, extra_preamble=''):
  219. """Write a launcher script from a 'module:function' entry point
  220. py_version and py_bitness are used to write an appropriate shebang line
  221. for the PEP 397 Windows launcher.
  222. """
  223. module, func = entrypt.split(":")
  224. with open(target, 'w') as f:
  225. f.write(self.SCRIPT_TEMPLATE.format(qualifier=self.py_qualifier,
  226. module=module, func=func, extra_preamble=extra_preamble))
  227. pkg = module.split('.')[0]
  228. if pkg not in self.packages:
  229. self.packages.append(pkg)
  230. def prepare_shortcuts(self):
  231. """Prepare shortcut files in the build directory.
  232. If entry_point is specified, write the script. If script is specified,
  233. copy to the build directory. Prepare target and parameters for these
  234. shortcuts.
  235. Also copies shortcut icons.
  236. """
  237. files = set()
  238. for scname, sc in self.shortcuts.items():
  239. if not sc.get('target'):
  240. if sc.get('entry_point'):
  241. sc['script'] = script = scname.replace(' ', '_') + '.launch.py' \
  242. + ('' if sc['console'] else 'w')
  243. specified_preamble = sc.get('extra_preamble', None)
  244. if isinstance(specified_preamble, str):
  245. # Filename
  246. extra_preamble = io.open(specified_preamble, encoding='utf-8')
  247. elif specified_preamble is None:
  248. extra_preamble = io.StringIO() # Empty
  249. else:
  250. # Passed a StringIO or similar object
  251. extra_preamble = specified_preamble
  252. self.write_script(sc['entry_point'], pjoin(self.build_dir, script),
  253. extra_preamble.read().rstrip())
  254. else:
  255. shutil.copy2(sc['script'], self.build_dir)
  256. target = '$INSTDIR\Python\python{}.exe'
  257. sc['target'] = target.format('' if sc['console'] else 'w')
  258. sc['parameters'] = '"%s"' % ntpath.join('$INSTDIR', sc['script'])
  259. files.add(os.path.basename(sc['script']))
  260. shutil.copy2(sc['icon'], self.build_dir)
  261. sc['icon'] = os.path.basename(sc['icon'])
  262. files.add(sc['icon'])
  263. self.install_files.extend([(f, '$INSTDIR') for f in files])
  264. def copy_license(self):
  265. """
  266. If a license file has been specified, ensure it's copied into the
  267. install directory and added to the install_files list.
  268. """
  269. if self.license_file:
  270. shutil.copy2(self.license_file, self.build_dir)
  271. license_file_name = os.path.basename(self.license_file)
  272. self.install_files.append((license_file_name, '$INSTDIR'))
  273. def prepare_packages(self):
  274. """Move requested packages into the build directory.
  275. If a pynsist_pkgs directory exists, it is copied into the build
  276. directory as pkgs/ . Any packages not already there are found on
  277. sys.path and copied in.
  278. """
  279. logger.info("Copying packages into build directory...")
  280. build_pkg_dir = pjoin(self.build_dir, 'pkgs')
  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 specified in pypi_wheel_reqs or in paths of local_wheels
  287. wg = WheelGetter(self.pypi_wheel_reqs, self.local_wheels, build_pkg_dir,
  288. py_version=self.py_version, bitness=self.py_bitness,
  289. extra_sources=self.extra_wheel_sources,
  290. exclude=self.exclude)
  291. wg.get_all()
  292. # 3. Copy importable modules
  293. copy_modules(self.packages, build_pkg_dir,
  294. py_version=self.py_version, exclude=self.exclude)
  295. def prepare_commands(self):
  296. command_dir = Path(self.build_dir) / 'bin'
  297. command_dir.mkdir()
  298. prepare_bin_directory(command_dir, self.commands, bitness=self.py_bitness)
  299. self.install_dirs.append((command_dir.name, '$INSTDIR'))
  300. self.extra_files.append((pjoin(_PKGDIR, '_system_path.py'), '$INSTDIR'))
  301. self.extra_files.append((pjoin(_PKGDIR, '_rewrite_shebangs.py'), '$INSTDIR'))
  302. def copytree_ignore_callback(self, directory, files):
  303. """This is being called back by our shutil.copytree call to implement the
  304. 'exclude' feature.
  305. """
  306. ignored = set()
  307. # Filter by file names relative to the build directory
  308. directory = os.path.normpath(directory)
  309. files = [os.path.join(directory, fname) for fname in files]
  310. # Execute all patterns
  311. for pattern in self.exclude:
  312. ignored.update([
  313. os.path.basename(fname)
  314. for fname in fnmatch.filter(files, pattern)
  315. ])
  316. return ignored
  317. def copy_extra_files(self):
  318. """Copy a list of files into the build directory, and add them to
  319. install_files or install_dirs as appropriate.
  320. """
  321. # Create installer.nsi, so that a data file with the same name will
  322. # automatically be renamed installer.1.nsi. All the other files needed
  323. # in the build directory should already be in place.
  324. Path(self.nsi_file).touch()
  325. for file, destination in self.extra_files:
  326. file = file.rstrip('/\\')
  327. in_build_dir = Path(self.build_dir, os.path.basename(file))
  328. # Find an unused name in the build directory,
  329. # similar to the source filename, e.g. foo.1.txt, foo.2.txt, ...
  330. stem, suffix = in_build_dir.stem, in_build_dir.suffix
  331. n = 1
  332. while in_build_dir.exists():
  333. name = '{}.{}{}'.format(stem, n, suffix)
  334. in_build_dir = in_build_dir.with_name(name)
  335. n += 1
  336. if destination:
  337. # Normalize destination paths to Windows-style
  338. destination = destination.replace('/', '\\')
  339. else:
  340. destination = '$INSTDIR'
  341. if os.path.isdir(file):
  342. if self.exclude:
  343. shutil.copytree(file, str(in_build_dir),
  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, str(in_build_dir))
  349. self.install_dirs.append((in_build_dir.name, destination))
  350. else:
  351. shutil.copy2(file, str(in_build_dir))
  352. self.install_files.append((in_build_dir.name, 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. makensis = shutil.which('makensis')
  368. if (makensis is None) and os.name == 'nt':
  369. try:
  370. makensis = find_makensis_win()
  371. except OSError:
  372. pass
  373. if makensis is None:
  374. print("makensis was not found. Install NSIS and try again.")
  375. print("http://nsis.sourceforge.net/Download")
  376. return 1
  377. logger.info('\n~~~ Running makensis ~~~')
  378. return call([makensis, self.nsi_file])
  379. def run(self, makensis=True):
  380. """Run all the steps to build an installer.
  381. """
  382. try: # Start with a clean build directory
  383. shutil.rmtree(self.build_dir)
  384. except FileNotFoundError:
  385. pass
  386. os.makedirs(self.build_dir)
  387. self.fetch_python_embeddable()
  388. if self.inc_msvcrt:
  389. self.prepare_msvcrt()
  390. self.prepare_shortcuts()
  391. self.copy_license()
  392. if self.commands:
  393. self.prepare_commands()
  394. # Packages
  395. self.prepare_packages()
  396. # Extra files
  397. self.copy_extra_files()
  398. self.write_nsi()
  399. if makensis:
  400. exitcode = self.run_nsis()
  401. if not exitcode:
  402. logger.info('Installer written to %s', pjoin(self.build_dir, self.installer_name))
  403. return exitcode
  404. return 0
  405. def main(argv=None):
  406. """Make an installer from the command line.
  407. This parses command line arguments and a config file, and calls
  408. :func:`all_steps` with the extracted information.
  409. """
  410. logger.setLevel(logging.INFO)
  411. logger.handlers = [logging.StreamHandler()]
  412. import argparse
  413. argp = argparse.ArgumentParser(prog='pynsist')
  414. argp.add_argument('config_file')
  415. argp.add_argument('--no-makensis', action='store_true',
  416. help='Prepare files and folders, stop before calling makensis. For debugging.'
  417. )
  418. options = argp.parse_args(argv)
  419. dirname, config_file = os.path.split(options.config_file)
  420. if dirname:
  421. os.chdir(dirname)
  422. from . import configreader
  423. try:
  424. cfg = configreader.read_and_validate(config_file)
  425. except configreader.InvalidConfig as e:
  426. logger.error('Error parsing configuration file:')
  427. logger.error(str(e))
  428. sys.exit(1)
  429. args = get_installer_builder_args(cfg)
  430. try:
  431. ec = InstallerBuilder(**args).run(makensis=(not options.no_makensis))
  432. except InputError as e:
  433. logger.error("Error in config values:")
  434. logger.error(str(e))
  435. sys.exit(1)
  436. return ec