aboutsummaryrefslogtreecommitdiffstats
path: root/python/fatcat_tools/reviewers/review_common.py
blob: d599b31f8aa1a926eb95d92c2d9b40dd84dd7a78 (plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import datetime
import subprocess
import time
from collections import Counter
from typing import Any, List, Optional

import fatcat_openapi_client
from fatcat_openapi_client import ApiClient, Editgroup, EditgroupAnnotation, EntityEdit

"""
checks should return:
- status: pass, fail, warning, skipped
- description

annotation extra should include:
- useragent
- git_rev
- submit timestamp

can apply to individual entity revs, or to entire editgroup

reviewbot takes an editgroup (object) and returns an annotation (object)
"""


class CheckResult:
    status = None
    description = None
    ident = None
    rev = None
    check_type = None

    def __init__(
        self,
        status: str,
        check_type: Optional[str] = None,
        description: Optional[str] = None,
        **kwargs
    ):
        self.status = status
        self.check_type = check_type
        self.description = description
        self.ident = kwargs.get("ident")
        self.rev = kwargs.get("rev")

    def __repr__(self):
        return str(self.__dict__)


class EditCheck:

    scope: List[Any] = []
    name: Optional[str] = None

    def check_editgroup(self, editgroup: fatcat_openapi_client.Editgroup) -> CheckResult:
        raise NotImplementedError

    def check_container(
        self,
        edit: EntityEdit,
        entity: fatcat_openapi_client.ContainerEntity,
    ) -> CheckResult:
        raise NotImplementedError

    def check_creator(
        self,
        edit: EntityEdit,
        entity: fatcat_openapi_client.CreatorEntity,
    ) -> CheckResult:
        raise NotImplementedError

    def check_file(
        self,
        edit: EntityEdit,
        entity: fatcat_openapi_client.FileEntity,
    ) -> CheckResult:
        raise NotImplementedError

    def check_fileset(
        self,
        edit: EntityEdit,
        entity: fatcat_openapi_client.FilesetEntity,
    ) -> CheckResult:
        raise NotImplementedError

    def check_webcapture(
        self,
        edit: EntityEdit,
        entity: fatcat_openapi_client.WebcaptureEntity,
    ) -> CheckResult:
        raise NotImplementedError

    def check_release(
        self,
        edit: EntityEdit,
        entity: fatcat_openapi_client.ReleaseEntity,
    ) -> CheckResult:
        raise NotImplementedError

    def check_work(
        self,
        edit: EntityEdit,
        work: fatcat_openapi_client.WorkEntity,
    ) -> CheckResult:
        raise NotImplementedError


class ReviewBot:
    def __init__(self, api: fatcat_openapi_client.ApiClient, verbose: bool = False, **kwargs):

        self.api = api
        self.checks: List[EditCheck] = []
        self.verbose = verbose
        self.extra = kwargs.get("extra", dict())
        self.extra["git_rev"] = self.extra.get(
            "git_rev", subprocess.check_output(["git", "describe", "--always"]).strip()
        ).decode("utf-8")
        self.extra["agent"] = self.extra.get("agent", "fatcat_tools.ReviewBot")
        self.poll_interval = kwargs.get("poll_interval", 10.0)

    def run_single(self, editgroup_id: str, annotate: bool = True) -> CheckResult:
        eg = self.api.get_editgroup(editgroup_id)
        annotation = self.review_editgroup(eg)
        if annotate:
            self.api.create_editgroup_annotation(eg.editgroup_id, annotation)
        return annotation

    def run(self, start_since: Optional[datetime.datetime] = None) -> None:
        if start_since is None:
            since = datetime.datetime.utcnow()
        else:
            since = start_since
        while True:
            # XXX: better isoformat conversion?
            eg_list = self.api.get_editgroups_reviewable(
                since=since.isoformat()[:19] + "Z", limit=100
            )
            if not eg_list:
                print("Sleeping {} seconds...".format(self.poll_interval))
                time.sleep(self.poll_interval)
                continue
            for eg in eg_list:
                # TODO: fetch annotations to ensure we haven't already annotated
                annotation = self.review_editgroup(eg)
                print(
                    "Reviewed {} disposition:{}".format(
                        eg.editgroup_id, annotation.extra["disposition"]
                    )
                )
                self.api.create_editgroup_annotation(eg.editgroup_id, annotation)
                since = eg.submitted
            # to prevent busy loops (TODO: needs review/rethink; multiple
            # editgroups in the same second)
            since = since + datetime.timedelta(seconds=1)

    def review_editgroup(self, editgroup: Editgroup) -> EditgroupAnnotation:
        results = self.run_checks(editgroup)
        result_counts = self.result_counts(results)
        disposition = self.disposition(results)
        if disposition == "accept":
            comment = "This editgroup looks great! All checks passed."
        elif disposition == "revise":
            comment = "Some issues were found, and changes or close review are recommended before accepting."
        elif disposition == "reject":
            comment = "Serious issues were found; this editgroup should **not** be accepted."
        else:
            raise ValueError

        for (status, title) in (("fail", "Failed check"), ("warning", "Warnings")):
            if result_counts[status] > 0:
                comment += "\n\n### {} ({}):\n".format(status, result_counts[status])
            for result in results:
                if result.status == status and result.check_type == "editgroup":
                    comment += "\n- {description}".format(description=result.description)
                if result.status == status and result.check_type != "editgroup":
                    comment += "\n- {check_type} [{rev}](/{entity_type}/rev/{rev}): {description}".format(
                        check_type=result.check_type,
                        rev=result.rev,
                        entity_type=result.check_type,
                        description=result.description,
                    )

        extra = self.extra.copy()
        extra.update(
            {
                "disposition": disposition,
                "submit_timestamp": editgroup.submitted.isoformat(),
                "checks": [check.name for check in self.checks],
                "result_counts": dict(result_counts),
            }
        )
        annotation = fatcat_openapi_client.EditgroupAnnotation(
            comment_markdown=comment,
            editgroup_id=editgroup.editgroup_id,
            extra=extra,
        )
        return annotation

    def result_counts(self, results: List[CheckResult]) -> Counter:
        counts: Counter = Counter()
        for result in results:
            counts["total"] += 1
            counts[result.status] += 1
        return counts

    def disposition(self, results: List[CheckResult]) -> str:
        """
        Returns one of: accept, revise, reject
        """
        raise NotImplementedError

    def run_checks(self, editgroup: Editgroup) -> List[CheckResult]:

        results = []

        # any full-editgroup checks
        for check in self.checks:
            if "editgroup" in check.scope:
                result = check.check_editgroup(editgroup)
                if self.verbose:
                    print(result)
                results.append(result)

        if not editgroup.edits:
            entity_edits = {}
        else:
            entity_edits = {
                "container": editgroup.edits.containers,
                "creator": editgroup.edits.creators,
                "file": editgroup.edits.files,
                "fileset": editgroup.edits.filesets,
                "webcapture": editgroup.edits.webcaptures,
                "release": editgroup.edits.releases,
                "work": editgroup.edits.works,
            }

        # entity-specific checks
        for entity_type, edits in entity_edits.items():
            for edit in edits:
                entity = None
                for check in self.checks:
                    if entity_type in check.scope:
                        # hack-y python munging
                        get_method = getattr(self.api, "get_{}_rev".format(entity_type))
                        check_method = getattr(check, "check_{}".format(entity_type))
                        entity = get_method(self.api, edit.rev)
                        result = check_method(check, edit, entity)
                        result.rev = edit.rev
                        result.ident = edit.ident
                        if self.verbose:
                            print(result)
                        results.append(result)

        return results


class DummyCheck(EditCheck):

    scope = ["editgroup", "work"]
    name = "DummyCheck"

    def check_editgroup(self, editgroup: Editgroup) -> CheckResult:
        return CheckResult(
            "pass",
            "editgroup",
            "every edit is precious, thanks [editor {editor_id}](/editor/{editor_id})!".format(
                editor_id=editgroup.editor_id
            ),
        )

    def check_work(
        self,
        edit: EntityEdit,
        work: fatcat_openapi_client.WorkEntity,
    ) -> CheckResult:
        return CheckResult("pass", "work", "this work edit is beautiful")


class DummyReviewBot(ReviewBot):
    """
    This bot reviews everything and always passes.
    """

    def __init__(self, api: ApiClient, **kwargs):
        super().__init__(api, **kwargs)
        self.checks = [DummyCheck()]

    def disposition(self, results: List[CheckResult]) -> str:
        return "accept"