You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

471 lines
17 KiB

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