Skip to content

Commit

Permalink
get_issue
Browse files Browse the repository at this point in the history
  • Loading branch information
ricardobranco777 committed Sep 8, 2023
1 parent 83af7f7 commit 12b19fc
Showing 1 changed file with 54 additions and 41 deletions.
95 changes: 54 additions & 41 deletions bugme.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import json
import sys
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urlparse
from urllib.parse import urlparse, parse_qs

from dateutil import parser
from pytz import utc
Expand All @@ -33,14 +33,50 @@ def dateit(date, time_format: str = "%a %b %d %H:%M:%S %Z %Y") -> str:
return date.astimezone().strftime(time_format)


class RepoIssue: # pylint: disable=too-few-public-methods
class Issue: # pylint: disable=too-few-public-methods
"""
Simple class to hold GitHub issue
Class to hold issue
"""

def __init__(self, repo: str, issue: str):
def __init__(self, host: str, repo: str = "", id: str = ""):
self.host = host
self.repo = repo
self.number = int(issue)
self.id = int(id)


def get_issue(string: str) -> Issue:
"""
Get URL from string
"""
if "#" not in string:
string = string if string.startswith("https://") else f"https://{string}"
url = urlparse(string)
if url.hostname.startswith("git"):
return Issue(
host=url.hostname,
repo=os.path.dirname(os.path.dirname(url.path.replace("/-/", "/"))).lstrip("/"),
id=int(os.path.basename(url.path)),
)
if url.hostname.startswith("bugzilla"):
return Issue(
host=url.hostname,
id=int(parse_qs(url.query)["id"][0]),
)
if url.hostname == "progress.opensuse.org":
return Issue(
host=url.hostname,
id=int(os.path.basename(url.path)),
)
return None
if string.startswith(("bnc#", "boo#", "bsc#")):
return Issue(host="bugzilla.suse.de", id=int(string.split("#", 1)[1]))
if string.startswith("poo#"):
return Issue(host="progress.opensuse.org", id=int(string.split("#", 1)[1]))
if string.startswith("gh#"):
return Issue(host="github.com", *string.split("#", 2)[1:])
if string.startswith("gl#"):
return Issue(host="gitlab.suse.de", *string.split("#", 2)[1:])
return None


class Item: # pylint: disable=too-few-public-methods
Expand All @@ -61,14 +97,11 @@ class Singleton(type):
def __init__(cls, name, bases, attrs):
super().__init__(name, bases, attrs)
cls._singleton_instances = {}
cls.__singleton_lock = threading.RLock()

def __call__(cls, *args, **kwargs):
key = (cls, args, frozenset(kwargs.items()))
if key not in cls._singleton_instances:
with cls.__singleton_lock:
if key not in cls._singleton_instances:
cls._singleton_instances[key] = super().__call__(*args, **kwargs)
cls._singleton_instances[key] = super().__call__(*args, **kwargs)
return cls._singleton_instances[key]


Expand Down Expand Up @@ -166,12 +199,12 @@ def __init__(self, creds: dict):
auth = Auth.Token(**creds)
self.client = Github(auth=auth)

def get_item(self, issue: RepoIssue) -> Item:
def get_item(self, issue: Issue) -> Item:
"""
Get Github issue
"""
try:
info = self.client.get_repo(issue.repo, lazy=True).get_issue(issue.number)
info = self.client.get_repo(issue.repo, lazy=True).get_issue(issue.id)
except GithubException as exc:
logging.error("Github: get_issue(%d): %s", issue, exc)
return None
Expand All @@ -183,7 +216,7 @@ def _to_item(self, info, issue) -> Item:
status=info.state,
title=info.title,
updated_at=info.last_modified,
url=f"{self.url}/{issue.repo}/issues/{issue.number}",
url=f"{self.url}/{issue.repo}/issues/{issue.id}",
extra=info.__dict__["_rawData"],
)

Expand All @@ -207,14 +240,12 @@ def __exit__(self, exc_type, exc_value, traceback):
pass
super().__exit__(exc_type, exc_value, traceback)

def get_item(self, issue: RepoIssue) -> Item:
def get_item(self, issue: Issue) -> Item:
"""
Get Gitlab issue
"""
try:
info = self.client.projects.get(issue.repo, lazy=True).issues.get(
issue.number
)
info = self.client.projects.get(issue.repo, lazy=True).issues.get(issue.id)
except GitlabError as exc:
logging.error("Gitlab: %s: get_issue(%d): %s", self.url, issue, exc)
return None
Expand All @@ -226,7 +257,7 @@ def _to_item(self, info, issue) -> Item:
status=info.state,
title=info.title,
updated_at=info.updated_at,
url=f"{self.url}/{issue.repo}/-/issues/{issue.number}",
url=f"{self.url}/{issue.repo}/-/issues/{issue.id}",
extra=info.asdict(),
)

Expand Down Expand Up @@ -266,35 +297,17 @@ def main():
"""
Main function
"""
bsc_list = []
poo_list = []
gh_list = []
gl_list = []
gsd_list = []

with open(CREDENTIALS_FILE, encoding="utf-8") as file:
if os.fstat(file.fileno()).st_mode & 0o77:
sys.exit(f"ERROR: {CREDENTIALS_FILE} has insecure permissions")
creds = json.load(file)

for arg in sys.argv[1:]:
if arg.startswith(("bnc#", "boo#", "bsc#")):
my_bugzilla = MyBugzilla("https://bugzilla.suse.com", creds["bugzilla.suse.com"])
bsc_list.append(int(arg.split("#", 1)[1]))
elif arg.startswith("poo#"):
my_redmine = MyRedmine("https://progress.opensuse.org", creds["progress.opensuse.org"])
poo_list.append(int(arg.split("#", 1)[1]))
elif arg.startswith("gh#"):
my_github = MyGithub(creds["github.com"])
gh_list.append(RepoIssue(*arg.split("#", 2)[1:]))
elif arg.startswith("gl#"):
my_gitlab = MyGitlab(creds["gitlab.com"])
gl_list.append(RepoIssue(*arg.split("#", 2)[1:]))
elif arg.startswith("gsd#"):
my_gitlab_suse_de = MyGitlab(creds["gitlab.suse.de"])
gsd_list.append(RepoIssue(*arg.split("#", 2)[1:]))
else:
print(f"Unsupported {arg}", file=sys.stderr)
_ = creds
# my_bugzilla = MyBugzilla("https://bugzilla.suse.com", creds["bugzilla.suse.com"])
# my_redmine = MyRedmine("https://progress.opensuse.org", creds["progress.opensuse.org"])
# my_github = MyGithub(creds["github.com"])
# my_gitlab = MyGitlab(creds["gitlab.com"])
# my_gitlab_suse_de = MyGitlab("https://gitlab.suse.de", creds["gitlab.suse.de"])


if __name__ == "__main__":
Expand Down

0 comments on commit 12b19fc

Please sign in to comment.