[Python-checkins] distutils2: Slight cleanup for mkcfg + fixed two bugs with except clauses.

tarek.ziade python-checkins at python.org
Wed Feb 16 22:23:56 CET 2011


tarek.ziade pushed 1d1d07ebb991 to distutils2:

http://hg.python.org/distutils2/rev/1d1d07ebb991
changeset:   1008:1d1d07ebb991
user:        ?ric Araujo <merwok at netwok.org>
date:        Thu Feb 03 20:13:36 2011 +0100
summary:
  Slight cleanup for mkcfg + fixed two bugs with except clauses.

files:
  distutils2/mkcfg.py
  distutils2/tests/test_mkcfg.py

diff --git a/distutils2/mkcfg.py b/distutils2/mkcfg.py
--- a/distutils2/mkcfg.py
+++ b/distutils2/mkcfg.py
@@ -25,18 +25,15 @@
 
 import os
 import sys
+import glob
 import re
 import shutil
-import glob
-import re
 from ConfigParser import RawConfigParser
 from textwrap import dedent
-if sys.version_info[:2] < (2, 6):
-    from sets import Set as set
 try:
     from hashlib import md5
 except ImportError:
-    from md5 import md5
+    from distutils2._backport.hashlib  import md5
 # importing this with an underscore as it should be replaced by the
 # dict form or another structures for all purposes
 from distutils2._trove import all_classifiers as _CLASSIFIERS_LIST
