scripts.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2013-2015 Vinay Sajip.
  4. # Licensed to the Python Software Foundation under a contributor agreement.
  5. # See LICENSE.txt and CONTRIBUTORS.txt.
  6. #
  7. from io import BytesIO
  8. import logging
  9. import os
  10. import re
  11. import struct
  12. import sys
  13. from .compat import sysconfig, detect_encoding, ZipFile
  14. from .resources import finder
  15. from .util import (FileOperator, get_export_entry, convert_path,
  16. get_executable, in_venv)
  17. logger = logging.getLogger(__name__)
  18. _DEFAULT_MANIFEST = '''
  19. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  20. <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  21. <assemblyIdentity version="1.0.0.0"
  22. processorArchitecture="X86"
  23. name="%s"
  24. type="win32"/>
  25. <!-- Identify the application security requirements. -->
  26. <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
  27. <security>
  28. <requestedPrivileges>
  29. <requestedExecutionLevel level="asInvoker" uiAccess="false"/>
  30. </requestedPrivileges>
  31. </security>
  32. </trustInfo>
  33. </assembly>'''.strip()
  34. # check if Python is called on the first line with this expression
  35. FIRST_LINE_RE = re.compile(b'^#!.*pythonw?[0-9.]*([ \t].*)?$')
  36. SCRIPT_TEMPLATE = '''# -*- coding: utf-8 -*-
  37. if __name__ == '__main__':
  38. import sys, re
  39. def _resolve(module, func):
  40. __import__(module)
  41. mod = sys.modules[module]
  42. parts = func.split('.')
  43. result = getattr(mod, parts.pop(0))
  44. for p in parts:
  45. result = getattr(result, p)
  46. return result
  47. try:
  48. sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
  49. func = _resolve('%(module)s', '%(func)s')
  50. rc = func() # None interpreted as 0
  51. except Exception as e: # only supporting Python >= 2.6
  52. sys.stderr.write('%%s\\n' %% e)
  53. rc = 1
  54. sys.exit(rc)
  55. '''
  56. def _enquote_executable(executable):
  57. if ' ' in executable:
  58. # make sure we quote only the executable in case of env
  59. # for example /usr/bin/env "/dir with spaces/bin/jython"
  60. # instead of "/usr/bin/env /dir with spaces/bin/jython"
  61. # otherwise whole
  62. if executable.startswith('/usr/bin/env '):
  63. env, _executable = executable.split(' ', 1)
  64. if ' ' in _executable and not _executable.startswith('"'):
  65. executable = '%s "%s"' % (env, _executable)
  66. else:
  67. if not executable.startswith('"'):
  68. executable = '"%s"' % executable
  69. return executable
  70. class ScriptMaker(object):
  71. """
  72. A class to copy or create scripts from source scripts or callable
  73. specifications.
  74. """
  75. script_template = SCRIPT_TEMPLATE
  76. executable = None # for shebangs
  77. def __init__(self, source_dir, target_dir, add_launchers=True,
  78. dry_run=False, fileop=None):
  79. self.source_dir = source_dir
  80. self.target_dir = target_dir
  81. self.add_launchers = add_launchers
  82. self.force = False
  83. self.clobber = False
  84. # It only makes sense to set mode bits on POSIX.
  85. self.set_mode = (os.name == 'posix') or (os.name == 'java' and
  86. os._name == 'posix')
  87. self.variants = set(('', 'X.Y'))
  88. self._fileop = fileop or FileOperator(dry_run)
  89. self._is_nt = os.name == 'nt' or (
  90. os.name == 'java' and os._name == 'nt')
  91. def _get_alternate_executable(self, executable, options):
  92. if options.get('gui', False) and self._is_nt: # pragma: no cover
  93. dn, fn = os.path.split(executable)
  94. fn = fn.replace('python', 'pythonw')
  95. executable = os.path.join(dn, fn)
  96. return executable
  97. if sys.platform.startswith('java'): # pragma: no cover
  98. def _is_shell(self, executable):
  99. """
  100. Determine if the specified executable is a script
  101. (contains a #! line)
  102. """
  103. try:
  104. with open(executable) as fp:
  105. return fp.read(2) == '#!'
  106. except (OSError, IOError):
  107. logger.warning('Failed to open %s', executable)
  108. return False
  109. def _fix_jython_executable(self, executable):
  110. if self._is_shell(executable):
  111. # Workaround for Jython is not needed on Linux systems.
  112. import java
  113. if java.lang.System.getProperty('os.name') == 'Linux':
  114. return executable
  115. elif executable.lower().endswith('jython.exe'):
  116. # Use wrapper exe for Jython on Windows
  117. return executable
  118. return '/usr/bin/env %s' % executable
  119. def _get_shebang(self, encoding, post_interp=b'', options=None):
  120. enquote = True
  121. if self.executable:
  122. executable = self.executable
  123. enquote = False # assume this will be taken care of
  124. elif not sysconfig.is_python_build():
  125. executable = get_executable()
  126. elif in_venv(): # pragma: no cover
  127. executable = os.path.join(sysconfig.get_path('scripts'),
  128. 'python%s' % sysconfig.get_config_var('EXE'))
  129. else: # pragma: no cover
  130. executable = os.path.join(
  131. sysconfig.get_config_var('BINDIR'),
  132. 'python%s%s' % (sysconfig.get_config_var('VERSION'),
  133. sysconfig.get_config_var('EXE')))
  134. if options:
  135. executable = self._get_alternate_executable(executable, options)
  136. if sys.platform.startswith('java'): # pragma: no cover
  137. executable = self._fix_jython_executable(executable)
  138. # Normalise case for Windows
  139. executable = os.path.normcase(executable)
  140. # If the user didn't specify an executable, it may be necessary to
  141. # cater for executable paths with spaces (not uncommon on Windows)
  142. if enquote:
  143. executable = _enquote_executable(executable)
  144. # Issue #51: don't use fsencode, since we later try to
  145. # check that the shebang is decodable using utf-8.
  146. executable = executable.encode('utf-8')
  147. # in case of IronPython, play safe and enable frames support
  148. if (sys.platform == 'cli' and '-X:Frames' not in post_interp
  149. and '-X:FullFrames' not in post_interp): # pragma: no cover
  150. post_interp += b' -X:Frames'
  151. shebang = b'#!' + executable + post_interp + b'\n'
  152. # Python parser starts to read a script using UTF-8 until
  153. # it gets a #coding:xxx cookie. The shebang has to be the
  154. # first line of a file, the #coding:xxx cookie cannot be
  155. # written before. So the shebang has to be decodable from
  156. # UTF-8.
  157. try:
  158. shebang.decode('utf-8')
  159. except UnicodeDecodeError: # pragma: no cover
  160. raise ValueError(
  161. 'The shebang (%r) is not decodable from utf-8' % shebang)
  162. # If the script is encoded to a custom encoding (use a
  163. # #coding:xxx cookie), the shebang has to be decodable from
  164. # the script encoding too.
  165. if encoding != 'utf-8':
  166. try:
  167. shebang.decode(encoding)
  168. except UnicodeDecodeError: # pragma: no cover
  169. raise ValueError(
  170. 'The shebang (%r) is not decodable '
  171. 'from the script encoding (%r)' % (shebang, encoding))
  172. return shebang
  173. def _get_script_text(self, entry):
  174. return self.script_template % dict(module=entry.prefix,
  175. func=entry.suffix)
  176. manifest = _DEFAULT_MANIFEST
  177. def get_manifest(self, exename):
  178. base = os.path.basename(exename)
  179. return self.manifest % base
  180. def _write_script(self, names, shebang, script_bytes, filenames, ext):
  181. use_launcher = self.add_launchers and self._is_nt
  182. linesep = os.linesep.encode('utf-8')
  183. if not use_launcher:
  184. script_bytes = shebang + linesep + script_bytes
  185. else: # pragma: no cover
  186. if ext == 'py':
  187. launcher = self._get_launcher('t')
  188. else:
  189. launcher = self._get_launcher('w')
  190. stream = BytesIO()
  191. with ZipFile(stream, 'w') as zf:
  192. zf.writestr('__main__.py', script_bytes)
  193. zip_data = stream.getvalue()
  194. script_bytes = launcher + shebang + linesep + zip_data
  195. for name in names:
  196. outname = os.path.join(self.target_dir, name)
  197. if use_launcher: # pragma: no cover
  198. n, e = os.path.splitext(outname)
  199. if e.startswith('.py'):
  200. outname = n
  201. outname = '%s.exe' % outname
  202. try:
  203. self._fileop.write_binary_file(outname, script_bytes)
  204. except Exception:
  205. # Failed writing an executable - it might be in use.
  206. logger.warning('Failed to write executable - trying to '
  207. 'use .deleteme logic')
  208. dfname = '%s.deleteme' % outname
  209. if os.path.exists(dfname):
  210. os.remove(dfname) # Not allowed to fail here
  211. os.rename(outname, dfname) # nor here
  212. self._fileop.write_binary_file(outname, script_bytes)
  213. logger.debug('Able to replace executable using '
  214. '.deleteme logic')
  215. try:
  216. os.remove(dfname)
  217. except Exception:
  218. pass # still in use - ignore error
  219. else:
  220. if self._is_nt and not outname.endswith('.' + ext): # pragma: no cover
  221. outname = '%s.%s' % (outname, ext)
  222. if os.path.exists(outname) and not self.clobber:
  223. logger.warning('Skipping existing file %s', outname)
  224. continue
  225. self._fileop.write_binary_file(outname, script_bytes)
  226. if self.set_mode:
  227. self._fileop.set_executable_mode([outname])
  228. filenames.append(outname)
  229. def _make_script(self, entry, filenames, options=None):
  230. post_interp = b''
  231. if options:
  232. args = options.get('interpreter_args', [])
  233. if args:
  234. args = ' %s' % ' '.join(args)
  235. post_interp = args.encode('utf-8')
  236. shebang = self._get_shebang('utf-8', post_interp, options=options)
  237. script = self._get_script_text(entry).encode('utf-8')
  238. name = entry.name
  239. scriptnames = set()
  240. if '' in self.variants:
  241. scriptnames.add(name)
  242. if 'X' in self.variants:
  243. scriptnames.add('%s%s' % (name, sys.version[0]))
  244. if 'X.Y' in self.variants:
  245. scriptnames.add('%s-%s' % (name, sys.version[:3]))
  246. if options and options.get('gui', False):
  247. ext = 'pyw'
  248. else:
  249. ext = 'py'
  250. self._write_script(scriptnames, shebang, script, filenames, ext)
  251. def _copy_script(self, script, filenames):
  252. adjust = False
  253. script = os.path.join(self.source_dir, convert_path(script))
  254. outname = os.path.join(self.target_dir, os.path.basename(script))
  255. if not self.force and not self._fileop.newer(script, outname):
  256. logger.debug('not copying %s (up-to-date)', script)
  257. return
  258. # Always open the file, but ignore failures in dry-run mode --
  259. # that way, we'll get accurate feedback if we can read the
  260. # script.
  261. try:
  262. f = open(script, 'rb')
  263. except IOError: # pragma: no cover
  264. if not self.dry_run:
  265. raise
  266. f = None
  267. else:
  268. first_line = f.readline()
  269. if not first_line: # pragma: no cover
  270. logger.warning('%s: %s is an empty file (skipping)',
  271. self.get_command_name(), script)
  272. return
  273. match = FIRST_LINE_RE.match(first_line.replace(b'\r\n', b'\n'))
  274. if match:
  275. adjust = True
  276. post_interp = match.group(1) or b''
  277. if not adjust:
  278. if f:
  279. f.close()
  280. self._fileop.copy_file(script, outname)
  281. if self.set_mode:
  282. self._fileop.set_executable_mode([outname])
  283. filenames.append(outname)
  284. else:
  285. logger.info('copying and adjusting %s -> %s', script,
  286. self.target_dir)
  287. if not self._fileop.dry_run:
  288. encoding, lines = detect_encoding(f.readline)
  289. f.seek(0)
  290. shebang = self._get_shebang(encoding, post_interp)
  291. if b'pythonw' in first_line: # pragma: no cover
  292. ext = 'pyw'
  293. else:
  294. ext = 'py'
  295. n = os.path.basename(outname)
  296. self._write_script([n], shebang, f.read(), filenames, ext)
  297. if f:
  298. f.close()
  299. @property
  300. def dry_run(self):
  301. return self._fileop.dry_run
  302. @dry_run.setter
  303. def dry_run(self, value):
  304. self._fileop.dry_run = value
  305. if os.name == 'nt' or (os.name == 'java' and os._name == 'nt'): # pragma: no cover
  306. # Executable launcher support.
  307. # Launchers are from https://bitbucket.org/vinay.sajip/simple_launcher/
  308. def _get_launcher(self, kind):
  309. if struct.calcsize('P') == 8: # 64-bit
  310. bits = '64'
  311. else:
  312. bits = '32'
  313. name = '%s%s.exe' % (kind, bits)
  314. # Issue 31: don't hardcode an absolute package name, but
  315. # determine it relative to the current package
  316. distlib_package = __name__.rsplit('.', 1)[0]
  317. result = finder(distlib_package).find(name).bytes
  318. return result
  319. # Public API follows
  320. def make(self, specification, options=None):
  321. """
  322. Make a script.
  323. :param specification: The specification, which is either a valid export
  324. entry specification (to make a script from a
  325. callable) or a filename (to make a script by
  326. copying from a source location).
  327. :param options: A dictionary of options controlling script generation.
  328. :return: A list of all absolute pathnames written to.
  329. """
  330. filenames = []
  331. entry = get_export_entry(specification)
  332. if entry is None:
  333. self._copy_script(specification, filenames)
  334. else:
  335. self._make_script(entry, filenames, options=options)
  336. return filenames
  337. def make_multiple(self, specifications, options=None):
  338. """
  339. Take a list of specifications and make scripts from them,
  340. :param specifications: A list of specifications.
  341. :return: A list of all absolute pathnames written to,
  342. """
  343. filenames = []
  344. for specification in specifications:
  345. filenames.extend(self.make(specification, options))
  346. return filenames