__init__.py 18 KB

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