-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglab-dev-env-setup.py
298 lines (244 loc) · 8.31 KB
/
glab-dev-env-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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CHAOSS
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
# Venu Vardhan Reddy Tekula <[email protected]>
#
import logging
import os
import os.path
import sys
import argparse
from argparse import RawTextHelpFormatter
from subprocess import call
import git.repo.base as grb
from github import Github, BadCredentialsException, GithubException
REPOS = [
"chaoss/grimoirelab-sirmordred",
"chaoss/grimoirelab-elk",
"chaoss/grimoirelab-kingarthur",
"chaoss/grimoirelab-graal",
"chaoss/grimoirelab-perceval",
"chaoss/grimoirelab-perceval-mozilla",
"chaoss/grimoirelab-perceval-opnfv",
"chaoss/grimoirelab-perceval-puppet",
"chaoss/grimoirelab-perceval-weblate",
"Bitergia/grimoirelab-perceval-finos",
"chaoss/grimoirelab-sortinghat",
"chaoss/grimoirelab-sigils",
"chaoss/grimoirelab-kidash",
"chaoss/grimoirelab-toolkit",
"chaoss/grimoirelab-cereslib",
"chaoss/grimoirelab-manuscripts"
]
GITHUB_URL = "https://github.com/"
CHECK_REMOTES_CMD = ['git', 'remote', '-v']
CHECKOUT_MASTER_CMD = ['git', 'checkout', 'master']
FETCH_UPSTREAM_CMD = ['git', 'fetch', 'upstream']
REBASE_UPSTREAM_CMD = ['git', 'rebase', 'upstream/master']
LOG_FORMAT = "[%(asctime)s] - %(message)s"
DEBUG_LOG_FORMAT = "[%(asctime)s - %(name)s - %(levelname)s] - %(message)s"
def configure_logging(debug):
"""
Configure logging.
This function sets basic attributes for logging.
:param debug: set the debug mode
"""
if not debug:
logging.basicConfig(level=logging.INFO,
format=LOG_FORMAT)
else:
logging.basicConfig(level=logging.DEBUG,
format=DEBUG_LOG_FORMAT)
def parse_args():
"""
Setup command line argument parsing with argparse.
"""
parser = argparse.ArgumentParser(
description="glab-dev-env-setup script argument parser",
formatter_class=RawTextHelpFormatter
)
parser.add_argument("-t", "--token",
required=True,
help="GitHub API Token\n\n")
parser.add_argument("-s", "--source",
default="sources",
help="folder of the dev env\n\n")
parser.add_argument("-d", "--debug",
action='store_true',
help="set debug mode for logging\n\n")
parser.add_argument("-u", "--update",
action='store_true',
help="update the forks.\n\n")
parser.add_argument("-c", "--create",
action='store_true',
help="create the repositories.\n\n")
return parser.parse_args()
def check_token(token):
"""
Verify token.
This function checks if the token is valid.
:param token: github personal access token
:returns g: GitHub auth object
"""
logging.info("checking the access token")
g = Github(token)
try:
user = g.get_user()
logging.info("access token is working, " + user.login)
return g
except BadCredentialsException as e:
logging.error("invalid token: " + str(e))
exit()
except Exception as e:
logging.error("exiting: " + str(e))
exit()
def move_into_folder(folder):
"""
Change the directory.
This function changes the working directory.
:param folder: required folder name
"""
req_path = os.path.join(os.getcwd(), folder)
if os.path.isdir(req_path):
logging.info("moving into " + req_path)
else:
logging.info("folder not existing, creating new " + req_path)
os.mkdir(req_path)
os.chdir(req_path)
def fork(user, repo):
"""
Fork the repository.
:param user: user
:param repo: repository
"""
try:
logging.info("forking the repository " + repo.name + " to " + user.login)
user.create_fork(repo)
except GithubException as e:
logging.error("forking aborted.")
logging.error("please select the appropriate scope (`repo`) for the token: " + str(e))
exit()
def clone_upstream(user, org, repo):
"""
Clone and set upstream for the repository.
:param user: user
:param org: organization
:param repo: repository
"""
try:
logging.info("cloning the forked repository " + repo.name)
local_repo = grb.Repo.clone_from(GITHUB_URL + user.login + "/" + repo.name + ".git",
"{0}/{1}".format(os.getcwd(), repo.name), branch="master")
logging.info("adding the `upstream` remote")
grb.Repo.create_remote(local_repo, "upstream", GITHUB_URL + org.login + "/" + repo.name + ".git")
except grb.GitCommandError:
logging.info("folder already exists and is not empty, cloning aborted")
pass
def check_remote():
"""
Check the remote of the repository.
"""
logging.info("checking remotes")
call(CHECK_REMOTES_CMD)
def sync():
"""
Update the forks.
This function fetched the upstream remote and
updates the master branch of the repository.
"""
try:
logging.info("fetching upstream")
call(FETCH_UPSTREAM_CMD)
logging.info("changing branch to master")
call(CHECKOUT_MASTER_CMD)
logging.info("rebasing")
call(REBASE_UPSTREAM_CMD)
except Exception as e:
logging.error(str(e))
exit()
def update(source):
"""
Updates the forks.
This function iterates through the repositories and
updates them to the latest fork.
:param source: dev env folder
"""
logging.info("updating the forks")
curr_path = os.getcwd()
for item in REPOS:
move_into_folder(curr_path + "/" + source)
org, repo = item.split("/")
move_into_folder(repo)
sync()
def create(g, source):
"""
Creates the folder with all 15 repositories.
This function iterates through the repositories and
fork, clone and sets the upstream in each of the
repository.
:param g: GitHub auth object
:param source: dev env folder
"""
logging.info("setting up the repositories")
curr_path = os.getcwd()
user = g.get_user()
for item in REPOS:
move_into_folder(curr_path + "/" + source)
org, repo = item.split("/")
org = g.get_organization(org)
repo = org.get_repo(repo)
fork(user, repo)
clone_upstream(user, org, repo)
move_into_folder(repo.name)
check_remote()
def main():
"""
A script for automating the process the setting up the development
environment for GrimoireLab.
The script can be run via the command line:
$ python3 glab-dev-env-setup.py -c -t xxxx
Examples:
--------
* Create a folder `sources` with all the 15 GrimoireLab
components forked, cloned and setting their upstream link
using the GitHub API token xxxx:
$ python3 glab-dev-env-setup.py --create --token xxxx --source sources
* Update the existing forks present in the `sources` folder
with the latest changes using the GitHub API token xxxx:
$ python3 glab-dev-env-setup.py --update --token xxxx --source sources
"""
args = parse_args()
token = str(args.token)
source = str(args.source) if args.source else "sources"
configure_logging(args.debug)
g = check_token(token)
if args.create:
create(g, source)
elif args.update:
update(source)
else:
logging.error("select any method, --create or --update")
return
if __name__ == '__main__':
try:
main()
logging.info("done!")
except KeyboardInterrupt:
sys.stderr.write("\n\nReceived Ctrl-C or other break signal. Exiting.\n")
sys.exit(0)