Skip to content

Commit

Permalink
Merge branch 'master' into release
Browse files Browse the repository at this point in the history
  • Loading branch information
OrkoHunter committed Feb 10, 2017
2 parents 2d136fc + 9112abe commit d426cf1
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 20 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,5 @@ ENV/

# Flask
flask_session

exports.sh
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# PEP8 Speaks
<img src="data/my_logo.png" >
> because it matters.
A GitHub integration which checks pep8 issues and then comments over Pull Requests
A GitHub :octocat: integration to automatically review Python code style over Pull Requests

<img src="data/readme.png" width="80%">

Expand Down Expand Up @@ -47,6 +48,8 @@ pycodestyle:
ignore: # Errors and warnings to ignore
- W391
- E203

no_blank_comment: False # If True, no comment is made when the bot does not find any pep8 errors
```
Note : See more [pycodestyle options](https://pycodestyle.readthedocs.io/en/latest/intro.html#example-usage-and-output)
Expand All @@ -65,3 +68,6 @@ Note : See more [pycodestyle options](https://pycodestyle.readthedocs.io/en/late
This is a very young project. If you have got any suggestions for new features or improvements, please comment over [here](https://github.com/OrkoHunter/pep8speaks/issues/1). Pull Requests are most welcome !

:heart:

<img src="https://raw.githubusercontent.com/OrkoHunter/pep8speaks/master/data/pep8speaks.commits.png" width="60%"><br>
###### Created using [commits.io](https://commits.io)
4 changes: 4 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ def main():
return handlers.handle_review(request)
elif event == "pull_request_review_comment":
return handlers.handle_review_comment(request)
elif event == "integration_installation":
return handlers.handle_integration_installation(request)
elif event == "integration_installation_repositories":
return handlers.handle_integration_installation_repo(request)
else:
return render_template('index.html')

Expand Down
Binary file added data/my_logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/pep8speaks.commits.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
44 changes: 38 additions & 6 deletions pep8speaks/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ def handle_pull_request(request):
# A variable which is set to False whenever a criteria is not met
# Ultimately if this is True, only then the comment is made
PERMITTED_TO_COMMENT = True
# This dictionary is used and updated after making API calls
data = {}

if request.json["action"] in ["synchronize", "opened", "reopened"]:
# This dictionary is used and updated after making API calls
data = {
"after_commit_hash": request.json["pull_request"]["head"]["sha"],
"repository": request.json["repository"]["full_name"],
Expand All @@ -32,7 +33,7 @@ def handle_pull_request(request):
helpers.update_users(data["repository"])

# Get the config from .pep8speaks.yml file of the repository
config = helpers.get_config(data["repository"])
config = helpers.get_config(data)

# Personalising the messages obtained from the config file
# Replace {name} with name of the author
Expand All @@ -50,12 +51,16 @@ def handle_pull_request(request):
helpers.run_pycodestyle(data, config)

# Construct the comment
header, body, footer = helpers.prepare_comment(request, data, config)
header, body, footer, ERROR = helpers.prepare_comment(request, data, config)

# If there is nothing in the comment body, no need to make the comment
if len(body) == 0:
PERMITTED_TO_COMMENT = False

if config["no_blank_comment"]: # If asked not to comment no-error messages
if not ERROR: # If there is no error in the PR
PERMITTED_TO_COMMENT = False

# Concatenate comment parts
comment = header + body + footer

Expand All @@ -78,14 +83,15 @@ def handle_pull_request(request):
response = requests.post(query, json={"body": comment}, headers=headers)
data["comment_response"] = response.json()

js = json.dumps(data)
return Response(js, status=200, mimetype='application/json')
js = json.dumps(data)
return Response(js, status=200, mimetype='application/json')


def handle_review(request):
# Handle the request when a new review is submitted

data = dict()
data["after_commit_hash"] = request.json["pull_request"]["head"]["sha"],
data["author"] = request.json["pull_request"]["user"]["login"]
data["reviewer"] = request.json["review"]["user"]["login"]
data["repository"] = request.json["repository"]["full_name"]
Expand All @@ -95,7 +101,7 @@ def handle_review(request):
data["pr_number"] = request.json["pull_request"]["number"]

# Get the .pep8speaks.yml config file from the repository
config = helpers.get_config(data["repository"])
config = helpers.get_config(data)

condition1 = request.json["action"] == "submitted"
# Mainly the summary of the review matters
Expand Down Expand Up @@ -180,3 +186,29 @@ def _create_diff(request, data, config):
def handle_review_comment(request):
# Figure out what does "position" mean in the response
pass


def handle_integration_installation(request):
# Follow user
data = {
"user": request.json["sender"]["login"]
}

helpers.follow_user(data["user"])
status_code = 200
js = json.dumps(data)
return Response(js, status=status_code, mimetype='application/json')



def handle_integration_installation_repo(request):
# Add the repo in the database
data = {
"repositories": request.json["repositories_added"],
}

for repo in data["repositories"]:
helpers.update_users(repo["full_name"])
status_code = 200
js = json.dumps(data)
return Response(js, status=status_code, mimetype='application/json')
50 changes: 37 additions & 13 deletions pep8speaks/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import re
import sys
import time
from bs4 import BeautifulSoup
from flask import abort
from markdown import markdown
import psycopg2
import pycodestyle
import requests
Expand Down Expand Up @@ -39,6 +41,18 @@ def update_users(repository):
conn.rollback()



def follow_user(user):
"""Follow the user of the service"""
headers = {
"Authorization": "token " + os.environ["GITHUB_TOKEN"],
"Content-Length": "0",
}
url = "https://api.github.com/user/following/{}"
url = url.format(user)
r = requests.put(url, headers=headers)


def update_dict(base, head):
"""
Recursively merge or update dict-like objects.
Expand Down Expand Up @@ -73,7 +87,7 @@ def match_webhook_secret(request):
return True


def get_config(repository):
def get_config(data):
"""
Get .pep8speaks.yml config file from the repository and return
the config dictionary
Expand Down Expand Up @@ -105,20 +119,21 @@ def get_config(repository):
"show-source": False,
"statistics": False,
"hang-closing": False,
}
},
"no_blank_comment": False,
}

headers = {"Authorization": "token " + os.environ["GITHUB_TOKEN"]}

# Configuration file
url = "https://api.github.com/repos/{}/contents/.pep8speaks.yml"
url = url.format(repository)
url = "https://raw.githubusercontent.com/{}/{}/{}/.pep8speaks.yml"
repo = data["repository"].split("/")[-1]
url = url.format(data["author"], repo, data["after_commit_hash"])
r = requests.get(url, headers=headers)
if r.status_code == 200:
PEP8SPEAKS_YML_FOUND = True
res = requests.get(r.json()["download_url"])
with open(".pep8speaks.yml", "w+") as config_file:
config_file.write(res.text)
config_file.write(r.text)

# Update default config with those provided
with open(".pep8speaks.yml", "r") as stream:
Expand Down Expand Up @@ -147,6 +162,9 @@ def get_config(repository):
arguments += "--{}={} ".format(conf, ','.join(confs[conf]))
config["pycodestyle_cmd_config"] = arguments

# pycodestyle is case-sensitive
config["pycodestyle"]["ignore"] = [e.upper() for e in list(config["pycodestyle"]["ignore"])]

return config


Expand Down Expand Up @@ -240,12 +258,14 @@ def prepare_comment(request, data, config):
comment_header = config["message"]["updated"]["header"] + "\n\n"

## Body
ERROR = False # Set to True when any pep8 error exists
comment_body = ""
for file in list(data["results"].keys()):
if len(data["results"][file]) == 0:
comment_body += " - There are no PEP8 issues in the" + \
" file [`{0}`]({1}) !".format(file, data[file + "_link"])
else:
ERROR = True
comment_body += " - In the file [`{0}`]({1}), following\
are the PEP8 issues :\n".format(file, data[file + "_link"])
for issue in data["results"][file]:
Expand Down Expand Up @@ -287,7 +307,7 @@ def prepare_comment(request, data, config):
else:
comment_footer += config["message"]["updated"]["footer"]

return comment_header, comment_body, comment_footer
return comment_header, comment_body, comment_footer, ERROR


def comment_permission_check(data, comment):
Expand All @@ -307,7 +327,10 @@ def comment_permission_check(data, comment):
if old_comment["user"]["id"] == 24736507: # ID of @pep8speaks
last_comment = old_comment["body"]
break
if comment == last_comment:

text1 = ''.join(BeautifulSoup(markdown(comment)).findAll(text=True))
text2 = ''.join(BeautifulSoup(markdown(last_comment)).findAll(text=True))
if text1 == text2.replace("submitting", "updating"):
PERMITTED_TO_COMMENT = False

## Do not comment on updating if no errors were introduced previously
Expand Down Expand Up @@ -413,11 +436,12 @@ def delete_if_forked(data):
headers = {"Authorization": "token " + os.environ["GITHUB_TOKEN"]}
r = requests.get(url, headers=headers)
for repo in r.json():
if data["target_repo_fullname"] in repo["description"]:
FORKED = True
r = requests.delete("https://api.github.com/repos/"
"{}".format(repo["full_name"]),
headers=headers)
if repo["description"]:
if data["target_repo_fullname"] in repo["description"]:
FORKED = True
r = requests.delete("https://api.github.com/repos/"
"{}".format(repo["full_name"]),
headers=headers)
return FORKED


Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ psycopg2
PyYAML
unidiff
autopep8
markdown
beautifulsoup4

0 comments on commit d426cf1

Please sign in to comment.