__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. import re
  10. import shutil
  11. from subprocess import call
  12. import sys
  13. import fnmatch
  14. import zipfile
  15. PY2 = sys.version_info[0] == 2
  16. if os.name == 'nt':
  17. if PY2:
  18. import _winreg as winreg
  19. else:
  20. import winreg
  21. else:
  22. winreg = None
  23. from .copymodules import copy_modules
  24. from .nsiswriter import NSISFileWriter
  25. from .pypi import fetch_pypi_wheels
  26. from .util import download, text_types, get_cache_dir
  27. __version__ = '1.6'
  28. pjoin = os.path.join
  29. logger = logging.getLogger(__name__)
  30. _PKGDIR = os.path.abspath(os.path.dirname(__file__))
  31. DEFAULT_PY_VERSION = '2.7.10' if PY2 else '3.5.0'
  32. DEFAULT_BUILD_DIR = pjoin('build', 'nsis')
  33. DEFAULT_ICON = pjoin(_PKGDIR, 'glossyorb.ico')
  34. if os.name == 'nt' and sys.maxsize == (2**63)-1:
  35. DEFAULT_BITNESS = 64
  36. else:
  37. DEFAULT_BITNESS = 32
  38. def find_makensis_win():
  39. """Locate makensis.exe on Windows by querying the registry"""
  40. try:
  41. nsis_install_dir = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\NSIS')
  42. except OSError:
  43. nsis_install_dir = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432Node\\NSIS')
  44. return pjoin(nsis_install_dir, 'makensis.exe')
  45. class InputError(ValueError):
  46. def __init__(self, param, value, expected):
  47. self.param = param
  48. self.value = value
  49. self.expected = expected
  50. def __str__(self):
  51. return "{e.value!r} is not valid for {e.param}, expected {e.expected}".format(e=self)
  52. class InstallerBuilder(object):
  53. """Controls building an installer. This includes three main steps:
  54. 1. Arranging the necessary files in the build directory.
  55. 2. Filling out the template NSI file to control NSIS.
  56. 3. Running ``makensis`` to build the installer.
  57. :param str appname: Application name
  58. :param str version: Application version
  59. :param dict shortcuts: Dictionary keyed by shortcut name, containing
  60. dictionaries whose keys match the fields of :ref:`shortcut_config`
  61. in the config file
  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 list pypi_reqs: Package specifications to fetch from PyPI as wheels
  65. :param list extra_files: List of 2-tuples (file, destination) of files to include
  66. :param list exclude: Paths of files to exclude that would otherwise be included
  67. :param str py_version: Full version of Python to bundle
  68. :param int py_bitness: Bitness of bundled Python (32 or 64)
  69. :param str build_dir: Directory to run the build in
  70. :param str installer_name: Filename of the installer to produce
  71. :param str nsi_template: Path to a template NSI file to use
  72. """
  73. def __init__(self, appname, version, shortcuts, icon=DEFAULT_ICON,
  74. packages=None, extra_files=None, py_version=DEFAULT_PY_VERSION,
  75. py_bitness=DEFAULT_BITNESS, py_format='installer',
  76. build_dir=DEFAULT_BUILD_DIR,
  77. installer_name=None, nsi_template=None,
  78. exclude=None, pypi_wheel_reqs=None):
  79. self.appname = appname
  80. self.version = version
  81. self.shortcuts = shortcuts
  82. self.icon = icon
  83. self.packages = packages or []
  84. self.exclude = [os.path.normpath(p) for p in (exclude or [])]
  85. self.extra_files = extra_files or []
  86. self.pypi_wheel_reqs = pypi_wheel_reqs or []
  87. # Python options
  88. self.py_version = py_version
  89. if not self._py_version_pattern.match(py_version):
  90. if not os.environ.get('PYNSIST_PY_PRERELEASE'):
  91. raise InputError('py_version', py_version,
  92. "a full Python version like '3.4.0'")
  93. self.py_bitness = py_bitness
  94. if py_bitness not in {32, 64}:
  95. raise InputError('py_bitness', py_bitness, "32 or 64")
  96. self.py_major_version = self.py_qualifier = '.'.join(self.py_version.split('.')[:2])
  97. if self.py_bitness == 32:
  98. self.py_qualifier += '-32'
  99. self.py_format = py_format
  100. if self.py_version_tuple >= (3, 5):
  101. if py_format not in {'installer', 'bundled'}:
  102. raise InputError('py_format', py_format, "installer or bundled")
  103. else:
  104. if py_format != 'installer':
  105. raise InputError('py_format', py_format, "installer (for Python < 3.5)")
  106. # Build details
  107. self.build_dir = build_dir
  108. self.installer_name = installer_name or self.make_installer_name()
  109. self.nsi_template = nsi_template
  110. if self.nsi_template is None:
  111. if self.py_format == 'bundled':
  112. self.nsi_template = 'pyapp_msvcrt.nsi'
  113. elif self.py_version_tuple < (3, 3):
  114. self.nsi_template = 'pyapp_w_pylauncher.nsi'
  115. else:
  116. self.nsi_template = 'pyapp_installpy.nsi'
  117. self.nsi_file = pjoin(self.build_dir, 'installer.nsi')
  118. # To be filled later
  119. self.install_files = []
  120. self.install_dirs = []
  121. _py_version_pattern = re.compile(r'\d\.\d+\.\d+$')
  122. @property
  123. def py_version_tuple(self):
  124. parts = self.py_version.split('.')
  125. return int(parts[0]), int(parts[1])
  126. def make_installer_name(self):
  127. """Generate the filename of the installer exe
  128. e.g. My_App_1.0.exe
  129. """
  130. s = self.appname + '_' + self.version + '.exe'
  131. return s.replace(' ', '_')
  132. def _python_download_url_filename(self):
  133. version = self.py_version
  134. bitness = self.py_bitness
  135. if self.py_version_tuple >= (3, 5):
  136. if self.py_format == 'bundled':
  137. filename = 'python-{}-embed-{}.zip'.format(version,
  138. 'amd64' if bitness==64 else 'win32')
  139. else:
  140. filename = 'python-{}{}.exe'.format(version,
  141. '-amd64' if bitness==64 else '')
  142. else:
  143. filename = 'python-{0}{1}.msi'.format(version,
  144. '.amd64' if bitness==64 else '')
  145. version_minus_prerelease = re.sub(r'(a|b|rc)\d+$', '', self.py_version)
  146. return 'https://www.python.org/ftp/python/{0}/{1}'.format(
  147. version_minus_prerelease, filename), filename
  148. def fetch_python(self):
  149. """Fetch the MSI for the specified version of Python.
  150. It will be placed in the build directory.
  151. """
  152. url, filename = self._python_download_url_filename()
  153. cache_file = get_cache_dir(ensure_existence=True) / filename
  154. if not cache_file.is_file():
  155. logger.info('Downloading Python installer...')
  156. logger.info('Getting %s', url)
  157. download(url, cache_file)
  158. logger.info('Copying Python installer to build directory')
  159. shutil.copy2(str(cache_file), self.build_dir)
  160. def fetch_python_embeddable(self):
  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. try:
  170. shutil.rmtree(python_dir)
  171. except OSError as e:
  172. if e.errno != errno.ENOENT:
  173. raise
  174. with zipfile.ZipFile(str(cache_file)) as z:
  175. z.extractall(python_dir)
  176. self.install_dirs.append(('Python', '$INSTDIR'))
  177. def fetch_pylauncher(self):
  178. """Fetch the MSI for PyLauncher (required for Python2.x).
  179. It will be placed in the build directory.
  180. """
  181. arch_tag = '.amd64' if (self.py_bitness == 64) else ''
  182. url = ("https://bitbucket.org/vinay.sajip/pylauncher/downloads/"
  183. "launchwin{0}.msi".format(arch_tag))
  184. target = pjoin(self.build_dir, 'launchwin{0}.msi'.format(arch_tag))
  185. if os.path.isfile(target):
  186. logger.info('PyLauncher MSI already in build directory.')
  187. return
  188. logger.info('Downloading PyLauncher MSI...')
  189. download(url, target)
  190. SCRIPT_TEMPLATE = """#!python{qualifier}
  191. import sys, os
  192. scriptdir, script = os.path.split(__file__)
  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, text_types):
  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. if self.py_format == 'bundled':
  257. target = '$INSTDIR\Python\python{}.exe'
  258. else:
  259. target = 'py{}'
  260. sc['target'] = target.format('' if sc['console'] else 'w')
  261. sc['parameters'] = '"%s"' % ntpath.join('$INSTDIR', sc['script'])
  262. files.add(os.path.basename(sc['script']))
  263. shutil.copy2(sc['icon'], self.build_dir)
  264. sc['icon'] = os.path.basename(sc['icon'])
  265. files.add(sc['icon'])
  266. self.install_files.extend([(f, '$INSTDIR') for f in files])
  267. def prepare_packages(self):
  268. """Move requested packages into the build directory.
  269. If a pynsist_pkgs directory exists, it is copied into the build
  270. directory as pkgs/ . Any packages not already there are found on
  271. sys.path and copied in.
  272. """
  273. logger.info("Copying packages into build directory...")
  274. build_pkg_dir = pjoin(self.build_dir, 'pkgs')
  275. if os.path.isdir(build_pkg_dir):
  276. shutil.rmtree(build_pkg_dir)
  277. # 1. Manually prepared packages
  278. if os.path.isdir('pynsist_pkgs'):
  279. shutil.copytree('pynsist_pkgs', build_pkg_dir)
  280. else:
  281. os.mkdir(build_pkg_dir)
  282. # 2. Wheels from PyPI
  283. fetch_pypi_wheels(self.pypi_wheel_reqs, build_pkg_dir,
  284. py_version=self.py_version, bitness=self.py_bitness)
  285. # 3. Copy importable modules
  286. copy_modules(self.packages, build_pkg_dir,
  287. py_version=self.py_version, exclude=self.exclude)
  288. def copytree_ignore_callback(self, directory, files):
  289. """This is being called back by our shutil.copytree call to implement the
  290. 'exclude' feature.
  291. """
  292. ignored = set()
  293. # Filter by file names relative to the build directory
  294. directory = os.path.normpath(directory)
  295. files = [os.path.join(directory, fname) for fname in files]
  296. # Execute all patterns
  297. for pattern in self.exclude:
  298. ignored.update([
  299. os.path.basename(fname)
  300. for fname in fnmatch.filter(files, pattern)
  301. ])
  302. return ignored
  303. def copy_extra_files(self):
  304. """Copy a list of files into the build directory, and add them to
  305. install_files or install_dirs as appropriate.
  306. """
  307. for file, destination in self.extra_files:
  308. file = file.rstrip('/\\')
  309. basename = os.path.basename(file)
  310. if not destination:
  311. destination = '$INSTDIR'
  312. if os.path.isdir(file):
  313. target_name = pjoin(self.build_dir, basename)
  314. if os.path.isdir(target_name):
  315. shutil.rmtree(target_name)
  316. elif os.path.exists(target_name):
  317. os.unlink(target_name)
  318. if self.exclude:
  319. shutil.copytree(file, target_name,
  320. ignore=self.copytree_ignore_callback)
  321. else:
  322. # Don't use our exclude callback if we don't need to,
  323. # as it slows things down.
  324. shutil.copytree(file, target_name)
  325. self.install_dirs.append((basename, destination))
  326. else:
  327. shutil.copy2(file, self.build_dir)
  328. self.install_files.append((basename, destination))
  329. def write_nsi(self):
  330. """Write the NSI file to define the NSIS installer.
  331. Most of the details of this are in the template and the
  332. :class:`nsist.nsiswriter.NSISFileWriter` class.
  333. """
  334. nsis_writer = NSISFileWriter(self.nsi_template, installerbuilder=self)
  335. logger.info('Writing NSI file to %s', self.nsi_file)
  336. # Sort by destination directory, so we can group them effectively
  337. self.install_files.sort(key=operator.itemgetter(1))
  338. nsis_writer.write(self.nsi_file)
  339. if self.nsi_template == 'pyapp_msvcrt.nsi':
  340. shutil.copy2(pjoin(_PKGDIR, 'windowsversion.nsh'), self.build_dir)
  341. def run_nsis(self):
  342. """Runs makensis using the specified .nsi file
  343. Returns the exit code.
  344. """
  345. try:
  346. if os.name == 'nt':
  347. makensis = find_makensis_win()
  348. else:
  349. makensis = 'makensis'
  350. return call([makensis, self.nsi_file])
  351. except OSError as e:
  352. # This should catch either the registry key or makensis being absent
  353. if e.errno == errno.ENOENT:
  354. print("makensis was not found. Install NSIS and try again.")
  355. print("http://nsis.sourceforge.net/Download")
  356. return 1
  357. def run(self, makensis=True):
  358. """Run all the steps to build an installer.
  359. """
  360. try:
  361. os.makedirs(self.build_dir)
  362. except OSError as e:
  363. if e.errno != errno.EEXIST:
  364. raise e
  365. if self.py_format == 'bundled':
  366. self.fetch_python_embeddable()
  367. else:
  368. self.fetch_python()
  369. if self.py_version < '3.3':
  370. self.fetch_pylauncher()
  371. self.prepare_shortcuts()
  372. # Packages
  373. self.prepare_packages()
  374. # Extra files
  375. self.copy_extra_files()
  376. self.write_nsi()
  377. if makensis:
  378. exitcode = self.run_nsis()
  379. if not exitcode:
  380. logger.info('Installer written to %s', pjoin(self.build_dir, self.installer_name))
  381. def main(argv=None):
  382. """Make an installer from the command line.
  383. This parses command line arguments and a config file, and calls
  384. :func:`all_steps` with the extracted information.
  385. """
  386. logger.setLevel(logging.INFO)
  387. logger.handlers = [logging.StreamHandler()]
  388. import argparse
  389. argp = argparse.ArgumentParser(prog='pynsist')
  390. argp.add_argument('config_file')
  391. argp.add_argument('--no-makensis', action='store_true',
  392. help='Prepare files and folders, stop before calling makensis. For debugging.'
  393. )
  394. options = argp.parse_args(argv)
  395. dirname, config_file = os.path.split(options.config_file)
  396. if dirname:
  397. os.chdir(dirname)
  398. from . import configreader
  399. try:
  400. cfg = configreader.read_and_validate(config_file)
  401. shortcuts = configreader.read_shortcuts_config(cfg)
  402. except configreader.InvalidConfig as e:
  403. logger.error('Error parsing configuration file:')
  404. logger.error(str(e))
  405. sys.exit(1)
  406. appcfg = cfg['Application']
  407. try:
  408. InstallerBuilder(
  409. appname = appcfg['name'],
  410. version = appcfg['version'],
  411. icon = appcfg.get('icon', DEFAULT_ICON),
  412. shortcuts = shortcuts,
  413. packages = cfg.get('Include', 'packages', fallback='').splitlines(),
  414. pypi_wheel_reqs = cfg.get('Include', 'pypi_wheels', fallback='').splitlines(),
  415. extra_files = configreader.read_extra_files(cfg),
  416. py_version = cfg.get('Python', 'version', fallback=DEFAULT_PY_VERSION),
  417. py_bitness = cfg.getint('Python', 'bitness', fallback=DEFAULT_BITNESS),
  418. py_format = cfg.get('Python', 'format', fallback='installer'),
  419. build_dir = cfg.get('Build', 'directory', fallback=DEFAULT_BUILD_DIR),
  420. installer_name = cfg.get('Build', 'installer_name', fallback=None),
  421. nsi_template = cfg.get('Build', 'nsi_template', fallback=None),
  422. exclude = cfg.get('Include', 'exclude', fallback='').splitlines(),
  423. ).run(makensis=(not options.no_makensis))
  424. except InputError as e:
  425. logger.error("Error in config values:")
  426. logger.error(str(e))
  427. sys.exit(1)