From 9606b42c49857db4a1abd36e2a16daf9e6a1298b Mon Sep 17 00:00:00 2001
From: Pierre-Yves Chibon <pingou@pingoured.fr>
Date: Feb 23 2017 21:40:49 +0000
Subject: [PATCH 1/3] Flake8 clean up of pagure.lib.model


---

diff --git a/pagure/lib/model.py b/pagure/lib/model.py
index 7a14e2e..a9322ec 100644
--- a/pagure/lib/model.py
+++ b/pagure/lib/model.py
@@ -8,8 +8,8 @@
 
 """
 
-__requires__ = ['SQLAlchemy >= 0.8', 'jinja2 >= 2.4']
-import pkg_resources
+__requires__ = ['SQLAlchemy >= 0.8', 'jinja2 >= 2.4']  # noqa
+import pkg_resources  # noqa
 
 import datetime
 import collections
@@ -32,7 +32,7 @@ from sqlalchemy.orm import relation
 CONVENTION = {
     "ix": 'ix_%(table_name)s_%(column_0_label)s',
     # Checks are currently buggy and prevent us from naming them correctly
-    #"ck": "ck_%(table_name)s_%(constraint_name)s",
+    # "ck": "ck_%(table_name)s_%(constraint_name)s",
     "fk": "%(table_name)s_%(column_0_name)s_fkey",
     "pk": "%(table_name)s_pkey",
     "uq": "%(table_name)s_%(column_0_name)s_key",
@@ -408,7 +408,8 @@ class Project(BASE):
         secondaryjoin="pagure_group.c.id==projects_groups.c.group_id",
         backref=backref(
             "projects",
-            order_by="func.lower(projects.c.namespace).desc(), func.lower(projects.c.name)"
+            order_by="func.lower(projects.c.namespace).desc(), \
+                      func.lower(projects.c.name)"
         )
     )
 
@@ -763,8 +764,10 @@ class DeployKey(BASE):
             'deploykeys', cascade="delete, delete-orphan", single_parent=True)
         )
 
-    creator_user = relation('User', foreign_keys=[creator_user_id],
-                    remote_side=[User.id])
+    creator_user = relation(
+        'User',
+        foreign_keys=[creator_user_id],
+        remote_side=[User.id])
 
 
 class Issue(BASE):
@@ -889,7 +892,9 @@ class Issue(BASE):
                     link, filename, display_name = extract_info(line)
                     attachments.append(
                         (link, filename, display_name,
-                         self.date_created.strftime('%Y-%m-%d %H:%M:%S'), None))
+                         self.date_created.strftime('%Y-%m-%d %H:%M:%S'),
+                         None)
+                    )
         if self.comments:
             # Check the comments for attachments
             for comment in self.comments:
@@ -903,7 +908,8 @@ class Issue(BASE):
                         link, filename, display_name = extract_info(line)
                         attachments.append(
                             (link, filename, display_name,
-                             comment.date_created.strftime('%Y-%m-%d %H:%M:%S'),
+                             comment.date_created.strftime(
+                                '%Y-%m-%d %H:%M:%S'),
                              str(comment.id)))
         return attachments
 
@@ -1173,13 +1179,15 @@ class IssueValues(BASE):
     issue = relation(
         'Issue', foreign_keys=[issue_uid], remote_side=[Issue.uid],
         backref=backref(
-            'other_fields', cascade="delete, delete-orphan", single_parent=True)
+            'other_fields',
+            cascade="delete, delete-orphan",
+            single_parent=True)
         )
 
     key = relation(
         'IssueKeys', foreign_keys=[key_id], remote_side=[IssueKeys.id],
         backref=backref('values', cascade="delete, delete-orphan")
-        )
+    )
 
 
 class Tag(BASE):
@@ -1228,7 +1236,6 @@ class TagIssue(BASE):
         return 'TagIssue(issue:%s, tag:%s)' % (self.issue.id, self.tag)
 
 
-
 class TagColored(BASE):
     """ Stores the colored tags.
 
