__main__.py 7.57 KB
Newer Older
Simon Chabot's avatar
Simon Chabot committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/env python3
# coding: utf-8
#
# copyright 2020-2020 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of assignbot.
#
# Assignbot is free software: you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
# any later version.
#
# Assignbot is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with assignbot.  If not, see <http://www.gnu.org/licenses/>.

import os
from argparse import ArgumentParser
24
from random import choice, shuffle
Simon Chabot's avatar
Simon Chabot committed
25
from datetime import datetime, timedelta
26
import logging
Simon Chabot's avatar
Simon Chabot committed
27
28
29
30
31
32
33
34
35
36
37
38
39

import yaml
import pandas as pd
from gitlab import Gitlab
from gitlab.exceptions import GitlabHttpError

from assignbot.s3_utils import download_file, upload_file

TO_REVIEW_LABEL = "To Review"
REVIEW_ACCESS_LEVEL = 30  # developper
CLIENT_PROJECT_TAG = "client-project"

STATE_FILENAME = "auto_assigned_reviewers.csv"
40
logging.basicConfig(level=os.getenv("AB_LOG_THRESHOLD", "INFO").upper())
Simon Chabot's avatar
Simon Chabot committed
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


class ReviewAssigner:
    def __init__(self, gitlab_url, gitlab_token, users_preferences_filepath):
        self.cnx = Gitlab(gitlab_url, gitlab_token)
        self.user_preferences = self._load_users_preferences(users_preferences_filepath)
        self.review_states = self._load_review_states()

    def _load_users_preferences(self, users_preferences_filepath):
        with open(users_preferences_filepath) as fobj:
            state = yaml.load(fobj, Loader=yaml.Loader)
        return state or {}

    def _load_review_states(self):
        try:
            return pd.read_csv(
                download_file(STATE_FILENAME),
                index_col=0,
                parse_dates=[
                    2,
                ],
            )
        except Exception:  # XXX
            df = pd.DataFrame([], columns=["username", "datetime", "mr_url"])
            df.datetime = pd.to_datetime(df.datetime)
            return df

    def save_review_states(self):
        upload_file(STATE_FILENAME, self.review_states.to_csv().encode("utf-8"))

    def _get_user_nb_auto_review_since(self, username, since):
        oldest_date = datetime.now() - since
        user_reviews = self.review_states.query(f"username == '{username}'")
        return sum(user_reviews.datetime > oldest_date)

    def get_user_nb_auto_review_this_day(self, username):
        return self._get_user_nb_auto_review_since(username, timedelta(hours=20))

    def get_user_nb_auto_review_this_week(self, username):
        return self._get_user_nb_auto_review_since(username, timedelta(days=6))

    def user_has_already_been_assigned_to_this_mr(self, user, merge_request):
        return self.review_states.query(
            f"username == '{user.username}' and " f"mr_url == '{merge_request.web_url}'"
        ).empty

    def user_can_review(self, user, project, merge_request):
        try:
            user_preferences = self.user_preferences[user.username]
        except KeyError:
            # the user did not specify any preferences
            # let's assume that s·he is not volunteer
            return False

        max_auto_review_per_week = user_preferences["max_auto_review_per_week"]
        max_auto_review_per_day = user_preferences["max_auto_review_per_day"]

        auto_review_this_day = self.get_user_nb_auto_review_this_day(user.username)
        auto_review_this_week = self.get_user_nb_auto_review_this_week(user.username)

        return (
            user.access_level >= REVIEW_ACCESS_LEVEL
            and user.state == "active"
            and auto_review_this_day < max_auto_review_per_day
            and auto_review_this_week < max_auto_review_per_week
            and merge_request.author["id"] != user.id
            and self.user_has_already_been_assigned_to_this_mr(user, merge_request)
        )

    def all_possible_reviewers(self, merge_request):
        project = self.cnx.projects.get(merge_request.project_id)
        members_with_review_access = (
            member
            for member in project.members.all(all=True, as_list=False)
            if self.user_can_review(member, project, merge_request)
        )

        return members_with_review_access

    def a_possible_reviewer(self, merge_request):
        return choice(list(self.all_possible_reviewers(merge_request)))

    def assign_reviewer(self, merge_request, user):
        try:
            self.cnx.http_put(
                f"/projects/{merge_request.project_id}/merge_requests/{merge_request.iid}",
                query_data={"assignee_id": user.id},
            )
        except GitlabHttpError:
130
131
132
133
            logging.error(
                "ERROR: no permission to assign a reviewer to %s (%s)",
                merge_request.title,
                merge_request.web_url,
134
            )
Simon Chabot's avatar
Simon Chabot committed
135
136
137
138
139
140
141
            return

        self.review_states.loc[len(self.review_states)] = (
            user.username,
            datetime.now(),
            merge_request.web_url,
        )
142
143
144
145
146
        logging.info(
            "%s has been assigned to %s",
            user.name,
            merge_request.title,
        )
Simon Chabot's avatar
Simon Chabot committed
147
148

    def all_reviews_to_do(self):
149
        merge_requests = self.cnx.mergerequests.list(
Simon Chabot's avatar
Simon Chabot committed
150
151
152
153
154
155
156
157
            labels=TO_REVIEW_LABEL,
            state="opened",
            wip="no",
            scope="all",
            assignee_id="None",
            all=True,
        )

158
159
160
161
162
163
164
165
166
        merge_requests.extend(
            self.cnx.mergerequests.list(
                labels="None",
                state="opened",
                wip="no",
                scope="all",
                assignee_id="None",
                all=True,
            )
Simon Chabot's avatar
Simon Chabot committed
167
168
        )

169
170
171
        shuffle(merge_requests)

        for merge_request in merge_requests:
172
173
174
175
176
177
            if merge_request.work_in_progress:
                # double check that the MR is not WIP.
                # it seems that filtering in the search parameters is not enough
                # XXX is it a Gitlab bug ?
                continue

Simon Chabot's avatar
Simon Chabot committed
178
179
180
181
            project = self.cnx.projects.get(merge_request.project_id)
            if CLIENT_PROJECT_TAG in project.tag_list:
                # it's a client project. Let's assume that someone will take
                # care of this MR.
182
183
184
                logging.info(
                    "%s would need review, but it's a client project",
                    merge_request.web_url
Simon Chabot's avatar
Simon Chabot committed
185
186
187
188
189
190
191
192
193
                )
                continue
            yield merge_request

    def assign_reviews(self):
        for mr in self.all_reviews_to_do():
            try:
                reviewer = self.a_possible_reviewer(mr)
            except IndexError:
194
195
196
197
198
                logging.warning(
                    "no reviewer available for %s (%s).",
                    mr.title,
                    mr.web_url,
                )
Simon Chabot's avatar
Simon Chabot committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
                continue
            self.assign_reviewer(mr, reviewer)


def main():
    parser = ArgumentParser()
    parser.add_argument("users_preferences_filepath")
    parser.add_argument("--gitlab-url", type=str, default=os.getenv("GITLAB_URL"))
    parser.add_argument("--gitlab-token", type=str, default=os.getenv("GITLAB_TOKEN"))
    args = parser.parse_args()

    assigner = ReviewAssigner(
        args.gitlab_url, args.gitlab_token, args.users_preferences_filepath
    )
    assigner.assign_reviews()
    assigner.save_review_states()


if __name__ == "__main__":
    main()