blob: 01b3f181c4422fac8ad6a847a26e3c0dd4bd6487 [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
Edward Lesmesb4721682020-11-19 22:59:57 +000041class InvalidOwnersConfig(Exception):
42 pass
43
44
Edward Lesmes91bb7502020-11-06 00:50:24 +000045class OwnersClient(object):
46 """Interact with OWNERS files in a repository.
47
48 This class allows you to interact with OWNERS files in a repository both the
49 Gerrit Code-Owners plugin REST API, and the owners database implemented by
50 Depot Tools in owners.py:
51
52 - List all the owners for a change.
53 - Check if a change has been approved.
54 - Check if the OWNERS configuration in a change is valid.
55
56 All code should use this class to interact with OWNERS files instead of the
57 owners database in owners.py
58 """
59 def __init__(self, host):
60 self._host = host
61
62 def ListOwnersForFile(self, project, branch, path):
Edward Lesmes64e80762020-11-24 19:46:45 +000063 """List all owners for a file.
64
65 The returned list is sorted so that better owners appear first.
66 """
Edward Lesmes91bb7502020-11-06 00:50:24 +000067 raise Exception('Not implemented')
68
Edward Lesmesd4e6fb62020-11-17 00:17:58 +000069 def GetChangeApprovalStatus(self, change_id):
Edward Lesmesb4721682020-11-19 22:59:57 +000070 """Check the approval status for the latest revision_id in a change.
Edward Lesmesd4e6fb62020-11-17 00:17:58 +000071
72 Returns a map of path to approval status, where the status can be one of:
73 - APPROVED: An owner of the file has reviewed the change.
74 - PENDING: An owner of the file has been added as a reviewer, but no owner
75 has approved.
76 - INSUFFICIENT_REVIEWERS: No owner of the file has been added as a reviewer.
77 """
Edward Lesmes91bb7502020-11-06 00:50:24 +000078 raise Exception('Not implemented')
79
Edward Lesmesb4721682020-11-19 22:59:57 +000080 def ValidateOwnersConfig(self, change_id):
Edward Lesmes91bb7502020-11-06 00:50:24 +000081 """Check if the owners configuration in a change is valid."""
82 raise Exception('Not implemented')
Edward Lesmesb4f42262020-11-10 23:41:35 +000083
Edward Lesmese7d18622020-11-19 23:46:17 +000084 def GetFilesApprovalStatus(
85 self, project, branch, paths, approvers, reviewers):
86 """Check the approval status for the given paths.
87
88 Utility method to check for approval status when a change has not yet been
89 created, given reviewers and approvers.
90
91 See GetChangeApprovalStatus for description of the returned value.
92 """
93 approvers = set(approvers)
94 reviewers = set(reviewers)
95 status = {}
96 for path in paths:
97 path_owners = set(self.ListOwnersForFile(project, branch, path))
98 if path_owners.intersection(approvers):
99 status[path] = APPROVED
100 elif path_owners.intersection(reviewers):
101 status[path] = PENDING
102 else:
103 status[path] = INSUFFICIENT_REVIEWERS
104 return status
105
Edward Lesmes295dd182020-11-24 23:07:26 +0000106 def SuggestOwners(self, project, branch, paths):
107 """Suggest a set of owners for the given paths."""
108 paths_by_owner = {}
109 score_by_owner = {}
110 for path in paths:
111 owners = self.ListOwnersForFile(project, branch, path)
112 for i, owner in enumerate(owners):
113 paths_by_owner.setdefault(owner, set()).add(path)
114 # Gerrit API lists owners of a path sorted by an internal score, so
115 # owners that appear first should be prefered.
116 # We define the score of an owner to be their minimum position in all
117 # paths.
118 score_by_owner[owner] = min(i, score_by_owner.get(owner, i))
119
120 # Sort owners by their score.
121 owners = sorted(score_by_owner, key=lambda o: score_by_owner[o])
122
123 # Select the minimum number of owners that can approve all paths.
124 # We start at 2 to avoid sending all changes that require multiple reviewers
125 # to top-level owners.
Edward Lesmesca45aff2020-12-03 23:11:01 +0000126 if len(owners) < 2:
127 return owners
128
129 for num_owners in range(2, len(owners)):
Edward Lesmes295dd182020-11-24 23:07:26 +0000130 # Iterate all combinations of `num_owners` by decreasing score, and select
131 # the first one that covers all paths.
132 for selected in _owner_combinations(owners, num_owners):
133 covered = set.union(*(paths_by_owner[o] for o in selected))
134 if len(covered) == len(paths):
135 return selected
Edward Lesmes295dd182020-11-24 23:07:26 +0000136
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 Lesmes8a791e72020-12-02 18:33:18 +0000151 f: scm.GIT.GetOldContents(self._root, f, self._branch).splitlines()
Edward Lesmesd4e6fb62020-11-17 00:17:58 +0000152 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)