Edward Lesmes | 91bb750 | 2020-11-06 00:50:24 +0000 | [diff] [blame] | 1 | # 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 Lesmes | 295dd18 | 2020-11-24 23:07:26 +0000 | [diff] [blame] | 5 | import itertools |
Edward Lesmes | d4e6fb6 | 2020-11-17 00:17:58 +0000 | [diff] [blame] | 6 | import os |
Edward Lesmes | 64e8076 | 2020-11-24 19:46:45 +0000 | [diff] [blame] | 7 | import random |
Edward Lesmes | d4e6fb6 | 2020-11-17 00:17:58 +0000 | [diff] [blame] | 8 | |
Edward Lesmes | 829ce02 | 2020-11-18 18:30:31 +0000 | [diff] [blame] | 9 | import gerrit_util |
Edward Lesmes | 64e8076 | 2020-11-24 19:46:45 +0000 | [diff] [blame] | 10 | import owners as owners_db |
Edward Lesmes | d4e6fb6 | 2020-11-17 00:17:58 +0000 | [diff] [blame] | 11 | import scm |
| 12 | |
| 13 | |
| 14 | APPROVED = 'APPROVED' |
| 15 | PENDING = 'PENDING' |
| 16 | INSUFFICIENT_REVIEWERS = 'INSUFFICIENT_REVIEWERS' |
Edward Lesmes | b4f4226 | 2020-11-10 23:41:35 +0000 | [diff] [blame] | 17 | |
Edward Lesmes | 91bb750 | 2020-11-06 00:50:24 +0000 | [diff] [blame] | 18 | |
Edward Lesmes | 295dd18 | 2020-11-24 23:07:26 +0000 | [diff] [blame] | 19 | def _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 Lesmes | b472168 | 2020-11-19 22:59:57 +0000 | [diff] [blame] | 41 | class InvalidOwnersConfig(Exception): |
| 42 | pass |
| 43 | |
| 44 | |
Edward Lesmes | 91bb750 | 2020-11-06 00:50:24 +0000 | [diff] [blame] | 45 | class 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 Lesmes | 64e8076 | 2020-11-24 19:46:45 +0000 | [diff] [blame] | 63 | """List all owners for a file. |
| 64 | |
| 65 | The returned list is sorted so that better owners appear first. |
| 66 | """ |
Edward Lesmes | 91bb750 | 2020-11-06 00:50:24 +0000 | [diff] [blame] | 67 | raise Exception('Not implemented') |
| 68 | |
Edward Lesmes | d4e6fb6 | 2020-11-17 00:17:58 +0000 | [diff] [blame] | 69 | def GetChangeApprovalStatus(self, change_id): |
Edward Lesmes | b472168 | 2020-11-19 22:59:57 +0000 | [diff] [blame] | 70 | """Check the approval status for the latest revision_id in a change. |
Edward Lesmes | d4e6fb6 | 2020-11-17 00:17:58 +0000 | [diff] [blame] | 71 | |
| 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 Lesmes | 91bb750 | 2020-11-06 00:50:24 +0000 | [diff] [blame] | 78 | raise Exception('Not implemented') |
| 79 | |
Edward Lesmes | b472168 | 2020-11-19 22:59:57 +0000 | [diff] [blame] | 80 | def ValidateOwnersConfig(self, change_id): |
Edward Lesmes | 91bb750 | 2020-11-06 00:50:24 +0000 | [diff] [blame] | 81 | """Check if the owners configuration in a change is valid.""" |
| 82 | raise Exception('Not implemented') |
Edward Lesmes | b4f4226 | 2020-11-10 23:41:35 +0000 | [diff] [blame] | 83 | |
Edward Lesmes | e7d1862 | 2020-11-19 23:46:17 +0000 | [diff] [blame] | 84 | 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 Lesmes | 295dd18 | 2020-11-24 23:07:26 +0000 | [diff] [blame] | 106 | 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 Lesmes | ca45aff | 2020-12-03 23:11:01 +0000 | [diff] [blame] | 126 | if len(owners) < 2: |
| 127 | return owners |
| 128 | |
| 129 | for num_owners in range(2, len(owners)): |
Edward Lesmes | 295dd18 | 2020-11-24 23:07:26 +0000 | [diff] [blame] | 130 | # 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 Lesmes | 295dd18 | 2020-11-24 23:07:26 +0000 | [diff] [blame] | 136 | |
Edward Lesmes | b4f4226 | 2020-11-10 23:41:35 +0000 | [diff] [blame] | 137 | |
| 138 | class DepotToolsClient(OwnersClient): |
| 139 | """Implement OwnersClient using owners.py Database.""" |
Edward Lesmes | eeca9c6 | 2020-11-20 00:00:17 +0000 | [diff] [blame] | 140 | def __init__(self, host, root, branch, fopen=open, os_path=os.path): |
Edward Lesmes | b4f4226 | 2020-11-10 23:41:35 +0000 | [diff] [blame] | 141 | super(DepotToolsClient, self).__init__(host) |
| 142 | self._root = root |
Edward Lesmes | b472168 | 2020-11-19 22:59:57 +0000 | [diff] [blame] | 143 | self._fopen = fopen |
| 144 | self._os_path = os_path |
Edward Lesmes | d4e6fb6 | 2020-11-17 00:17:58 +0000 | [diff] [blame] | 145 | self._branch = branch |
Edward Lesmes | 64e8076 | 2020-11-24 19:46:45 +0000 | [diff] [blame] | 146 | self._db = owners_db.Database(root, fopen, os_path) |
Edward Lesmes | 829ce02 | 2020-11-18 18:30:31 +0000 | [diff] [blame] | 147 | self._db.override_files = self._GetOriginalOwnersFiles() |
| 148 | |
| 149 | def _GetOriginalOwnersFiles(self): |
| 150 | return { |
Edward Lesmes | 8a791e7 | 2020-12-02 18:33:18 +0000 | [diff] [blame] | 151 | f: scm.GIT.GetOldContents(self._root, f, self._branch).splitlines() |
Edward Lesmes | d4e6fb6 | 2020-11-17 00:17:58 +0000 | [diff] [blame] | 152 | for _, f in scm.GIT.CaptureStatus(self._root, self._branch) |
| 153 | if os.path.basename(f) == 'OWNERS' |
Edward Lesmes | 829ce02 | 2020-11-18 18:30:31 +0000 | [diff] [blame] | 154 | } |
Edward Lesmes | b4f4226 | 2020-11-10 23:41:35 +0000 | [diff] [blame] | 155 | |
| 156 | def ListOwnersForFile(self, _project, _branch, path): |
Edward Lesmes | 64e8076 | 2020-11-24 19:46:45 +0000 | [diff] [blame] | 157 | # 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 Lesmes | d4e6fb6 | 2020-11-17 00:17:58 +0000 | [diff] [blame] | 166 | |
| 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 Lesmes | 829ce02 | 2020-11-18 18:30:31 +0000 | [diff] [blame] | 176 | label = data['labels']['Code-Review'] |
Edward Lesmes | d4e6fb6 | 2020-11-17 00:17:58 +0000 | [diff] [blame] | 177 | 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 Lesmes | e7d1862 | 2020-11-19 23:46:17 +0000 | [diff] [blame] | 181 | return self.GetFilesApprovalStatus(None, None, files, approvers, reviewers) |
Edward Lesmes | b472168 | 2020-11-19 22:59:57 +0000 | [diff] [blame] | 182 | |
| 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 Lesmes | 64e8076 | 2020-11-24 19:46:45 +0000 | [diff] [blame] | 191 | db = owners_db.Database(self._root, self._fopen, self._os_path) |
Edward Lesmes | b472168 | 2020-11-19 22:59:57 +0000 | [diff] [blame] | 192 | 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) |
Gavin Mak | c94b21d | 2020-12-10 20:27:32 +0000 | [diff] [blame^] | 197 | |
| 198 | |
| 199 | class GerritClient(OwnersClient): |
| 200 | """Implement OwnersClient using OWNERS REST API.""" |
| 201 | def __init__(self, host): |
| 202 | super(GerritClient, self).__init__(host) |
| 203 | |
| 204 | def ListOwnersForFile(self, project, branch, path): |
| 205 | # GetOwnersForFile returns a list of account details sorted by order of |
| 206 | # best reviewer for path. If code owners have the same score, the order is |
| 207 | # random. |
| 208 | data = gerrit_util.GetOwnersForFile(self._host, project, branch, path) |
| 209 | return [d['account']['email'] for d in data] |