__init__.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 copy_extra_files(filelist, build_dir):
  85. """Copy a list of files into the build directory.
  86. Returns two lists, files and directories, with only the base filenames
  87. (i.e. no leading path components)
  88. """
  89. files, directories = [], []
  90. for file in filelist:
  91. file = file.rstrip('/\\')
  92. basename = os.path.basename(file)
  93. if os.path.isdir(file):
  94. target_name = pjoin(build_dir, basename)
  95. if os.path.isdir(target_name):
  96. shutil.rmtree(target_name)
  97. elif os.path.exists(target_name):
  98. os.unlink(target_name)
  99. shutil.copytree(file, target_name)
  100. directories.append(basename)
  101. else:
  102. shutil.copy2(file, build_dir)
  103. files.append(basename)
  104. return files, directories
  105. def make_installer_name(appname, version):
  106. """Generate the filename of the installer exe
  107. e.g. My_App_1.0.exe
  108. """
  109. s = appname + '_' + version + '.exe'
  110. return s.replace(' ', '_')
  111. def run_nsis(nsi_file):
  112. """Runs makensis using the specified .nsi file
  113. Returns the exit code.
  114. """
  115. try:
  116. if os.name == 'nt':
  117. makensis = pjoin(winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\NSIS'),
  118. 'makensis.exe')
  119. else:
  120. makensis = 'makensis'
  121. return call([makensis, nsi_file])
  122. except OSError as e:
  123. # This should catch either the registry key or makensis being absent
  124. if e.errno == errno.ENOENT:
  125. print("makensis was not found. Install NSIS and try again.")
  126. print("http://nsis.sourceforge.net/Download")
  127. return 1
  128. def all_steps(appname, version, script=None, entry_point=None, icon=DEFAULT_ICON, console=False,
  129. packages=None, extra_files=None, py_version=DEFAULT_PY_VERSION,
  130. py_bitness=DEFAULT_BITNESS, build_dir=DEFAULT_BUILD_DIR,
  131. installer_name=None, nsi_template=DEFAULT_NSI_TEMPLATE):
  132. """Run all the steps to build an installer.
  133. For details of the parameters, see the documentation for the config file
  134. options.
  135. """
  136. installer_name = installer_name or make_installer_name(appname, version)
  137. try:
  138. os.makedirs(build_dir)
  139. except OSError as e:
  140. if e.errno != errno.EEXIST:
  141. raise e
  142. fetch_python(version=py_version, bitness=py_bitness, destination=build_dir)
  143. if PY2:
  144. fetch_pylauncher(bitness=py_bitness, destination=build_dir)
  145. if entry_point is not None:
  146. if script is not None:
  147. raise ValueError('Both script and entry_point were specified.')
  148. script = 'launch.py'
  149. write_script(entry_point, py_version, py_bitness, pjoin(build_dir, script))
  150. elif script is not None:
  151. shutil.copy2(script, build_dir)
  152. else:
  153. raise ValueError('Neither script nor entry_point was specified.')
  154. shutil.copy2(icon, build_dir)
  155. # Packages
  156. logger.info("Copying packages into build directory...")
  157. build_pkg_dir = pjoin(build_dir, 'pkgs')
  158. if os.path.isdir(build_pkg_dir):
  159. shutil.rmtree(build_pkg_dir)
  160. if os.path.isdir('pynsist_pkgs'):
  161. shutil.copytree('pynsist_pkgs', build_pkg_dir)
  162. else:
  163. os.mkdir(build_pkg_dir)
  164. copy_modules(packages or [], build_pkg_dir)
  165. nsis_writer = NSISFileWriter(nsi_template,
  166. definitions = {'PRODUCT_NAME': appname,
  167. 'PRODUCT_VERSION': version,
  168. 'PY_VERSION': py_version,
  169. 'SCRIPT': os.path.basename(script),
  170. 'PRODUCT_ICON': os.path.basename(icon),
  171. 'INSTALLER_NAME': installer_name,
  172. 'ARCH_TAG': '.amd64' if (py_bitness==64) else '',
  173. 'PY_EXE': 'py' if console else 'pyw',
  174. }
  175. )
  176. # Extra files
  177. nsis_writer.files, nsis_writer.directories = \
  178. copy_extra_files(extra_files or [], build_dir)
  179. nsi_file = pjoin(build_dir, 'installer.nsi')
  180. nsis_writer.write(nsi_file)
  181. exitcode = run_nsis(nsi_file)
  182. if not exitcode:
  183. logger.info('Installer written to %s', pjoin(build_dir, installer_name))
  184. def main(argv=None):
  185. """Make an installer from the command line.
  186. This parses command line arguments and a config file, and calls
  187. :func:`all_steps` with the extracted information.
  188. """
  189. logger.setLevel(logging.INFO)
  190. logger.addHandler(logging.StreamHandler())
  191. import argparse
  192. argp = argparse.ArgumentParser(prog='pynsist')
  193. argp.add_argument('config_file')
  194. options = argp.parse_args(argv)
  195. dirname, config_file = os.path.split(options.config_file)
  196. if dirname:
  197. os.chdir(dirname)
  198. import configparser
  199. cfg = configparser.ConfigParser()
  200. cfg.read(config_file)
  201. appcfg = cfg['Application']
  202. all_steps(
  203. appname = appcfg['name'],
  204. version = appcfg['version'],
  205. script = appcfg.get('script', fallback=None),
  206. entry_point = appcfg.get('entry_point', fallback=None),
  207. icon = appcfg.get('icon', DEFAULT_ICON),
  208. console = appcfg.getboolean('console', fallback=False),
  209. packages = cfg.get('Include', 'packages', fallback='').splitlines(),
  210. extra_files = cfg.get('Include', 'files', fallback='').splitlines(),
  211. py_version = cfg.get('Python', 'version', fallback=DEFAULT_PY_VERSION),
  212. py_bitness = cfg.getint('Python', 'bitness', fallback=DEFAULT_BITNESS),
  213. build_dir = cfg.get('Build', 'directory', fallback=DEFAULT_BUILD_DIR),
  214. installer_name = cfg.get('Build', 'installer_name', fallback=None),
  215. nsi_template = cfg.get('Build', 'nsi_template', fallback=DEFAULT_NSI_TEMPLATE),
  216. )