bdist_egg.py 18 KB

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