Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

bdist_egg.py 16KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. """setuptools.command.bdist_egg
  2. Build .egg distributions"""
  3. from distutils.dir_util import remove_tree, mkpath
  4. from distutils import log
  5. from types import CodeType
  6. import sys
  7. import os
  8. import re
  9. import textwrap
  10. import marshal
  11. from pkg_resources import get_build_platform, Distribution, ensure_directory
  12. from setuptools.extension import Library
  13. from setuptools import Command
  14. from sysconfig import get_path, get_python_version
  15. def _get_purelib():
  16. return get_path("purelib")
  17. def strip_module(filename):
  18. if '.' in filename:
  19. filename = os.path.splitext(filename)[0]
  20. if filename.endswith('module'):
  21. filename = filename[:-6]
  22. return filename
  23. def sorted_walk(dir):
  24. """Do os.walk in a reproducible way,
  25. independent of indeterministic filesystem readdir order
  26. """
  27. for base, dirs, files in os.walk(dir):
  28. dirs.sort()
  29. files.sort()
  30. yield base, dirs, files
  31. def write_stub(resource, pyfile):
  32. _stub_template = textwrap.dedent("""
  33. def __bootstrap__():
  34. global __bootstrap__, __loader__, __file__
  35. import sys, pkg_resources, importlib.util
  36. __file__ = pkg_resources.resource_filename(__name__, %r)
  37. __loader__ = None; del __bootstrap__, __loader__
  38. spec = importlib.util.spec_from_file_location(__name__,__file__)
  39. mod = importlib.util.module_from_spec(spec)
  40. spec.loader.exec_module(mod)
  41. __bootstrap__()
  42. """).lstrip()
  43. with open(pyfile, 'w') as f:
  44. f.write(_stub_template % resource)
  45. class bdist_egg(Command):
  46. description = "create an \"egg\" distribution"
  47. user_options = [
  48. ('bdist-dir=', 'b',
  49. "temporary directory for creating the distribution"),
  50. ('plat-name=', 'p', "platform name to embed in generated filenames "
  51. "(default: %s)" % get_build_platform()),
  52. ('exclude-source-files', None,
  53. "remove all .py files from the generated egg"),
  54. ('keep-temp', 'k',
  55. "keep the pseudo-installation tree around after " +
  56. "creating the distribution archive"),
  57. ('dist-dir=', 'd',
  58. "directory to put final built distributions in"),
  59. ('skip-build', None,
  60. "skip rebuilding everything (for testing/debugging)"),
  61. ]
  62. boolean_options = [
  63. 'keep-temp', 'skip-build', 'exclude-source-files'
  64. ]
  65. def initialize_options(self):
  66. self.bdist_dir = None
  67. self.plat_name = None
  68. self.keep_temp = 0
  69. self.dist_dir = None
  70. self.skip_build = 0
  71. self.egg_output = None
  72. self.exclude_source_files = None
  73. def finalize_options(self):
  74. ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info")
  75. self.egg_info = ei_cmd.egg_info
  76. if self.bdist_dir is None:
  77. bdist_base = self.get_finalized_command('bdist').bdist_base
  78. self.bdist_dir = os.path.join(bdist_base, 'egg')
  79. if self.plat_name is None:
  80. self.plat_name = get_build_platform()
  81. self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
  82. if self.egg_output is None:
  83. # Compute filename of the output egg
  84. basename = Distribution(
  85. None, None, ei_cmd.egg_name, ei_cmd.egg_version,
  86. get_python_version(),
  87. self.distribution.has_ext_modules() and self.plat_name
  88. ).egg_name()
  89. self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
  90. def do_install_data(self):
  91. # Hack for packages that install data to install's --install-lib
  92. self.get_finalized_command('install').install_lib = self.bdist_dir
  93. site_packages = os.path.normcase(os.path.realpath(_get_purelib()))
  94. old, self.distribution.data_files = self.distribution.data_files, []
  95. for item in old:
  96. if isinstance(item, tuple) and len(item) == 2:
  97. if os.path.isabs(item[0]):
  98. realpath = os.path.realpath(item[0])
  99. normalized = os.path.normcase(realpath)
  100. if normalized == site_packages or normalized.startswith(
  101. site_packages + os.sep
  102. ):
  103. item = realpath[len(site_packages) + 1:], item[1]
  104. # XXX else: raise ???
  105. self.distribution.data_files.append(item)
  106. try:
  107. log.info("installing package data to %s", self.bdist_dir)
  108. self.call_command('install_data', force=0, root=None)
  109. finally:
  110. self.distribution.data_files = old
  111. def get_outputs(self):
  112. return [self.egg_output]
  113. def call_command(self, cmdname, **kw):
  114. """Invoke reinitialized command `cmdname` with keyword args"""
  115. for dirname in INSTALL_DIRECTORY_ATTRS:
  116. kw.setdefault(dirname, self.bdist_dir)
  117. kw.setdefault('skip_build', self.skip_build)
  118. kw.setdefault('dry_run', self.dry_run)
  119. cmd = self.reinitialize_command(cmdname, **kw)
  120. self.run_command(cmdname)
  121. return cmd
  122. def run(self): # noqa: C901 # is too complex (14) # FIXME
  123. # Generate metadata first
  124. self.run_command("egg_info")
  125. # We run install_lib before install_data, because some data hacks
  126. # pull their data path from the install_lib command.
  127. log.info("installing library code to %s", self.bdist_dir)
  128. instcmd = self.get_finalized_command('install')
  129. old_root = instcmd.root
  130. instcmd.root = None
  131. if self.distribution.has_c_libraries() and not self.skip_build:
  132. self.run_command('build_clib')
  133. cmd = self.call_command('install_lib', warn_dir=0)
  134. instcmd.root = old_root
  135. all_outputs, ext_outputs = self.get_ext_outputs()
  136. self.stubs = []
  137. to_compile = []
  138. for (p, ext_name) in enumerate(ext_outputs):
  139. filename, ext = os.path.splitext(ext_name)
  140. pyfile = os.path.join(self.bdist_dir, strip_module(filename) +
  141. '.py')
  142. self.stubs.append(pyfile)
  143. log.info("creating stub loader for %s", ext_name)
  144. if not self.dry_run:
  145. write_stub(os.path.basename(ext_name), pyfile)
  146. to_compile.append(pyfile)
  147. ext_outputs[p] = ext_name.replace(os.sep, '/')
  148. if to_compile:
  149. cmd.byte_compile(to_compile)
  150. if self.distribution.data_files:
  151. self.do_install_data()
  152. # Make the EGG-INFO directory
  153. archive_root = self.bdist_dir
  154. egg_info = os.path.join(archive_root, 'EGG-INFO')
  155. self.mkpath(egg_info)
  156. if self.distribution.scripts:
  157. script_dir = os.path.join(egg_info, 'scripts')
  158. log.info("installing scripts to %s", script_dir)
  159. self.call_command('install_scripts', install_dir=script_dir,
  160. no_ep=1)
  161. self.copy_metadata_to(egg_info)
  162. native_libs = os.path.join(egg_info, "native_libs.txt")
  163. if all_outputs:
  164. log.info("writing %s", native_libs)
  165. if not self.dry_run:
  166. ensure_directory(native_libs)
  167. libs_file = open(native_libs, 'wt')
  168. libs_file.write('\n'.join(all_outputs))
  169. libs_file.write('\n')
  170. libs_file.close()
  171. elif os.path.isfile(native_libs):
  172. log.info("removing %s", native_libs)
  173. if not self.dry_run:
  174. os.unlink(native_libs)
  175. write_safety_flag(
  176. os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()
  177. )
  178. if os.path.exists(os.path.join(self.egg_info, 'depends.txt')):
  179. log.warn(
  180. "WARNING: 'depends.txt' will not be used by setuptools 0.6!\n"
  181. "Use the install_requires/extras_require setup() args instead."
  182. )
  183. if self.exclude_source_files:
  184. self.zap_pyfiles()
  185. # Make the archive
  186. make_zipfile(self.egg_output, archive_root, verbose=self.verbose,
  187. dry_run=self.dry_run, mode=self.gen_header())
  188. if not self.keep_temp:
  189. remove_tree(self.bdist_dir, dry_run=self.dry_run)
  190. # Add to 'Distribution.dist_files' so that the "upload" command works
  191. getattr(self.distribution, 'dist_files', []).append(
  192. ('bdist_egg', get_python_version(), self.egg_output))
  193. def zap_pyfiles(self):
  194. log.info("Removing .py files from temporary directory")
  195. for base, dirs, files in walk_egg(self.bdist_dir):
  196. for name in files:
  197. path = os.path.join(base, name)
  198. if name.endswith('.py'):
  199. log.debug("Deleting %s", path)
  200. os.unlink(path)
  201. if base.endswith('__pycache__'):
  202. path_old = path
  203. pattern = r'(?P<name>.+)\.(?P<magic>[^.]+)\.pyc'
  204. m = re.match(pattern, name)
  205. path_new = os.path.join(
  206. base, os.pardir, m.group('name') + '.pyc')
  207. log.info(
  208. "Renaming file from [%s] to [%s]"
  209. % (path_old, path_new))
  210. try:
  211. os.remove(path_new)
  212. except OSError:
  213. pass
  214. os.rename(path_old, path_new)
  215. def zip_safe(self):
  216. safe = getattr(self.distribution, 'zip_safe', None)
  217. if safe is not None:
  218. return safe
  219. log.warn("zip_safe flag not set; analyzing archive contents...")
  220. return analyze_egg(self.bdist_dir, self.stubs)
  221. def gen_header(self):
  222. return 'w'
  223. def copy_metadata_to(self, target_dir):
  224. "Copy metadata (egg info) to the target_dir"
  225. # normalize the path (so that a forward-slash in egg_info will
  226. # match using startswith below)
  227. norm_egg_info = os.path.normpath(self.egg_info)
  228. prefix = os.path.join(norm_egg_info, '')
  229. for path in self.ei_cmd.filelist.files:
  230. if path.startswith(prefix):
  231. target = os.path.join(target_dir, path[len(prefix):])
  232. ensure_directory(target)
  233. self.copy_file(path, target)
  234. def get_ext_outputs(self):
  235. """Get a list of relative paths to C extensions in the output distro"""
  236. all_outputs = []
  237. ext_outputs = []
  238. paths = {self.bdist_dir: ''}
  239. for base, dirs, files in sorted_walk(self.bdist_dir):
  240. for filename in files:
  241. if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS:
  242. all_outputs.append(paths[base] + filename)
  243. for filename in dirs:
  244. paths[os.path.join(base, filename)] = (paths[base] +
  245. filename + '/')
  246. if self.distribution.has_ext_modules():
  247. build_cmd = self.get_finalized_command('build_ext')
  248. for ext in build_cmd.extensions:
  249. if isinstance(ext, Library):
  250. continue
  251. fullname = build_cmd.get_ext_fullname(ext.name)
  252. filename = build_cmd.get_ext_filename(fullname)
  253. if not os.path.basename(filename).startswith('dl-'):
  254. if os.path.exists(os.path.join(self.bdist_dir, filename)):
  255. ext_outputs.append(filename)
  256. return all_outputs, ext_outputs
  257. NATIVE_EXTENSIONS = dict.fromkeys('.dll .so .dylib .pyd'.split())
  258. def walk_egg(egg_dir):
  259. """Walk an unpacked egg's contents, skipping the metadata directory"""
  260. walker = sorted_walk(egg_dir)
  261. base, dirs, files = next(walker)
  262. if 'EGG-INFO' in dirs:
  263. dirs.remove('EGG-INFO')
  264. yield base, dirs, files
  265. for bdf in walker:
  266. yield bdf
  267. def analyze_egg(egg_dir, stubs):
  268. # check for existing flag in EGG-INFO
  269. for flag, fn in safety_flags.items():
  270. if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):
  271. return flag
  272. if not can_scan():
  273. return False
  274. safe = True
  275. for base, dirs, files in walk_egg(egg_dir):
  276. for name in files:
  277. if name.endswith('.py') or name.endswith('.pyw'):
  278. continue
  279. elif name.endswith('.pyc') or name.endswith('.pyo'):
  280. # always scan, even if we already know we're not safe
  281. safe = scan_module(egg_dir, base, name, stubs) and safe
  282. return safe
  283. def write_safety_flag(egg_dir, safe):
  284. # Write or remove zip safety flag file(s)
  285. for flag, fn in safety_flags.items():
  286. fn = os.path.join(egg_dir, fn)
  287. if os.path.exists(fn):
  288. if safe is None or bool(safe) != flag:
  289. os.unlink(fn)
  290. elif safe is not None and bool(safe) == flag:
  291. f = open(fn, 'wt')
  292. f.write('\n')
  293. f.close()
  294. safety_flags = {
  295. True: 'zip-safe',
  296. False: 'not-zip-safe',
  297. }
  298. def scan_module(egg_dir, base, name, stubs):
  299. """Check whether module possibly uses unsafe-for-zipfile stuff"""
  300. filename = os.path.join(base, name)
  301. if filename[:-1] in stubs:
  302. return True # Extension module
  303. pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')
  304. module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]
  305. if sys.version_info < (3, 7):
  306. skip = 12 # skip magic & date & file size
  307. else:
  308. skip = 16 # skip magic & reserved? & date & file size
  309. f = open(filename, 'rb')
  310. f.read(skip)
  311. code = marshal.load(f)
  312. f.close()
  313. safe = True
  314. symbols = dict.fromkeys(iter_symbols(code))
  315. for bad in ['__file__', '__path__']:
  316. if bad in symbols:
  317. log.warn("%s: module references %s", module, bad)
  318. safe = False
  319. if 'inspect' in symbols:
  320. for bad in [
  321. 'getsource', 'getabsfile', 'getsourcefile', 'getfile'
  322. 'getsourcelines', 'findsource', 'getcomments', 'getframeinfo',
  323. 'getinnerframes', 'getouterframes', 'stack', 'trace'
  324. ]:
  325. if bad in symbols:
  326. log.warn("%s: module MAY be using inspect.%s", module, bad)
  327. safe = False
  328. return safe
  329. def iter_symbols(code):
  330. """Yield names and strings used by `code` and its nested code objects"""
  331. for name in code.co_names:
  332. yield name
  333. for const in code.co_consts:
  334. if isinstance(const, str):
  335. yield const
  336. elif isinstance(const, CodeType):
  337. for name in iter_symbols(const):
  338. yield name
  339. def can_scan():
  340. if not sys.platform.startswith('java') and sys.platform != 'cli':
  341. # CPython, PyPy, etc.
  342. return True
  343. log.warn("Unable to analyze compiled code on this platform.")
  344. log.warn("Please ask the author to include a 'zip_safe'"
  345. " setting (either True or False) in the package's setup.py")
  346. # Attribute names of options for commands that might need to be convinced to
  347. # install to the egg build directory
  348. INSTALL_DIRECTORY_ATTRS = [
  349. 'install_lib', 'install_dir', 'install_data', 'install_base'
  350. ]
  351. def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
  352. mode='w'):
  353. """Create a zip file from all the files under 'base_dir'. The output
  354. zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
  355. Python module (if available) or the InfoZIP "zip" utility (if installed
  356. and found on the default search path). If neither tool is available,
  357. raises DistutilsExecError. Returns the name of the output zip file.
  358. """
  359. import zipfile
  360. mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
  361. log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
  362. def visit(z, dirname, names):
  363. for name in names:
  364. path = os.path.normpath(os.path.join(dirname, name))
  365. if os.path.isfile(path):
  366. p = path[len(base_dir) + 1:]
  367. if not dry_run:
  368. z.write(path, p)
  369. log.debug("adding '%s'", p)
  370. compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED
  371. if not dry_run:
  372. z = zipfile.ZipFile(zip_filename, mode, compression=compression)
  373. for dirname, dirs, files in sorted_walk(base_dir):
  374. visit(z, dirname, files)
  375. z.close()
  376. else:
  377. for dirname, dirs, files in sorted_walk(base_dir):
  378. visit(None, dirname, files)
  379. return zip_filename