1
0

__init__.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. """Build NSIS installers for Python applications.
  2. """
  3. import logging
  4. import os
  5. import shutil
  6. from subprocess import check_output, call
  7. import sys
  8. from urllib.request import urlretrieve
  9. if os.name == 'nt':
  10. import winreg
  11. else:
  12. winreg = None
  13. from .copymodules import copy_modules
  14. from .nsiswriter import NSISFileWriter
  15. pjoin = os.path.join
  16. logger = logging.getLogger(__name__)
  17. _PKGDIR = os.path.abspath(os.path.dirname(__file__))
  18. DEFAULT_PY_VERSION = '3.3.2'
  19. DEFAULT_BUILD_DIR = pjoin('build', 'nsis')
  20. DEFAULT_NSI_TEMPLATE = pjoin(_PKGDIR, 'template.nsi')
  21. DEFAULT_ICON = pjoin(_PKGDIR, 'glossyorb.ico')
  22. if os.name == 'nt' and sys.maxsize == (2**63)-1:
  23. DEFAULT_BITNESS = 64
  24. else:
  25. DEFAULT_BITNESS = 32
  26. def fetch_python(version=DEFAULT_PY_VERSION, bitness=DEFAULT_BITNESS,
  27. destination=DEFAULT_BUILD_DIR):
  28. """Fetch the MSI for the specified version of Python.
  29. It will be placed in the destination directory, and validated using GPG
  30. if possible.
  31. """
  32. arch_tag = '.amd64' if (bitness==64) else ''
  33. url = 'http://python.org/ftp/python/{0}/python-{0}{1}.msi'.format(version, arch_tag)
  34. target = pjoin(destination, 'python-{0}{1}.msi'.format(version, arch_tag))
  35. if os.path.isfile(target):
  36. logger.info('Python MSI already in build directory.')
  37. return
  38. logger.info('Downloading Python MSI...')
  39. urlretrieve(url, target)
  40. urlretrieve(url+'.asc', target+'.asc')
  41. try:
  42. keys_file = os.path.join(_PKGDIR, 'python-pubkeys.txt')
  43. check_output(['gpg', '--import', keys_file])
  44. check_output(['gpg', '--verify', target+'.asc'])
  45. except FileNotFoundError:
  46. logger.warn("GPG not available - could not check signature of {0}".format(target))
  47. SCRIPT_TEMPLATE = """#!python{qualifier}
  48. import sys
  49. sys.path.insert(0, 'pkgs')
  50. from {module} import {func}
  51. {func}()
  52. """
  53. def write_script(entrypt, python_version, bitness, target):
  54. """Write a launcher script from a 'module:function' entry point
  55. python_version and bitness are used to write an appropriate shebang line
  56. for the PEP 397 Windows launcher.
  57. """
  58. qualifier = '.'.join(python_version.split('.')[:2])
  59. if bitness == 32:
  60. qualifier += '-32'
  61. module, func = entrypt.split(":")
  62. with open(target, 'w') as f:
  63. f.write(SCRIPT_TEMPLATE.format(qualifier=qualifier, module=module, func=func))
  64. def copy_extra_files(filelist, build_dir):
  65. """Copy a list of files into the build directory.
  66. Returns a list of 2-tuples: the filename without any path coomponents,
  67. and a boolean that is True if the file is a directory.
  68. """
  69. results = [] # name, is_directory
  70. for file in filelist:
  71. file = file.rstrip('/\\')
  72. basename = os.path.basename(file)
  73. if os.path.isdir(file):
  74. target_name = pjoin(build_dir, basename)
  75. if os.path.isdir(target_name):
  76. shutil.rmtree(target_name)
  77. elif os.path.exists(target_name):
  78. os.unlink(target_name)
  79. shutil.copytree(file, target_name)
  80. results.append((basename, True))
  81. else:
  82. shutil.copy2(file, build_dir)
  83. results.append((basename, False))
  84. return results
  85. def make_installer_name(appname, version):
  86. """Generate the filename of the installer exe
  87. e.g. My_App_1.0.exe
  88. """
  89. s = appname + '_' + version + '.exe'
  90. return s.replace(' ', '_')
  91. def run_nsis(nsi_file):
  92. """Runs makensis using the specified .nsi file
  93. Returns the exit code.
  94. """
  95. try:
  96. if os.name == 'nt':
  97. makensis = pjoin(winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\NSIS'),
  98. 'makensis.exe')
  99. else:
  100. makensis = 'makensis'
  101. return call([makensis, nsi_file])
  102. except FileNotFoundError:
  103. # FileNotFoundError catches both the registry lookup failing and call()
  104. # not finding makensis
  105. print("makensis was not found. Install NSIS and try again.")
  106. print("http://nsis.sourceforge.net/Download")
  107. return 1
  108. def all_steps(appname, version, script=None, entry_point=None, icon=DEFAULT_ICON, console=False,
  109. packages=None, extra_files=None, py_version=DEFAULT_PY_VERSION,
  110. py_bitness=DEFAULT_BITNESS, build_dir=DEFAULT_BUILD_DIR,
  111. installer_name=None, nsi_template=DEFAULT_NSI_TEMPLATE):
  112. """Run all the steps to build an installer.
  113. For details of the parameters, see the documentation for the config file
  114. options.
  115. """
  116. installer_name = installer_name or make_installer_name(appname, version)
  117. os.makedirs(build_dir, exist_ok=True)
  118. fetch_python(version=py_version, bitness=py_bitness, destination=build_dir)
  119. if entry_point is not None:
  120. if script is not None:
  121. raise ValueError('Both script and entry_point were specified.')
  122. script = 'launch.py'
  123. write_script(entry_point, py_version, py_bitness, pjoin(build_dir, script))
  124. elif script is not None:
  125. shutil.copy2(script, build_dir)
  126. else:
  127. raise ValueError('Neither script nor entry_point was specified.')
  128. shutil.copy2(icon, build_dir)
  129. # Packages
  130. logger.info("Copying packages into build directory...")
  131. build_pkg_dir = pjoin(build_dir, 'pkgs')
  132. if os.path.isdir(build_pkg_dir):
  133. shutil.rmtree(build_pkg_dir)
  134. if os.path.isdir('pynsist_pkgs'):
  135. shutil.copytree('pynsist_pkgs', build_pkg_dir)
  136. else:
  137. os.mkdir(build_pkg_dir)
  138. copy_modules(packages or [], build_pkg_dir)
  139. nsis_writer = NSISFileWriter(nsi_template,
  140. definitions = {'PRODUCT_NAME': appname,
  141. 'PRODUCT_VERSION': version,
  142. 'PY_VERSION': py_version,
  143. 'SCRIPT': os.path.basename(script),
  144. 'PRODUCT_ICON': os.path.basename(icon),
  145. 'INSTALLER_NAME': installer_name,
  146. 'ARCH_TAG': '.amd64' if (py_bitness==64) else '',
  147. 'PY_EXE': 'py' if console else 'pyw',
  148. }
  149. )
  150. # Extra files
  151. nsis_writer.extra_files = copy_extra_files(extra_files or [], build_dir)
  152. nsi_file = pjoin(build_dir, 'installer.nsi')
  153. nsis_writer.write(nsi_file)
  154. exitcode = run_nsis(nsi_file)
  155. if not exitcode:
  156. logger.info('Installer written to %s', pjoin(build_dir, installer_name))
  157. def main(argv=None):
  158. """Make an installer from the command line.
  159. This parses command line arguments and a config file, and calls
  160. :func:`all_steps` with the extracted information.
  161. """
  162. logger.setLevel(logging.INFO)
  163. logger.addHandler(logging.StreamHandler())
  164. import argparse
  165. argp = argparse.ArgumentParser(prog='pynsist')
  166. argp.add_argument('config_file')
  167. options = argp.parse_args(argv)
  168. dirname, config_file = os.path.split(options.config_file)
  169. if dirname:
  170. os.chdir(dirname)
  171. import configparser
  172. cfg = configparser.ConfigParser()
  173. cfg.read(config_file)
  174. appcfg = cfg['Application']
  175. all_steps(
  176. appname = appcfg['name'],
  177. version = appcfg['version'],
  178. script = appcfg.get('script', fallback=None),
  179. entry_point = appcfg.get('entry_point', fallback=None),
  180. icon = appcfg.get('icon', DEFAULT_ICON),
  181. console = appcfg.getboolean('console', fallback=False),
  182. packages = cfg.get('Include', 'packages', fallback='').splitlines(),
  183. extra_files = cfg.get('Include', 'files', fallback='').splitlines(),
  184. py_version = cfg.get('Python', 'version', fallback=DEFAULT_PY_VERSION),
  185. py_bitness = cfg.getint('Python', 'bitness', fallback=DEFAULT_BITNESS),
  186. build_dir = cfg.get('Build', 'directory', fallback=DEFAULT_BUILD_DIR),
  187. installer_name = cfg.get('Build', 'installer_name', fallback=None),
  188. nsi_template = cfg.get('Build', 'nsi_template', fallback=DEFAULT_NSI_TEMPLATE),
  189. )