bdist_egg.py 17 KB

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