-
Notifications
You must be signed in to change notification settings - Fork 73
/
github_label_setup.py
executable file
·187 lines (162 loc) · 6.6 KB
/
github_label_setup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env python
"""
github_label_setup.py
===================
Python script to setup Issue Labels on GitHub Repositories.
Your GitHub API token should either be in your global (user) git config
as github.token, or in a GITHUB_TOKEN environment variable.
Takes configuration (currently in this script) of the labels you want on your
repos, or your org's. Makes it so. Has a dry-run mode.
Requirements
-------------
github3.py (`pip install github3.py`) >= 1.2.0
License
--------
Copyright 2015 Jason Antman <[email protected]> <http://www.jasonantman.com>
Free for any use provided that patches are submitted back to me.
The latest version of this script can be found at:
<https://github.com/jantman/misc-scripts/blob/master/github_label_setup.py>
CHANGELOG
----------
2018-12-02 Jason Antman <[email protected]>:
- Fix bug in handling of Archived repositories.
2018-02-18 Jason Antman <[email protected]>:
- Fix unicode error when reading token from git config under py3.
2018-02-15 Jason Antman <[email protected]>:
- fix bug in dryrun logic (not implemented at all)
- on exceptions adding label, log exception and continue
- add "stale" label
2015-11-25 Jason Antman <[email protected]>:
- initial version of script
"""
import sys
import argparse
import logging
import subprocess
import os
from github3 import login, GitHub
from pprint import pprint
FORMAT = "[%(levelname)s %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(level=logging.ERROR, format=FORMAT)
logger = logging.getLogger(__name__)
##################################
# configuration of labels to set #
##################################
LABELS = {}
# GitHub default labels
LABELS['bug'] = 'fc2929'
LABELS['duplicate'] = 'cccccc'
LABELS['enhancement'] = '84b6eb'
LABELS['invalid'] = 'e6e6e6'
LABELS['question'] = 'cc317c'
LABELS['wontfix'] = 'ffffff'
# custom labels
LABELS['discussion'] = 'c7def8'
LABELS['Docs'] = 'fbca04'
LABELS['help wanted'] = '159818'
LABELS['needs decision'] = 'fad8c7'
LABELS['testing'] = 'bfe5bf'
LABELS['unreleased fix'] = '0052cc'
LABELS['Waiting For Response'] = 'fef2c0'
LABELS['unsupported-repo'] = 'b60205'
LABELS['stale'] = 'f9d0c4'
#####################
# end configuration #
#####################
class GitHubLabelFixer:
def __init__(self, apitoken, orgname, dry_run=False):
""" init method, run at class creation """
self.dry_run = dry_run
logger.debug("Connecting to GitHub")
self.gh = login(token=apitoken)
logger.info("Connected to GitHub API")
self.me = self.gh.me()
self.orgname = orgname
if orgname is None:
# no orgname specified, so current user
self.orgname = self.me.login
def run(self):
"""iterate your repos and fix the labels"""
for repo in self.gh.repositories():
if repo.archived:
logger.debug('Skipping archived repo: %s', repo.full_name)
continue
labels = {}
colors = {}
if repo.owner.login != self.orgname:
logger.debug("Skipping %s", repo.full_name)
continue
for label in repo.labels():
labels[label.name] = label
colors[label.name] = label.color
logger.debug("%s labels: %s", repo.full_name, colors)
for name, color in LABELS.items():
if name not in labels:
try:
if self.dry_run:
res = True
print('Would add label %s (%s) to repo %s' % (
name, color, repo.full_name
))
else:
logger.info("Adding '%s' (%s) to %s",
name, color, repo.full_name)
res = repo.create_label(name, color)
if res is None:
logger.error("Error creating label %s on %s",
name, repo.full_name)
except Exception:
logger.error("Error creating label %s on %s",
name, repo.full_name, exc_info=True)
elif colors[name] != color:
if self.dry_run:
print("Would update '%s' on %s - color %s to %s" % (
name, repo.full_name, colors[name], color
))
else:
logger.info("Updating '%s' on %s - color %s to %s",
name, repo.full_name, colors[name], color)
res = labels[name].update(name, color)
if not res:
logger.error("Error updating color")
def parse_args(argv):
"""
parse arguments/options
this uses the new argparse module instead of optparse
see: <https://docs.python.org/2/library/argparse.html>
"""
p = argparse.ArgumentParser(description='Fix labels on GitHub Repos')
p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0,
help='verbose output. specify twice for debug-level output.')
p.add_argument('-d', '--dry-run', dest='dry_run', action='store_true',
default=False, help='List what changes would be made, but '
'do not make any.')
p.add_argument('-o', '--orgname', dest='orgname', action='store',
help='repository owner name, if different from login user',
default=None)
args = p.parse_args(argv)
return args
def get_api_token():
""" get GH api token """
apikey = subprocess.check_output(['git', 'config', '--global',
'github.token']).strip()
if isinstance(apikey, bytes):
apikey = apikey.decode()
if len(apikey) != 40:
raise SystemExit("ERROR: invalid github api token from `git config "
"--global github.token`: '%s'" % apikey)
return apikey
if __name__ == "__main__":
args = parse_args(sys.argv[1:])
if args.verbose > 1:
logger.setLevel(logging.DEBUG)
elif args.verbose > 0:
logger.setLevel(logging.INFO)
if 'GITHUB_TOKEN' in os.environ:
logger.debug('Using github token from GITHUB_TOKEN env var')
token = os.environ['GITHUB_TOKEN']
else:
logger.debug('Using github token from github.token in ~/.gitconfig')
token = get_api_token()
script = GitHubLabelFixer(token, args.orgname, dry_run=args.dry_run)
script.run()