-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit-deploy.py
352 lines (239 loc) · 8.78 KB
/
git-deploy.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
#!/usr/bin/python3
# pylint: disable=C0103, C0111
import os
import subprocess
import getpass
import argparse
import tempfile
import urllib.request
parser = argparse.ArgumentParser(description='Generate repository and branch for git-hooks')
parser.add_argument('path', help='Path for the git repository')
parser.add_argument('-o', '--origin', default='dev', help='Origin to use for the hint')
parser.add_argument('-b', '--branch', default='hooks', help='Branch for the hooks')
parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Set verbosity')
parser.add_argument('--git-user', default='GitBot', help='Username for the commit')
parser.add_argument('--git-email', default='gitbot@localhost', help='Email for the commit')
parser.add_argument('--git-msg', default='Initial config', help='Message for the commit')
parser.add_argument('--offline', action='store_true', default=False, help='Skip IP detecting')
args = parser.parse_args()
args.path = os.path.normpath(os.path.abspath(args.path))
# default config file
config = r'''
{
"*": {
"allow": true,
"work-tree": null,
"pre-message": null,
"post-message": null,
"timeout-message": null,
"timeout": null,
"exec": null
}
}
'''
# default pre-receive & post-receive handler
receive = r'''
#!/usr/bin/python3
import os, sys, json, shlex, subprocess
# loading the config file from the branch
try:
config = json.loads(open('hooks/custom/config.json').read())
# invalid config file
except json.JSONDecodeError as ex:
print('Config file is broken: ' + str(ex))
config = {}
# missing config file
except IOError as ex:
print('No config file found')
config = {}
def get_config(branch):
"""
Get the configuration for a branch.
"""
# default values
values = {
'allow': True,
'work-tree': None,
'pre-message': None,
'post-message': None,
'timeout-message': None,
'timeout': None,
'exec': None,
}
# load branch specific settings
if branch in config:
values.update(config[branch])
# load global settings
elif '*' in config:
values.update(config['*'])
return values
def git_checkout(path, branch):
"""
Checkout the branch to path.
"""
# cache is not allowed
os.system('unset GIT_INDEX_FILE')
os.makedirs(path, exist_ok = True)
# simulate a standard git checkout
# git will think we are checking out the same branch as before
open('HEAD', 'w').write('ref: refs/heads/%s\n' % branch)
cmd = ['git', '--work-tree=' + path, 'checkout', branch, '-f', '--quiet']
proc = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
proc.wait()
# keep the master as the main branch
open('HEAD', 'w').write('ref: refs/heads/master\n')
return proc.stdout.read().decode()
"""
git-hooks:
pre-receive:
This is called on the remote repo just before updating the pushed
refs. A non-zero status will abort the process. Although it receives
no parameters, it is passed a string through stdin in the form of
"<old-value> <new-value> <ref-name>" for each ref.
post-receive:
This is run on the remote when pushing after the all refs have been
updated. It does not take parameters, but receives info through stdin
in the form of "<old-value> <new-value> <ref-name>". Because it is
called after the updates, it cannot abort the process.
"""
lines = sys.stdin.read().splitlines()
script = sys.argv[0].split('/')[-1]
for line in lines:
old, new, ref = line.split()
branch = ref.split('/')[-1]
# check for the HOOKS_BRANCH branch
if branch == 'HOOKS_BRANCH':
git_checkout('hooks/custom', 'HOOKS_BRANCH')
continue
# load the config for the branch
cfg = get_config(branch)
# check if the the push is allowed
if script == 'pre-receive':
if cfg['pre-message']:
print(cfg['pre-message'])
if not cfg['allow']:
exit(1)
# check if we have post-receive task
if script == 'post-receive':
# message
if cfg['post-message']:
print(cfg['post-message'])
# checkout
if cfg['work-tree']:
message = git_checkout(cfg['work-tree'], branch)
if message:
print(message, end = '' if message.endswith('\n') else '\n')
# post-receive task
if cfg['exec']:
try:
if type(cfg['exec']) is str:
cfg['exec'] = shlex.split(cfg['exec'])
proc = subprocess.Popen(cfg['exec'], cwd = 'hooks/custom', stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
proc.wait(cfg['timeout'])
# process timed out
except subprocess.TimeoutExpired:
if cfg['timeout-message']:
print(cfg['timeout-message'])
proc.kill()
# process failed
except Exception as ex:
print(ex)
# print stdout
finally:
try:
stdout = proc.stdout.read().decode()
if stdout:
print(stdout, end = '' if stdout.endswith('\n') else '\n')
except:
pass
'''
# commands
name = 'user.name=' + args.git_user
email = 'user.email=' + args.git_email
branch_commands = [
['git', 'init', '--quiet'],
['git', 'add', 'config.json'],
['git', 'checkout', '-b', args.branch, '--quiet'],
['git', '-c', name, '-c', email, 'commit', '-m', args.git_msg, '--quiet'],
['git', 'remote', 'add', 'origin', args.path],
['git', 'push', 'origin', args.branch, '--quiet'],
]
hooks_commands = [
['ln', '-s', 'receive.py', 'pre-receive'],
['ln', '-s', 'receive.py', 'post-receive'],
['chmod', '755', 'pre-receive', 'post-receive'],
]
try:
cmd_join = subprocess.list2cmdline
except AttributeError:
def cmd_join(x):
return str(x)
def execute(cmd, cwd):
'''
Execute a command in a directory
'''
settings = {
'stderr': subprocess.STDOUT,
'stdout': subprocess.PIPE,
'cwd': cwd,
}
if args.verbose:
print('\033[97m%s\033[m' % cmd_join(cmd))
proc = subprocess.Popen(cmd, **settings)
proc.wait()
if args.verbose:
msg = proc.stdout.read().decode().strip('\n')
if msg:
print('\n' + msg)
if proc.returncode != 0:
print('\033[31mTask `%s` failed with %d errorcode\033[m' % (cmd_join(cmd), proc.returncode))
exit(1)
# initialize the repo
if os.path.exists(args.path):
if not os.path.exists(os.path.join(args.path, 'HEAD')):
print('\033[31m%s is probably not a git repository\033[m' % args.path)
exit(1)
if os.path.exists(os.path.join(args.path, 'refs', 'heads', args.branch)):
print('\033[31mBranch %s already exists\033[m' % args.branch)
exit(1)
else:
os.mkdir(args.path)
if args.verbose:
print('\nWorking in %s\n' % args.path)
execute(['git', 'init', '--bare', '--quiet'], args.path)
# initialize the branch
with tempfile.TemporaryDirectory() as temp:
if args.verbose:
print('\nWorking in %s\n' % temp)
open(os.path.join(temp, 'config.json'), 'w').write(config.strip('\n') + '\n')
for command in branch_commands:
execute(command, temp)
# initialize hooks
hooks = os.path.join(args.path, 'hooks')
open(os.path.join(hooks, 'receive.py'), 'w').write(receive.replace('HOOKS_BRANCH', args.branch).strip('\n') + '\n')
if args.verbose:
print('\nWorking in %s\n' % hooks)
for command in hooks_commands:
execute(command, hooks)
# checkout hooks
custom = os.path.join(hooks, 'custom')
if args.verbose:
print('\nWorking in %s\n' % args.path)
os.mkdir(custom)
open(os.path.join(args.path, 'HEAD'), 'w').write('ref: refs/heads/%s\n' % args.branch)
execute(['git', '--work-tree=' + custom, 'checkout', args.branch, '-f', '--quiet'], args.path)
open(os.path.join(args.path, 'HEAD'), 'w').write('ref: refs/heads/master\n')
# show the hints
if not args.offline:
host = urllib.request.urlopen('https://api.ipify.org').read().decode()
user = getpass.getuser()
short_path = os.path.relpath(args.path, os.path.expanduser('~'))
base_name = os.path.basename(short_path)
print('\n\n')
print('Add or set the remote url:')
print('\t\033[92mgit remote add %s %s@%s:%s\033[0m' % (args.origin, user, host, short_path))
print('\t\033[92mgit remote set-url %s %s@%s:%s\033[0m' % (args.origin, user, host, short_path))
print('\n')
print('Clone the %s branch:' % args.branch)
print('\t\033[92mgit clone -b %s %s@%s:%s %s-hooks\033[0m' % (args.branch, user, host, short_path, base_name))
print('\n\n')