__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. """Build NSIS installers for Python applications.
  2. """
  3. import errno
  4. import logging
  5. import os
  6. import shutil
  7. from subprocess import check_output, call
  8. import sys
  9. PY2 = sys.version_info[0] == 2
  10. if PY2:
  11. from urllib import urlretrieve
  12. else:
  13. from urllib.request import urlretrieve
  14. if os.name == 'nt' and PY2:
  15. import _winreg as winreg
  16. elif os.name == 'nt':
  17. import winreg
  18. else:
  19. winreg = None
  20. from .copymodules import copy_modules
  21. from .nsiswriter import NSISFileWriter
  22. __version__ = '0.2'
  23. pjoin = os.path.join
  24. logger = logging.getLogger(__name__)
  25. _PKGDIR = os.path.abspath(os.path.dirname(__file__))
  26. DEFAULT_PY_VERSION = '2.7.6' if PY2 else '3.4.0'
  27. DEFAULT_BUILD_DIR = pjoin('build', 'nsis')
  28. DEFAULT_NSI_TEMPLATE = pjoin(_PKGDIR, 'template.nsi')
  29. DEFAULT_ICON = pjoin(_PKGDIR, 'glossyorb.ico')
  30. if os.name == 'nt' and sys.maxsize == (2**63)-1:
  31. DEFAULT_BITNESS = 64
  32. else:
  33. DEFAULT_BITNESS = 32
  34. def fetch_python(version=DEFAULT_PY_VERSION, bitness=DEFAULT_BITNESS,
  35. destination=DEFAULT_BUILD_DIR):
  36. """Fetch the MSI for the specified version of Python.
  37. It will be placed in the destination directory, and validated using GPG
  38. if possible.
  39. """
  40. arch_tag = '.amd64' if (bitness==64) else ''
  41. url = 'http://python.org/ftp/python/{0}/python-{0}{1}.msi'.format(version, arch_tag)
  42. target = pjoin(destination, 'python-{0}{1}.msi'.format(version, arch_tag))
  43. if os.path.isfile(target):
  44. logger.info('Python MSI already in build directory.')
  45. return
  46. logger.info('Downloading Python MSI...')
  47. urlretrieve(url, target)
  48. urlretrieve(url+'.asc', target+'.asc')
  49. try:
  50. keys_file = os.path.join(_PKGDIR, 'python-pubkeys.txt')
  51. check_output(['gpg', '--import', keys_file])
  52. check_output(['gpg', '--verify', target+'.asc'])
  53. except OSError:
  54. logger.warn("GPG not available - could not check signature of {0}".format(target))
  55. def fetch_pylauncher(bitness=DEFAULT_BITNESS, destination=DEFAULT_BUILD_DIR):
  56. """Fetch the MSI for PyLauncher (required for Python2.x).
  57. It will be placed in the destination directory.
  58. """
  59. arch_tag = '.amd64' if (bitness == 64) else ''
  60. url = ("https://bitbucket.org/vinay.sajip/pylauncher/downloads/"
  61. "launchwin{0}.msi".format(arch_tag))
  62. target = pjoin(destination, 'launchwin{0}.msi'.format(arch_tag))
  63. if os.path.isfile(target):
  64. logger.info('PyLauncher MSI already in build directory.')
  65. return
  66. logger.info('Downloading PyLauncher MSI...')
  67. urlretrieve(url, target)
  68. SCRIPT_TEMPLATE = """#!python{qualifier}
  69. import sys, os
  70. scriptdir, script = os.path.split(__file__)
  71. pkgdir = os.path.join(scriptdir, 'pkgs')
  72. sys.path.insert(0, pkgdir)
  73. os.environ['PYTHONPATH'] = pkgdir + os.pathsep + os.environ.get('PYTHONPATH', '')
  74. def excepthook(etype, value, tb):
  75. "Write unhandled exceptions to a file rather than exiting silently."
  76. import traceback
  77. with open(os.path.join(scriptdir, script+'.log'), 'w') as f:
  78. traceback.print_exception(etype, value, tb, file=f)
  79. sys.excepthook = excepthook
  80. from {module} import {func}
  81. {func}()
  82. """
  83. def write_script(entrypt, python_version, bitness, target):
  84. """Write a launcher script from a 'module:function' entry point
  85. python_version and bitness are used to write an appropriate shebang line
  86. for the PEP 397 Windows launcher.
  87. """
  88. qualifier = '.'.join(python_version.split('.')[:2])
  89. if bitness == 32:
  90. qualifier += '-32'
  91. module, func = entrypt.split(":")
  92. with open(target, 'w') as f:
  93. f.write(SCRIPT_TEMPLATE.format(qualifier=qualifier, module=module, func=func))
  94. def prepare_shortcuts(shortcuts, py_version, py_bitness, build_dir):
  95. files = set()
  96. for scname, sc in shortcuts.items():
  97. if sc.get('entry_point'):
  98. sc['script'] = script = scname.replace(' ', '_') + '.launch.py'
  99. write_script(sc['entry_point'], py_version, py_bitness,
  100. pjoin(build_dir, script))
  101. else:
  102. shutil.copy2(sc['script'], build_dir)
  103. shutil.copy2(sc['icon'], build_dir)
  104. sc['icon'] = os.path.basename(sc['icon'])
  105. sc['script'] = os.path.basename(sc['script'])
  106. files.add(sc['script'])
  107. files.add(sc['icon'])
  108. return files
  109. def copy_extra_files(filelist, build_dir):
  110. """Copy a list of files into the build directory.
  111. Returns two lists, files and directories, with only the base filenames
  112. (i.e. no leading path components)
  113. """
  114. files, directories = [], []
  115. for file in filelist:
  116. file = file.rstrip('/\\')
  117. basename = os.path.basename(file)
  118. if os.path.isdir(file):
  119. target_name = pjoin(build_dir, basename)
  120. if os.path.isdir(target_name):
  121. shutil.rmtree(target_name)
  122. elif os.path.exists(target_name):
  123. os.unlink(target_name)
  124. shutil.copytree(file, target_name)
  125. directories.append(basename)
  126. else:
  127. shutil.copy2(file, build_dir)
  128. files.append(basename)
  129. return files, directories
  130. def make_installer_name(appname, version):
  131. """Generate the filename of the installer exe
  132. e.g. My_App_1.0.exe
  133. """
  134. s = appname + '_' + version + '.exe'
  135. return s.replace(' ', '_')
  136. def run_nsis(nsi_file):
  137. """Runs makensis using the specified .nsi file
  138. Returns the exit code.
  139. """
  140. try:
  141. if os.name == 'nt':
  142. makensis = pjoin(winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\NSIS'),
  143. 'makensis.exe')
  144. else:
  145. makensis = 'makensis'
  146. return call([makensis, nsi_file])
  147. except OSError as e:
  148. # This should catch either the registry key or makensis being absent
  149. if e.errno == errno.ENOENT:
  150. print("makensis was not found. Install NSIS and try again.")
  151. print("http://nsis.sourceforge.net/Download")
  152. return 1
  153. def all_steps(appname, version, shortcuts, icon=DEFAULT_ICON,
  154. packages=None, extra_files=None, py_version=DEFAULT_PY_VERSION,
  155. py_bitness=DEFAULT_BITNESS, build_dir=DEFAULT_BUILD_DIR,
  156. installer_name=None, nsi_template=DEFAULT_NSI_TEMPLATE):
  157. """Run all the steps to build an installer.
  158. For details of the parameters, see the documentation for the config file
  159. options.
  160. """
  161. installer_name = installer_name or make_installer_name(appname, version)
  162. try:
  163. os.makedirs(build_dir)
  164. except OSError as e:
  165. if e.errno != errno.EEXIST:
  166. raise e
  167. fetch_python(version=py_version, bitness=py_bitness, destination=build_dir)
  168. if PY2:
  169. fetch_pylauncher(bitness=py_bitness, destination=build_dir)
  170. shortcuts_files = prepare_shortcuts(shortcuts, py_version, py_bitness, build_dir)
  171. # Packages
  172. logger.info("Copying packages into build directory...")
  173. build_pkg_dir = pjoin(build_dir, 'pkgs')
  174. if os.path.isdir(build_pkg_dir):
  175. shutil.rmtree(build_pkg_dir)
  176. if os.path.isdir('pynsist_pkgs'):
  177. shutil.copytree('pynsist_pkgs', build_pkg_dir)
  178. else:
  179. os.mkdir(build_pkg_dir)
  180. copy_modules(packages or [], build_pkg_dir, py_version=py_version)
  181. nsis_writer = NSISFileWriter(nsi_template,
  182. definitions = {'PRODUCT_NAME': appname,
  183. 'PRODUCT_VERSION': version,
  184. 'PY_VERSION': py_version,
  185. 'PRODUCT_ICON': os.path.basename(icon),
  186. 'INSTALLER_NAME': installer_name,
  187. 'ARCH_TAG': '.amd64' if (py_bitness==64) else '',
  188. }
  189. )
  190. # Extra files
  191. nsis_writer.files, nsis_writer.directories = \
  192. copy_extra_files(extra_files or [], build_dir)
  193. nsis_writer.files.extend(shortcuts_files)
  194. nsis_writer.shortcuts = shortcuts
  195. nsi_file = pjoin(build_dir, 'installer.nsi')
  196. nsis_writer.write(nsi_file)
  197. exitcode = run_nsis(nsi_file)
  198. if not exitcode:
  199. logger.info('Installer written to %s', pjoin(build_dir, installer_name))
  200. def read_shortcuts_config(cfg):
  201. shortcuts = {}
  202. def _check_shortcut(name, sc, section):
  203. if ('entry_point' not in sc) and ('script' not in sc):
  204. raise ValueError('Section {} has neither entry_point nor script.'.format(section))
  205. elif ('entry_point' in sc) and ('script' in sc):
  206. raise ValueError('Section {} has both entry_point and script.'.format(section))
  207. # Copy to a regular dict so it can hold a boolean value
  208. sc2 = dict(sc)
  209. if 'icon' not in sc2:
  210. sc2['icon'] = DEFAULT_ICON
  211. sc2['console'] = sc.getboolean('console', fallback=False)
  212. shortcuts[name] = sc2
  213. for section in cfg.sections():
  214. if section.startswith("Shortcut "):
  215. name = section[len("Shortcut "):]
  216. _check_shortcut(name, cfg[section], section)
  217. appcfg = cfg['Application']
  218. _check_shortcut(appcfg['name'], appcfg, 'Application')
  219. return shortcuts
  220. def main(argv=None):
  221. """Make an installer from the command line.
  222. This parses command line arguments and a config file, and calls
  223. :func:`all_steps` with the extracted information.
  224. """
  225. logger.setLevel(logging.INFO)
  226. logger.addHandler(logging.StreamHandler())
  227. import argparse
  228. argp = argparse.ArgumentParser(prog='pynsist')
  229. argp.add_argument('config_file')
  230. options = argp.parse_args(argv)
  231. dirname, config_file = os.path.split(options.config_file)
  232. if dirname:
  233. os.chdir(dirname)
  234. try:
  235. from . import configreader
  236. cfg = configreader.read_and_validate(config_file)
  237. except configreader.InvalidConfig as e:
  238. logger.error('Error parsing configuration file:')
  239. logger.error(str(e))
  240. sys.exit(1)
  241. appcfg = cfg['Application']
  242. all_steps(
  243. appname = appcfg['name'],
  244. version = appcfg['version'],
  245. icon = appcfg.get('icon', DEFAULT_ICON),
  246. shortcuts = read_shortcuts_config(cfg),
  247. packages = cfg.get('Include', 'packages', fallback='').splitlines(),
  248. extra_files = cfg.get('Include', 'files', fallback='').splitlines(),
  249. py_version = cfg.get('Python', 'version', fallback=DEFAULT_PY_VERSION),
  250. py_bitness = cfg.getint('Python', 'bitness', fallback=DEFAULT_BITNESS),
  251. build_dir = cfg.get('Build', 'directory', fallback=DEFAULT_BUILD_DIR),
  252. installer_name = cfg.get('Build', 'installer_name', fallback=None),
  253. nsi_template = cfg.get('Build', 'nsi_template', fallback=DEFAULT_NSI_TEMPLATE),
  254. )