blob: 4cc48a9f0a251a32f1b05c2baa48092c3f910734 [file] [log] [blame]
Edward Lesmes91bb7502020-11-06 00:50:24 +00001# Copyright (c) 2020 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Edward Lesmes295dd182020-11-24 23:07:26 +00005import itertools
Edward Lesmesd4e6fb62020-11-17 00:17:58 +00006import os
Edward Lesmes64e80762020-11-24 19:46:45 +00007import random
Edward Lesmesd4e6fb62020-11-17 00:17:58 +00008
Edward Lesmes829ce022020-11-18 18:30:31 +00009import gerrit_util
Edward Lesmes64e80762020-11-24 19:46:45 +000010import owners as owners_db
Edward Lesmesd4e6fb62020-11-17 00:17:58 +000011import scm
12
13
14APPROVED = 'APPROVED'
15PENDING = 'PENDING'
16INSUFFICIENT_REVIEWERS = 'INSUFFICIENT_REVIEWERS'
Edward Lesmesb4f42262020-11-10 23:41:35 +000017
Edward Lesmes91bb7502020-11-06 00:50:24 +000018
Edward Lesmes295dd182020-11-24 23:07:26 +000019def _owner_combinations(owners, num_owners):
20 """Iterate owners combinations by decrasing score.
21
22 The score of an owner is its position on the owners list.
23 The score of a set of owners is the maximum score of all owners on the set.
24
25 Returns all combinations of up to `num_owners` sorted by decreasing score:
26 _owner_combinations(['0', '1', '2', '3'], 2) == [
27 # score 1
28 ('1', '0'),
29 # score 2
30 ('2', '0'),
31 ('2', '1'),
32 # score 3
33 ('3', '0'),
34 ('3', '1'),
35 ('3', '2'),
36 ]
37 """
38 return reversed(list(itertools.combinations(reversed(owners), num_owners)))
39
40
41
Edward Lesmesb4721682020-11-19 22:59:57 +000042class InvalidOwnersConfig(Exception):
43 pass
44
45
Edward Lesmes91bb7502020-11-06 00:50:24 +000046class OwnersClient(object):
47 """Interact with OWNERS files in a repository.
48
49 This class allows you to interact with OWNERS files in a repository both the
50 Gerrit Code-Owners plugin REST API, and the owners database implemented by
51 Depot Tools in owners.py:
52
53 - List all the owners for a change.
54 - Check if a change has been approved.
55 - Check if the OWNERS configuration in a change is valid.
56
57 All code should use this class to interact with OWNERS files instead of the
58 owners database in owners.py
59 """
60 def __init__(self, host):
61 self._host = host
62
63 def ListOwnersForFile(self, project, branch, path):
Edward Lesmes64e80762020-11-24 19:46:45 +000064 """List all owners for a file.
65
66 The returned list is sorted so that better owners appear first.
67 """
Edward Lesmes91bb7502020-11-06 00:50:24 +000068 raise Exception('Not implemented')
69
Edward Lesmesd4e6fb62020-11-17 00:17:58 +000070 def GetChangeApprovalStatus(self, change_id):
Edward Lesmesb4721682020-11-19 22:59:57 +000071 """Check the approval status for the latest revision_id in a change.
Edward Lesmesd4e6fb62020-11-17 00:17:58 +000072
73 Returns a map of path to approval status, where the status can be one of:
74 - APPROVED: An owner of the file has reviewed the change.
75 - PENDING: An owner of the file has been added as a reviewer, but no owner
76 has approved.
77 - INSUFFICIENT_REVIEWERS: No owner of the file has been added as a reviewer.
78 """
Edward Lesmes91bb7502020-11-06 00:50:24 +000079 raise Exception('Not implemented')
80
Edward Lesmesb4721682020-11-19 22:59:57 +000081 def ValidateOwnersConfig(self, change_id):
Edward Lesmes91bb7502020-11-06 00:50:24 +000082 """Check if the owners configuration in a change is valid."""
83 raise Exception('Not implemented')
Edward Lesmesb4f42262020-11-10 23:41:35 +000084
Edward Lesmese7d18622020-11-19 23:46:17 +000085 def GetFilesApprovalStatus(
86 self, project, branch, paths, approvers, reviewers):
87 """Check the approval status for the given paths.
88
89 Utility method to check for approval status when a change has not yet been
90 created, given reviewers and approvers.
91
92 See GetChangeApprovalStatus for description of the returned value.
93 """
94 approvers = set(approvers)
95 reviewers = set(reviewers)
96 status = {}
97 for path in paths:
98 path_owners = set(self.ListOwnersForFile(project, branch, path))
99 if path_owners.intersection(approvers):
100 status[path] = APPROVED
101 elif path_owners.intersection(reviewers):
102 status[path] = PENDING
103 else:
104 status[path] = INSUFFICIENT_REVIEWERS
105 return status
106
Edward Lesmes295dd182020-11-24 23:07:26 +0000107 def SuggestOwners(self, project, branch, paths):
108 """Suggest a set of owners for the given paths."""
109 paths_by_owner = {}
110 score_by_owner = {}
111 for path in paths:
112 owners = self.ListOwnersForFile(project, branch, path)
113 for i, owner in enumerate(owners):
114 paths_by_owner.setdefault(owner, set()).add(path)
115 # Gerrit API lists owners of a path sorted by an internal score, so
116 # owners that appear first should be prefered.
117 # We define the score of an owner to be their minimum position in all
118 # paths.
119 score_by_owner[owner] = min(i, score_by_owner.get(owner, i))
120
121 # Sort owners by their score.
122 owners = sorted(score_by_owner, key=lambda o: score_by_owner[o])
123
124 # Select the minimum number of owners that can approve all paths.
125 # We start at 2 to avoid sending all changes that require multiple reviewers
126 # to top-level owners.
127 num_owners = 2
128 while True:
129 # Iterate all combinations of `num_owners` by decreasing score, and select
130 # the first one that covers all paths.
131 for selected in _owner_combinations(owners, num_owners):
132 covered = set.union(*(paths_by_owner[o] for o in selected))
133 if len(covered) == len(paths):
134 return selected
135 num_owners += 1
136
Edward Lesmesb4f42262020-11-10 23:41:35 +0000137
138class DepotToolsClient(OwnersClient):
139 """Implement OwnersClient using owners.py Database."""
Edward Lesmeseeca9c62020-11-20 00:00:17 +0000140 def __init__(self, host, root, branch, fopen=open, os_path=os.path):
Edward Lesmesb4f42262020-11-10 23:41:35 +0000141 super(DepotToolsClient, self).__init__(host)
142 self._root = root
Edward Lesmesb4721682020-11-19 22:59:57 +0000143 self._fopen = fopen
144 self._os_path = os_path
Edward Lesmesd4e6fb62020-11-17 00:17:58 +0000145 self._branch = branch
Edward Lesmes64e80762020-11-24 19:46:45 +0000146 self._db = owners_db.Database(root, fopen, os_path)
Edward Lesmes829ce022020-11-18 18:30:31 +0000147 self._db.override_files = self._GetOriginalOwnersFiles()
148
149 def _GetOriginalOwnersFiles(self):
150 return {
Edward Lesmesd4e6fb62020-11-17 00:17:58 +0000151 f: scm.GIT.GetOldContents(self._root, f, self._branch)
152 for _, f in scm.GIT.CaptureStatus(self._root, self._branch)
153 if os.path.basename(f) == 'OWNERS'
Edward Lesmes829ce022020-11-18 18:30:31 +0000154 }
Edward Lesmesb4f42262020-11-10 23:41:35 +0000155
156 def ListOwnersForFile(self, _project, _branch, path):
Edward Lesmes64e80762020-11-24 19:46:45 +0000157 # all_possible_owners returns a dict {owner: [(path, distance)]}. We want to
158 # return a list of owners sorted by increasing distance.
159 distance_by_owner = self._db.all_possible_owners([path], None)
160 # We add a small random number to the distance, so that owners at the same
161 # distance are returned in random order to avoid overloading those who would
162 # appear first.
163 return sorted(
164 distance_by_owner,
165 key=lambda o: distance_by_owner[o][0][1] + random.random())
Edward Lesmesd4e6fb62020-11-17 00:17:58 +0000166
167 def GetChangeApprovalStatus(self, change_id):
168 data = gerrit_util.GetChange(
169 self._host, change_id,
170 ['DETAILED_ACCOUNTS', 'DETAILED_LABELS', 'CURRENT_FILES',
171 'CURRENT_REVISION'])
172
173 reviewers = [r['email'] for r in data['reviewers']['REVIEWER']]
174
175 # Get reviewers that have approved this change
Edward Lesmes829ce022020-11-18 18:30:31 +0000176 label = data['labels']['Code-Review']
Edward Lesmesd4e6fb62020-11-17 00:17:58 +0000177 max_value = max(int(v) for v in label['values'])
178 approvers = [v['email'] for v in label['all'] if v['value'] == max_value]
179
180 files = data['revisions'][data['current_revision']]['files']
Edward Lesmese7d18622020-11-19 23:46:17 +0000181 return self.GetFilesApprovalStatus(None, None, files, approvers, reviewers)
Edward Lesmesb4721682020-11-19 22:59:57 +0000182
183 def ValidateOwnersConfig(self, change_id):
184 data = gerrit_util.GetChange(
185 self._host, change_id,
186 ['DETAILED_ACCOUNTS', 'DETAILED_LABELS', 'CURRENT_FILES',
187 'CURRENT_REVISION'])
188
189 files = data['revisions'][data['current_revision']]['files']
190
Edward Lesmes64e80762020-11-24 19:46:45 +0000191 db = owners_db.Database(self._root, self._fopen, self._os_path)
Edward Lesmesb4721682020-11-19 22:59:57 +0000192 try:
193 db.load_data_needed_for(
194 [f for f in files if os.path.basename(f) == 'OWNERS'])
195 except Exception as e:
196 raise InvalidOwnersConfig('Error parsing OWNERS files:\n%s' % e)