blob: e0b4e07b5e9ab2e1c916e104b743982d743a9cc8 [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
17 | "per-file" \s+ glob "=" directive
18 | 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.org6dada4e2011-03-08 22:32:40 +000052import re
53
54
55# If this is present by itself on a line, this means that everyone can review.
56EVERYONE = '*'
57
58
59# Recognizes 'X@Y' email addresses. Very simplistic.
60BASIC_EMAIL_REGEXP = r'^[\w\-\+\%\.]+\@[\w\-\+\%\.]+$'
dpranke@chromium.org2a009622011-03-01 02:43:31 +000061
dpranke@chromium.org2a009622011-03-01 02:43:31 +000062
dpranke@chromium.org923950f2011-03-17 23:40:00 +000063def _assert_is_collection(obj):
dpranke@chromium.orge6a4ab32011-03-31 01:23:08 +000064 assert not isinstance(obj, basestring)
maruel@chromium.org725f1c32011-04-01 20:24:54 +000065 # Module 'collections' has no 'Iterable' member
66 # pylint: disable=E1101
dpranke@chromium.orge6a4ab32011-03-31 01:23:08 +000067 if hasattr(collections, 'Iterable') and hasattr(collections, 'Sized'):
68 assert (isinstance(obj, collections.Iterable) and
69 isinstance(obj, collections.Sized))
dpranke@chromium.org923950f2011-03-17 23:40:00 +000070
71
dpranke@chromium.org898a10e2011-03-04 21:54:43 +000072class SyntaxErrorInOwnersFile(Exception):
dpranke@chromium.org86bbf192011-03-09 21:37:06 +000073 def __init__(self, path, lineno, msg):
74 super(SyntaxErrorInOwnersFile, self).__init__((path, lineno, msg))
dpranke@chromium.org898a10e2011-03-04 21:54:43 +000075 self.path = path
dpranke@chromium.org86bbf192011-03-09 21:37:06 +000076 self.lineno = lineno
dpranke@chromium.org898a10e2011-03-04 21:54:43 +000077 self.msg = msg
78
79 def __str__(self):
dpranke@chromium.org86bbf192011-03-09 21:37:06 +000080 return "%s:%d syntax error: %s" % (self.path, self.lineno, self.msg)
dpranke@chromium.org898a10e2011-03-04 21:54:43 +000081
82
dpranke@chromium.org898a10e2011-03-04 21:54:43 +000083class Database(object):
84 """A database of OWNERS files for a repository.
85
86 This class allows you to find a suggested set of reviewers for a list
87 of changed files, and see if a list of changed files is covered by a
88 list of reviewers."""
89
dpranke@chromium.org17cc2442012-10-17 21:12:09 +000090 def __init__(self, root, fopen, os_path, glob):
dpranke@chromium.org898a10e2011-03-04 21:54:43 +000091 """Args:
dpranke@chromium.org2a009622011-03-01 02:43:31 +000092 root: the path to the root of the Repository
dpranke@chromium.org2a009622011-03-01 02:43:31 +000093 open: function callback to open a text file for reading
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +000094 os_path: module/object callback with fields for 'abspath', 'dirname',
95 'exists', and 'join'
dpranke@chromium.org17cc2442012-10-17 21:12:09 +000096 glob: function callback to list entries in a directory match a glob
97 (i.e., glob.glob)
dpranke@chromium.org2a009622011-03-01 02:43:31 +000098 """
99 self.root = root
100 self.fopen = fopen
101 self.os_path = os_path
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000102 self.glob = glob
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000103
dpranke@chromium.org627ea672011-03-11 23:29:03 +0000104 # Pick a default email regexp to use; callers can override as desired.
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000105 self.email_regexp = re.compile(BASIC_EMAIL_REGEXP)
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000106
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000107 # Mapping of owners to the paths they own.
108 self.owned_by = {EVERYONE: set()}
109
110 # Mapping of paths to authorized owners.
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000111 self.owners_for = {}
112
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000113 # Set of paths that stop us from looking above them for owners.
114 # (This is implicitly true for the root directory).
115 self.stop_looking = set([''])
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000116
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000117 def reviewers_for(self, files):
dpranke@chromium.orgfdecfb72011-03-16 23:27:23 +0000118 """Returns a suggested set of reviewers that will cover the files.
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000119
dpranke@chromium.orgfdecfb72011-03-16 23:27:23 +0000120 files is a sequence of paths relative to (and under) self.root."""
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000121 self._check_paths(files)
122 self._load_data_needed_for(files)
123 return self._covering_set_of_owners_for(files)
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000124
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000125 # TODO(dpranke): rename to objects_not_covered_by
pam@chromium.orgf46aed92012-03-08 09:18:17 +0000126 def directories_not_covered_by(self, files, reviewers):
127 """Returns the set of directories that are not owned by a reviewer.
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000128
pam@chromium.orgf46aed92012-03-08 09:18:17 +0000129 Determines which of the given files are not owned by at least one of the
130 reviewers, then returns a set containing the applicable enclosing
131 directories, i.e. the ones upward from the files that have OWNERS files.
dpranke@chromium.orgfdecfb72011-03-16 23:27:23 +0000132
133 Args:
134 files is a sequence of paths relative to (and under) self.root.
pam@chromium.orgf46aed92012-03-08 09:18:17 +0000135 reviewers is a sequence of strings matching self.email_regexp.
136 """
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000137 self._check_paths(files)
138 self._check_reviewers(reviewers)
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000139 self._load_data_needed_for(files)
pam@chromium.orgf46aed92012-03-08 09:18:17 +0000140
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000141 objs = set()
142 for f in files:
143 if f in self.owners_for:
144 objs.add(f)
145 else:
146 objs.add(self.os_path.dirname(f))
pam@chromium.orgf46aed92012-03-08 09:18:17 +0000147
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000148 covered_objs = self._objs_covered_by(reviewers)
149 uncovered_objs = [self._enclosing_obj_with_owners(o) for o in objs
150 if not self._is_obj_covered_by(o, covered_objs)]
151
152 return set(uncovered_objs)
153
154 objects_not_covered_by = directories_not_covered_by
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000155
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000156 def _check_paths(self, files):
157 def _is_under(f, pfx):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000158 return self.os_path.abspath(self.os_path.join(pfx, f)).startswith(pfx)
dpranke@chromium.org923950f2011-03-17 23:40:00 +0000159 _assert_is_collection(files)
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000160 assert all(_is_under(f, self.os_path.abspath(self.root)) for f in files)
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000161
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000162 def _check_reviewers(self, reviewers):
dpranke@chromium.org923950f2011-03-17 23:40:00 +0000163 _assert_is_collection(reviewers)
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000164 assert all(self.email_regexp.match(r) for r in reviewers)
165
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000166 # TODO(dpranke): Rename to _objs_covered_by and update_callers
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000167 def _dirs_covered_by(self, reviewers):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000168 dirs = self.owned_by[EVERYONE]
169 for r in reviewers:
170 dirs = dirs | self.owned_by.get(r, set())
171 return dirs
172
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000173 _objs_covered_by = _dirs_covered_by
174
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000175 def _stop_looking(self, dirname):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000176 return dirname in self.stop_looking
177
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000178 # TODO(dpranke): Rename to _is_dir_covered_by and update callers.
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000179 def _is_dir_covered_by(self, dirname, covered_dirs):
180 while not dirname in covered_dirs and not self._stop_looking(dirname):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000181 dirname = self.os_path.dirname(dirname)
182 return dirname in covered_dirs
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000183
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000184 _is_obj_covered_by = _is_dir_covered_by
185
186 # TODO(dpranke): Rename to _enclosing_obj_with_owners and update callers.
pam@chromium.orgf46aed92012-03-08 09:18:17 +0000187 def _enclosing_dir_with_owners(self, directory):
188 """Returns the innermost enclosing directory that has an OWNERS file."""
189 dirpath = directory
190 while not dirpath in self.owners_for:
191 if self._stop_looking(dirpath):
192 break
193 dirpath = self.os_path.dirname(dirpath)
194 return dirpath
195
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000196 _enclosing_obj_with_owners = _enclosing_dir_with_owners
197
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000198 def _load_data_needed_for(self, files):
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000199 for f in files:
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000200 dirpath = self.os_path.dirname(f)
201 while not dirpath in self.owners_for:
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000202 self._read_owners_in_dir(dirpath)
203 if self._stop_looking(dirpath):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000204 break
205 dirpath = self.os_path.dirname(dirpath)
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000206
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000207 def _read_owners_in_dir(self, dirpath):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000208 owners_path = self.os_path.join(self.root, dirpath, 'OWNERS')
209 if not self.os_path.exists(owners_path):
210 return
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000211
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000212 lineno = 0
213 for line in self.fopen(owners_path):
214 lineno += 1
215 line = line.strip()
bauerb@chromium.org20d19432011-06-08 16:34:18 +0000216 if line.startswith('#') or line == '':
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000217 continue
218 if line == 'set noparent':
219 self.stop_looking.add(dirpath)
220 continue
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000221
222 m = re.match("per-file (.+)=(.+)", line)
223 if m:
224 glob_string = m.group(1)
225 directive = m.group(2)
226 full_glob_string = self.os_path.join(self.root, dirpath, glob_string)
dpranke@chromium.orge3b1c3d2012-10-20 22:28:14 +0000227 if self.os_path.sep in glob_string:
228 raise SyntaxErrorInOwnersFile(owners_path, lineno,
229 'per-file globs cannot span directories: "%s"' % line)
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000230 baselines = self.glob(full_glob_string)
dpranke@chromium.orge3b1c3d2012-10-20 22:28:14 +0000231 for baseline in (self.os_path.relpath(b, self.root) for b in baselines):
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000232 self._add_entry(baseline, directive, "per-file line",
233 owners_path, lineno)
234 continue
235
dpranke@chromium.org86bbf192011-03-09 21:37:06 +0000236 if line.startswith('set '):
237 raise SyntaxErrorInOwnersFile(owners_path, lineno,
238 'unknown option: "%s"' % line[4:].strip())
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000239
240 self._add_entry(dirpath, line, "line", owners_path, lineno)
241
242 def _add_entry(self, path, directive, line_type, owners_path, lineno):
243 if directive == "set noparent":
244 self.stop_looking.add(path)
245 elif self.email_regexp.match(directive) or directive == EVERYONE:
246 self.owned_by.setdefault(directive, set()).add(path)
247 self.owners_for.setdefault(path, set()).add(directive)
248 else:
dpranke@chromium.org86bbf192011-03-09 21:37:06 +0000249 raise SyntaxErrorInOwnersFile(owners_path, lineno,
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000250 ('%s is not a "set" directive, "*", '
251 'or an email address: "%s"' % (line_type, directive)))
252
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000253
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000254 def _covering_set_of_owners_for(self, files):
zork@chromium.org046e1752012-05-07 05:56:12 +0000255 # Get the set of directories from the files.
256 dirs = set()
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000257 for f in files:
zork@chromium.org046e1752012-05-07 05:56:12 +0000258 dirs.add(self.os_path.dirname(f))
259
260 owned_dirs = {}
261 dir_owners = {}
262
263 for current_dir in dirs:
264 # Get the list of owners for each directory.
265 current_owners = set()
266 dirname = current_dir
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000267 while dirname in self.owners_for:
zork@chromium.org04704f72012-05-15 01:15:30 +0000268 current_owners |= self.owners_for[dirname]
dpranke@chromium.org7eea2592011-03-09 21:35:46 +0000269 if self._stop_looking(dirname):
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000270 break
zork@chromium.org04704f72012-05-15 01:15:30 +0000271 prev_parent = dirname
dpranke@chromium.org6dada4e2011-03-08 22:32:40 +0000272 dirname = self.os_path.dirname(dirname)
zork@chromium.org04704f72012-05-15 01:15:30 +0000273 if prev_parent == dirname:
274 break
zork@chromium.org046e1752012-05-07 05:56:12 +0000275
276 # Map each directory to a list of its owners.
277 dir_owners[current_dir] = current_owners
278
279 # Add the directory to the list of each owner.
280 for owner in current_owners:
zork@chromium.org04704f72012-05-15 01:15:30 +0000281 owned_dirs.setdefault(owner, set()).add(current_dir)
zork@chromium.org046e1752012-05-07 05:56:12 +0000282
283 final_owners = set()
284 while dirs:
285 # Find the owner that has the most directories.
286 max_count = 0
287 max_owner = None
288 owner_count = {}
289 for dirname in dirs:
290 for owner in dir_owners[dirname]:
291 count = owner_count.get(owner, 0) + 1
292 owner_count[owner] = count
293 if count >= max_count:
294 max_owner = owner
zork@chromium.org04704f72012-05-15 01:15:30 +0000295 max_count = count
zork@chromium.org046e1752012-05-07 05:56:12 +0000296
297 # If no more directories have OWNERS, we're done.
298 if not max_owner:
299 break
300
301 final_owners.add(max_owner)
302
303 # Remove all directories owned by the current owner from the remaining
304 # list.
305 for dirname in owned_dirs[max_owner]:
zork@chromium.org04704f72012-05-15 01:15:30 +0000306 dirs.discard(dirname)
zork@chromium.org046e1752012-05-07 05:56:12 +0000307
308 return final_owners