forked from mrlesmithjr/python-gitlab-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitlab-management.py
More file actions
284 lines (244 loc) · 9.29 KB
/
gitlab-management.py
File metadata and controls
284 lines (244 loc) · 9.29 KB
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
#!/usr/bin/env python
"""Manage GitLab using Python."""
import argparse
from os.path import expanduser
import json
import yaml
import gitlab
__author__ = "Larry Smith Jr."
__email___ = "mrlesmithjr@gmail.com"
__maintainer__ = "Larry Smith Jr."
__status__ = "Development"
# http://everythingshouldbevirtual.com
# @mrlesmithjr
def main():
"""Main function."""
home = user_home()
args = parse_args(home)
gl = auth(args)
current_user = user_details(gl)
decide_action(args, current_user, gl)
def auth(args):
"""Authorize user."""
gl = gitlab.Gitlab(args.url, args.token, api_version=args.apiversion)
gl.auth()
return gl
def decide_action(args, current_user, gl):
"""Decide action to take based on positional arguments."""
if args.action == "get_all_groups":
get_all_groups(args, gl)
elif args.action == "get_group_details":
get_all_groups(args, gl)
elif args.action == "get_group_projects":
get_group_projects(args, gl)
elif args.action == "get_issues":
get_issues(args, gl)
elif args.action == "get_user_projects":
get_user_projects(args, gl, current_user)
elif args.action == "manage_runners":
manage_runners(args, gl)
elif args.action == "manage_ssh_keys":
ssh_keys(args, current_user)
def get_all_groups(args, gl):
"""Get all groups that exist in account."""
# Capture a list of groups
all_groups_list = gl.groups.list()
# Create an array to collect group(s) attributes
all_groups = []
# Iterate over list of groups
for group in all_groups_list:
group_attrs = group.attributes
if args.filter and args.action != "get_group_details":
if args.filter == "namesonly":
all_groups.append(group_attrs['name'])
else:
all_groups.append(group_attrs)
if args.action == "get_group_details":
get_group_details(all_groups, args, gl)
else:
# Check if output flag has been defined to print in either json or yaml
if args.output:
if args.output == "yaml":
print(yaml.dump(yaml.load(json.dumps(all_groups)),
default_flow_style=False))
elif args.output == "json":
print(json.dumps(all_groups, indent=4))
else:
if args.action != "get_group_projects":
print(all_groups)
return all_groups
def get_group_details(all_groups, args, gl):
"""Get group projects."""
for group in all_groups:
group_id = group['id']
group_attrs = gl.groups.get(group_id).attributes
# Check if output flag has been defined to print in either json or yaml
if args.output:
if args.output == "yaml":
print(yaml.dump(yaml.load(json.dumps(group_attrs)),
default_flow_style=False))
elif args.output == "json":
print(json.dumps(group_attrs, indent=4))
else:
print(gl.groups.get(group_id))
def get_group_projects(args, gl):
"""Get group based projects."""
groups_list = gl.groups.list()
groups_list = sorted(groups_list)
groups_projects = []
for group in groups_list:
group_projects = []
projects = group.projects.list(all=True)
for project in projects:
project_attrs = project.attributes
group_projects.append(project_attrs)
if group_projects != []:
groups_projects.append(group_projects)
# Check if output flag has been defined to print in either json or yaml
if args.output:
if args.output == "yaml":
print(yaml.dump(yaml.load(json.dumps(groups_projects)),
default_flow_style=False))
elif args.output == "json":
print(json.dumps(groups_projects, indent=4))
else:
print(groups_projects)
def get_issues(args, gl):
"""Get a list of issues."""
# Check if filter has been passed as an argument and
# set appropriately if so
if args.filter:
if args.filter == "closed":
issues = gl.issues.list(state="closed")
elif args.filter == "opened":
issues = gl.issues.list(state="opened")
else:
issues = gl.issues.list()
# Iterate over list of issues
for issue in issues:
issue_attrs = issue.attributes
# Check if output flag has been defined to print in either json or yaml
if args.output:
if args.output == "yaml":
print(yaml.dump(yaml.load(json.dumps(issue_attrs)),
default_flow_style=False))
elif args.output == "json":
print(json.dumps(issue_attrs, indent=4))
else:
print(issue_attrs)
def get_user_projects(args, gl, current_user):
"""Get users projects."""
# Defines users attributes
user_attrs = current_user.attributes
# Defines users user variable to use for capturing users projects
user_name = gl.users.list(
username=user_attrs['username'])[0]
# Captures users projects
projects = user_name.projects.list(all=True)
# Defines an array to collect all of users projects
user_projects = []
# Iterate over each of users projects
for project in projects:
project_attrs = project.attributes
if args.filter:
if args.filter == "namesonly":
user_projects.append(project_attrs['name'])
else:
user_projects.append(project_attrs)
user_projects = sorted(user_projects)
# Check if output flag has been defined to print in either json or yaml
if args.output:
if args.output == "yaml":
print(yaml.dump(yaml.load(json.dumps(user_projects)),
default_flow_style=False))
elif args.output == "json":
print(json.dumps(user_projects, indent=4))
else:
print(user_projects)
return user_projects
def manage_runners(args, gl):
"""Manage runners."""
# Captures all currently registered runners
runners_list = gl.runners.list()
# Defines an array to collect all runner details
runners = []
# Iterate over registered runners captured
for runner in runners_list:
runner_attrs = runner.attributes
runner_id = runner_attrs['id']
runner_details = gl.runners.get(runner_id)
runners.append(runner_details.attributes)
# Check if output flag has been defined to print in either json or yaml
if args.output:
if args.output == "yaml":
print(yaml.dump(yaml.load(json.dumps(runners)),
default_flow_style=False))
elif args.output == "json":
print(json.dumps(runners, indent=4))
else:
print(runners)
def parse_args(home):
"""Parse CLI arguments."""
parser = argparse.ArgumentParser(description="Manage GitLab via API.")
parser.add_argument("action", help="Define action to take.", choices=[
"get_all_groups", "get_group_details", "get_group_projects",
"get_issues", "get_user_projects", "manage_runners",
"manage_ssh_keys"])
parser.add_argument(
"--apiversion", help="Set the API version.", default="4",
choices=["3", "4"])
parser.add_argument(
"-f", "--filter", help="Filter output.",
choices=["closed", "namesonly", "opened"])
parser.add_argument(
"-o", "--output", help="Output format if desired.",
choices=["json", "yaml"])
parser.add_argument(
"--sshpubkey", help="Your SSH Key File",
default="%s/.ssh/id_rsa.pub" % home)
parser.add_argument("--token", help="Your GitLab API private token.")
parser.add_argument("--url", help="Your GitLab API Url.",
default="https://gitlab.com")
args = parser.parse_args()
return args
def ssh_keys(args, current_user):
"""Manage user ssh keys."""
try:
with open(args.sshpubkey, "r") as sshpubkey:
_sshpubkey_contents = sshpubkey.read()
_sshpubkey_found = True
except IOError:
print("%s file not found." % args.sshpubkey)
_sshpubkey_found = False
user_ssh_keys = current_user.keys.list()
if _sshpubkey_found is True:
_sshpubkey = _sshpubkey_contents.split()
if user_ssh_keys is not None:
matching_ssh_key_found = False
# Loop through existing SSH keys and try to find a match.
for key in user_ssh_keys:
_key = key.attributes['key'].split()
if "".join(_sshpubkey) == "".join(_key):
matching_ssh_key_found = True
break
else:
matching_ssh_key_found = False
print("Matching SSH key found: %s" % matching_ssh_key_found)
def user_details(gl):
"""Capture user details for various other usages."""
current_user = gl.user
user_attrs = current_user.attributes
user_id = user_attrs['id']
user_name = user_attrs['username']
user_web_url = user_attrs['web_url']
print("user_id: %s" % user_id)
print("user_name: %s" % user_name)
print("user_web_url: %s" % user_web_url)
print("\n")
return current_user
def user_home():
"""Capture users home directory."""
home = expanduser("~")
return home
if __name__ == "__main__":
main()