Commits

Brad Montgomery committed d015c2b Draft

PEP8

  • Participants
  • Parent commits 2dd678f

Comments (0)

Files changed (2)

 https://github.com/dustin/py-github
 
 """
-import datetime, hashlib, re, time
+import datetime
+import hashlib
+import re
+import time
 from functools import wraps
 from urllib2 import Request, urlopen, URLError
 from urllib import urlencode
 
-from stripperparser import strip_tags
-
-
 try:
     import json
+    assert json  # silence pyflakes
 except ImportError:
     import simplejson as json
 
     """Urlencode's provided keyword arguments.  If any kwargs are None, it does
     not include those."""
     args = dict(kwargs)
-    for k,v in args.items():
+    for k, v in args.items():
         if v is None:
             del args[k]
     if not args:
 
     def build_request(self, url, data=None):
         if not all((self.username, self.password)):
-            return Request(url,data)
+            return Request(url, data)
         auth = '{0}:{1}'.format(self.username, self.password)
         auth = auth.encode("base64").strip()
         auth = {'Authorization': 'Basic {0}'.format(auth)}
 
     def load_url(self, url, quiet=False, method=None, data=None):
         """NOTE: Raises urllib2.HTTPError if something goes wrong (eg 404)"""
-        request = self.build_request(url,data)
+        request = self.build_request(url, data)
         if method:
-            request.get_method = lambda : method
+            request.get_method = lambda: method
         result = urlopen(request).read()
         return result
 
 
     def repository(self, username, slug):
         return Repository(self, username, slug)
-    
+
     @requires_authentication
-    def new_repository(self,name,**data):
+    def new_repository(self, name, **data):
         """Create a new repository with the given name for the authenticated
         user. Returns a Repository object
         """
         url = api_base + 'repositories/'
         data['name'] = name
-        response = json.loads(self.load_url(url,data=data))
+        response = json.loads(self.load_url(url, data=data))
         if 'slug' in response:
-            return self.repository(self.username,response['slug'])
-        
+            return self.repository(self.username, response['slug'])
+
     @requires_authentication
-    def remove_repository(self,slug):
+    def remove_repository(self, slug):
         """Given a slug, remove a repository from the authenticated user"""
         url = api_base + 'repositories/{0}/{1}'.format(self.username, slug)
         method = 'DELETE'
-        self.load_url(url,method=method)
+        self.load_url(url, method=method)
         return True
-        
-        
+
     @requires_authentication
     def emails(self):
         """Returns a list of configured email addresses for the authenticated
         try:
             return json.loads(self.load_url(url))
         except ValueError:
-            raise urllib2.URLError
+            raise URLError
 
     def __repr__(self):
         extra = ''
         """Get information about changesets on a repository."""
         url = self.base_url + 'changesets/'
         query = smart_encode(limit=limit, start=start)
-        if query: url += '?{0}'.format(query)
+        if query:
+            url += '?{0}'.format(query)
         return self.bb._loads(url)
 
     def parse_changeset_for_author(self, cset):
-        """ try to pull username, full name, email from changeset info, return a dict """
+        """Try to pull username, full name, email from changeset info.
+        Returns a dictionary.
+
+        """
         author = cset.get('author', '')
         raw_author = cset.get('raw_author', '')
         full_name = email = ''
-        try: # parse email from the raw_author field
-            full_name, email = re.search("([^<]*)(<.+>)?", raw_author).groups()  # leaves email as <name@example.com>
+        try:  # parse email from the raw_author field
+            # leaves email as <name@example.com>
+            full_name, email = re.search("([^<]*)(<.+>)?", raw_author).groups()
             if email:
                 email = re.sub('[<|>]', '', email)
             elif email is None:
                 email = ''
         except AttributeError:
             pass
-        
+
         return {
-            'name':full_name or '', 
-            'author':author, 
-            'email':email,
+            'name': full_name or '',
+            'author': author,
+            'email': email,
             'gravatar_id': hashlib.md5(email.lower()).hexdigest()
         }
 
     def issues(self, start=None, limit=None):
         url = self.base_url + 'issues/'
         query = smart_encode(start=start, limit=limit)
-        if query: url += '?{0}'.format(query)
+        if query:
+            url += '?{0}'.format(query)
         return self.bb._loads(url)
 
     def events(self, start=None, limit=None):
         url = self.base_url + 'events/'
         query = smart_encode(start=start, limit=limit)
-        if query: url += '?{0}'.format(query)
+        if query:
+            url += '?{0}'.format(query)
         return self.bb._loads(url)
 
     def followers(self):
         url = self.base_url + 'followers/'
         return self.bb._loads(url)
-    
+
     def forks(self):
         """Number of times this Repo has been forked."""
         data = self.get()
         return data.get("forks_count", 0)
-    
+
     def fork(self):
         """Is this a fork of another Repo? Returns True or False."""
         data = self.get()
         return data.get("is_fork", False)
