scripts.py 16 KB

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