-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgitlab_email_list.py
executable file
·141 lines (108 loc) · 4.29 KB
/
gitlab_email_list.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
#!/usr/bin/env python
"""
gitlab_email_list.py
====================
Dump a list of all GitLab user email addresses.
If you have ideas for improvements, or want the latest version, it's at:
<https://github.com/jantman/gitlab-scripts/blob/master/gitlab_email_list.py>
Usage
-----
1. Export your GitLab Private API token as GITLAB_TOKEN, or you will be prompted
for it interactively.
2. Run the script:
gitlab_email_list.py http://gitlab.example.com
Requirements
-------------
python-gitlab (tested with 0.9.2; `pip install python-gitlab`)
WARNING - Note that per https://github.com/gpocentek/python-gitlab/issues/63
python-gitlab 0.9.2 doesn't handle paginated responses, so it will silently
disregard anything past the 20th result.
Copyright and License
----------------------
Copyright 2015 Jason Antman <[email protected]> <http://www.jasonantman.com>
This file is part of gitlab-scripts.
gitlab-scripts 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.
gitlab-scripts 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 gitlab-scripts. If not, see <http://www.gnu.org/licenses/>.
Changelog
----------
2015-07-28 Jason Antman <[email protected]>:
- initial version of script
"""
import sys
import argparse
import logging
import gitlab
import os
import json
FORMAT = "[%(levelname)s %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)
logger = logging.getLogger()
# suppress requests internal logging
requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.WARNING)
requests_log.propagate = True
gitlab_log = logging.getLogger("gitlab")
gitlab_log.setLevel(logging.WARNING)
gitlab_log.propagate = True
class GitLabEmailList:
"""sync local ssh authorized_keys to GitLab"""
def __init__(self, url, apikey):
"""connect to GitLab"""
logger.debug("Connecting to GitLab")
self.conn = gitlab.Gitlab(url, apikey)
self.conn.auth()
logger.info("Connected to GitLab as %s",
self.conn.user.username)
def run(self, out_format):
"""main entry point"""
logger.debug("Getting users...")
result = self.conn.User()
logger.debug("Got users")
logger.info("Found %d users", len(result))
users = {}
for user in result:
users[user.id] = user.email
if out_format == 'json':
print(json.dumps(users, sort_keys=True, indent=4))
return
if out_format == 'csv':
print(', '.join(sorted(users.values())))
return
for u in sorted(users.values()):
print(u)
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='Dump list of GitLab user emails ')
p.add_argument('-v', '--verbose', dest='verbose', action='store_true',
default=False,
help='verbose output')
p.add_argument('-f', '--format', dest='out_format', action='store', type=str,
default='list', choices=['list', 'csv', 'json'],
help="output format; one of: 'list' (one email per line), "
"'json' (JSON of user ID to email), 'csv' (CSV email addresses)")
p.add_argument('gitlab_url', action='store',
help='URL to GitLab instance')
args = p.parse_args(argv)
return args
def get_api_key():
if 'GITLAB_TOKEN' in os.environ:
return os.environ['GITLAB_TOKEN']
return raw_input("Enter your GitLab Private API token: ")
if __name__ == "__main__":
args = parse_args(sys.argv[1:])
if args.verbose:
logger.setLevel(logging.DEBUG)
syncer = GitLabEmailList(args.gitlab_url, get_api_key())
syncer.run(args.out_format)