-    
+
     def contributors(self, limit=50, sleep_after=None, sleep_for=None):
         """
-        NOTE: This method is not very nice to the bitbucket API. 
-            
+        NOTE: This method is not very nice to the bitbucket API.
+
         Use Sparingly.
 
-        Get contributors for a repo, and attempt to provide info similar to 
-        Github's ``contributors``. To do this, we look for data in all of a 
-        project's changesets, and ``limit`` controls how many of those we 
+        Get contributors for a repo, and attempt to provide info similar to
+        Github's ``contributors``. To do this, we look for data in all of a
+        project's changesets, and ``limit`` controls how many of those we
         query at once.
 
         The ``sleep_after`` parameter instructs this method to sleep for
         ``sleep_for`` seconds after ``sleep_after``-many calls to the api.
-        Both of these parameters must be provided for this to work... (yeah, I know)
+        Both of these parameters must be provided for this to work  :-(
 
         >>> repo.contributors(sleep_after=5, sleep_for=3)
 
-        The above example will sleep for 3 seconds after every 5th call to the 
+        The above example will sleep for 3 seconds after every 5th call to the
         changesets API.
-        
+
         This method returns a dictionary of the form:
 
             {
             }
 
         """
-        contributors = {} # user data, keyed by author/username
+        contributors = {}  # user data, keyed by author/username
+
         def _update_contributors(cset, contributors):
             author_data = self.parse_changeset_for_author(cset)
             author = author_data.get('author', '')
-            
+
             if author and author in contributors.keys():
                 contributors[author]['contributions'] += 1
             elif author:
                 contributors[author] = {
-                    'name':author_data.get('name', ''),
-                    'login':author,
-                    'email':author_data.get('email', ''),
-                    'gravatar_id':author_data.get('gravatar_id', ''),
-                    'contributions':1,
+                    'name': author_data.get('name', ''),
+                    'login': author,
+                    'email': author_data.get('email', ''),
+                    'gravatar_id': author_data.get('gravatar_id', ''),
+                    'contributions': 1,
                 }
 
         api_hit_count = 0
-        # Do this for every "page" of the changsets... 
+        # Do this for every "page" of the changsets...
         start = None
         remaining_changesets = 1
         retrieved_changesets = 0
         while remaining_changesets > 0:
-            changesets = self.changesets(limit=limit, start=start)  # initial group of changesets
+            # initial group of changesets
+            changesets = self.changesets(limit=limit, start=start)
             if start:
                 start = start + limit + 1
             else:
                 start = limit + 1
-            api_hit_count += 1 # see how many times we've hit the api
+            api_hit_count += 1  # see how many times we've hit the api
             for cset in changesets.get('changesets', []):
                 _update_contributors(cset, contributors)
             retrieved_changesets += len(changesets.get('changesets', []))
             if remaining_changesets < start:
                 start = changesets['count'] - remaining_changesets
 
-            if sleep_after and sleep_for and api_hit_count > 0 and api_hit_count % sleep_after == 0:
+            sleep_enabled = sleep_after and sleep_for
+            hit_count_reached = (api_hit_count > 0 and
+                                 api_hit_count % sleep_after == 0)
+            if sleep_enabled and hit_count_reached:
                 time.sleep(sleep_for)
-        
+
         #TODO sort based on contributions, like github does?
-        for k,v in contributors.items():
-            v.update({'name':k})
+        for k, v in contributors.items():
+            v.update({'name': k})
         return {'contributors': contributors.values()}
 
     def __repr__(self):
         path = 'repositories/{0}/{1}/issues/{2}'.format(username, slug, number)
         self.base_url = api_base + path
         self._data = None
-    
+
     def get(self):
         if self._data is None:
             self._data = self.bb._loads(self.base_url)

bitbucket/tests/test_bitbucket.py

 from nose.tools import eq_, ok_
-from bitbucket import *
+from bitbucket import BitBucket
 
 
 def test_bitbucket():
     eq_(user.username, 'bkmontgomery')
     # Test user methods in ``test_user``
 
-
     # repository
-    repo = bb.repository('bkmontgomery', 'python-bitbucket')
+    bb.repository('bkmontgomery', 'python-bitbucket')
 
     # --- the following methods require authentication ---
     # new_repository
     # remove_repository
     # emails
 
+
 def test_user():
     bb = BitBucket()
     user = bb.user('bkmontgomery')
     eq_(u['user']['username'], u'bkmontgomery')
     eq_(u['user']['first_name'], u'Brad')
     eq_(u['user']['last_name'], u'Montgomery')
-    
+
     eq_('<User: bkmontgomery>', '%s' % user)
 
+
 def test_repository():
     bb = BitBucket()
     repo = bb.repository('bkmontgomery', 'python-bitbucket')
-    
+
     # get
     data = repo.get()
 
     # __repr__
     eq_("%s" % repo, "<Repository: bkmontgomery's python-bitbucket>")
 
+
 def test_issue():
     bb = BitBucket()
     repo = bb.repository('bkmontgomery', 'python-bitbucket')