bdist_egg.py 16 KB

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