blob: d08ca59ed911d80c7358a36555c63c50989bffd5 [file] [log] [blame]
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +00001# Copyright 2013 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
5"""Interactive tool for finding reviewers/owners for a change."""
6
7import os
8import copy
9import owners as owners_module
10
11
12def first(iterable):
13 for element in iterable:
14 return element
15
16
17class OwnersFinder(object):
18 COLOR_LINK = '\033[4m'
19 COLOR_BOLD = '\033[1;32m'
20 COLOR_GREY = '\033[0;37m'
21 COLOR_RESET = '\033[0m'
22
23 indentation = 0
24
Edward Lemur707d70b2018-02-07 00:50:14 +010025 def __init__(self, files, local_root, author, reviewers,
dtu944b6052016-07-14 14:48:21 -070026 fopen, os_path,
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +000027 email_postfix='@chromium.org',
Jochen Eisingerd0573ec2017-04-13 10:55:06 +020028 disable_color=False,
29 override_files=None):
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +000030 self.email_postfix = email_postfix
31
32 if os.name == 'nt' or disable_color:
33 self.COLOR_LINK = ''
34 self.COLOR_BOLD = ''
35 self.COLOR_GREY = ''
36 self.COLOR_RESET = ''
37
Jochen Eisingereb744762017-04-05 11:00:05 +020038 self.db = owners_module.Database(local_root, fopen, os_path)
Jochen Eisingerd0573ec2017-04-13 10:55:06 +020039 self.db.override_files = override_files or {}
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +000040 self.db.load_data_needed_for(files)
41
42 self.os_path = os_path
43
44 self.author = author
45
46 filtered_files = files
47
Edward Lemur707d70b2018-02-07 00:50:14 +010048 reviewers = list(reviewers)
49 if author:
50 reviewers.append(author)
51
52 # Eliminate files that existing reviewers can review.
dtu944b6052016-07-14 14:48:21 -070053 filtered_files = list(self.db.files_not_covered_by(
Edward Lemur707d70b2018-02-07 00:50:14 +010054 filtered_files, reviewers))
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +000055
56 # If some files are eliminated.
57 if len(filtered_files) != len(files):
58 files = filtered_files
59 # Reload the database.
Jochen Eisingereb744762017-04-05 11:00:05 +020060 self.db = owners_module.Database(local_root, fopen, os_path)
Jochen Eisingerd0573ec2017-04-13 10:55:06 +020061 self.db.override_files = override_files or {}
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +000062 self.db.load_data_needed_for(files)
63
64 self.all_possible_owners = self.db.all_possible_owners(files, None)
65
66 self.owners_to_files = {}
67 self._map_owners_to_files(files)
68
69 self.files_to_owners = {}
70 self._map_files_to_owners()
71
72 self.owners_score = self.db.total_costs_by_owner(
73 self.all_possible_owners, files)
74
75 self.original_files_to_owners = copy.deepcopy(self.files_to_owners)
76 self.comments = self.db.comments
77
78 # This is the queue that will be shown in the interactive questions.
79 # It is initially sorted by the score in descending order. In the
80 # interactive questions a user can choose to "defer" its decision, then the
81 # owner will be put to the end of the queue and shown later.
82 self.owners_queue = []
83
84 self.unreviewed_files = set()
85 self.reviewed_by = {}
86 self.selected_owners = set()
87 self.deselected_owners = set()
88 self.reset()
89
90 def run(self):
91 self.reset()
92 while self.owners_queue and self.unreviewed_files:
93 owner = self.owners_queue[0]
94
95 if (owner in self.selected_owners) or (owner in self.deselected_owners):
96 continue
97
98 if not any((file_name in self.unreviewed_files)
99 for file_name in self.owners_to_files[owner]):
100 self.deselect_owner(owner)
101 continue
102
103 self.print_info(owner)
104
105 while True:
106 inp = self.input_command(owner)
107 if inp == 'y' or inp == 'yes':
108 self.select_owner(owner)
109 break
110 elif inp == 'n' or inp == 'no':
111 self.deselect_owner(owner)
112 break
113 elif inp == '' or inp == 'd' or inp == 'defer':
114 self.owners_queue.append(self.owners_queue.pop(0))
115 break
116 elif inp == 'f' or inp == 'files':
117 self.list_files()
118 break
119 elif inp == 'o' or inp == 'owners':
120 self.list_owners(self.owners_queue)
121 break
122 elif inp == 'p' or inp == 'pick':
123 self.pick_owner(raw_input('Pick an owner: '))
124 break
125 elif inp.startswith('p ') or inp.startswith('pick '):
126 self.pick_owner(inp.split(' ', 2)[1].strip())
127 break
128 elif inp == 'r' or inp == 'restart':
129 self.reset()
130 break
131 elif inp == 'q' or inp == 'quit':
132 # Exit with error
133 return 1
134
135 self.print_result()
136 return 0
137
138 def _map_owners_to_files(self, files):
139 for owner in self.all_possible_owners:
140 for dir_name, _ in self.all_possible_owners[owner]:
141 for file_name in files:
142 if file_name.startswith(dir_name):
143 self.owners_to_files.setdefault(owner, set())
144 self.owners_to_files[owner].add(file_name)
145
146 def _map_files_to_owners(self):
147 for owner in self.owners_to_files:
148 for file_name in self.owners_to_files[owner]:
149 self.files_to_owners.setdefault(file_name, set())
150 self.files_to_owners[file_name].add(owner)
151
152 def reset(self):
153 self.files_to_owners = copy.deepcopy(self.original_files_to_owners)
154 self.unreviewed_files = set(self.files_to_owners.keys())
155 self.reviewed_by = {}
156 self.selected_owners = set()
157 self.deselected_owners = set()
158
159 # Initialize owners queue, sort it by the score
160 self.owners_queue = list(sorted(self.owners_to_files.keys(),
161 key=lambda owner: self.owners_score[owner]))
162 self.find_mandatory_owners()
163
164 def select_owner(self, owner, findMandatoryOwners=True):
165 if owner in self.selected_owners or owner in self.deselected_owners\
166 or not (owner in self.owners_queue):
167 return
168 self.writeln('Selected: ' + owner)
169 self.owners_queue.remove(owner)
170 self.selected_owners.add(owner)
171 for file_name in filter(
172 lambda file_name: file_name in self.unreviewed_files,
173 self.owners_to_files[owner]):
174 self.unreviewed_files.remove(file_name)
175 self.reviewed_by[file_name] = owner
176 if findMandatoryOwners:
177 self.find_mandatory_owners()
178
179 def deselect_owner(self, owner, findMandatoryOwners=True):
180 if owner in self.selected_owners or owner in self.deselected_owners\
181 or not (owner in self.owners_queue):
182 return
183 self.writeln('Deselected: ' + owner)
184 self.owners_queue.remove(owner)
185 self.deselected_owners.add(owner)
186 for file_name in self.owners_to_files[owner] & self.unreviewed_files:
187 self.files_to_owners[file_name].remove(owner)
188 if findMandatoryOwners:
189 self.find_mandatory_owners()
190
191 def find_mandatory_owners(self):
192 continues = True
193 for owner in self.owners_queue:
194 if owner in self.selected_owners:
195 continue
196 if owner in self.deselected_owners:
197 continue
198 if len(self.owners_to_files[owner] & self.unreviewed_files) == 0:
199 self.deselect_owner(owner, False)
200
201 while continues:
202 continues = False
203 for file_name in filter(
204 lambda file_name: len(self.files_to_owners[file_name]) == 1,
205 self.unreviewed_files):
206 owner = first(self.files_to_owners[file_name])
207 self.select_owner(owner, False)
208 continues = True
209 break
210
211 def print_comments(self, owner):
212 if owner not in self.comments:
213 self.writeln(self.bold_name(owner))
214 else:
215 self.writeln(self.bold_name(owner) + ' is commented as:')
216 self.indent()
Jochen Eisinger72606f82017-04-04 10:44:18 +0200217 if owners_module.GLOBAL_STATUS in self.comments[owner]:
218 self.writeln(
219 self.greyed(self.comments[owner][owners_module.GLOBAL_STATUS]) +
220 ' (global status)')
221 if len(self.comments[owner]) == 1:
222 self.unindent()
223 return
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +0000224 for path in self.comments[owner]:
Jochen Eisinger72606f82017-04-04 10:44:18 +0200225 if path == owners_module.GLOBAL_STATUS:
226 continue
227 elif len(self.comments[owner][path]) > 0:
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +0000228 self.writeln(self.greyed(self.comments[owner][path]) +
229 ' (at ' + self.bold(path or '<root>') + ')')
230 else:
231 self.writeln(self.greyed('[No comment] ') + ' (at ' +
232 self.bold(path or '<root>') + ')')
233 self.unindent()
234
235 def print_file_info(self, file_name, except_owner=''):
236 if file_name not in self.unreviewed_files:
237 self.writeln(self.greyed(file_name +
238 ' (by ' +
239 self.bold_name(self.reviewed_by[file_name]) +
240 ')'))
241 else:
242 if len(self.files_to_owners[file_name]) <= 3:
243 other_owners = []
244 for ow in self.files_to_owners[file_name]:
245 if ow != except_owner:
246 other_owners.append(self.bold_name(ow))
247 self.writeln(file_name +
248 ' [' + (', '.join(other_owners)) + ']')
249 else:
250 self.writeln(file_name + ' [' +
251 self.bold(str(len(self.files_to_owners[file_name]))) +
252 ']')
253
254 def print_file_info_detailed(self, file_name):
255 self.writeln(file_name)
256 self.indent()
257 for ow in sorted(self.files_to_owners[file_name]):
258 if ow in self.deselected_owners:
259 self.writeln(self.bold_name(self.greyed(ow)))
260 elif ow in self.selected_owners:
261 self.writeln(self.bold_name(self.greyed(ow)))
262 else:
263 self.writeln(self.bold_name(ow))
264 self.unindent()
265
266 def print_owned_files_for(self, owner):
267 # Print owned files
268 self.print_comments(owner)
269 self.writeln(self.bold_name(owner) + ' owns ' +
270 str(len(self.owners_to_files[owner])) + ' file(s):')
271 self.indent()
272 for file_name in sorted(self.owners_to_files[owner]):
273 self.print_file_info(file_name, owner)
274 self.unindent()
275 self.writeln()
276
277 def list_owners(self, owners_queue):
278 if (len(self.owners_to_files) - len(self.deselected_owners) -
279 len(self.selected_owners)) > 3:
280 for ow in owners_queue:
281 if ow not in self.deselected_owners and ow not in self.selected_owners:
282 self.print_comments(ow)
283 else:
284 for ow in owners_queue:
285 if ow not in self.deselected_owners and ow not in self.selected_owners:
286 self.writeln()
287 self.print_owned_files_for(ow)
288
289 def list_files(self):
290 self.indent()
291 if len(self.unreviewed_files) > 5:
292 for file_name in sorted(self.unreviewed_files):
293 self.print_file_info(file_name)
294 else:
295 for file_name in self.unreviewed_files:
296 self.print_file_info_detailed(file_name)
297 self.unindent()
298
299 def pick_owner(self, ow):
300 # Allowing to omit domain suffixes
301 if ow not in self.owners_to_files:
302 if ow + self.email_postfix in self.owners_to_files:
303 ow += self.email_postfix
304
305 if ow not in self.owners_to_files:
306 self.writeln('You cannot pick ' + self.bold_name(ow) + ' manually. ' +
307 'It\'s an invalid name or not related to the change list.')
308 return False
309 elif ow in self.selected_owners:
310 self.writeln('You cannot pick ' + self.bold_name(ow) + ' manually. ' +
311 'It\'s already selected.')
312 return False
313 elif ow in self.deselected_owners:
314 self.writeln('You cannot pick ' + self.bold_name(ow) + ' manually.' +
315 'It\'s already unselected.')
316 return False
317
318 self.select_owner(ow)
319 return True
320
321 def print_result(self):
322 # Print results
323 self.writeln()
324 self.writeln()
325 self.writeln('** You selected these owners **')
326 self.writeln()
327 for owner in self.selected_owners:
328 self.writeln(self.bold_name(owner) + ':')
329 self.indent()
330 for file_name in sorted(self.owners_to_files[owner]):
331 self.writeln(file_name)
332 self.unindent()
333
334 def bold(self, text):
335 return self.COLOR_BOLD + text + self.COLOR_RESET
336
337 def bold_name(self, name):
338 return (self.COLOR_BOLD +
339 name.replace(self.email_postfix, '') + self.COLOR_RESET)
340
341 def greyed(self, text):
342 return self.COLOR_GREY + text + self.COLOR_RESET
343
344 def indent(self):
345 self.indentation += 1
346
347 def unindent(self):
348 self.indentation -= 1
349
350 def print_indent(self):
351 return ' ' * self.indentation
352
353 def writeln(self, text=''):
354 print self.print_indent() + text
355
356 def hr(self):
357 self.writeln('=====================')
358
359 def print_info(self, owner):
360 self.hr()
361 self.writeln(
362 self.bold(str(len(self.unreviewed_files))) + ' file(s) left.')
363 self.print_owned_files_for(owner)
364
365 def input_command(self, owner):
366 self.writeln('Add ' + self.bold_name(owner) + ' as your reviewer? ')
367 return raw_input(
368 '[yes/no/Defer/pick/files/owners/quit/restart]: ').lower()