1# Copyright 2014 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
5import re
6import urllib2
7
8# This is based on code from:
9# https://chromium.googlesource.com/chromium/tools/build/+/master/scripts/tools/blink_roller/auto_roll.py
10# Ideally we should share code between these.
11
12# FIXME: This probably belongs in config.py?
13BLINK_SHERIFF_URL = (
14    'http://build.chromium.org/p/chromium.webkit/sheriff_webkit.js')
15
16
17# Does not support unicode or special characters.
18VALID_EMAIL_REGEXP = re.compile(r'^[A-Za-z0-9\.&\'\+-/=_]+@[A-Za-z0-9\.-]+$')
19
20
21def _complete_email(name):
22    """If the name does not include '@', append '@chromium.org'."""
23    if '@' not in name:
24        return name + '@chromium.org'
25    return name
26
27
28def _names_from_sheriff_js(sheriff_js):
29    match = re.match(r'document.write\(\'(.*)\'\)', sheriff_js)
30    emails_string = match.group(1)
31    # Detect 'none (channel is sheriff)' text and ignore it.
32    if 'channel is sheriff' in emails_string.lower():
33        return []
34    return map(str.strip, emails_string.split(','))
35
36
37def _email_is_valid(email):
38    """Determines whether the given email address is valid."""
39    return VALID_EMAIL_REGEXP.match(email) is not None
40
41
42def _filter_emails(emails):
43    """Returns the given list with any invalid email addresses removed."""
44    rv = []
45    for email in emails:
46        if _email_is_valid(email):
47            rv.append(email)
48        else:
49            print 'WARNING: Not including %s (invalid email address)' % email
50    return rv
51
52
53def _emails_from_url(sheriff_url):
54    sheriff_js = urllib2.urlopen(sheriff_url).read()
55    return map(_complete_email, _names_from_sheriff_js(sheriff_js))
56
57
58def current_gardener_emails():
59    return _emails_from_url(BLINK_SHERIFF_URL)
60