-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathnotifier.py
93 lines (73 loc) · 2.81 KB
/
notifier.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import logging
from dataclasses import dataclass
from enum import Enum
from typing import Literal
from asgiref.sync import async_to_sync
from shared.torngit.base import TorngitBaseAdapter
from shared.torngit.exceptions import TorngitClientError
from database.models import Commit
from services.repository import (
EnrichedPull,
fetch_and_update_pull_request_information_from_commit,
get_repo_provider_service,
)
from services.yaml import UserYaml
log = logging.getLogger(__name__)
class NotifierResult(Enum):
COMMENT_POSTED = "comment_posted"
TORNGIT_ERROR = "torngit_error"
NO_PULL = "no_pull"
@dataclass
class BaseNotifier:
commit: Commit
commit_yaml: UserYaml | None
_pull: EnrichedPull | None | Literal[False] = False
_repo_service: TorngitBaseAdapter | None = None
def get_pull(self, do_log=True) -> EnrichedPull | None:
repo_service = self.get_repo_service()
if self._pull is False:
self._pull = async_to_sync(
fetch_and_update_pull_request_information_from_commit
)(repo_service, self.commit, self.commit_yaml)
if self._pull is None and do_log:
log.info(
"Not notifying since there is no pull request associated with this commit",
extra=dict(commitid=self.commit.commitid),
)
return self._pull
def get_repo_service(self) -> TorngitBaseAdapter:
if self._repo_service is None:
self._repo_service = get_repo_provider_service(self.commit.repository)
return self._repo_service
def send_to_provider(self, pull: EnrichedPull, message: str) -> bool:
repo_service = self.get_repo_service()
assert repo_service
pullid = pull.database_pull.pullid
try:
comment_id = pull.database_pull.commentid
if comment_id:
async_to_sync(repo_service.edit_comment)(pullid, comment_id, message)
else:
res = async_to_sync(repo_service.post_comment)(pullid, message)
pull.database_pull.commentid = res["id"]
return True
except TorngitClientError:
log.error(
"Error creating/updating PR comment",
extra=dict(
commitid=self.commit.commitid,
pullid=pullid,
),
)
return False
def build_message(self) -> str:
raise NotImplementedError
def notify(self) -> NotifierResult:
pull = self.get_pull()
if pull is None:
return NotifierResult.NO_PULL
message = self.build_message()
sent_to_provider = self.send_to_provider(pull, message)
if sent_to_provider == False:
return NotifierResult.TORNGIT_ERROR
return NotifierResult.COMMENT_POSTED