Skip to content

Commit

Permalink
Update IssueCommentEvent.py (#6)
Browse files Browse the repository at this point in the history
* Update IssueCommentEvent.py

* issue comment created test

* style: format code with Black and isort

This commit fixes the style issues introduced in bc2fc32 according to the output
from Black and isort.

Details: #6

* issue comment deleted test

* style: format code with Black and isort

This commit fixes the style issues introduced in 2929832 according to the output
from Black and isort.

Details: #6

* removing commented code

* style: format code with Black and isort

This commit fixes the style issues introduced in 81b1bda according to the output
from Black and isort.

Details: #6

* remove vcr

* style: format code with Black and isort

This commit fixes the style issues introduced in ec24cbc according to the output
from Black and isort.

Details: #6

* some fixes

* style: format code with Black and isort

This commit fixes the style issues introduced in 2db104e according to the output
from Black and isort.

Details: #6

* some fixes

* style: format code with Black and isort

This commit fixes the style issues introduced in c36ec12 according to the output
from Black and isort.

Details: #6

* refactor: autofix issues in 2 files

Resolved issues in the following files with DeepSource Autofix:
1. github_app/Event.py
2. tests/test_lazy_completable_gituhb_objects.py

* style: format code with Black and isort

This commit fixes the style issues introduced in d3fc00b according to the output
from Black and isort.

Details: #6

* some fixes

* fix test

---------

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
  • Loading branch information
heitorpolidoro and deepsource-autofix[bot] committed Dec 17, 2023
1 parent 80d4444 commit c4aa65e
Show file tree
Hide file tree
Showing 24 changed files with 305 additions and 1,153 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ A handler helper to create Github App easily

[![codecov](https://codecov.io/gh/heitorpolidoro/GithubAppHandlerBase/graph/badge.svg?token=JcFgZlsm0y)](https://codecov.io/gh/heitorpolidoro/GithubAppHandlerBase)


[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=heitorpolidoro_GithubAppHandlerBase&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=heitorpolidoro_GithubAppHandlerBase)
[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=heitorpolidoro_GithubAppHandlerBase&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=heitorpolidoro_GithubAppHandlerBase)
[![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=heitorpolidoro_GithubAppHandlerBase&metric=code_smells)](https://sonarcloud.io/summary/new_code?id=heitorpolidoro_GithubAppHandlerBase)
Expand Down
42 changes: 26 additions & 16 deletions github_app/Event.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import os

from github import GithubIntegration
class Event:
"""Event base class
This class represents a generic GitHub webhook event. It provides common
attributes and methods for parsing event data from the request headers and body.
def requester(_):
if Event._requester is None:
integration = GithubIntegration(681139, os.getenv("PRIVATE_KEY"))
Event._requester = integration.get_app()._requester
return Event._requester
Attributes:
name (str): The name of the event (e.g. 'issue').
action (str): The action that triggered the event (e.g. 'opened').
Methods:
parse_event(headers, body): Parses the event from the request.
"""

class Event:
name = None
action = None
_requester = None
installation_id = None

def __init__(self, headers, installation):
self.hook_id = headers["X-Github-Hook-Id"]
Expand All @@ -25,21 +26,30 @@ def __init__(self, headers, installation):
self.hook_installation_target_id = headers[
"X-Github-Hook-Installation-Target-Id"
]
self.installation_id = installation["id"]
Event.installation_id = installation["id"]

@classmethod
def parse_event(cls, headers, body):
"""Returns an Event classe for the event in webhook"""
event = headers["X-Github-Event"]
action = body.pop("action")
event_class = cls.get_webhook_class(event, action)
return event_class(headers=headers, **body)

@classmethod
def get_webhook_class(cls, event, action):
for event_class in cls.__subclasses__():
if event_class.name == event:
for action_class in event_class.__subclasses__():
if action_class.action == action:
return action_class
"""Returns the webhook class for the event and action in webhook"""
event_classes = list(filter(lambda x: x.name == event, cls.__subclasses__()))
if len(event_classes) > 1:
raise ValueError(f"Multiple webhook classes for '{event}'")
if len(event_classes) == 1:
event_class = event_classes[0]
action_classes = list(
filter(lambda x: x.action == action, event_class.__subclasses__())
)
if len(action_classes) > 1:
raise ValueError(f"Multiple webhook classes for '{event}.{action}'")
if len(action_classes) == 1:
return action_classes[0]

raise NotImplementedError(f"No webhook class for '{event}.{action}'")
78 changes: 42 additions & 36 deletions github_app/IssueCommentEvent.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,42 @@
# from github.Issue import Issue
# from github.IssueComment import IssueComment
# from github.NamedUser import NamedUser
# from github.Repository import Repository
#
# from github_app.Event import Event
# from github_app.LazyCompletableGithubObject import LazyCompletableGithubObject
#
#
# class IssueCommentEvent(Event):
# name = "issue_comment"
#
# def __init__(self, comment, issue, repository, sender, **kwargs):
# super().__init__(**kwargs)
# self.issue: Issue = LazyCompletableGithubObject.get_lazy_instance(
# Issue, attributes=issue
# )
# self.issue_comment: IssueComment = (
# LazyCompletableGithubObject.get_lazy_instance(
# IssueComment, attributes=comment
# )
# )
# self.repository: Repository = LazyCompletableGithubObject.get_lazy_instance(
# Repository, attributes=repository
# )
# self.sender: NamedUser = LazyCompletableGithubObject.get_lazy_instance(
# NamedUser, attributes=sender
# )
#
#
# class IssueCommentCreatedEvent(IssueCommentEvent):
# action = "created"
#
#
# class IssueCommentDeletedEvent(IssueCommentEvent):
# action = "deleted"
from github.Issue import Issue
from github.IssueComment import IssueComment
from github.NamedUser import NamedUser
from github.Repository import Repository

from github_app.Event import Event
from github_app.LazyCompletableGithubObject import LazyCompletableGithubObject


class IssueCommentEvent(Event):
"""This class represents a generic issue comment event."""

name = "issue_comment"

def __init__(self, comment, issue, repository, sender, **kwargs):
super().__init__(**kwargs)
self.issue: Issue = LazyCompletableGithubObject.get_lazy_instance(
Issue, attributes=issue
)
self.issue_comment: IssueComment = (
LazyCompletableGithubObject.get_lazy_instance(
IssueComment, attributes=comment
)
)
self.repository: Repository = LazyCompletableGithubObject.get_lazy_instance(
Repository, attributes=repository
)
self.sender: NamedUser = LazyCompletableGithubObject.get_lazy_instance(
NamedUser, attributes=sender
)


class IssueCommentCreatedEvent(IssueCommentEvent):
"""This class represents an event when a comment in an Issue is created."""

action = "created"


class IssueCommentDeletedEvent(IssueCommentEvent):
"""This class represents an event when a comment in an Issue is deleted."""

action = "deleted"
45 changes: 22 additions & 23 deletions github_app/LazyCompletableGithubObject.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,40 @@
import os
from typing import Any
from typing import Any, Union

from github import Consts, GithubIntegration, GithubRetry
from github.Auth import AppAuth, Token
from github.GithubObject import CompletableGithubObject
from github.Requester import Requester

from github_app.Event import Event


class LazyCompletableGithubObject(CompletableGithubObject):
def __init__(self, attributes: dict[str, Any]):
def __init__(
self,
requester: "Requester" = None,
headers: dict[str, Union[str, int]] = None,
attributes: dict[str, Any] = None,
completed: bool = True,
):
self._lazy_initialized = False
# noinspection PyTypeChecker
super().__init__(
requester=None, headers={}, attributes=attributes, completed=True
CompletableGithubObject.__init__(
self,
requester=requester,
headers=headers or {},
attributes=attributes,
completed=completed,
)
self._lazy_initialized = True
self._lazy_refreshed = False
self._lazy_requester = None

@property
def lazy_requester(self):
if self._lazy_requester is None:
token = (
GithubIntegration(auth=AppAuth(681139, os.getenv("PRIVATE_KEY")))
.get_access_token(45043978)
.get_access_token(Event.installation_id)
.token
)
self._lazy_requester = Requester(
Expand All @@ -43,31 +54,19 @@ def __getattribute__(self, item):
if (
not item.startswith("_lazy")
and self._lazy_initialized
and not self._lazy_refreshed
and self._lazy_requester is None
and value is None
):
headers, data = self.lazy_requester.requestJsonAndCheck("GET", self.url)
parent_github_class = next(
filter(
lambda c: c != LazyCompletableGithubObject
and issubclass(c, CompletableGithubObject),
self.__class__.__bases__,
),
None,
)
new_self = parent_github_class(
new_self = self.__class__(
self.lazy_requester, headers, data, completed=True
)
assert (
self.url == new_self.url
), f"{self.url} != {new_self.url}\n{self.lazy_requester.base_url=}"
self.__dict__.update(new_self.__dict__)
self._lazy_refreshed = True
value = super().__getattribute__(item)
return value

@staticmethod
def get_lazy_instance(cls, attributes):
return type(cls.__name__, (cls, LazyCompletableGithubObject), {})(
attributes=attributes
)
if LazyCompletableGithubObject not in cls.__bases__:
cls.__bases__ = tuple([LazyCompletableGithubObject] + list(cls.__bases__))
return cls(attributes=attributes)
23 changes: 22 additions & 1 deletion github_app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,24 @@
from github_app.ReleaseEvent import ReleaseReleasedEvent
from github_app.IssueCommentEvent import (
IssueCommentCreatedEvent,
IssueCommentDeletedEvent,
IssueCommentEvent,
)
from github_app.ReleaseEvent import ReleaseEvent, ReleaseReleasedEvent

__version__ = "0.0.1"

__all__ = [
"IssueCommentEvent",
"IssueCommentCreatedEvent",
"IssueCommentDeletedEvent",
"ReleaseEvent",
"ReleaseReleasedEvent",
"IssueCommentEvent",
"IssueCommentCreatedEvent",
"IssueCommentDeletedEvent",
"ReleaseEvent",
"ReleaseReleasedEvent",
"IssueCommentEvent",
"IssueCommentCreatedEvent",
"IssueCommentDeletedEvent",
]
1 change: 0 additions & 1 deletion requirements.test.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
-r requirements.txt
pytest==7.4.3
pytest-cov==4.1.0
pytest-vcr==1.0.2
cryptography==41.0.7
Loading

0 comments on commit c4aa65e

Please sign in to comment.