blob: 8007e171c29c059589be1b0ea77f7a9b74694413 [file] [log] [blame]
pam@chromium.orgf46aed92012-03-08 09:18:17 +00001# Copyright (c) 2012 The Chromium Authors. All rights reserved.
dpranke@chromium.org2a009622011-03-01 02:43:31 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
dpranke@chromium.org17cc2442012-10-17 21:12:09 +00005"""A database of OWNERS files.
6
7OWNERS files indicate who is allowed to approve changes in a specific directory
8(or who is allowed to make changes without needing approval of another OWNER).
9Note that all changes must still be reviewed by someone familiar with the code,
10so you may need approval from both an OWNER and a reviewer in many cases.
11
12The syntax of the OWNERS file is, roughly:
13
14lines := (\s* line? \s* "\n")*
15
16line := directive
dpranke@chromium.orgd16e48b2012-12-03 21:53:49 +000017 | "per-file" \s+ glob \s* "=" \s* directive
dpranke@chromium.org17cc2442012-10-17 21:12:09 +000018 | comment
19
20directive := "set noparent"
21 | email_address
22 | "*"
23
24glob := [a-zA-Z0-9_-*?]+
25
26comment := "#" [^"\n"]*
27
28Email addresses must follow the foo@bar.com short form (exact syntax given
29in BASIC_EMAIL_REGEXP, below). Filename globs follow the simple unix
30shell conventions, and relative and absolute paths are not allowed (i.e.,
31globs only refer to the files in the current directory).
32
33If a user's email is one of the email_addresses in the file, the user is
34considered an "OWNER" for all files in the directory.
35
36If the "per-file" directive is used, the line only applies to files in that
37directory that match the filename glob specified.
38
39If the "set noparent" directive used, then only entries in this OWNERS file
40apply to files in this directory; if the "set noparent" directive is not
41used, then entries in OWNERS files in enclosing (upper) directories also
42apply (up until a "set noparent is encountered").
43
44If "per-file glob=set noparent" is used, then global directives are ignored
45for the glob, and only the "per-file" owners are used for files matching that
46glob.
47
48Examples for all of these combinations can be found in tests/owners_unittest.py.
49"""
dpranke@chromium.org2a009622011-03-01 02:43:31 +000050
dpranke@chromium.orgfdecfb72011-03-16 23:27:23 +000051import collections
dpranke@chromium.orgc591a702012-12-20 20:14:58 +000052import random
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +000053import re
54
55
56# If this is present by itself on a line, this means that everyone can review.
57EVERYONE = '*'
58
59
60# Recognizes 'X@Y' email addresses. Very simplistic.
61BASIC_EMAIL_REGEXP = r'^[\w\-\+\%\.]+\@[\w\-\+\%\.]+$'
dpranke@chromium.org2a009622011-03-01 02:43:31 +000062
dpranke@chromium.org2a009622011-03-01 02:43:31 +000063
dpranke@chromium.org923950f2011-03-17 23:40:00 +000064def _assert_is_collection(obj):
dpranke@chromium.orge6a4ab32011-03-31 01:23:08 +000065 assert not isinstance(obj, basestring)
maruel@chromium.org725f1c32011-04-01 20:24:54 +000066 # Module 'collections' has no 'Iterable' member
67 # pylint: disable=E1101
dpranke@chromium.orge6a4ab32011-03-31 01:23:08 +000068 if hasattr(collections, 'Iterable') and hasattr(collections, 'Sized'):
69 assert (isinstance(obj, collections.Iterable) and
70 isinstance(obj, collections.Sized))
dpranke@chromium.org923950f2011-03-17 23:40:00 +000071
72
dpranke@chromium.org898a10e2011-03-04 21:54:43 +000073class SyntaxErrorInOwnersFile(Exception):
dpranke@chromium.org86bbf192011-03-09 21:37:06 +000074 def __init__(self, path, lineno, msg):
75 super(SyntaxErrorInOwnersFile, self).__init__((path, lineno, msg))
dpranke@chromium.org898a10e2011-03-04 21:54:43 +000076 self.path = path
dpranke@chromium.org86bbf192011-03-09 21:37:06 +000077 self.lineno = lineno
dpranke@chromium.org898a10e2011-03-04 21:54:43 +000078 self.msg = msg
79
80 def __str__(self):
dpranke@chromium.org86bbf192011-03-09 21:37:06 +000081 return "%s:%d syntax error: %s" % (self.path, self.lineno, self.msg)
dpranke@chromium.org898a10e2011-03-04 21:54:43 +000082
83
dpranke@chromium.org898a10e2011-03-04 21:54:43 +000084class Database(object):
85 """A database of OWNERS files for a repository.
86
87 This class allows you to find a suggested set of reviewers for a list
88 of changed files, and see if a list of changed files is covered by a
89 list of reviewers."""
90
dpranke@chromium.org17cc2442012-10-17 21:12:09 +000091 def __init__(self, root, fopen, os_path, glob):
dpranke@chromium.org898a10e2011-03-04 21:54:43 +000092 """Args:
dpranke@chromium.org2a009622011-03-01 02:43:31 +000093 root: the path to the root of the Repository
dpranke@chromium.org2a009622011-03-01 02:43:31 +000094 open: function callback to open a text file for reading
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +000095 os_path: module/object callback with fields for 'abspath', 'dirname',
96 'exists', and 'join'
dpranke@chromium.org17cc2442012-10-17 21:12:09 +000097 glob: function callback to list entries in a directory match a glob
98 (i.e., glob.glob)
dpranke@chromium.org2a009622011-03-01 02:43:31 +000099 """
100 self.root = root
101 self.fopen = fopen
102 self.os_path = os_path
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000103 self.glob = glob
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000104
dpranke@chromium.org627ea672011-03-11 23:29:03 +0000105 # Pick a default email regexp to use; callers can override as desired.
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000106 self.email_regexp = re.compile(BASIC_EMAIL_REGEXP)
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000107
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000108 # Mapping of owners to the paths they own.
109 self.owned_by = {EVERYONE: set()}
110
111 # Mapping of paths to authorized owners.
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000112 self.owners_for = {}
113
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000114 # Set of paths that stop us from looking above them for owners.
115 # (This is implicitly true for the root directory).
116 self.stop_looking = set([''])
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000117
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000118 def reviewers_for(self, files):
dpranke@chromium.orgfdecfb72011-03-16 23:27:23 +0000119 """Returns a suggested set of reviewers that will cover the files.
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000120
dpranke@chromium.orgfdecfb72011-03-16 23:27:23 +0000121 files is a sequence of paths relative to (and under) self.root."""
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000122 self._check_paths(files)
123 self._load_data_needed_for(files)
dpranke@chromium.org9d66f482013-01-18 02:57:11 +0000124 suggested_owners = self._covering_set_of_owners_for(files)
125 if EVERYONE in suggested_owners:
126 if len(suggested_owners) > 1:
127 suggested_owners.remove(EVERYONE)
128 else:
129 suggested_owners = set(['<anyone>'])
130 return suggested_owners
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000131
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000132 # TODO(dpranke): rename to objects_not_covered_by
pam@chromium.orgf46aed92012-03-08 09:18:17 +0000133 def directories_not_covered_by(self, files, reviewers):
134 """Returns the set of directories that are not owned by a reviewer.
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000135
pam@chromium.orgf46aed92012-03-08 09:18:17 +0000136 Determines which of the given files are not owned by at least one of the
137 reviewers, then returns a set containing the applicable enclosing
138 directories, i.e. the ones upward from the files that have OWNERS files.
dpranke@chromium.orgfdecfb72011-03-16 23:27:23 +0000139
140 Args:
141 files is a sequence of paths relative to (and under) self.root.
pam@chromium.orgf46aed92012-03-08 09:18:17 +0000142 reviewers is a sequence of strings matching self.email_regexp.
143 """
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000144 self._check_paths(files)
145 self._check_reviewers(reviewers)
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000146 self._load_data_needed_for(files)
pam@chromium.orgf46aed92012-03-08 09:18:17 +0000147
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000148 objs = set()
149 for f in files:
150 if f in self.owners_for:
151 objs.add(f)
152 else:
153 objs.add(self.os_path.dirname(f))
pam@chromium.orgf46aed92012-03-08 09:18:17 +0000154
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000155 covered_objs = self._objs_covered_by(reviewers)
156 uncovered_objs = [self._enclosing_obj_with_owners(o) for o in objs
157 if not self._is_obj_covered_by(o, covered_objs)]
158
159 return set(uncovered_objs)
160
161 objects_not_covered_by = directories_not_covered_by
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000162
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000163 def _check_paths(self, files):
164 def _is_under(f, pfx):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000165 return self.os_path.abspath(self.os_path.join(pfx, f)).startswith(pfx)
dpranke@chromium.org923950f2011-03-17 23:40:00 +0000166 _assert_is_collection(files)
dpranke@chromium.orgb54a78e2012-12-13 23:37:23 +0000167 assert all(not self.os_path.isabs(f) and
168 _is_under(f, self.os_path.abspath(self.root)) for f in files)
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000169
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000170 def _check_reviewers(self, reviewers):
dpranke@chromium.org923950f2011-03-17 23:40:00 +0000171 _assert_is_collection(reviewers)
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000172 assert all(self.email_regexp.match(r) for r in reviewers)
173
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000174 # TODO(dpranke): Rename to _objs_covered_by and update_callers
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000175 def _dirs_covered_by(self, reviewers):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000176 dirs = self.owned_by[EVERYONE]
177 for r in reviewers:
178 dirs = dirs | self.owned_by.get(r, set())
179 return dirs
180
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000181 _objs_covered_by = _dirs_covered_by
182
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000183 def _stop_looking(self, dirname):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000184 return dirname in self.stop_looking
185
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000186 # TODO(dpranke): Rename to _is_dir_covered_by and update callers.
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000187 def _is_dir_covered_by(self, dirname, covered_dirs):
188 while not dirname in covered_dirs and not self._stop_looking(dirname):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000189 dirname = self.os_path.dirname(dirname)
190 return dirname in covered_dirs
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000191
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000192 _is_obj_covered_by = _is_dir_covered_by
193
194 # TODO(dpranke): Rename to _enclosing_obj_with_owners and update callers.
pam@chromium.orgf46aed92012-03-08 09:18:17 +0000195 def _enclosing_dir_with_owners(self, directory):
196 """Returns the innermost enclosing directory that has an OWNERS file."""
197 dirpath = directory
198 while not dirpath in self.owners_for:
199 if self._stop_looking(dirpath):
200 break
201 dirpath = self.os_path.dirname(dirpath)
202 return dirpath
203
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000204 _enclosing_obj_with_owners = _enclosing_dir_with_owners
205
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000206 def _load_data_needed_for(self, files):
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000207 for f in files:
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000208 dirpath = self.os_path.dirname(f)
209 while not dirpath in self.owners_for:
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000210 self._read_owners_in_dir(dirpath)
211 if self._stop_looking(dirpath):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000212 break
213 dirpath = self.os_path.dirname(dirpath)
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000214
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000215 def _read_owners_in_dir(self, dirpath):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000216 owners_path = self.os_path.join(self.root, dirpath, 'OWNERS')
217 if not self.os_path.exists(owners_path):
218 return
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000219
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000220 lineno = 0
221 for line in self.fopen(owners_path):
222 lineno += 1
223 line = line.strip()
bauerb@chromium.org20d19432011-06-08 16:34:18 +0000224 if line.startswith('#') or line == '':
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000225 continue
226 if line == 'set noparent':
227 self.stop_looking.add(dirpath)
228 continue
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000229
230 m = re.match("per-file (.+)=(.+)", line)
231 if m:
dpranke@chromium.orgd16e48b2012-12-03 21:53:49 +0000232 glob_string = m.group(1).strip()
233 directive = m.group(2).strip()
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000234 full_glob_string = self.os_path.join(self.root, dirpath, glob_string)
dpranke@chromium.org9e227d52012-10-20 23:47:42 +0000235 if '/' in glob_string or '\\' in glob_string:
dpranke@chromium.orge3b1c3d2012-10-20 22:28:14 +0000236 raise SyntaxErrorInOwnersFile(owners_path, lineno,
dpranke@chromium.org9e227d52012-10-20 23:47:42 +0000237 'per-file globs cannot span directories or use escapes: "%s"' %
238 line)
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000239 baselines = self.glob(full_glob_string)
dpranke@chromium.orge3b1c3d2012-10-20 22:28:14 +0000240 for baseline in (self.os_path.relpath(b, self.root) for b in baselines):
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000241 self._add_entry(baseline, directive, "per-file line",
242 owners_path, lineno)
243 continue
244
dpranke@chromium.org86bbf192011-03-09 21:37:06 +0000245 if line.startswith('set '):
246 raise SyntaxErrorInOwnersFile(owners_path, lineno,
247 'unknown option: "%s"' % line[4:].strip())
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000248
249 self._add_entry(dirpath, line, "line", owners_path, lineno)
250
251 def _add_entry(self, path, directive, line_type, owners_path, lineno):
252 if directive == "set noparent":
253 self.stop_looking.add(path)
254 elif self.email_regexp.match(directive) or directive == EVERYONE:
255 self.owned_by.setdefault(directive, set()).add(path)
256 self.owners_for.setdefault(path, set()).add(directive)
257 else:
dpranke@chromium.org86bbf192011-03-09 21:37:06 +0000258 raise SyntaxErrorInOwnersFile(owners_path, lineno,
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000259 ('%s is not a "set" directive, "*", '
260 'or an email address: "%s"' % (line_type, directive)))
261
dpranke@chromium.org5e5d37b2012-12-19 21:04:58 +0000262 def _covering_set_of_owners_for(self, files):
dpranke@chromium.orgc591a702012-12-20 20:14:58 +0000263 dirs_remaining = set(self._enclosing_dir_with_owners(f) for f in files)
264 all_possible_owners = self._all_possible_owners(dirs_remaining)
265 suggested_owners = set()
266 while dirs_remaining:
267 owner = self.lowest_cost_owner(all_possible_owners, dirs_remaining)
268 suggested_owners.add(owner)
269 dirs_to_remove = set(el[0] for el in all_possible_owners[owner])
270 dirs_remaining -= dirs_to_remove
271 return suggested_owners
dpranke@chromium.org5e5d37b2012-12-19 21:04:58 +0000272
dpranke@chromium.orgc591a702012-12-20 20:14:58 +0000273 def _all_possible_owners(self, dirs):
274 """Returns a list of (potential owner, distance-from-dir) tuples; a
275 distance of 1 is the lowest/closest possible distance (which makes the
276 subsequent math easier)."""
277 all_possible_owners = {}
zork@chromium.org046e1752012-05-07 05:56:12 +0000278 for current_dir in dirs:
zork@chromium.org046e1752012-05-07 05:56:12 +0000279 dirname = current_dir
dpranke@chromium.orgc591a702012-12-20 20:14:58 +0000280 distance = 1
281 while True:
282 for owner in self.owners_for.get(dirname, []):
283 all_possible_owners.setdefault(owner, [])
284 # If the same person is in multiple OWNERS files above a given
285 # directory, only count the closest one.
286 if not any(current_dir == el[0] for el in all_possible_owners[owner]):
287 all_possible_owners[owner].append((current_dir, distance))
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000288 if self._stop_looking(dirname):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000289 break
290 dirname = self.os_path.dirname(dirname)
dpranke@chromium.orgc591a702012-12-20 20:14:58 +0000291 distance += 1
292 return all_possible_owners
zork@chromium.org046e1752012-05-07 05:56:12 +0000293
dpranke@chromium.orgc591a702012-12-20 20:14:58 +0000294 @staticmethod
295 def lowest_cost_owner(all_possible_owners, dirs):
296 # We want to minimize both the number of reviewers and the distance
297 # from the files/dirs needing reviews. The "pow(X, 1.75)" below is
298 # an arbitrarily-selected scaling factor that seems to work well - it
299 # will select one reviewer in the parent directory over three reviewers
300 # in subdirs, but not one reviewer over just two.
301 total_costs_by_owner = {}
302 for owner in all_possible_owners:
303 total_distance = 0
304 num_directories_owned = 0
305 for dirname, distance in all_possible_owners[owner]:
306 if dirname in dirs:
307 total_distance += distance
308 num_directories_owned += 1
309 if num_directories_owned:
310 total_costs_by_owner[owner] = (total_distance /
311 pow(num_directories_owned, 1.75))
zork@chromium.org046e1752012-05-07 05:56:12 +0000312
dpranke@chromium.orgc591a702012-12-20 20:14:58 +0000313 # Return the lowest cost owner. In the case of a tie, pick one randomly.
314 lowest_cost = min(total_costs_by_owner.itervalues())
315 lowest_cost_owners = filter(
316 lambda owner: total_costs_by_owner[owner] == lowest_cost,
317 total_costs_by_owner)
318 return random.Random().choice(lowest_cost_owners)