bdist_egg.py 18 KB

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