__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. """Build NSIS installers for Python applications.
  2. """
  3. import errno
  4. import io
  5. import logging
  6. import ntpath
  7. import operator
  8. import os
  9. import re
  10. import shutil
  11. from subprocess import call
  12. import sys
  13. import fnmatch
  14. PY2 = sys.version_info[0] == 2
  15. if os.name == 'nt':
  16. if PY2:
  17. import _winreg as winreg
  18. else:
  19. import winreg
  20. else:
  21. winreg = None
  22. from .copymodules import copy_modules
  23. from .nsiswriter import NSISFileWriter
  24. from .util import download, text_types
  25. __version__ = '1.5'
  26. pjoin = os.path.join
  27. logger = logging.getLogger(__name__)
  28. _PKGDIR = os.path.abspath(os.path.dirname(__file__))
  29. DEFAULT_PY_VERSION = '2.7.9' if PY2 else '3.4.3'
  30. DEFAULT_BUILD_DIR = pjoin('build', 'nsis')
  31. DEFAULT_ICON = pjoin(_PKGDIR, 'glossyorb.ico')
  32. if os.name == 'nt' and sys.maxsize == (2**63)-1:
  33. DEFAULT_BITNESS = 64
  34. else:
  35. DEFAULT_BITNESS = 32
  36. def find_makensis_win():
  37. """Locate makensis.exe on Windows by querying the registry"""
  38. try:
  39. nsis_install_dir = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\NSIS')
  40. except OSError:
  41. nsis_install_dir = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432Node\\NSIS')
  42. return pjoin(nsis_install_dir, 'makensis.exe')
  43. class InputError(ValueError):
  44. def __init__(self, param, value, expected):
  45. self.param = param
  46. self.value = value
  47. self.expected = expected
  48. def __str__(self):
  49. return "{e.value!r} is not valid for {e.param}, expected {e.expected}".format(e=self)
  50. class InstallerBuilder(object):
  51. """Controls building an installer. This includes three main steps:
  52. 1. Arranging the necessary files in the build directory.
  53. 2. Filling out the template NSI file to control NSIS.
  54. 3. Running ``makensis`` to build the installer.
  55. :param str appname: Application name
  56. :param str version: Application version
  57. :param list shortcuts: Dictionary keyed by shortcut name, containing
  58. dictionaries whose keys match the fields of :ref:`shortcut_config`
  59. in the config file
  60. :param str icon: Path to an icon for the application
  61. :param list packages: List of strings for importable packages to include
  62. :param list extra_files: List of 2-tuples (file, destination) of files to include
  63. :param str py_version: Full version of Python to bundle
  64. :param int py_bitness: Bitness of bundled Python (32 or 64)
  65. :param str build_dir: Directory to run the build in
  66. :param str installer_name: Filename of the installer to produce
  67. :param str nsi_template: Path to a template NSI file to use
  68. """
  69. def __init__(self, appname, version, shortcuts, icon=DEFAULT_ICON,
  70. packages=None, extra_files=None, py_version=DEFAULT_PY_VERSION,
  71. py_bitness=DEFAULT_BITNESS, build_dir=DEFAULT_BUILD_DIR,
  72. installer_name=None, nsi_template=None,
  73. exclude=None):
  74. self.appname = appname
  75. self.version = version
  76. self.shortcuts = shortcuts
  77. self.icon = icon
  78. self.packages = packages or []
  79. self.exclude = [os.path.normpath(p) for p in (exclude or [])]
  80. self.extra_files = extra_files or []
  81. self.py_version = py_version
  82. if not self._py_version_pattern.match(py_version):
  83. raise InputError('py_version', py_version, "a full Python version like '3.4.0'")
  84. self.py_bitness = py_bitness
  85. if py_bitness not in {32, 64}:
  86. raise InputError('py_bitness', py_bitness, "32 or 64")
  87. self.build_dir = build_dir
  88. self.installer_name = installer_name or self.make_installer_name()
  89. self.nsi_template = nsi_template
  90. if self.nsi_template is None:
  91. if self.py_version < '3.3':
  92. self.nsi_template = 'pyapp_w_pylauncher.nsi'
  93. else:
  94. self.nsi_template = 'pyapp.nsi'
  95. self.nsi_file = pjoin(self.build_dir, 'installer.nsi')
  96. self.py_major_version = self.py_qualifier = '.'.join(self.py_version.split('.')[:2])
  97. if self.py_bitness == 32:
  98. self.py_qualifier += '-32'
  99. # To be filled later
  100. self.install_files = []
  101. self.install_dirs = []
  102. _py_version_pattern = re.compile(r'\d\.\d+\.\d+$')
  103. def make_installer_name(self):
  104. """Generate the filename of the installer exe
  105. e.g. My_App_1.0.exe
  106. """
  107. s = self.appname + '_' + self.version + '.exe'
  108. return s.replace(' ', '_')
  109. def fetch_python(self):
  110. """Fetch the MSI for the specified version of Python.
  111. It will be placed in the build directory.
  112. """
  113. version = self.py_version
  114. arch_tag = '.amd64' if (self.py_bitness==64) else ''
  115. url = 'https://python.org/ftp/python/{0}/python-{0}{1}.msi'.format(version, arch_tag)
  116. target = pjoin(self.build_dir, 'python-{0}{1}.msi'.format(version, arch_tag))
  117. if os.path.isfile(target):
  118. logger.info('Python MSI already in build directory.')
  119. return
  120. logger.info('Downloading Python MSI...')
  121. download(url, target)
  122. def fetch_pylauncher(self):
  123. """Fetch the MSI for PyLauncher (required for Python2.x).
  124. It will be placed in the build directory.
  125. """
  126. arch_tag = '.amd64' if (self.py_bitness == 64) else ''
  127. url = ("https://bitbucket.org/vinay.sajip/pylauncher/downloads/"
  128. "launchwin{0}.msi".format(arch_tag))
  129. target = pjoin(self.build_dir, 'launchwin{0}.msi'.format(arch_tag))
  130. if os.path.isfile(target):
  131. logger.info('PyLauncher MSI already in build directory.')
  132. return
  133. logger.info('Downloading PyLauncher MSI...')
  134. download(url, target)
  135. SCRIPT_TEMPLATE = """#!python{qualifier}
  136. import sys, os
  137. scriptdir, script = os.path.split(__file__)
  138. pkgdir = os.path.join(scriptdir, 'pkgs')
  139. sys.path.insert(0, pkgdir)
  140. os.environ['PYTHONPATH'] = pkgdir + os.pathsep + os.environ.get('PYTHONPATH', '')
  141. # APPDATA should always be set, but in case it isn't, try user home
  142. # If none of APPDATA, HOME, USERPROFILE or HOMEPATH are set, this will fail.
  143. appdata = os.environ.get('APPDATA', None) or os.path.expanduser('~')
  144. if 'pythonw' in sys.executable:
  145. # Running with no console - send all stdstream output to a file.
  146. kw = {{'errors': 'replace'}} if (sys.version_info[0] >= 3) else {{}}
  147. sys.stdout = sys.stderr = open(os.path.join(appdata, script+'.log'), 'w', **kw)
  148. else:
  149. # In a console. But if the console was started just for this program, it
  150. # will close as soon as we exit, so write the traceback to a file as well.
  151. def excepthook(etype, value, tb):
  152. "Write unhandled exceptions to a file and to stderr."
  153. import traceback
  154. traceback.print_exception(etype, value, tb)
  155. with open(os.path.join(appdata, script+'.log'), 'w') as f:
  156. traceback.print_exception(etype, value, tb, file=f)
  157. sys.excepthook = excepthook
  158. {extra_preamble}
  159. if __name__ == '__main__':
  160. from {module} import {func}
  161. {func}()
  162. """
  163. def write_script(self, entrypt, target, extra_preamble=''):
  164. """Write a launcher script from a 'module:function' entry point
  165. py_version and py_bitness are used to write an appropriate shebang line
  166. for the PEP 397 Windows launcher.
  167. """
  168. module, func = entrypt.split(":")
  169. with open(target, 'w') as f:
  170. f.write(self.SCRIPT_TEMPLATE.format(qualifier=self.py_qualifier,
  171. module=module, func=func, extra_preamble=extra_preamble))
  172. pkg = module.split('.')[0]
  173. if pkg not in self.packages:
  174. self.packages.append(pkg)
  175. def prepare_shortcuts(self):
  176. """Prepare shortcut files in the build directory.
  177. If entry_point is specified, write the script. If script is specified,
  178. copy to the build directory. Prepare target and parameters for these
  179. shortcuts.
  180. Also copies shortcut icons
  181. """
  182. files = set()
  183. for scname, sc in self.shortcuts.items():
  184. if not sc.get('target'):
  185. if sc.get('entry_point'):
  186. sc['script'] = script = scname.replace(' ', '_') + '.launch.py' \
  187. + ('' if sc['console'] else 'w')
  188. specified_preamble = sc.get('extra_preamble', None)
  189. if isinstance(specified_preamble, text_types):
  190. # Filename
  191. extra_preamble = io.open(specified_preamble, encoding='utf-8')
  192. elif specified_preamble is None:
  193. extra_preamble = io.StringIO() # Empty
  194. else:
  195. # Passed a StringIO or similar object
  196. extra_preamble = specified_preamble
  197. self.write_script(sc['entry_point'], pjoin(self.build_dir, script),
  198. extra_preamble.read().rstrip())
  199. else:
  200. shutil.copy2(sc['script'], self.build_dir)
  201. sc['target'] = 'py' if sc['console'] else 'pyw'
  202. sc['parameters'] = '"%s"' % ntpath.join('$INSTDIR', sc['script'])
  203. files.add(os.path.basename(sc['script']))
  204. shutil.copy2(sc['icon'], self.build_dir)
  205. sc['icon'] = os.path.basename(sc['icon'])
  206. files.add(sc['icon'])
  207. self.install_files.extend([(f, '$INSTDIR') for f in files])
  208. def prepare_packages(self):
  209. """Move requested packages into the build directory.
  210. If a pynsist_pkgs directory exists, it is copied into the build
  211. directory as pkgs/ . Any packages not already there are found on
  212. sys.path and copied in.
  213. """
  214. logger.info("Copying packages into build directory...")
  215. build_pkg_dir = pjoin(self.build_dir, 'pkgs')
  216. if os.path.isdir(build_pkg_dir):
  217. shutil.rmtree(build_pkg_dir)
  218. if os.path.isdir('pynsist_pkgs'):
  219. shutil.copytree('pynsist_pkgs', build_pkg_dir)
  220. else:
  221. os.mkdir(build_pkg_dir)
  222. copy_modules(self.packages, build_pkg_dir,
  223. py_version=self.py_version, exclude=self.exclude)
  224. def copytree_ignore_callback(self, directory, files):
  225. """This is being called back by our shutil.copytree call to implement the
  226. 'exclude' feature.
  227. """
  228. ignored = set()
  229. # Filter by file names relative to the build directory
  230. directory = os.path.normpath(directory)
  231. files = [os.path.join(directory, fname) for fname in files]
  232. # Execute all patterns
  233. for pattern in self.exclude:
  234. ignored.update([
  235. os.path.basename(fname)
  236. for fname in fnmatch.filter(files, pattern)
  237. ])
  238. return ignored
  239. def copy_extra_files(self):
  240. """Copy a list of files into the build directory, and add them to
  241. install_files or install_dirs as appropriate.
  242. """
  243. for file, destination in self.extra_files:
  244. file = file.rstrip('/\\')
  245. basename = os.path.basename(file)
  246. if not destination:
  247. destination = '$INSTDIR'
  248. if os.path.isdir(file):
  249. target_name = pjoin(self.build_dir, basename)
  250. if os.path.isdir(target_name):
  251. shutil.rmtree(target_name)
  252. elif os.path.exists(target_name):
  253. os.unlink(target_name)
  254. if self.exclude:
  255. shutil.copytree(file, target_name,
  256. ignore=self.copytree_ignore_callback)
  257. else:
  258. # Don't use our exclude callback if we don't need to,
  259. # as it slows things down.
  260. shutil.copytree(file, target_name)
  261. self.install_dirs.append((basename, destination))
  262. else:
  263. shutil.copy2(file, self.build_dir)
  264. self.install_files.append((basename, destination))
  265. def write_nsi(self):
  266. """Write the NSI file to define the NSIS installer.
  267. Most of the details of this are in the template and the
  268. :class:`nsist.nsiswriter.NSISFileWriter` class.
  269. """
  270. nsis_writer = NSISFileWriter(self.nsi_template, installerbuilder=self)
  271. logger.info('Writing NSI file to %s', self.nsi_file)
  272. # Sort by destination directory, so we can group them effectively
  273. self.install_files.sort(key=operator.itemgetter(1))
  274. nsis_writer.write(self.nsi_file)
  275. def run_nsis(self):
  276. """Runs makensis using the specified .nsi file
  277. Returns the exit code.
  278. """
  279. try:
  280. if os.name == 'nt':
  281. makensis = find_makensis_win()
  282. else:
  283. makensis = 'makensis'
  284. return call([makensis, self.nsi_file])
  285. except OSError as e:
  286. # This should catch either the registry key or makensis being absent
  287. if e.errno == errno.ENOENT:
  288. print("makensis was not found. Install NSIS and try again.")
  289. print("http://nsis.sourceforge.net/Download")
  290. return 1
  291. def run(self, makensis=True):
  292. """Run all the steps to build an installer.
  293. """
  294. try:
  295. os.makedirs(self.build_dir)
  296. except OSError as e:
  297. if e.errno != errno.EEXIST:
  298. raise e
  299. self.fetch_python()
  300. if self.py_version < '3.3':
  301. self.fetch_pylauncher()
  302. self.prepare_shortcuts()
  303. # Packages
  304. self.prepare_packages()
  305. # Extra files
  306. self.copy_extra_files()
  307. self.write_nsi()
  308. if makensis:
  309. exitcode = self.run_nsis()
  310. if not exitcode:
  311. logger.info('Installer written to %s', pjoin(self.build_dir, self.installer_name))
  312. def main(argv=None):
  313. """Make an installer from the command line.
  314. This parses command line arguments and a config file, and calls
  315. :func:`all_steps` with the extracted information.
  316. """
  317. logger.setLevel(logging.INFO)
  318. logger.handlers = [logging.StreamHandler()]
  319. import argparse
  320. argp = argparse.ArgumentParser(prog='pynsist')
  321. argp.add_argument('config_file')
  322. argp.add_argument('--no-makensis', action='store_true',
  323. help='Prepare files and folders, stop before calling makensis. For debugging.'
  324. )
  325. options = argp.parse_args(argv)
  326. dirname, config_file = os.path.split(options.config_file)
  327. if dirname:
  328. os.chdir(dirname)
  329. try:
  330. from . import configreader
  331. cfg = configreader.read_and_validate(config_file)
  332. shortcuts = configreader.read_shortcuts_config(cfg)
  333. except configreader.InvalidConfig as e:
  334. logger.error('Error parsing configuration file:')
  335. logger.error(str(e))
  336. sys.exit(1)
  337. appcfg = cfg['Application']
  338. try:
  339. InstallerBuilder(
  340. appname = appcfg['name'],
  341. version = appcfg['version'],
  342. icon = appcfg.get('icon', DEFAULT_ICON),
  343. shortcuts = shortcuts,
  344. packages = cfg.get('Include', 'packages', fallback='').splitlines(),
  345. extra_files = configreader.read_extra_files(cfg),
  346. py_version = cfg.get('Python', 'version', fallback=DEFAULT_PY_VERSION),
  347. py_bitness = cfg.getint('Python', 'bitness', fallback=DEFAULT_BITNESS),
  348. build_dir = cfg.get('Build', 'directory', fallback=DEFAULT_BUILD_DIR),
  349. installer_name = cfg.get('Build', 'installer_name', fallback=None),
  350. nsi_template = cfg.get('Build', 'nsi_template', fallback=None),
  351. exclude = cfg.get('Include', 'exclude', fallback='').splitlines(),
  352. ).run(makensis=(not options.no_makensis))
  353. except InputError as e:
  354. logger.error("Error in config values:")
  355. logger.error(str(e))
  356. sys.exit(1)