repo_check.py 4.53 KB
Newer Older
1
2
3
4
5
6
7
8
#!/usr/bin/env python

"""
Check repository settings.
"""

import sys
import os
Greg Wilson's avatar
Greg Wilson committed
9
from subprocess import Popen, PIPE
10
11
12
13
14
15
16
17
18
19
20
21
22
import re
from optparse import OptionParser

from util import Reporter, load_yaml, require

# Import this way to produce a more useful error message.
try:
    import requests
except ImportError:
    print('Unable to import requests module: please install requests', file=sys.stderr)
    sys.exit(1)


Greg Wilson's avatar
Greg Wilson committed
23
24
25
26
27
28
29
# Pattern to match Git command-line output for remotes => (user name, project name).
P_GIT_REMOTE = re.compile(r'upstream\s+[^:]+:([^/]+)/([^.]+)\.git\s+\(fetch\)')

# Repository URL format string.
F_REPO_URL = 'https://github.com/{0}/{1}/'

# Pattern to match repository URLs => (user name, project name)
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
P_REPO_URL = re.compile(r'https?://github\.com/([^.]+)/([^/]+)/?')

# API URL format string.
F_API_URL = 'https://api.github.com/repos/{0}/{1}/labels'

# Expected labels and colors.
EXPECTED = {
    'bug' : 'bd2c00',
    'discussion' : 'fc8dc1',
    'enhancement' : '9cd6dc',
    'help-wanted' : 'f4fd9c',
    'instructor-training' : '6e5494',
    'newcomer-friendly' : 'eec275',
    'question' : '808040',
    'template-and-tools' : '2b3990',
    'work-in-progress' : '7ae78e'
}


def main():
    """
    Main driver.
    """

    args = parse_args()
    reporter = Reporter()
Greg Wilson's avatar
Greg Wilson committed
56
    repo_url = get_repo_url(args.source_dir, args.repo_url)
57
58
59
60
61
62
63
64
65
66
    check_labels(reporter, repo_url)
    reporter.report()


def parse_args():
    """
    Parse command-line arguments.
    """

    parser = OptionParser()
Greg Wilson's avatar
Greg Wilson committed
67
68
69
70
    parser.add_option('-r', '--repo',
                      default=None,
                      dest='repo_url',
                      help='repository URL')
71
72
73
74
75
76
77
78
79
80
81
82
    parser.add_option('-s', '--source',
                      default=os.curdir,
                      dest='source_dir',
                      help='source directory')

    args, extras = parser.parse_args()
    require(not extras,
            'Unexpected trailing command-line arguments "{0}"'.format(extras))

    return args


Greg Wilson's avatar
Greg Wilson committed
83
def get_repo_url(source_dir, repo_url):
84
85
86
87
    """
    Figure out which repository to query.
    """

Greg Wilson's avatar
Greg Wilson committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
    # Explicitly specified.
    if repo_url is not None:
        return repo_url

    # Guess.
    cmd = 'git remote -v'
    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True, universal_newlines=True)
    stdout_data, stderr_data = p.communicate()
    stdout_data = stdout_data.split('\n')
    matches = [P_GIT_REMOTE.match(line) for line in stdout_data]
    matches = [m for m in matches if m is not None]
    require(len(matches) == 1,
            'Unexpected output from git remote command: "{0}"'.format(matches))

    username = matches[0].group(1)
    require(username, 'empty username in git remote output {0}'.format(matches[0]))

    project_name = matches[0].group(2)
    require(username, 'empty project name in git remote output {0}'.format(matches[0]))
107

Greg Wilson's avatar
Greg Wilson committed
108
109
    url = F_REPO_URL.format(username, project_name)
    return url
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165


def check_labels(reporter, repo_url):
    """
    Check labels in repository.
    """

    actual = get_labels(repo_url)
    extra = set(actual.keys()) - set(EXPECTED.keys())

    reporter.check(not extra,
                   None,
                   'Extra label(s) in repository {0}: {1}',
                   repo_url, ', '.join(sorted(extra)))

    missing = set(EXPECTED.keys()) - set(actual.keys())
    reporter.check(not missing,
                   None,
                   'Missing label(s) in repository {0}: {1}',
                   repo_url, ', '.join(sorted(missing)))

    overlap = set(EXPECTED.keys()).intersection(set(actual.keys()))
    for name in sorted(overlap):
        reporter.check(EXPECTED[name] == actual[name],
                       None,
                       'Color mis-match for label {0} in {1}: expected {2}, found {3}',
                       name, repo_url, EXPECTED[name], actual[name])


def get_labels(repo_url):
    """
    Get actual labels from repository.
    """

    m = P_REPO_URL.match(repo_url)
    require(m, 'repository URL {0} does not match expected pattern'.format(repo_url))

    username = m.group(1)
    require(username, 'empty username in repository URL {0}'.format(repo_url))

    project_name = m.group(2)
    require(username, 'empty project name in repository URL {0}'.format(repo_url))

    url = F_API_URL.format(username, project_name)
    r = requests.get(url)
    require(r.status_code == 200,
            'Request for {0} failed with {1}'.format(url, r.status_code))

    result = {}
    for entry in r.json():
        result[entry['name']] = entry['color']
    return result


if __name__ == '__main__':
    main()