Skip to content

Commit

Permalink
Merge pull request #25 from Justintime50/v2.4.0
Browse files Browse the repository at this point in the history
chore: drop support for Python 3.6, format with Black
  • Loading branch information
Justintime50 authored Sep 21, 2021
2 parents f09edfd + c942300 commit 64535c5
Show file tree
Hide file tree
Showing 15 changed files with 357 additions and 298 deletions.
2 changes: 1 addition & 1 deletion .flake8
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[flake8]
max-line-length=120
max-line-length = 120
1 change: 0 additions & 1 deletion .github/FUNDING.yml

This file was deleted.

2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
pythonversion: ["3.6", "3.7", "3.8", "3.9"]
pythonversion: ["3.7", "3.8", "3.9"]
steps:
- name: Checkout Repository
uses: actions/checkout@v2
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# CHANGELOG

## v2.4.0 (2021-09-20)

* Drops support for Python 3.6
* Swaps `mock` library for builtin `unittest.mock` library
* Formats entire project with `Black`

## v2.3.0 (2021-05-31)

* Pin dependencies
Expand Down
51 changes: 30 additions & 21 deletions pullbug/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@
LOGGER = logging.getLogger(__name__)


class PullBugCLI():
class PullBugCLI:
def __init__(self):
"""Initiate CLI args.
"""
"""Initiate CLI args."""
parser = argparse.ArgumentParser(
description='Get bugged via Slack or RocketChat to merge your GitHub pull requests or GitLab merge requests.' # noqa
)
Expand All @@ -31,55 +30,55 @@ def __init__(self):
required=False,
action='store_true',
default=False,
help='Get bugged about pull requests from GitHub.'
help='Get bugged about pull requests from GitHub.',
)
parser.add_argument(
'-gl',
'--gitlab',
required=False,
action='store_true',
default=False,
help='Get bugged about merge requests from GitLab.'
help='Get bugged about merge requests from GitLab.',
)
parser.add_argument(
'-d',
'--discord',
required=False,
action='store_true',
default=False,
help='Send Pullbug messages to Discord.'
help='Send Pullbug messages to Discord.',
)
parser.add_argument(
'-s',
'--slack',
required=False,
action='store_true',
default=False,
help='Send Pullbug messages to Slack.'
help='Send Pullbug messages to Slack.',
)
parser.add_argument(
'-rc',
'--rocketchat',
required=False,
action='store_true',
default=False,
help='Send Pullbug messages to Rocket.Chat.'
help='Send Pullbug messages to Rocket.Chat.',
)
parser.add_argument(
'-w',
'--wip',
required=False,
action='store_true',
default=False,
help='Include "Work in Progress" pull or merge requests.'
help='Include "Work in Progress" pull or merge requests.',
)
parser.add_argument(
'-gho',
'--github_owner',
required=False,
type=str,
default=None,
help='The GitHub owner to retrieve pull requests from (can be a user or organization).'
help='The GitHub owner to retrieve pull requests from (can be a user or organization).',
)
parser.add_argument(
'-ghs',
Expand All @@ -88,7 +87,7 @@ def __init__(self):
type=str,
default='open',
choices=['open', 'closed', 'all'],
help='The GitHub state to retrieve pull requests with.'
help='The GitHub state to retrieve pull requests with.',
)
parser.add_argument(
'-ghc',
Expand All @@ -97,7 +96,7 @@ def __init__(self):
type=str,
default='orgs',
choices=['orgs', 'users'],
help='The GitHub context to retrieve pull requests with.'
help='The GitHub context to retrieve pull requests with.',
)
parser.add_argument(
'-glst',
Expand All @@ -106,7 +105,7 @@ def __init__(self):
type=str,
default='opened',
choices=['opened', 'closed', 'locked', 'merged'],
help='The GitLab state to retrieve merge requests with.'
help='The GitLab state to retrieve merge requests with.',
)
parser.add_argument(
'-glsc',
Expand All @@ -115,13 +114,12 @@ def __init__(self):
type=str,
default='all',
choices=['all', 'created_by_me', 'assigned_to_me'],
help='The GitLab state to retrieve pull requests with.'
help='The GitLab state to retrieve pull requests with.',
)
parser.parse_args(namespace=self)

