bdist_egg.py 17 KB

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