PageRenderTime 4401ms CodeModel.GetById 32ms RepoModel.GetById 6ms app.codeStats 0ms

/setuptools/current/setuptools/command/egg_info.py

https://github.com/xdissent/vendor
Python | 451 lines | 448 code | 1 blank | 2 comment | 3 complexity | 26d41661c352b2248b09dcae0c9bcb35 MD5 | raw file
Possible License(s): Apache-2.0, MIT
  1. """setuptools.command.egg_info
  2. Create a distribution's .egg-info directory and contents"""
  3. # This module should be kept compatible with Python 2.3
  4. import os, re
  5. from setuptools import Command
  6. from distutils.errors import *
  7. from distutils import log
  8. from setuptools.command.sdist import sdist
  9. from distutils.util import convert_path
  10. from distutils.filelist import FileList
  11. from pkg_resources import parse_requirements, safe_name, parse_version, \
  12. safe_version, yield_lines, EntryPoint, iter_entry_points, to_filename
  13. from sdist import walk_revctrl
  14. class egg_info(Command):
  15. description = "create a distribution's .egg-info directory"
  16. user_options = [
  17. ('egg-base=', 'e', "directory containing .egg-info directories"
  18. " (default: top of the source tree)"),
  19. ('tag-svn-revision', 'r',
  20. "Add subversion revision ID to version number"),
  21. ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
  22. ('tag-build=', 'b', "Specify explicit tag to add to version number"),
  23. ('no-svn-revision', 'R',
  24. "Don't add subversion revision ID [default]"),
  25. ('no-date', 'D', "Don't include date stamp [default]"),
  26. ]
  27. boolean_options = ['tag-date', 'tag-svn-revision']
  28. negative_opt = {'no-svn-revision': 'tag-svn-revision',
  29. 'no-date': 'tag-date'}
  30. def initialize_options(self):
  31. self.egg_name = None
  32. self.egg_version = None
  33. self.egg_base = None
  34. self.egg_info = None
  35. self.tag_build = None
  36. self.tag_svn_revision = 0
  37. self.tag_date = 0
  38. self.broken_egg_info = False
  39. self.vtags = None
  40. def save_version_info(self, filename):
  41. from setopt import edit_config
  42. edit_config(
  43. filename,
  44. {'egg_info':
  45. {'tag_svn_revision':0, 'tag_date': 0, 'tag_build': self.tags()}
  46. }
  47. )
  48. def finalize_options (self):
  49. self.egg_name = safe_name(self.distribution.get_name())
  50. self.vtags = self.tags()
  51. self.egg_version = self.tagged_version()
  52. try:
  53. list(
  54. parse_requirements('%s==%s' % (self.egg_name,self.egg_version))
  55. )
  56. except ValueError:
  57. raise DistutilsOptionError(
  58. "Invalid distribution name or version syntax: %s-%s" %
  59. (self.egg_name,self.egg_version)
  60. )
  61. if self.egg_base is None:
  62. dirs = self.distribution.package_dir
  63. self.egg_base = (dirs or {}).get('',os.curdir)
  64. self.ensure_dirname('egg_base')
  65. self.egg_info = to_filename(self.egg_name)+'.egg-info'
  66. if self.egg_base != os.curdir:
  67. self.egg_info = os.path.join(self.egg_base, self.egg_info)
  68. if '-' in self.egg_name: self.check_broken_egg_info()
  69. # Set package version for the benefit of dumber commands
  70. # (e.g. sdist, bdist_wininst, etc.)
  71. #
  72. self.distribution.metadata.version = self.egg_version
  73. # If we bootstrapped around the lack of a PKG-INFO, as might be the
  74. # case in a fresh checkout, make sure that any special tags get added
  75. # to the version info
  76. #
  77. pd = self.distribution._patched_dist
  78. if pd is not None and pd.key==self.egg_name.lower():
  79. pd._version = self.egg_version
  80. pd._parsed_version = parse_version(self.egg_version)
  81. self.distribution._patched_dist = None
  82. def write_or_delete_file(self, what, filename, data, force=False):
  83. """Write `data` to `filename` or delete if empty
  84. If `data` is non-empty, this routine is the same as ``write_file()``.
  85. If `data` is empty but not ``None``, this is the same as calling
  86. ``delete_file(filename)`. If `data` is ``None``, then this is a no-op
  87. unless `filename` exists, in which case a warning is issued about the
  88. orphaned file (if `force` is false), or deleted (if `force` is true).
  89. """
  90. if data:
  91. self.write_file(what, filename, data)
  92. elif os.path.exists(filename):
  93. if data is None and not force:
  94. log.warn(
  95. "%s not set in setup(), but %s exists", what, filename
  96. )
  97. return
  98. else:
  99. self.delete_file(filename)
  100. def write_file(self, what, filename, data):
  101. """Write `data` to `filename` (if not a dry run) after announcing it
  102. `what` is used in a log message to identify what is being written
  103. to the file.
  104. """
  105. log.info("writing %s to %s", what, filename)
  106. if not self.dry_run:
  107. f = open(filename, 'wb')
  108. f.write(data)
  109. f.close()
  110. def delete_file(self, filename):
  111. """Delete `filename` (if not a dry run) after announcing it"""
  112. log.info("deleting %s", filename)
  113. if not self.dry_run:
  114. os.unlink(filename)
  115. def tagged_version(self):
  116. return safe_version(self.distribution.get_version() + self.vtags)
  117. def run(self):
  118. self.mkpath(self.egg_info)
  119. installer = self.distribution.fetch_build_egg
  120. for ep in iter_entry_points('egg_info.writers'):
  121. writer = ep.load(installer=installer)
  122. writer(self, ep.name, os.path.join(self.egg_info,ep.name))
  123. # Get rid of native_libs.txt if it was put there by older bdist_egg
  124. nl = os.path.join(self.egg_info, "native_libs.txt")
  125. if os.path.exists(nl):
  126. self.delete_file(nl)
  127. self.find_sources()
  128. def tags(self):
  129. version = ''
  130. if self.tag_build:
  131. version+=self.tag_build
  132. if self.tag_svn_revision and (
  133. os.path.exists('.svn') or os.path.exists('PKG-INFO')
  134. ): version += '-r%s' % self.get_svn_revision()
  135. if self.tag_date:
  136. import time; version += time.strftime("-%Y%m%d")
  137. return version
  138. def get_svn_revision(self):
  139. revision = 0
  140. urlre = re.compile('url="([^"]+)"')
  141. revre = re.compile('committed-rev="(\d+)"')
  142. for base,dirs,files in os.walk(os.curdir):
  143. if '.svn' not in dirs:
  144. dirs[:] = []
  145. continue # no sense walking uncontrolled subdirs
  146. dirs.remove('.svn')
  147. f = open(os.path.join(base,'.svn','entries'))
  148. data = f.read()
  149. f.close()
  150. if data.startswith('10') or data.startswith('9') or data.startswith('8'):
  151. data = map(str.splitlines,data.split('\n\x0c\n'))
  152. del data[0][0] # get rid of the '8' or '9'
  153. dirurl = data[0][3]
  154. localrev = max([int(d[9]) for d in data if len(d)>9 and d[9]]+[0])
  155. elif data.startswith('<?xml'):
  156. dirurl = urlre.search(data).group(1) # get repository URL
  157. localrev = max([int(m.group(1)) for m in revre.finditer(data)]+[0])
  158. else:
  159. log.warn("unrecognized .svn/entries format; skipping %s", base)
  160. dirs[:] = []
  161. continue
  162. if base==os.curdir:
  163. base_url = dirurl+'/' # save the root url
  164. elif not dirurl.startswith(base_url):
  165. dirs[:] = []
  166. continue # not part of the same svn tree, skip it
  167. revision = max(revision, localrev)
  168. return str(revision or get_pkg_info_revision())
  169. def find_sources(self):
  170. """Generate SOURCES.txt manifest file"""
  171. manifest_filename = os.path.join(self.egg_info,"SOURCES.txt")
  172. mm = manifest_maker(self.distribution)
  173. mm.manifest = manifest_filename
  174. mm.run()
  175. self.filelist = mm.filelist
  176. def check_broken_egg_info(self):
  177. bei = self.egg_name+'.egg-info'
  178. if self.egg_base != os.curdir:
  179. bei = os.path.join(self.egg_base, bei)
  180. if os.path.exists(bei):
  181. log.warn(
  182. "-"*78+'\n'
  183. "Note: Your current .egg-info directory has a '-' in its name;"
  184. '\nthis will not work correctly with "setup.py develop".\n\n'
  185. 'Please rename %s to %s to correct this problem.\n'+'-'*78,
  186. bei, self.egg_info
  187. )
  188. self.broken_egg_info = self.egg_info
  189. self.egg_info = bei # make it work for now
  190. class FileList(FileList):
  191. """File list that accepts only existing, platform-independent paths"""
  192. def append(self, item):
  193. if item.endswith('\r'): # Fix older sdists built on Windows
  194. item = item[:-1]
  195. path = convert_path(item)
  196. if os.path.exists(path):
  197. self.files.append(path)
  198. class manifest_maker(sdist):
  199. template = "MANIFEST.in"
  200. def initialize_options (self):
  201. self.use_defaults = 1
  202. self.prune = 1
  203. self.manifest_only = 1
  204. self.force_manifest = 1
  205. def finalize_options(self):
  206. pass
  207. def run(self):
  208. self.filelist = FileList()
  209. if not os.path.exists(self.manifest):
  210. self.write_manifest() # it must exist so it'll get in the list
  211. self.filelist.findall()
  212. self.add_defaults()
  213. if os.path.exists(self.template):
  214. self.read_template()
  215. self.prune_file_list()
  216. self.filelist.sort()
  217. self.filelist.remove_duplicates()
  218. self.write_manifest()
  219. def write_manifest (self):
  220. """Write the file list in 'self.filelist' (presumably as filled in
  221. by 'add_defaults()' and 'read_template()') to the manifest file
  222. named by 'self.manifest'.
  223. """
  224. files = self.filelist.files
  225. if os.sep!='/':
  226. files = [f.replace(os.sep,'/') for f in files]
  227. self.execute(write_file, (self.manifest, files),
  228. "writing manifest file '%s'" % self.manifest)
  229. def warn(self, msg): # suppress missing-file warnings from sdist
  230. if not msg.startswith("standard file not found:"):
  231. sdist.warn(self, msg)
  232. def add_defaults(self):
  233. sdist.add_defaults(self)
  234. self.filelist.append(self.template)
  235. self.filelist.append(self.manifest)
  236. rcfiles = list(walk_revctrl())
  237. if rcfiles:
  238. self.filelist.extend(rcfiles)
  239. elif os.path.exists(self.manifest):
  240. self.read_manifest()
  241. ei_cmd = self.get_finalized_command('egg_info')
  242. self.filelist.include_pattern("*", prefix=ei_cmd.egg_info)
  243. def prune_file_list (self):
  244. build = self.get_finalized_command('build')
  245. base_dir = self.distribution.get_fullname()
  246. self.filelist.exclude_pattern(None, prefix=build.build_base)
  247. self.filelist.exclude_pattern(None, prefix=base_dir)
  248. sep = re.escape(os.sep)
  249. self.filelist.exclude_pattern(sep+r'(RCS|CVS|\.svn)'+sep, is_regex=1)
  250. def write_file (filename, contents):
  251. """Create a file with the specified name and write 'contents' (a
  252. sequence of strings without line terminators) to it.
  253. """
  254. f = open(filename, "wb") # always write POSIX-style manifest
  255. f.write("\n".join(contents))
  256. f.close()
  257. def write_pkg_info(cmd, basename, filename):
  258. log.info("writing %s", filename)
  259. if not cmd.dry_run:
  260. metadata = cmd.distribution.metadata
  261. metadata.version, oldver = cmd.egg_version, metadata.version
  262. metadata.name, oldname = cmd.egg_name, metadata.name
  263. try:
  264. # write unescaped data to PKG-INFO, so older pkg_resources
  265. # can still parse it
  266. metadata.write_pkg_info(cmd.egg_info)
  267. finally:
  268. metadata.name, metadata.version = oldname, oldver
  269. safe = getattr(cmd.distribution,'zip_safe',None)
  270. import bdist_egg; bdist_egg.write_safety_flag(cmd.egg_info, safe)
  271. def warn_depends_obsolete(cmd, basename, filename):
  272. if os.path.exists(filename):
  273. log.warn(
  274. "WARNING: 'depends.txt' is not used by setuptools 0.6!\n"
  275. "Use the install_requires/extras_require setup() args instead."
  276. )
  277. def write_requirements(cmd, basename, filename):
  278. dist = cmd.distribution
  279. data = ['\n'.join(yield_lines(dist.install_requires or ()))]
  280. for extra,reqs in (dist.extras_require or {}).items():
  281. data.append('\n\n[%s]\n%s' % (extra, '\n'.join(yield_lines(reqs))))
  282. cmd.write_or_delete_file("requirements", filename, ''.join(data))
  283. def write_toplevel_names(cmd, basename, filename):
  284. pkgs = dict.fromkeys(
  285. [k.split('.',1)[0]
  286. for k in cmd.distribution.iter_distribution_names()
  287. ]
  288. )
  289. cmd.write_file("top-level names", filename, '\n'.join(pkgs)+'\n')
  290. def overwrite_arg(cmd, basename, filename):
  291. write_arg(cmd, basename, filename, True)
  292. def write_arg(cmd, basename, filename, force=False):
  293. argname = os.path.splitext(basename)[0]
  294. value = getattr(cmd.distribution, argname, None)
  295. if value is not None:
  296. value = '\n'.join(value)+'\n'
  297. cmd.write_or_delete_file(argname, filename, value, force)
  298. def write_entries(cmd, basename, filename):
  299. ep = cmd.distribution.entry_points
  300. if isinstance(ep,basestring) or ep is None:
  301. data = ep
  302. elif ep is not None:
  303. data = []
  304. for section, contents in ep.items():
  305. if not isinstance(contents,basestring):
  306. contents = EntryPoint.parse_group(section, contents)
  307. contents = '\n'.join(map(str,contents.values()))
  308. data.append('[%s]\n%s\n\n' % (section,contents))
  309. data = ''.join(data)
  310. cmd.write_or_delete_file('entry points', filename, data, True)
  311. def get_pkg_info_revision():
  312. # See if we can get a -r### off of PKG-INFO, in case this is an sdist of
  313. # a subversion revision
  314. #
  315. if os.path.exists('PKG-INFO'):
  316. f = open('PKG-INFO','rU')
  317. for line in f:
  318. match = re.match(r"Version:.*-r(\d+)\s*$", line)
  319. if match:
  320. return int(match.group(1))
  321. return 0
  322. #