Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

scripts.py 16KB

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