blob: 087a6ecadde3b2fd25425a94472e52da963699af [file] [log] [blame]
Tarek Ziade1231a4e2011-05-19 13:07:25 +02001"""PEP 376 implementation."""
2
3import io
4import os
5import re
6import csv
7import sys
8import zipimport
9from hashlib import md5
10from packaging import logger
11from packaging.errors import PackagingError
12from packaging.version import suggest_normalized_version, VersionPredicate
13from packaging.metadata import Metadata
14
15
16__all__ = [
17 'Distribution', 'EggInfoDistribution', 'distinfo_dirname',
18 'get_distributions', 'get_distribution', 'get_file_users',
19 'provides_distribution', 'obsoletes_distribution',
20 'enable_cache', 'disable_cache', 'clear_cache',
21]
22
23
24# TODO update docs
25
26DIST_FILES = ('INSTALLER', 'METADATA', 'RECORD', 'REQUESTED', 'RESOURCES')
27
28# Cache
29_cache_name = {} # maps names to Distribution instances
30_cache_name_egg = {} # maps names to EggInfoDistribution instances
31_cache_path = {} # maps paths to Distribution instances
32_cache_path_egg = {} # maps paths to EggInfoDistribution instances
33_cache_generated = False # indicates if .dist-info distributions are cached
34_cache_generated_egg = False # indicates if .dist-info and .egg are cached
35_cache_enabled = True
36
37
38def enable_cache():
39 """
40 Enables the internal cache.
41
42 Note that this function will not clear the cache in any case, for that
43 functionality see :func:`clear_cache`.
44 """
45 global _cache_enabled
46
47 _cache_enabled = True
48
49
50def disable_cache():
51 """
52 Disables the internal cache.
53
54 Note that this function will not clear the cache in any case, for that
55 functionality see :func:`clear_cache`.
56 """
57 global _cache_enabled
58
59 _cache_enabled = False
60
61
62def clear_cache():
63 """ Clears the internal cache. """
64 global _cache_name, _cache_name_egg, _cache_path, _cache_path_egg, \
65 _cache_generated, _cache_generated_egg
66
67 _cache_name = {}
68 _cache_name_egg = {}
69 _cache_path = {}
70 _cache_path_egg = {}
71 _cache_generated = False
72 _cache_generated_egg = False
73
74
75def _yield_distributions(include_dist, include_egg, paths=sys.path):
76 """
77 Yield .dist-info and .egg(-info) distributions, based on the arguments
78
79 :parameter include_dist: yield .dist-info distributions
80 :parameter include_egg: yield .egg(-info) distributions
81 """
82 for path in paths:
83 realpath = os.path.realpath(path)
84 if not os.path.isdir(realpath):
85 continue
86 for dir in os.listdir(realpath):
87 dist_path = os.path.join(realpath, dir)
88 if include_dist and dir.endswith('.dist-info'):
89 yield Distribution(dist_path)
90 elif include_egg and (dir.endswith('.egg-info') or
91 dir.endswith('.egg')):
92 yield EggInfoDistribution(dist_path)
93
94
95def _generate_cache(use_egg_info=False, paths=sys.path):
96 global _cache_generated, _cache_generated_egg
97
98 if _cache_generated_egg or (_cache_generated and not use_egg_info):
99 return
100 else:
101 gen_dist = not _cache_generated
102 gen_egg = use_egg_info
103
104 for dist in _yield_distributions(gen_dist, gen_egg, paths):
105 if isinstance(dist, Distribution):
106 _cache_path[dist.path] = dist
107 if not dist.name in _cache_name:
108 _cache_name[dist.name] = []
109 _cache_name[dist.name].append(dist)
110 else:
111 _cache_path_egg[dist.path] = dist
112 if not dist.name in _cache_name_egg:
113 _cache_name_egg[dist.name] = []
114 _cache_name_egg[dist.name].append(dist)
115
116 if gen_dist:
117 _cache_generated = True
118 if gen_egg:
119 _cache_generated_egg = True
120
121
122class Distribution:
123 """Created with the *path* of the ``.dist-info`` directory provided to the
124 constructor. It reads the metadata contained in ``METADATA`` when it is
125 instantiated."""
126
127 name = ''
128 """The name of the distribution."""
129
130 version = ''
131 """The version of the distribution."""
132
133 metadata = None
134 """A :class:`packaging.metadata.Metadata` instance loaded with
135 the distribution's ``METADATA`` file."""
136
137 requested = False
138 """A boolean that indicates whether the ``REQUESTED`` metadata file is
139 present (in other words, whether the package was installed by user
140 request or it was installed as a dependency)."""
141
142 def __init__(self, path):
143 if _cache_enabled and path in _cache_path:
144 self.metadata = _cache_path[path].metadata
145 else:
146 metadata_path = os.path.join(path, 'METADATA')
147 self.metadata = Metadata(path=metadata_path)
148
149 self.name = self.metadata['Name']
150 self.version = self.metadata['Version']
151 self.path = path
152
153 if _cache_enabled and not path in _cache_path:
154 _cache_path[path] = self
155
156 def __repr__(self):
157 return '<Distribution %r %s at %r>' % (
158 self.name, self.version, self.path)
159
160 def _get_records(self, local=False):
161 with self.get_distinfo_file('RECORD') as record:
162 record_reader = csv.reader(record, delimiter=',')
163 # XXX needs an explaining comment
164 for row in record_reader:
165 path, checksum, size = (row[:] +
166 [None for i in range(len(row), 3)])
167 if local:
168 path = path.replace('/', os.sep)
169 path = os.path.join(sys.prefix, path)
170 yield path, checksum, size
171
172 def get_resource_path(self, relative_path):
173 with self.get_distinfo_file('RESOURCES') as resources_file:
174 resources_reader = csv.reader(resources_file, delimiter=',')
175 for relative, destination in resources_reader:
176 if relative == relative_path:
177 return destination
178 raise KeyError(
179 'no resource file with relative path %r is installed' %
180 relative_path)
181
182 def list_installed_files(self, local=False):
183 """
184 Iterates over the ``RECORD`` entries and returns a tuple
185 ``(path, md5, size)`` for each line. If *local* is ``True``,
186 the returned path is transformed into a local absolute path.
187 Otherwise the raw value from RECORD is returned.
188
189 A local absolute path is an absolute path in which occurrences of
190 ``'/'`` have been replaced by the system separator given by ``os.sep``.
191
192 :parameter local: flag to say if the path should be returned a local
193 absolute path
194
195 :type local: boolean
196 :returns: iterator of (path, md5, size)
197 """
198 return self._get_records(local)
199
200 def uses(self, path):
201 """
202 Returns ``True`` if path is listed in ``RECORD``. *path* can be a local
203 absolute path or a relative ``'/'``-separated path.
204
205 :rtype: boolean
206 """
207 for p, checksum, size in self._get_records():
208 local_absolute = os.path.join(sys.prefix, p)
209 if path == p or path == local_absolute:
210 return True
211 return False
212
213 def get_distinfo_file(self, path, binary=False):
214 """
215 Returns a file located under the ``.dist-info`` directory. Returns a
216 ``file`` instance for the file pointed by *path*.
217
218 :parameter path: a ``'/'``-separated path relative to the
219 ``.dist-info`` directory or an absolute path;
220 If *path* is an absolute path and doesn't start
221 with the ``.dist-info`` directory path,
222 a :class:`PackagingError` is raised
223 :type path: string
224 :parameter binary: If *binary* is ``True``, opens the file in read-only
225 binary mode (``rb``), otherwise opens it in
226 read-only mode (``r``).
227 :rtype: file object
228 """
229 open_flags = 'r'
230 if binary:
231 open_flags += 'b'
232
233 # Check if it is an absolute path # XXX use relpath, add tests
234 if path.find(os.sep) >= 0:
235 # it's an absolute path?
236 distinfo_dirname, path = path.split(os.sep)[-2:]
237 if distinfo_dirname != self.path.split(os.sep)[-1]:
238 raise PackagingError(
239 'dist-info file %r does not belong to the %r %s '
240 'distribution' % (path, self.name, self.version))
241
242 # The file must be relative
243 if path not in DIST_FILES:
244 raise PackagingError('invalid path for a dist-info file: %r' %
245 path)
246
247 path = os.path.join(self.path, path)
248 return open(path, open_flags)
249
250 def list_distinfo_files(self, local=False):
251 """
252 Iterates over the ``RECORD`` entries and returns paths for each line if
253 the path is pointing to a file located in the ``.dist-info`` directory
254 or one of its subdirectories.
255
256 :parameter local: If *local* is ``True``, each returned path is
257 transformed into a local absolute path. Otherwise the
258 raw value from ``RECORD`` is returned.
259 :type local: boolean
260 :returns: iterator of paths
261 """
262 for path, checksum, size in self._get_records(local):
263 yield path
264
265 def __eq__(self, other):
266 return isinstance(other, Distribution) and self.path == other.path
267
268 # See http://docs.python.org/reference/datamodel#object.__hash__
269 __hash__ = object.__hash__
270
271
272class EggInfoDistribution:
273 """Created with the *path* of the ``.egg-info`` directory or file provided
274 to the constructor. It reads the metadata contained in the file itself, or
275 if the given path happens to be a directory, the metadata is read from the
276 file ``PKG-INFO`` under that directory."""
277
278 name = ''
279 """The name of the distribution."""
280
281 version = ''
282 """The version of the distribution."""
283
284 metadata = None
285 """A :class:`packaging.metadata.Metadata` instance loaded with
286 the distribution's ``METADATA`` file."""
287
288 _REQUIREMENT = re.compile(
289 r'(?P<name>[-A-Za-z0-9_.]+)\s*'
290 r'(?P<first>(?:<|<=|!=|==|>=|>)[-A-Za-z0-9_.]+)?\s*'
291 r'(?P<rest>(?:\s*,\s*(?:<|<=|!=|==|>=|>)[-A-Za-z0-9_.]+)*)\s*'
292 r'(?P<extras>\[.*\])?')
293
294 def __init__(self, path):
295 self.path = path
296 if _cache_enabled and path in _cache_path_egg:
297 self.metadata = _cache_path_egg[path].metadata
298 self.name = self.metadata['Name']
299 self.version = self.metadata['Version']
300 return
301
302 # reused from Distribute's pkg_resources
303 def yield_lines(strs):
304 """Yield non-empty/non-comment lines of a ``basestring``
305 or sequence"""
306 if isinstance(strs, str):
307 for s in strs.splitlines():
308 s = s.strip()
309 # skip blank lines/comments
310 if s and not s.startswith('#'):
311 yield s
312 else:
313 for ss in strs:
314 for s in yield_lines(ss):
315 yield s
316
317 requires = None
318
319 if path.endswith('.egg'):
320 if os.path.isdir(path):
321 meta_path = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
322 self.metadata = Metadata(path=meta_path)
323 try:
324 req_path = os.path.join(path, 'EGG-INFO', 'requires.txt')
325 with open(req_path, 'r') as fp:
326 requires = fp.read()
327 except IOError:
328 requires = None
329 else:
330 # FIXME handle the case where zipfile is not available
331 zipf = zipimport.zipimporter(path)
332 fileobj = io.StringIO(
333 zipf.get_data('EGG-INFO/PKG-INFO').decode('utf8'))
334 self.metadata = Metadata(fileobj=fileobj)
335 try:
336 requires = zipf.get_data('EGG-INFO/requires.txt')
337 except IOError:
338 requires = None
339 self.name = self.metadata['Name']
340 self.version = self.metadata['Version']
341
342 elif path.endswith('.egg-info'):
343 if os.path.isdir(path):
344 path = os.path.join(path, 'PKG-INFO')
345 try:
346 with open(os.path.join(path, 'requires.txt'), 'r') as fp:
347 requires = fp.read()
348 except IOError:
349 requires = None
350 self.metadata = Metadata(path=path)
351 self.name = self.metadata['name']
352 self.version = self.metadata['Version']
353
354 else:
355 raise ValueError('path must end with .egg-info or .egg, got %r' %
356 path)
357
358 if requires is not None:
359 if self.metadata['Metadata-Version'] == '1.1':
360 # we can't have 1.1 metadata *and* Setuptools requires
361 for field in ('Obsoletes', 'Requires', 'Provides'):
362 del self.metadata[field]
363
364 reqs = []
365
366 if requires is not None:
367 for line in yield_lines(requires):
368 if line.startswith('['):
369 logger.warning(
370 'extensions in requires.txt are not supported '
371 '(used by %r %s)', self.name, self.version)
372 break
373 else:
374 match = self._REQUIREMENT.match(line.strip())
375 if not match:
376 # this happens when we encounter extras; since they
377 # are written at the end of the file we just exit
378 break
379 else:
380 if match.group('extras'):
381 msg = ('extra requirements are not supported '
382 '(used by %r %s)', self.name, self.version)
383 logger.warning(msg, self.name)
384 name = match.group('name')
385 version = None
386 if match.group('first'):
387 version = match.group('first')
388 if match.group('rest'):
389 version += match.group('rest')
390 version = version.replace(' ', '') # trim spaces
391 if version is None:
392 reqs.append(name)
393 else:
394 reqs.append('%s (%s)' % (name, version))
395
396 if len(reqs) > 0:
397 self.metadata['Requires-Dist'] += reqs
398
399 if _cache_enabled:
400 _cache_path_egg[self.path] = self
401
402 def __repr__(self):
403 return '<EggInfoDistribution %r %s at %r>' % (
404 self.name, self.version, self.path)
405
406 def list_installed_files(self, local=False):
407
408 def _md5(path):
409 with open(path, 'rb') as f:
410 content = f.read()
411 return md5(content).hexdigest()
412
413 def _size(path):
414 return os.stat(path).st_size
415
416 path = self.path
417 if local:
418 path = path.replace('/', os.sep)
419
420 # XXX What about scripts and data files ?
421 if os.path.isfile(path):
422 return [(path, _md5(path), _size(path))]
423 else:
424 files = []
425 for root, dir, files_ in os.walk(path):
426 for item in files_:
427 item = os.path.join(root, item)
428 files.append((item, _md5(item), _size(item)))
429 return files
430
431 return []
432
433 def uses(self, path):
434 return False
435
436 def __eq__(self, other):
437 return (isinstance(other, EggInfoDistribution) and
438 self.path == other.path)
439
440 # See http://docs.python.org/reference/datamodel#object.__hash__
441 __hash__ = object.__hash__
442
443
444def distinfo_dirname(name, version):
445 """
446 The *name* and *version* parameters are converted into their
447 filename-escaped form, i.e. any ``'-'`` characters are replaced
448 with ``'_'`` other than the one in ``'dist-info'`` and the one
449 separating the name from the version number.
450
451 :parameter name: is converted to a standard distribution name by replacing
452 any runs of non- alphanumeric characters with a single
453 ``'-'``.
454 :type name: string
455 :parameter version: is converted to a standard version string. Spaces
456 become dots, and all other non-alphanumeric characters
457 (except dots) become dashes, with runs of multiple
458 dashes condensed to a single dash.
459 :type version: string
460 :returns: directory name
461 :rtype: string"""
462 file_extension = '.dist-info'
463 name = name.replace('-', '_')
464 normalized_version = suggest_normalized_version(version)
465 # Because this is a lookup procedure, something will be returned even if
466 # it is a version that cannot be normalized
467 if normalized_version is None:
468 # Unable to achieve normality?
469 normalized_version = version
470 return '-'.join([name, normalized_version]) + file_extension
471
472
473def get_distributions(use_egg_info=False, paths=sys.path):
474 """
475 Provides an iterator that looks for ``.dist-info`` directories in
476 ``sys.path`` and returns :class:`Distribution` instances for each one of
477 them. If the parameters *use_egg_info* is ``True``, then the ``.egg-info``
478 files and directores are iterated as well.
479
480 :rtype: iterator of :class:`Distribution` and :class:`EggInfoDistribution`
481 instances
482 """
483 if not _cache_enabled:
484 for dist in _yield_distributions(True, use_egg_info, paths):
485 yield dist
486 else:
487 _generate_cache(use_egg_info, paths)
488
489 for dist in _cache_path.values():
490 yield dist
491
492 if use_egg_info:
493 for dist in _cache_path_egg.values():
494 yield dist
495
496
497def get_distribution(name, use_egg_info=False, paths=None):
498 """
499 Scans all elements in ``sys.path`` and looks for all directories
500 ending with ``.dist-info``. Returns a :class:`Distribution`
501 corresponding to the ``.dist-info`` directory that contains the
502 ``METADATA`` that matches *name* for the *name* metadata field.
503 If no distribution exists with the given *name* and the parameter
504 *use_egg_info* is set to ``True``, then all files and directories ending
505 with ``.egg-info`` are scanned. A :class:`EggInfoDistribution` instance is
506 returned if one is found that has metadata that matches *name* for the
507 *name* metadata field.
508
509 This function only returns the first result found, as no more than one
510 value is expected. If the directory is not found, ``None`` is returned.
511
512 :rtype: :class:`Distribution` or :class:`EggInfoDistribution` or None
513 """
514 if paths == None:
515 paths = sys.path
516
517 if not _cache_enabled:
518 for dist in _yield_distributions(True, use_egg_info, paths):
519 if dist.name == name:
520 return dist
521 else:
522 _generate_cache(use_egg_info, paths)
523
524 if name in _cache_name:
525 return _cache_name[name][0]
526 elif use_egg_info and name in _cache_name_egg:
527 return _cache_name_egg[name][0]
528 else:
529 return None
530
531
532def obsoletes_distribution(name, version=None, use_egg_info=False):
533 """
534 Iterates over all distributions to find which distributions obsolete
535 *name*.
536
537 If a *version* is provided, it will be used to filter the results.
538 If the argument *use_egg_info* is set to ``True``, then ``.egg-info``
539 distributions will be considered as well.
540
541 :type name: string
542 :type version: string
543 :parameter name:
544 """
545 for dist in get_distributions(use_egg_info):
546 obsoleted = (dist.metadata['Obsoletes-Dist'] +
547 dist.metadata['Obsoletes'])
548 for obs in obsoleted:
549 o_components = obs.split(' ', 1)
550 if len(o_components) == 1 or version is None:
551 if name == o_components[0]:
552 yield dist
553 break
554 else:
555 try:
556 predicate = VersionPredicate(obs)
557 except ValueError:
558 raise PackagingError(
559 'distribution %r has ill-formed obsoletes field: '
560 '%r' % (dist.name, obs))
561 if name == o_components[0] and predicate.match(version):
562 yield dist
563 break
564
565
566def provides_distribution(name, version=None, use_egg_info=False):
567 """
568 Iterates over all distributions to find which distributions provide *name*.
569 If a *version* is provided, it will be used to filter the results. Scans
570 all elements in ``sys.path`` and looks for all directories ending with
571 ``.dist-info``. Returns a :class:`Distribution` corresponding to the
572 ``.dist-info`` directory that contains a ``METADATA`` that matches *name*
573 for the name metadata. If the argument *use_egg_info* is set to ``True``,
574 then all files and directories ending with ``.egg-info`` are considered
575 as well and returns an :class:`EggInfoDistribution` instance.
576
577 This function only returns the first result found, since no more than
578 one values are expected. If the directory is not found, returns ``None``.
579
580 :parameter version: a version specifier that indicates the version
581 required, conforming to the format in ``PEP-345``
582
583 :type name: string
584 :type version: string
585 """
586 predicate = None
587 if not version is None:
588 try:
589 predicate = VersionPredicate(name + ' (' + version + ')')
590 except ValueError:
591 raise PackagingError('invalid name or version: %r, %r' %
592 (name, version))
593
594 for dist in get_distributions(use_egg_info):
595 provided = dist.metadata['Provides-Dist'] + dist.metadata['Provides']
596
597 for p in provided:
598 p_components = p.rsplit(' ', 1)
599 if len(p_components) == 1 or predicate is None:
600 if name == p_components[0]:
601 yield dist
602 break
603 else:
604 p_name, p_ver = p_components
605 if len(p_ver) < 2 or p_ver[0] != '(' or p_ver[-1] != ')':
606 raise PackagingError(
607 'distribution %r has invalid Provides field: %r' %
608 (dist.name, p))
609 p_ver = p_ver[1:-1] # trim off the parenthesis
610 if p_name == name and predicate.match(p_ver):
611 yield dist
612 break
613
614
615def get_file_users(path):
616 """
617 Iterates over all distributions to find out which distributions use
618 *path*.
619
620 :parameter path: can be a local absolute path or a relative
621 ``'/'``-separated path.
622 :type path: string
623 :rtype: iterator of :class:`Distribution` instances
624 """
625 for dist in get_distributions():
626 if dist.uses(path):
627 yield dist