-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGitLab_Sync.py
207 lines (162 loc) · 5.86 KB
/
GitLab_Sync.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
import sys
import ConfigParser
import json
import logging
import logging.handlers
import os
import gitlab
from git import Repo
config = None
logger = None
def start():
app_init()
process_args()
def app_init():
_init_conf()
_init_logs()
def _init_conf():
global config
config = ConfigParser.ConfigParser()
try:
config.read('configs/host.conf')
except Exception, e:
print "Failed to read base config file: {0}".format(str(e))
def _init_logs():
global logger
app_name = "GitLab-Sync"
try:
app_name = config.get('Host', 'app_name')
except Exception:
pass
logger = logging.getLogger(app_name)
logger.setLevel(logging.DEBUG)
# Write to file
handler = logging.handlers.RotatingFileHandler(app_name + '.log', maxBytes=10485760, backupCount=4)
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%d/%m/%Y %I:%M:%S'))
logger.addHandler(handler)
# Write to console
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',
'%d/%m/%Y %I:%M:%S'))
logger.addHandler(stream_handler)
def process_args():
args = sys.argv
act_type = None
for arg in args[1:]:
arg = arg.lower()
if 'config=' in arg:
config_dir = arg.replace('config=', '')
init_custom_conf(config_dir)
elif arg in ['repos', 'ignore', 'all', '*']:
act_type = arg
else:
print "Unsupported argument: " + arg
sys.exit(1)
action(act_type)
def init_custom_conf(path):
conf_path = os.path.join(path, 'host.conf')
if os.path.exists(conf_path):
try:
global config
config = ConfigParser.ConfigParser()
config.read(conf_path)
config.set('Host', 'conf_dir', path)
except Exception, e:
logger.error("Failed to read config: {0}".format(str(e)))
sys.exit(1)
else:
logger.error("'host.conf' no found at specified path: [{0}]".format(path))
sys.exit(1)
def action(act_type):
if act_type is None or act_type == '*' or act_type == 'all':
sync_all()
return
if act_type == 'repos':
sync_repos()
return
if act_type == 'ignore':
sync_all(True)
return
else:
print "Unknown argument, expected: [ No Arguments | all | * | repos | ignore]"
def sync_all(ignore=False):
ignored = []
if ignore:
ignored = get_ignores()
base_local_path = os.path.expanduser(config.get('Host', 'local_path'))
git_lab = gitlab.Gitlab(config.get('Host', 'gitlab_host'), config.get('Host', 'gitlab_secret_token'),
ssl_verify=config.getboolean('Host', 'gitlab_verify_ssl'))
for project in git_lab.projects.list(all=True):
if ignore:
if project.ssh_url_to_repo in ignored or project.http_url_to_repo in ignored:
continue
project_local_path = os.path.join(base_local_path, project.path_with_namespace)
if os.path.exists(project_local_path):
fetch(project_local_path)
else:
project_root = os.path.join(base_local_path, project.path_with_namespace)
if not os.path.exists(project_root):
os.makedirs(project_root)
is_ssh = (config.get('Host', 'connection_type').lower() == 'ssh')
remote_url = is_ssh and project.ssh_url_to_repo or project.http_url_to_repo
clone(project_root, remote_url)
logger.info("All Done")
def get_ignores():
ignore_json = 'configs/ignore.json'
try:
conf_dir = config.get('Host', 'conf_dir')
ignore_json = os.path.join(conf_dir, 'ignore.json')
except Exception:
pass
try:
with open(ignore_json) as f:
ignores = f.read()
return json.loads(ignores)
except Exception, e:
logger.error("Failed to read [ignore.json]. " + str(e))
sys.exit(1)
def clone(project_root, remote_url):
logger.info("Cloning: [{0}] to [{1}]".format(remote_url, project_root))
try:
Repo().clone_from(remote_url, project_root, git_progress_handler)
except Exception, e:
logger.error("Failed to clone from: {0}. Exception: {1}".format(remote_url, str(e)))
def fetch(project_local_path):
logger.info("Fetching: [" + project_local_path + "]")
try:
Repo(project_local_path).git.fetch('--all')
except Exception, e:
logger.error("Failed to fetch all. Exception: {0}".format(str(e)))
def git_progress_handler(op_code, cur_count, max_count=None, message=''):
if message:
logger.info("Message: {0}".format(message))
def sync_repos():
repos = get_repos()
for dir_name in repos:
dir_name_expand = os.path.expanduser(dir_name)
for remote_url in repos[dir_name]:
url_split_path = remote_url.split('/')
project_name = url_split_path[len(url_split_path) - 1].split('.')[0]
group_name = url_split_path[len(url_split_path) - 2]
full_project_path = os.path.join(dir_name_expand, group_name, project_name)
if os.path.exists(full_project_path):
fetch(full_project_path)
else:
clone(full_project_path, remote_url)
logger.info("All Done")
def get_repos():
repos_json = 'configs/repos.json'
try:
conf_dir = config.get('Host', 'conf_dir')
repos_json = os.path.join(conf_dir, 'repos.json')
except Exception:
pass
try:
with open(repos_json) as f:
repos = f.read()
return json.loads(repos)
except Exception, e:
logger.error("Failed to read [repos.json]. " + str(e))
sys.exit(1)
if __name__ == '__main__':
start()