__init__.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import logging
  2. import os
  3. import re
  4. import shutil
  5. from subprocess import check_output, call
  6. import sys
  7. from urllib.request import urlretrieve
  8. from .copymodules import copy_modules
  9. pjoin = os.path.join
  10. logger = logging.getLogger(__name__)
  11. _PKGDIR = os.path.dirname(__file__)
  12. DEFAULT_PY_VERSION = '3.3.2'
  13. DEFAULT_BUILD_DIR = pjoin('build', 'nsis')
  14. DEFAULT_ICON = pjoin(_PKGDIR, 'glossyorb.ico')
  15. if os.name == 'nt' and sys.maxsize == (2**63)-1:
  16. DEFAULT_BITNESS = 64
  17. else:
  18. DEFAULT_BITNESS = 32
  19. def fetch_python(version=DEFAULT_PY_VERSION, bitness=DEFAULT_BITNESS,
  20. destination=DEFAULT_BUILD_DIR):
  21. """Fetch the MSI for the specified version of Python.
  22. It will be placed in the destination directory, and validated using GPG
  23. if possible.
  24. """
  25. arch_tag = '.amd64' if (bitness==64) else ''
  26. url = 'http://python.org/ftp/python/{0}/python-{0}{1}.msi'.format(version, arch_tag)
  27. target = pjoin(destination, 'python-{0}{1}.msi'.format(version, arch_tag))
  28. if os.path.isfile(target):
  29. logger.info('Python MSI already in build directory.')
  30. return
  31. logger.info('Downloading Python MSI...')
  32. urlretrieve(url, target)
  33. urlretrieve(url+'.asc', target+'.asc')
  34. try:
  35. keys_file = os.path.join(_PKGDIR, 'python-pubkeys.txt')
  36. check_output(['gpg', '--import', keys_file])
  37. check_output(['gpg', '--verify', target+'.asc'])
  38. except FileNotFoundError:
  39. logger.warn("GPG not available - could not check signature of {0}".format(target))
  40. def copy_extra_files(filelist, build_dir):
  41. results = [] # name, is_directory
  42. for file in filelist:
  43. file = file.rstrip('/\\')
  44. basename = os.path.basename(file)
  45. if os.path.isdir(file):
  46. target_name = pjoin(build_dir, basename)
  47. if os.path.isdir(target_name):
  48. shutil.rmtree(target_name)
  49. elif os.path.exists(target_name):
  50. os.unlink(target_name)
  51. shutil.copytree(file, target_name)
  52. results.append((basename, True))
  53. else:
  54. shutil.copy2(file, build_dir)
  55. results.append((basename, False))
  56. return results
  57. def make_installer_name(appname, version):
  58. s = appname + '_' + version + '.exe'
  59. return s.replace(' ', '_')
  60. def _write_extra_files_install(f, extra_files, indent):
  61. for file, is_dir in extra_files:
  62. if is_dir:
  63. f.write(indent+'SetOutPath "$INSTDIR\{}"\n'.format(file))
  64. f.write(indent+'File /r "{}\*.*"\n'.format(file))
  65. f.write(indent+'SetOutPath "$INSTDIR"\n')
  66. else:
  67. f.write(indent+'File "{}"\n'.format(file))
  68. def _write_extra_files_uninstall(f, extra_files, indent):
  69. for file, is_dir in extra_files:
  70. if is_dir:
  71. f.write(indent+'RMDir /r "$INSTDIR\{}"\n'.format(file))
  72. else:
  73. f.write(indent+'Delete "$INSTDIR\{}"\n'.format(file))
  74. def write_nsis_file(nsi_file, definitions, extra_files):
  75. with open(nsi_file, 'w') as f:
  76. for name, value in definitions.items():
  77. f.write('!define {} "{}"\n'.format(name, value))
  78. with open(pjoin(_PKGDIR, 'template.nsi')) as f2:
  79. for line in f2:
  80. f.write(line)
  81. if line.strip() == ';EXTRA_FILES_INSTALL':
  82. indent = re.match('\s*', line).group(0)
  83. _write_extra_files_install(f, extra_files, indent)
  84. elif line.strip() == ';EXTRA_FILES_UNINSTALL':
  85. indent = re.match('\s*', line).group(0)
  86. _write_extra_files_uninstall(f, extra_files, indent)
  87. def run_nsis(nsi_file):
  88. call(['makensis', nsi_file])
  89. def all_steps(appname, version, script, icon=DEFAULT_ICON, packages=None,
  90. extra_files=None, py_version=DEFAULT_PY_VERSION,
  91. py_bitness=DEFAULT_BITNESS, build_dir=DEFAULT_BUILD_DIR,
  92. installer_name=None):
  93. installer_name = installer_name or make_installer_name(appname, version)
  94. os.makedirs(build_dir, exist_ok=True)
  95. fetch_python(version=py_version, bitness=py_bitness, destination=build_dir)
  96. shutil.copy2(script, build_dir)
  97. shutil.copy2(icon, build_dir)
  98. # Packages
  99. build_pkg_dir = pjoin(build_dir, 'pkgs')
  100. if os.path.isdir(build_pkg_dir):
  101. shutil.rmtree(build_pkg_dir)
  102. if os.path.isdir('pynsist_pkgs'):
  103. shutil.copytree('pynsist_pkgs', build_pkg_dir)
  104. else:
  105. os.mkdir(build_pkg_dir)
  106. copy_modules(packages or [], build_pkg_dir)
  107. # Extra files
  108. extra_files_copied = copy_extra_files(extra_files or [], build_dir)
  109. nsi_file = pjoin(build_dir, 'installer.nsi')
  110. definitions = {'PRODUCT_NAME': appname,
  111. 'PRODUCT_VERSION': version,
  112. 'PY_VERSION': py_version,
  113. 'SCRIPT': os.path.basename(script),
  114. 'PRODUCT_ICON': os.path.basename(icon),
  115. 'INSTALLER_NAME': installer_name,
  116. 'ARCH_TAG': '.amd64' if (py_bitness==64) else ''
  117. }
  118. write_nsis_file(nsi_file, definitions, extra_files_copied)
  119. run_nsis(nsi_file)
  120. logger.info('Installer written to %s', pjoin(build_dir, installer_name))
  121. def main(argv=None):
  122. logger.setLevel(logging.INFO)
  123. logger.addHandler(logging.StreamHandler())
  124. import argparse
  125. argp = argparse.ArgumentParser(prog='pynsist')
  126. argp.add_argument('config_file')
  127. options = argp.parse_args(argv)
  128. dirname, config_file = os.path.split(options.config_file)
  129. if dirname:
  130. os.chdir(dirname)
  131. import configparser
  132. cfg = configparser.ConfigParser()
  133. cfg.read(config_file)
  134. appcfg = cfg['Application']
  135. all_steps(
  136. appname = appcfg['name'],
  137. version = appcfg['version'],
  138. script = appcfg['script'],
  139. icon = appcfg.get('icon', DEFAULT_ICON),
  140. packages = cfg.get('Include', 'packages', fallback='').splitlines(),
  141. extra_files = cfg.get('Include', 'files', fallback='').splitlines(),
  142. py_version = cfg.get('Python', 'version', fallback=DEFAULT_PY_VERSION),
  143. py_bitness = cfg.getint('Python', 'bitness', fallback=DEFAULT_BITNESS),
  144. build_dir = cfg.get('Build', 'directory', fallback=DEFAULT_BUILD_DIR),
  145. installer_name = cfg.get('Build', 'installer_name', fallback=None),
  146. )