bdist_egg.py 18 KB

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