@@ -92,10 +89,10 @@
 Optionally, you can set other trove identifiers for things such as the
 human language, programming language, user interface, etc...
 ''',
-    'setup.py found':'''
+    'setup.py found': '''
 The setup.py script will be executed to retrieve the metadata.
 A wizard will be run if you answer "n",
-'''
+''',
 }
 
 # XXX everything needs docstrings and tests (both low-level tests of various
@@ -162,6 +159,7 @@
 
 CLASSIFIERS = _build_classifiers_dict(_CLASSIFIERS_LIST)
 
+
 def _build_licences(classifiers):
     res = []
     for index, item in enumerate(classifiers):
@@ -172,6 +170,7 @@
 
 LICENCES = _build_licences(_CLASSIFIERS_LIST)
 
+
 class MainProgram(object):
     def __init__(self):
         self.configparser = None
@@ -235,8 +234,8 @@
             if ans != 'y':
                 return
 
-        #_______mock setup start
         data = self.data
+
         def setup(**attrs):
             """Mock the setup(**attrs) in order to retrive metadata."""
             # use the distutils v1 processings to correctly parse metadata.
@@ -272,11 +271,12 @@
                 if len(dist.data_files) < 2 or \
                    isinstance(dist.data_files[1], str):
                     dist.data_files = [('', dist.data_files)]
-                #add tokens in the destination paths
-                vars = {'distribution.name':data['name']}
+                # add tokens in the destination paths
+                vars = {'distribution.name': data['name']}
                 path_tokens = sysconfig.get_paths(vars=vars).items()
-                #sort tokens to use the longest one first
-                path_tokens.sort(cmp=lambda x,y: cmp(len(y), len(x)),
+                # sort tokens to use the longest one first
+                # TODO chain two sorted with key arguments, remove cmp
+                path_tokens.sort(cmp=lambda x, y: cmp(len(y), len(x)),
                                  key=lambda x: x[1])
                 for dest, srcs in (dist.data_files or []):
                     dest = os.path.join(sys.prefix, dest)
@@ -291,29 +291,31 @@
             package_dirs = dist.package_dir or {}
             for package, extras in dist.package_data.iteritems() or []:
                 package_dir = package_dirs.get(package, package)
-                fils = [os.path.join(package_dir, fil) for fil in extras]
-                data['extra_files'].extend(fils)
+                files = [os.path.join(package_dir, f) for f in extras]
+                data['extra_files'].extend(files)
 
             # Use README file if its content is the desciption
             if "description" in data:
                 ref = md5(re.sub('\s', '', self.data['description']).lower())
                 ref = ref.digest()
                 for readme in glob.glob('README*'):
-                    fob = open(readme)
-                    val = md5(re.sub('\s', '', fob.read()).lower()).digest()
-                    fob.close()
+                    fp = open(readme)
+                    try:
+                        contents = fp.read()
+                    finally:
+                        fp.close()
+                    val = md5(re.sub('\s', '', contents.lower())).digest()
                     if val == ref:
                         del data['description']
                         data['description-file'] = readme
                         break
-        #_________ mock setup end
 
         # apply monkey patch to distutils (v1) and setuptools (if needed)
         # (abord the feature if distutils v1 has been killed)
         try:
             import distutils.core as DC
-            getattr(DC, 'setup') # ensure distutils v1
-        except ImportError, AttributeError:
+            DC.setup  # ensure distutils v1
+        except (ImportError, AttributeError):
             return
         saved_setups = [(DC, DC.setup)]
         DC.setup = setup
@@ -321,15 +323,15 @@
             import setuptools
             saved_setups.append((setuptools, setuptools.setup))
             setuptools.setup = setup
-        except ImportError, AttributeError:
+        except (ImportError, AttributeError):
             pass
         # get metadata by executing the setup.py with the patched setup(...)
-        success = False # for python < 2.4
+        success = False  # for python < 2.4
         try:
             pyenv = globals().copy()
             execfile(setuppath, pyenv)
             success = True
-        finally: #revert monkey patches
+        finally:  # revert monkey patches
             for patched_module, original_setup in saved_setups:
                 patched_module.setup = original_setup
         if not self.data:
@@ -339,7 +341,8 @@
     def inspect_file(self, path):
         fp = open(path, 'r')
         try:
-            for line in [fp.readline() for _ in range(10)]:
+            for _ in xrange(10):
+                line = fp.readline()
                 m = re.match(r'^#!.*python((?P<major>\d)(\.\d+)?)?$', line)
                 if m:
                     if m.group('major') == '3':
@@ -393,7 +396,6 @@
                         helptext=_helptext['extra_files']) == 'y':
                 self._set_multi('Extra file/dir name', 'extra_files')
 
-
         if ask_yn('Do you want to set Trove classifiers?',
                   helptext=_helptext['do_classifier']) == 'y':
             self.set_classifier()
@@ -413,7 +415,6 @@
         _pref = ['lib', 'include', 'dist', 'build', '.', '~']
         _suf = ['.pyc']
 
-
         def to_skip(path):
             path = relative(path)
 
diff --git a/distutils2/tests/test_mkcfg.py b/distutils2/tests/test_mkcfg.py
--- a/distutils2/tests/test_mkcfg.py
+++ b/distutils2/tests/test_mkcfg.py
@@ -1,11 +1,8 @@
 # -*- coding: utf-8 -*-
 """Tests for distutils.mkcfg."""
 import os
-import os.path as osp
 import sys
 import StringIO
-if sys.version_info[:2] < (2, 6):
-    from sets import Set as set
 from textwrap import dedent
 
 from distutils2.tests import run_unittest, support, unittest
@@ -114,9 +111,11 @@
         sys.stdin.write('y\n')
         sys.stdin.seek(0)
         main()
-        fid = open(osp.join(self.wdir, 'setup.cfg'))
-        lines = set([line.rstrip() for line in fid])
-        fid.close()
+        fp = open(os.path.join(self.wdir, 'setup.cfg'))
+        try:
+            lines = set([line.rstrip() for line in fp])
+        finally:
+            fp.close()
         self.assertEqual(lines, set(['',
             '[metadata]',
             'version = 0.2',
@@ -183,9 +182,11 @@
         sys.stdin.write('y\n')
         sys.stdin.seek(0)
         main()
-        fid = open(osp.join(self.wdir, 'setup.cfg'))
-        lines = set([line.strip() for line in fid])
-        fid.close()
+        fp = open(os.path.join(self.wdir, 'setup.cfg'))
+        try:
+            lines = set([line.strip() for line in fp])
+        finally:
+            fp.close()
         self.assertEqual(lines, set(['',
             '[metadata]',
             'version = 0.2',

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


More information about the Python-checkins mailing list