def run(self):
"""Send command line args to the main run function.
"""
"""Send command line args to the main run function."""
PullBug.run(
github=self.github,
gitlab=self.gitlab,
Expand All @@ -137,12 +135,23 @@ def run(self):
)


class PullBug():
class PullBug:
@classmethod
def run(cls, github, gitlab, discord, slack, rocketchat, wip, github_owner,
github_state, github_context, gitlab_state, gitlab_scope):
"""Run Pullbug based on the configuration.
"""
def run(
cls,
github,
gitlab,
discord,
slack,
rocketchat,
wip,
github_owner,
github_state,
github_context,
gitlab_state,
gitlab_scope,
):
"""Run Pullbug based on the configuration."""
PullBugLogger._setup_logging(LOGGER)
LOGGER.info('Running Pullbug...')
load_dotenv()
Expand Down
43 changes: 25 additions & 18 deletions pullbug/github_bug.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,23 @@
GITHUB_TOKEN = os.getenv('GITHUB_TOKEN')
GITHUB_HEADERS = {
'Authorization': f'token {GITHUB_TOKEN}',
'Content-Type': 'application/json; charset=utf-8'
'Content-Type': 'application/json; charset=utf-8',
}
LOGGER = logging.getLogger(__name__)


class GithubBug():
class GithubBug:
@classmethod
def run(cls, github_owner=None, github_state='open', github_context='orgs', wip=False,
discord=False, slack=False, rocketchat=False):
def run(
cls,
github_owner=None,
github_state='open',
github_context='orgs',
wip=False,
discord=False,
slack=False,
rocketchat=False,
):
"""Run the logic to get PR's from GitHub and
send that data via message.
"""
Expand All @@ -28,6 +36,7 @@ def run(cls, github_owner=None, github_state='open', github_context='orgs', wip=
if pull_requests == []:
message = 'No pull requests are available from GitHub.'
LOGGER.info(message)

return message

message_preamble = '\n:bug: *The following pull requests on GitHub are still open and need your help!*\n'
Expand All @@ -44,13 +53,11 @@ def run(cls, github_owner=None, github_state='open', github_context='orgs', wip=

@classmethod
def get_repos(cls, github_owner, github_context=''):
"""Get all repos of the github_owner.
"""
"""Get all repos of the github_owner."""
LOGGER.info('Bugging GitHub for repos...')
try:
response = requests.get(
f'https://api.github.com/{github_context}/{github_owner}/repos?per_page=100',
headers=GITHUB_HEADERS
f'https://api.github.com/{github_context}/{github_owner}/repos?per_page=100', headers=GITHUB_HEADERS
)
LOGGER.debug(response.text)
LOGGER.info('GitHub repos retrieved!')
Expand All @@ -59,23 +66,21 @@ def get_repos(cls, github_owner, github_context=''):
LOGGER.error(error)
raise ValueError(error)
except requests.exceptions.RequestException as response_error:
LOGGER.error(
f'Could not retrieve GitHub repos: {response_error}'
)
LOGGER.error(f'Could not retrieve GitHub repos: {response_error}')
raise requests.exceptions.RequestException(response_error)

return response.json()

@classmethod
def get_pull_requests(cls, repos, github_owner, github_state):
"""Grab all pull requests from each repo.
"""
"""Grab all pull requests from each repo."""
LOGGER.info('Bugging GitHub for pull requests...')
pull_requests = []
for repo in repos:
try:
pull_response = requests.get(
f'https://api.github.com/repos/{github_owner}/{repo["name"]}/pulls?state={github_state}&per_page=100', # noqa
headers=GITHUB_HEADERS
headers=GITHUB_HEADERS,
)
if pull_response and pull_response.json():
LOGGER.debug(pull_response.text)
Expand All @@ -85,15 +90,16 @@ def get_pull_requests(cls, repos, github_owner, github_state):
# Repo has no pull requests
continue
except requests.exceptions.RequestException as response_error:
LOGGER.error(
f'Could not retrieve GitHub pull requests for {repo["name"]}: {response_error}'
)
LOGGER.error(f'Could not retrieve GitHub pull requests for {repo["name"]}: {response_error}')
raise requests.exceptions.RequestException(response_error)
except TypeError:
error = f'Could not retrieve GitHub pull requests due to bad parameter: {github_owner} | {github_state}.' # noqa
error = (
f'Could not retrieve GitHub pull requests due to bad parameter: {github_owner} | {github_state}.'
)
LOGGER.error(error)
raise TypeError(error)
LOGGER.info('Pull requests retrieved!')

return pull_requests

@classmethod
Expand All @@ -110,4 +116,5 @@ def iterate_pull_requests(cls, pull_requests, wip, discord, slack, rocketchat):
message, discord_message = Messages.prepare_github_message(pull_request, discord, slack, rocketchat)
message_array.append(message)
discord_message_array.append(discord_message)

return message_array, discord_message_array
19 changes: 10 additions & 9 deletions pullbug/gitlab_bug.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
GITLAB_API_URL = os.getenv('GITLAB_API_URL', 'https://gitlab.com/api/v4')
IGNORE_WIP = os.getenv('IGNORE_WIP')
GITLAB_HEADERS = {
'authorization': f'Bearer {GITLAB_API_KEY}'
'authorization': f'Bearer {GITLAB_API_KEY}',
}
LOGGER = logging.getLogger(__name__)


class GitlabBug():
class GitlabBug:
@classmethod
def run(cls, gitlab_scope='all', gitlab_state='opened', wip=False, discord=False, slack=False, rocketchat=False):
"""Run the logic to get MR's from GitLab and
Expand Down Expand Up @@ -43,25 +43,25 @@ def run(cls, gitlab_scope='all', gitlab_state='opened', wip=False, discord=False

@classmethod
def get_merge_requests(cls, gitlab_scope, gitlab_state):
"""Get all repos of the GITLAB_API_URL.
"""
"""Get all repos of the GITLAB_API_URL."""
LOGGER.info('Bugging GitLab for merge requests...')
try:
response = requests.get(
f"{GITLAB_API_URL}/merge_requests?scope={gitlab_scope}&state={gitlab_state}&per_page=100",
headers=GITLAB_HEADERS
headers=GITLAB_HEADERS,
)
LOGGER.debug(response.text)
LOGGER.info('GitLab merge requests retrieved!')
if 'does not have a valid value' in response.text:
error = f'Could not retrieve GitLab merge requests due to bad parameter: {gitlab_scope} | {gitlab_state}.' # noqa
error = (
f'Could not retrieve GitLab merge requests due to bad parameter: {gitlab_scope} | {gitlab_state}.'
)
LOGGER.error(error)
raise ValueError(error)
except requests.exceptions.RequestException as response_error:
LOGGER.error(
f'Could not retrieve GitLab merge requests: {response_error}'
)
LOGGER.error(f'Could not retrieve GitLab merge requests: {response_error}')
raise requests.exceptions.RequestException(response_error)

return response.json()

@classmethod
Expand All @@ -80,4 +80,5 @@ def iterate_merge_requests(cls, merge_requests, wip, discord, slack, rocketchat)
message, discord_message = Messages.prepare_gitlab_message(merge_request, discord, slack, rocketchat)
message_array.append(message)
discord_message_array.append(discord_message)

return message_array, discord_message_array
15 changes: 5 additions & 10 deletions pullbug/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,24 @@
import logging.handlers
import os

PULLBUG_LOCATION = os.path.expanduser(
os.getenv('PULLBUG_LOCATION', '~/pullbug')
)
PULLBUG_LOCATION = os.path.expanduser(os.getenv('PULLBUG_LOCATION', '~/pullbug'))
LOG_PATH = os.path.join(PULLBUG_LOCATION, 'logs')
LOG_FILE = os.path.join(LOG_PATH, 'pullbug.log')


class PullBugLogger():
class PullBugLogger:
@classmethod
def _setup_logging(cls, logger):
"""Setup project logging (to console and log file).
"""
"""Setup project logging (to console and log file)."""
if not os.path.exists(LOG_PATH):
os.makedirs(LOG_PATH)
logger.setLevel(logging.INFO)
handler = logging.handlers.RotatingFileHandler(
LOG_FILE,
maxBytes=200000,
backupCount=5
)
formatter = logging.Formatter(
"%(asctime)s - %(levelname)s - %(message)s"
backupCount=5,
)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(logging.StreamHandler())
logger.addHandler(handler)
Loading

0 comments on commit 64535c5

Please sign in to comment.