scripts.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 - COMMENTED OUT
  155. # executable = os.path.normcase(executable)
  156. # N.B. The normalising operation above has been commented out: See
  157. # issue #124. Although paths in Windows are generally case-insensitive,
  158. # they aren't always. For example, a path containing a ẞ (which is a
  159. # LATIN CAPITAL LETTER SHARP S - U+1E9E) is normcased to ß (which is a
  160. # LATIN SMALL LETTER SHARP S' - U+00DF). The two are not considered by
  161. # Windows as equivalent in path names.
  162. # If the user didn't specify an executable, it may be necessary to
  163. # cater for executable paths with spaces (not uncommon on Windows)
  164. if enquote:
  165. executable = _enquote_executable(executable)
  166. # Issue #51: don't use fsencode, since we later try to
  167. # check that the shebang is decodable using utf-8.
  168. executable = executable.encode('utf-8')
  169. # in case of IronPython, play safe and enable frames support
  170. if (sys.platform == 'cli' and '-X:Frames' not in post_interp
  171. and '-X:FullFrames' not in post_interp): # pragma: no cover
  172. post_interp += b' -X:Frames'
  173. shebang = self._build_shebang(executable, post_interp)
  174. # Python parser starts to read a script using UTF-8 until
  175. # it gets a #coding:xxx cookie. The shebang has to be the
  176. # first line of a file, the #coding:xxx cookie cannot be
  177. # written before. So the shebang has to be decodable from
  178. # UTF-8.
  179. try:
  180. shebang.decode('utf-8')
  181. except UnicodeDecodeError: # pragma: no cover
  182. raise ValueError(
  183. 'The shebang (%r) is not decodable from utf-8' % shebang)
  184. # If the script is encoded to a custom encoding (use a
  185. # #coding:xxx cookie), the shebang has to be decodable from
  186. # the script encoding too.
  187. if encoding != 'utf-8':
  188. try:
  189. shebang.decode(encoding)
  190. except UnicodeDecodeError: # pragma: no cover
  191. raise ValueError(
  192. 'The shebang (%r) is not decodable '
  193. 'from the script encoding (%r)' % (shebang, encoding))
  194. return shebang
  195. def _get_script_text(self, entry):
  196. return self.script_template % dict(module=entry.prefix,
  197. import_name=entry.suffix.split('.')[0],
  198. func=entry.suffix)
  199. manifest = _DEFAULT_MANIFEST
  200. def get_manifest(self, exename):
  201. base = os.path.basename(exename)
  202. return self.manifest % base
  203. def _write_script(self, names, shebang, script_bytes, filenames, ext):
  204. use_launcher = self.add_launchers and self._is_nt
  205. linesep = os.linesep.encode('utf-8')
  206. if not shebang.endswith(linesep):
  207. shebang += linesep
  208. if not use_launcher:
  209. script_bytes = shebang + script_bytes
  210. else: # pragma: no cover
  211. if ext == 'py':
  212. launcher = self._get_launcher('t')
  213. else:
  214. launcher = self._get_launcher('w')
  215. stream = BytesIO()
  216. with ZipFile(stream, 'w') as zf:
  217. zf.writestr('__main__.py', script_bytes)
  218. zip_data = stream.getvalue()
  219. script_bytes = launcher + shebang + zip_data
  220. for name in names:
  221. outname = os.path.join(self.target_dir, name)
  222. if use_launcher: # pragma: no cover
  223. n, e = os.path.splitext(outname)
  224. if e.startswith('.py'):
  225. outname = n
  226. outname = '%s.exe' % outname
  227. try:
  228. self._fileop.write_binary_file(outname, script_bytes)
  229. except Exception:
  230. # Failed writing an executable - it might be in use.
  231. logger.warning('Failed to write executable - trying to '
  232. 'use .deleteme logic')
  233. dfname = '%s.deleteme' % outname
  234. if os.path.exists(dfname):
  235. os.remove(dfname) # Not allowed to fail here
  236. os.rename(outname, dfname) # nor here
  237. self._fileop.write_binary_file(outname, script_bytes)
  238. logger.debug('Able to replace executable using '
  239. '.deleteme logic')
  240. try:
  241. os.remove(dfname)
  242. except Exception:
  243. pass # still in use - ignore error
  244. else:
  245. if self._is_nt and not outname.endswith('.' + ext): # pragma: no cover
  246. outname = '%s.%s' % (outname, ext)
  247. if os.path.exists(outname) and not self.clobber:
  248. logger.warning('Skipping existing file %s', outname)
  249. continue
  250. self._fileop.write_binary_file(outname, script_bytes)
  251. if self.set_mode:
  252. self._fileop.set_executable_mode([outname])
  253. filenames.append(outname)
  254. def _make_script(self, entry, filenames, options=None):
  255. post_interp = b''
  256. if options:
  257. args = options.get('interpreter_args', [])
  258. if args:
  259. args = ' %s' % ' '.join(args)
  260. post_interp = args.encode('utf-8')
  261. shebang = self._get_shebang('utf-8', post_interp, options=options)
  262. script = self._get_script_text(entry).encode('utf-8')
  263. name = entry.name
  264. scriptnames = set()
  265. if '' in self.variants:
  266. scriptnames.add(name)
  267. if 'X' in self.variants:
  268. scriptnames.add('%s%s' % (name, sys.version_info[0]))
  269. if 'X.Y' in self.variants:
  270. scriptnames.add('%s-%s.%s' % (name, sys.version_info[0],
  271. sys.version_info[1]))
  272. if options and options.get('gui', False):
  273. ext = 'pyw'
  274. else:
  275. ext = 'py'
  276. self._write_script(scriptnames, shebang, script, filenames, ext)
  277. def _copy_script(self, script, filenames):
  278. adjust = False
  279. script = os.path.join(self.source_dir, convert_path(script))
  280. outname = os.path.join(self.target_dir, os.path.basename(script))
  281. if not self.force and not self._fileop.newer(script, outname):
  282. logger.debug('not copying %s (up-to-date)', script)
  283. return
  284. # Always open the file, but ignore failures in dry-run mode --
  285. # that way, we'll get accurate feedback if we can read the
  286. # script.
  287. try:
  288. f = open(script, 'rb')
  289. except IOError: # pragma: no cover
  290. if not self.dry_run:
  291. raise
  292. f = None
  293. else:
  294. first_line = f.readline()
  295. if not first_line: # pragma: no cover
  296. logger.warning('%s: %s is an empty file (skipping)',
  297. self.get_command_name(), script)
  298. return
  299. match = FIRST_LINE_RE.match(first_line.replace(b'\r\n', b'\n'))
  300. if match:
  301. adjust = True
  302. post_interp = match.group(1) or b''
  303. if not adjust:
  304. if f:
  305. f.close()
  306. self._fileop.copy_file(script, outname)
  307. if self.set_mode:
  308. self._fileop.set_executable_mode([outname])
  309. filenames.append(outname)
  310. else:
  311. logger.info('copying and adjusting %s -> %s', script,
  312. self.target_dir)
  313. if not self._fileop.dry_run:
  314. encoding, lines = detect_encoding(f.readline)
  315. f.seek(0)
  316. shebang = self._get_shebang(encoding, post_interp)
  317. if b'pythonw' in first_line: # pragma: no cover
  318. ext = 'pyw'
  319. else:
  320. ext = 'py'
  321. n = os.path.basename(outname)
  322. self._write_script([n], shebang, f.read(), filenames, ext)
  323. if f:
  324. f.close()
  325. @property
  326. def dry_run(self):
  327. return self._fileop.dry_run
  328. @dry_run.setter
  329. def dry_run(self, value):
  330. self._fileop.dry_run = value
  331. if os.name == 'nt' or (os.name == 'java' and os._name == 'nt'): # pragma: no cover
  332. # Executable launcher support.
  333. # Launchers are from https://bitbucket.org/vinay.sajip/simple_launcher/
  334. def _get_launcher(self, kind):
  335. if struct.calcsize('P') == 8: # 64-bit
  336. bits = '64'
  337. else:
  338. bits = '32'
  339. name = '%s%s.exe' % (kind, bits)
  340. # Issue 31: don't hardcode an absolute package name, but
  341. # determine it relative to the current package
  342. distlib_package = __name__.rsplit('.', 1)[0]
  343. resource = finder(distlib_package).find(name)
  344. if not resource:
  345. msg = ('Unable to find resource %s in package %s' % (name,
  346. distlib_package))
  347. raise ValueError(msg)
  348. return resource.bytes
  349. # Public API follows
  350. def make(self, specification, options=None):
  351. """
  352. Make a script.
  353. :param specification: The specification, which is either a valid export
  354. entry specification (to make a script from a
  355. callable) or a filename (to make a script by
  356. copying from a source location).
  357. :param options: A dictionary of options controlling script generation.
  358. :return: A list of all absolute pathnames written to.
  359. """
  360. filenames = []
  361. entry = get_export_entry(specification)
  362. if entry is None:
  363. self._copy_script(specification, filenames)
  364. else:
  365. self._make_script(entry, filenames, options=options)
  366. return filenames
  367. def make_multiple(self, specifications, options=None):
  368. """
  369. Take a list of specifications and make scripts from them,
  370. :param specifications: A list of specifications.
  371. :return: A list of all absolute pathnames written to,
  372. """
  373. filenames = []
  374. for specification in specifications:
  375. filenames.extend(self.make(specification, options))
  376. return filenames