__init__.py 20 KB

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