__init__.py 10 KB

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