@@ -2088,7 +2095,9 @@ class PullRequestWatcher(BASE):
     )
 
     pull_request = relation(
-        'PullRequest', foreign_keys=[pull_request_uid], remote_side=[PullRequest.uid],
+        'PullRequest',
+        foreign_keys=[pull_request_uid],
+        remote_side=[PullRequest.uid],
         backref=backref(
             'watchers', cascade="delete, delete-orphan",
         ),

From 867097dc25bea470ed3d53cbd28c390e22d52b01 Mon Sep 17 00:00:00 2001
From: Pierre-Yves Chibon <pingou@pingoured.fr>
Date: Feb 23 2017 21:40:49 +0000
Subject: [PATCH 2/3] Finish cleaning up with flake8 the pagure.lib module


---

diff --git a/pagure/lib/__init__.py b/pagure/lib/__init__.py
index 10b86db..6c1b135 100644
--- a/pagure/lib/__init__.py
+++ b/pagure/lib/__init__.py
@@ -225,9 +225,6 @@ def create_deploykeys_ssh_keys_on_disk(project, gitolite_keydir):
         # Nothing to do here, move right along
         return
 
-        #keyline_file = os.path.join(gitolite_keydir,
-        #                            'keys_%i' % i,
-        #                            '%s.pub' % user.user)
     # First remove deploykeys that no longer exist
     keyfiles = ['deploykey_%s_%s.pub' %
                 (werkzeug.secure_filename(project.fullname),
@@ -605,9 +602,6 @@ def add_issue_dependency(
             repo=issue_blocked.project,
             repofolder=ticketfolder)
 
-        #pagure.lib.notify.notify_assigned_issue(issue, user_obj)
-        #pagure.lib.notify.notify_assigned_issue(issue_blocked, user_obj)
-
         if not issue.private:
             pagure.lib.notify.log(
                 issue.project,
@@ -665,9 +659,6 @@ def remove_issue_dependency(
             repo=issue_blocked.project,
             repofolder=ticketfolder)
 
-        #pagure.lib.notify.notify_assigned_issue(issue, user_obj)
-        #pagure.lib.notify.notify_assigned_issue(issue_blocked, user_obj)
-
         if not issue.private:
             pagure.lib.notify.log(
                 issue.project,
@@ -810,8 +801,8 @@ def edit_issue_tags(
 
     # check for change
     no_change_in_tag = old_tag.tag == new_tag \
-                       and old_tag_description == new_tag_description \
-                       and old_tag_color == new_tag_color
+        and old_tag_description == new_tag_description \
+        and old_tag_color == new_tag_color
     if no_change_in_tag:
         raise pagure.exceptions.PagureException(
             'No change.  Old tag "%s(%s)[%s]" is the same as '
@@ -852,9 +843,12 @@ def edit_issue_tags(
             issue, repo=issue.project, repofolder=ticketfolder)
 
     msgs = []
-    msgs.append('Edited tag: %s(%s)[%s] to %s(%s)[%s]' %
-                (old_tag_name, old_tag_description, old_tag_color,
-                new_tag, new_tag_description, new_tag_color))
+    msgs.append(
+        'Edited tag: %s(%s)[%s] to %s(%s)[%s]' % (
+            old_tag_name, old_tag_description, old_tag_color,
+            new_tag, new_tag_description, new_tag_color
+        )
+    )
     pagure.lib.notify.log(
         project,
         topic='project.tag.edited',
@@ -897,7 +891,7 @@ def add_deploykey_to_project(session, project, ssh_key, pushaccess, user):
     # If we dupe keys, gitolite might choke.
     ssh_search_key = ssh_short_key.split(' ')[1]
     if session.query(model.DeployKey).filter(
-            model.DeployKey.ssh_search_key==ssh_search_key).count() != 0:
+            model.DeployKey.ssh_search_key == ssh_search_key).count() != 0:
         raise pagure.exceptions.PagureException(
             'Deploy key already exists.'
         )
@@ -926,8 +920,11 @@ def add_user_to_project(session, project, new_user, user, access='admin'):
     new_user_obj = get_user(session, new_user)
     user_obj = get_user(session, user)
 
-    users = set([user_.user for user_ in
-        get_project_users(session, project, access, combine=False)])
+    users = set([
+        user_.user
+        for user_ in get_project_users(
+            session, project, access, combine=False)
+    ])
     users.add(project.user.user)
 
     if new_user in users:
@@ -1014,8 +1011,11 @@ def add_group_to_project(
             'You are not allowed to add a group of users to this project'
         )
 
-    groups = set([group.group_name for group in
-        get_project_groups(session, project, access, combine=False)])
+    groups = set([
+        group.group_name
+        for group in get_project_groups(
+            session, project, access, combine=False)
+    ])
 
     if new_group in groups:
         raise pagure.exceptions.PagureException(
@@ -1302,7 +1302,7 @@ def new_project(session, user, name, blacklist, allowed_prefix,
     if repo:
         raise pagure.exceptions.RepoExistsException(
             'The project repo "%s" already exists in the database' % (
-            path)
+                path)
         )
 
     project = model.Project(
@@ -2505,7 +2505,7 @@ def close_pull_request(session, request, user, requestfolder, merged=True):
 def reset_status_pull_request(session, project):
     ''' Reset the status of all opened Pull-Requests of a project.
     '''
-    query = session.query(
+    session.query(
         model.PullRequest
     ).filter(
         model.PullRequest.project_id == project.id
@@ -2750,7 +2750,6 @@ def update_dependency_issue(
     toadd = set(depends) - set(issue.depends_text)
     torm = set(issue.depends_text) - set(depends)
     messages = []
-    comment = ""
 
     # Add issue depending
     for depend in sorted([int(i) for i in toadd]):
@@ -2817,7 +2816,6 @@ def update_blocked_issue(
             # we should never be in this case but better safe than sorry...
             continue
 
-
         add_issue_dependency(
             session,
             issue=issue,
@@ -3302,7 +3300,7 @@ def text2markdown(text, extended=True, readme=False):
     if text:
         try:
             text = md_processor.convert(text)
-        except Exception as err:
+        except Exception:
             LOG.debug(
                 'A markdown error occured while processing: ``%s``',
                 str(text))
@@ -3333,12 +3331,12 @@ def clean_input(text, ignore=None):
     attrs['table'] = ['class']
     attrs['span'] = ['class', 'id']
     attrs['div'] = ['class']
-    if not ignore or not 'img' in ignore:
+    if not ignore or 'img' not in ignore:
         attrs['img'] = filter_img_src
 
     tags = bleach.ALLOWED_TAGS + [
         'p', 'br', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
-        'table', 'td', 'tr', 'th', 'thead','tbody',
+        'table', 'td', 'tr', 'th', 'thead', 'tbody',
         'col', 'pre', 'img', 'hr', 'dl', 'dt', 'dd', 'span',
         'kbd', 'var', 'del', 'cite',
     ]
@@ -3971,6 +3969,7 @@ def tokenize_search_string(pattern):
     """
     if pattern is None:
         return {}, None
+
     def finalize_token(token, custom_search):
         if ':' in token:
             # This was a "key:value" parameter
diff --git a/pagure/lib/encoding_utils.py b/pagure/lib/encoding_utils.py
index 70569d6..6ca7cba 100644
--- a/pagure/lib/encoding_utils.py
+++ b/pagure/lib/encoding_utils.py
@@ -17,7 +17,7 @@ import logging
 
 from chardet import universaldetector
 
-from pagure.exceptions import PagureException
+from pagure.exceptions import PagureEncodingException
 
 
 _log = logging.getLogger(__name__)
diff --git a/pagure/lib/git.py b/pagure/lib/git.py
index afae8e3..0311f0e 100644
--- a/pagure/lib/git.py
+++ b/pagure/lib/git.py
@@ -1210,7 +1210,7 @@ def merge_pull_request(
     refname = '%s:refs/heads/%s' % (branch_ref.name, request.branch)
     if (
             (merge is not None and merge.is_uptodate)
-            or
+            or  # noqa
             (merge is None and
              mergecode & pygit2.GIT_MERGE_ANALYSIS_UP_TO_DATE)):
 
@@ -1236,7 +1236,7 @@ def merge_pull_request(
 
     elif (
             (merge is not None and merge.is_fastforward)
-            or
+            or  # noqa
             (merge is None and
              mergecode & pygit2.GIT_MERGE_ANALYSIS_FASTFORWARD)):
 
@@ -1349,7 +1349,8 @@ def diff_pull_request(
         raise pagure.exceptions.PagureException(
             'Fork is empty, there are no commits to request pulling')
 
-    if not orig_repo.is_empty and request.branch not in orig_repo.listall_branches():
+    if not orig_repo.is_empty \
+            and request.branch not in orig_repo.listall_branches():
         raise pagure.exceptions.PagureException(
             'The branch into which this pull-request was to be merged: %s '
             'seems to no longer be present in this repo' % request.branch)
diff --git a/pagure/lib/lib_ci.py b/pagure/lib/lib_ci.py
index 5107c63..a89aa0e 100644
--- a/pagure/lib/lib_ci.py
+++ b/pagure/lib/lib_ci.py
@@ -14,8 +14,6 @@
 
 import pagure.exceptions
 import pagure.lib
-from pagure.lib import model
-from pagure.hooks import pagure_ci
 
 
 BUILD_STATS = {

From 2ae922b66cd0fbc81dfc63fc500ba9abe5966080 Mon Sep 17 00:00:00 2001
From: Pierre-Yves Chibon <pingou@pingoured.fr>
Date: Feb 23 2017 21:40:49 +0000
Subject: [PATCH 3/3] Use is_() and isnot() when filtering for None or not None in queries


---

diff --git a/pagure/lib/__init__.py b/pagure/lib/__init__.py
index 6c1b135..4089f7f 100644
--- a/pagure/lib/__init__.py
+++ b/pagure/lib/__init__.py
@@ -2197,11 +2197,11 @@ def search_issues(
                 )
         elif str(assignee).lower() in ['true', '1']:
             query = query.filter(
-                model.Issue.assignee_id != None
+                model.Issue.assignee_id.isnot(None)
             )
         else:
             query = query.filter(
-                model.Issue.assignee_id == None
+                model.Issue.assignee_id.is_(None)
             )
     if author is not None:
         query = query.filter(
@@ -2232,13 +2232,13 @@ def search_issues(
         if isinstance(milestones, basestring):
             milestones = [milestones]
         query = query.filter(
-            (model.Issue.milestone == None) |
+            (model.Issue.milestone.is_(None)) |
             (model.Issue.milestone.in_(milestones))
         )
     elif no_milestones:
         # Asking for issues without a milestone
         query = query.filter(
-            model.Issue.milestone == None
+            model.Issue.milestone.is_(None)
         )
     elif milestones is not None and milestones != []:
         # Asking for a single specific milestone
@@ -2428,11 +2428,11 @@ def search_pull_requests(
                 )
         elif str(assignee).lower() in ['true', '1']:
             query = query.filter(
-                model.PullRequest.assignee_id != None
+                model.PullRequest.assignee_id.isnot(None)
             )
         else:
             query = query.filter(
-                model.PullRequest.assignee_id == None
+                model.PullRequest.assignee_id.is_(None)
             )
 
     if author is not None:

