[Python-checkins] distutils2: savepoint

tarek.ziade python-checkins at python.org
Sun Dec 26 14:21:44 CET 2010


tarek.ziade pushed 6ef9296573a6 to distutils2:

http://hg.python.org/distutils2/rev/6ef9296573a6
changeset:   825:6ef9296573a6
user:        Tarek Ziade <tarek at ziade.org>
date:        Sat Nov 27 15:52:01 2010 +0100
summary:
  savepoint

files:
  distutils2/_backport/pkgutil.py
  distutils2/depgraph.py
  distutils2/metadata.py
  distutils2/run.py
  distutils2/tests/test_depgraph.py

diff --git a/distutils2/_backport/pkgutil.py b/distutils2/_backport/pkgutil.py
--- a/distutils2/_backport/pkgutil.py
+++ b/distutils2/_backport/pkgutil.py
@@ -738,6 +738,9 @@
         if _cache_enabled and not path in _cache_path:
             _cache_path[path] = self
 
+    def __repr__(self):
+        return '%s-%s at %s' % (self.name, self.metadata.version, self.path)
+
     def _get_records(self, local=False):
         RECORD = os.path.join(self.path, 'RECORD')
         record_reader = csv_reader(open(RECORD, 'rb'), delimiter=',')
@@ -856,9 +859,9 @@
         r'(?P<rest>(?:\s*,\s*(?:<|<=|!=|==|>=|>)[-A-Za-z0-9_.]+)*)\s*' \
         r'(?P<extras>\[.*\])?')
 
-    def __init__(self, path):
+    def __init__(self, path, display_warnings=False):
         self.path = path
-
+        self.display_warnings = display_warnings
         if _cache_enabled and path in _cache_path_egg:
             self.metadata = _cache_path_egg[path].metadata
             self.name = self.metadata['Name']
@@ -912,23 +915,32 @@
 
         provides = "%s (%s)" % (self.metadata['name'],
                                 self.metadata['version'])
-        if self.metadata['Metadata-Version'] == '1.2':
+        #if self.metadata['Metadata-Version'] == '1.2':
+        #    self.metadata['Provides-Dist'] += (provides,)
+        #else:
+        #    self.metadata['Provides'] += (provides,)
+
+        if len(provides) > 0:
             self.metadata['Provides-Dist'] += (provides,)
-        else:
-            self.metadata['Provides'] += (provides,)
+
         reqs = []
+
         if requires is not None:
             for line in yield_lines(requires):
-                if line[0] == '[':
+                if line[0] == '[' and self.display_warnings:
                     warnings.warn('distutils2 does not support extensions '
                                   'in requires.txt')
                     break
                 else:
                     match = self._REQUIREMENT.match(line.strip())
                     if not match:
-                        raise ValueError('Distribution %s has ill formed '
-                                         'requires.txt file (%s)' %
-                                         (self.name, line))
+                        # this happens when we encounter extras
+                        # since they are written at the end of the file
+                        # we just exit
+                        break
+                        #raise ValueError('Distribution %s has ill formed '
+                        #                 'requires.txt file (%s)' %
+                        #                 (self.name, line))
                     else:
                         if match.group('extras'):
                             s = (('Distribution %s uses extra requirements '
@@ -946,14 +958,20 @@
                             reqs.append(name)
                         else:
                             reqs.append('%s (%s)' % (name, version))
-            if self.metadata['Metadata-Version'] == '1.2':
+            #if self.metadata['Metadata-Version'] == '1.2':
+            #    self.metadata['Requires-Dist'] += reqs
+            #else:
+            #    self.metadata['Requires'] += reqs
+            if len(reqs) > 0:
                 self.metadata['Requires-Dist'] += reqs
-            else:
-                self.metadata['Requires'] += reqs
+
 
         if _cache_enabled:
             _cache_path_egg[self.path] = self
 
+    def __repr__(self):
+        return '%s-%s at %s' % (self.name, self.metadata.version, self.path)
+
     def get_installed_files(self, local=False):
         return []
 
diff --git a/distutils2/depgraph.py b/distutils2/depgraph.py
--- a/distutils2/depgraph.py
+++ b/distutils2/depgraph.py
@@ -66,18 +66,28 @@
         """
         self.missing[distribution].append(requirement)
 
+    def _repr_dist(self, dist):
+        return '%s %s' % (dist.name, dist.metadata['Version'])
+
+    def repr_node(self, dist, level=1):
+        """Prints only a subgraph"""
+        output = []
+        output.append(self._repr_dist(dist))
+        for other, label in self.adjacency_list[dist]:
+            dist = self._repr_dist(other)
+            if label is not None:
+                dist = '%s [%s]' % (dist, label)
+            output.append('    ' * level + '%s' % dist)
+            suboutput = self.repr_node(other, level+1)
+            subs = suboutput.split('\n')
+            output.extend(subs[1:])
+        return '\n'.join(output)
+
     def __repr__(self):
         """Representation of the graph"""
-        def _repr_dist(dist):
-            return '%s %s' % (dist.name, dist.metadata['Version'])
         output = []
         for dist, adjs in self.adjacency_list.iteritems():
-            output.append(_repr_dist(dist))
-            for other, label in adjs:
-                dist = _repr_dist(other)
-                if label is not None:
-                    dist = '%s [%s]' % (dist, label)
-                output.append('    %s' % dist)
+            output.append(self.repr_node(dist))
         return '\n'.join(output)
 
 
@@ -129,7 +139,9 @@
     # first, build the graph and find out the provides
     for dist in dists:
         graph.add_distribution(dist)
-        provides = dist.metadata['Provides-Dist'] + dist.metadata['Provides']
+        provides = (dist.metadata['Provides-Dist'] + dist.metadata['Provides'] +
+                    ['%s (%s)' % (dist.name, dist.metadata['Version'])])
+
 
         for p in provides:
             comps = p.strip().rsplit(" ", 1)
@@ -149,7 +161,13 @@
     for dist in dists:
         requires = dist.metadata['Requires-Dist'] + dist.metadata['Requires']
         for req in requires:
-            predicate = VersionPredicate(req)
+            try:
+                predicate = VersionPredicate(req)
+            except IrrationalVersionError:
+                # XXX compat-mode if cannot read the version
+                name = req.split()[0]
+                predicate = VersionPredicate(name)
+
             name = predicate.name
 
             if not name in provided:
@@ -172,7 +190,6 @@
                         break
                 if not matched:
                     graph.add_missing(dist, req)
-
     return graph
 
 
diff --git a/distutils2/metadata.py b/distutils2/metadata.py
--- a/distutils2/metadata.py
+++ b/distutils2/metadata.py
@@ -195,8 +195,10 @@
     # also document the mapping API and UNKNOWN default key
 
     def __init__(self, path=None, platform_dependent=False,
-                 execution_context=None, fileobj=None, mapping=None):
+                 execution_context=None, fileobj=None, mapping=None,
+                 display_warnings=False):
         self._fields = {}
+        self.display_warnings = display_warnings
         self.version = None
         self.docutils_support = _HAS_DOCUTILS
         self.platform_dependent = platform_dependent
@@ -387,21 +389,22 @@
             else:
                 value = []
 
-        if name in _PREDICATE_FIELDS and value is not None:
-            for v in value:
-                # check that the values are valid predicates
-                if not is_valid_predicate(v.split(';')[0]):
-                    logger.warn('"%s" is not a valid predicate (field "%s")' %
-                         (v, name))
-        # FIXME this rejects UNKNOWN, is that right?
-        elif name in _VERSIONS_FIELDS and value is not None:
-            if not is_valid_versions(value):
-                logger.warn('"%s" is not a valid version (field "%s")' %
-                     (value, name))
-        elif name in _VERSION_FIELDS and value is not None:
-            if not is_valid_version(value):
-                logger.warn('"%s" is not a valid version (field "%s")' %
-                     (value, name))
+        if self.display_warnings:
+            if name in _PREDICATE_FIELDS and value is not None:
+                for v in value:
+                    # check that the values are valid predicates
+                    if not is_valid_predicate(v.split(';')[0]):
+                        logger.warn('"%s" is not a valid predicate (field "%s")' %
+                            (v, name))
+            # FIXME this rejects UNKNOWN, is that right?
+            elif name in _VERSIONS_FIELDS and value is not None:
+                if not is_valid_versions(value):
+                    logger.warn('"%s" is not a valid version (field "%s")' %
+                        (value, name))
+            elif name in _VERSION_FIELDS and value is not None:
+                if not is_valid_version(value):
+                    logger.warn('"%s" is not a valid version (field "%s")' %
+                        (value, name))
 
         if name in _UNICODEFIELDS:
             value = self._encode_field(value)
diff --git a/distutils2/run.py b/distutils2/run.py
--- a/distutils2/run.py
+++ b/distutils2/run.py
@@ -7,6 +7,8 @@
                                DistutilsError, CCompilerError)
 from distutils2.dist import Distribution
 from distutils2 import __version__
+from distutils2._backport.pkgutil import get_distributions, get_distribution
+from distutils2.depgraph import generate_graph
 
 # This is a barebones help message generated displayed when the user
 # runs the setup script with no arguments at all.  More useful help
@@ -120,11 +122,51 @@
                   action="store_true", dest="version", default=False,
                   help="Prints out the version of Distutils2 and exits.")
 
+    parser.add_option("-s", "--search",
+                  action="store", dest="search", default=None,
+                  help="Search for installed distributions.")
+
+    parser.add_option("-g", "--graph",
+                  action="store", dest="graph", default=None,
+                  help="Display the graph for a given installed distribution.")
+
+    parser.add_option("-f", "--full-graph",
+                  action="store_true", dest="fgraph", default=False,
+                  help="Display the full graph for installed distribution.")
+
     options, args = parser.parse_args()
     if options.version:
         print('Distutils2 %s' % __version__)
         sys.exit(0)
 
+    if options.search is not None:
+        search = options.search.lower()
+        for dist in get_distributions(use_egg_info=True):
+            name = dist.name.lower()
+            if search in name:
+                print('%s %s at %s' % (dist.name, dist.metadata['version'],
+                                     dist.path))
+
+        sys.exit(0)
+
+    if options.graph is not None:
+        name = options.graph
+        dist = get_distribution(name, use_egg_info=True)
+        if dist is None:
+            print('Distribution not found.')
+        else:
+            dists = get_distributions(use_egg_info=True)
+            graph = generate_graph(dists)
+            print(graph.repr_node(dist))
+
+        sys.exit(0)
+
+    if options.fgraph:
+        dists = get_distributions(use_egg_info=True)
+        graph = generate_graph(dists)
+        print(graph)
+        sys.exit(0)
+
     if len(args) == 0:
         parser.print_help()
 
diff --git a/distutils2/tests/test_depgraph.py b/distutils2/tests/test_depgraph.py
--- a/distutils2/tests/test_depgraph.py
+++ b/distutils2/tests/test_depgraph.py
@@ -231,6 +231,7 @@
         # checks what main did XXX could do more here
         tempout.seek(0)
         res = tempout.read()
+        import pdb; pdb.set_trace()
         self.assertTrue('towel' in res)
 
 

--
Repository URL: http://hg.python.org/distutils2


More information about the Python-checkins mailing list