forked from llvm/llvm-project
- Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathpre-push.py
executable file
·221 lines (177 loc) · 6.81 KB
/
pre-push.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
#!/usr/bin/env python3
#
# ======- pre-push - LLVM Git Help Integration ---------*- python -*--========#
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# ==------------------------------------------------------------------------==#
"""
pre-push git hook integration
=============================
This script is intended to be setup as a pre-push hook, from the root of the
repo run:
ln -sf ../../llvm/utils/git/pre-push.py .git/hooks/pre-push
From the git doc:
The pre-push hook runs during git push, after the remote refs have been
updated but before any objects have been transferred. It receives the name
and location of the remote as parameters, and a list of to-be-updated refs
through stdin. You can use it to validate a set of ref updates before a push
occurs (a non-zero exit code will abort the push).
"""
importargparse
importcollections
importos
importre
importshutil
importsubprocess
importsys
importtime
importgetpass
fromshleximportquote
VERBOSE=False
QUIET=False
dev_null_fd=None
z40='0000000000000000000000000000000000000000'
defeprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
deflog(*args, **kwargs):
ifQUIET:
return
print(*args, **kwargs)
deflog_verbose(*args, **kwargs):
ifnotVERBOSE:
return
print(*args, **kwargs)
defdie(msg):
eprint(msg)
sys.exit(1)
defask_confirm(prompt):
whileTrue:
query=input('%s (y/N): '% (prompt))
ifquery.lower() notin ['y', 'n', '']:
print('Expect y or n!')
continue
returnquery.lower() =='y'
defget_dev_null():
"""Lazily create a /dev/null fd for use in shell()"""
globaldev_null_fd
ifdev_null_fdisNone:
dev_null_fd=open(os.devnull, 'w')
returndev_null_fd
defshell(cmd, strip=True, cwd=None, stdin=None, die_on_failure=True,
ignore_errors=False, text=True, print_raw_stderr=False):
# Escape args when logging for easy repro.
quoted_cmd= [quote(arg) forargincmd]
cwd_msg=''
ifcwd:
cwd_msg=' in %s'%cwd
log_verbose('Running%s: %s'% (cwd_msg, ' '.join(quoted_cmd)))
err_pipe=subprocess.PIPE
ifignore_errors:
# Silence errors if requested.
err_pipe=get_dev_null()
start=time.time()
p=subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=err_pipe,
stdin=subprocess.PIPE,
universal_newlines=text)
stdout, stderr=p.communicate(input=stdin)
elapsed=time.time() -start
log_verbose('Command took %0.1fs'%elapsed)
ifp.returncode==0orignore_errors:
ifstderrandnotignore_errors:
ifnotprint_raw_stderr:
eprint('`%s` printed to stderr:'%' '.join(quoted_cmd))
eprint(stderr.rstrip())
ifstrip:
iftext:
stdout=stdout.rstrip('\r\n')
else:
stdout=stdout.rstrip(b'\r\n')
ifVERBOSE:
forlinstdout.splitlines():
log_verbose('STDOUT: %s'%l)
returnstdout
err_msg='`%s` returned %s'% (' '.join(quoted_cmd), p.returncode)
eprint(err_msg)
ifstderr:
eprint(stderr.rstrip())
ifdie_on_failure:
sys.exit(2)
raiseRuntimeError(err_msg)
defgit(*cmd, **kwargs):
returnshell(['git'] +list(cmd), **kwargs)
defget_revs_to_push(range):
commits=git('rev-list', range).splitlines()
# Reverse the order so we print the oldest commit first
commits.reverse()
returncommits
defhandle_push(args, local_ref, local_sha, remote_ref, remote_sha):
'''Check a single push request (which can include multiple revisions)'''
log_verbose('Handle push, reproduce with '
'`echo %s %s %s %s | pre-push.py %s %s'
% (local_ref, local_sha, remote_ref, remote_sha, args.remote,
args.url))
# Handle request to delete
iflocal_sha==z40:
ifnotask_confirm('Are you sure you want to delete "%s" on remote "%s"?'% (remote_ref, args.url)):
die("Aborting")
return
# Push a new branch
ifremote_sha==z40:
ifnotask_confirm('Are you sure you want to push a new branch/tag "%s" on remote "%s"?'% (remote_ref, args.url)):
die("Aborting")
range=local_sha
return
else:
# Update to existing branch, examine new commits
range='%s..%s'% (remote_sha, local_sha)
# Check that the remote commit exists, otherwise let git proceed
if"commit"notingit('cat-file','-t', remote_sha, ignore_errors=True):
return
revs=get_revs_to_push(range)
ifnotrevs:
# This can happen if someone is force pushing an older revision to a branch
return
# Print the revision about to be pushed commits
print('Pushing to "%s" on remote "%s"'% (remote_ref, args.url))
forshainrevs:
print(' - '+git('show', '--oneline', '--quiet', sha))
iflen(revs) >1:
ifnotask_confirm('Are you sure you want to push %d commits?'%len(revs)):
die('Aborting')
forshainrevs:
msg=git('log', '--format=%B', '-n1', sha)
if'Differential Revision'notinmsg:
continue
forlineinmsg.splitlines():
fortagin ['Summary', 'Reviewers', 'Subscribers', 'Tags']:
ifline.startswith(tag+':'):
eprint('Please remove arcanist tags from the commit message (found "%s" tag in %s)'% (tag, sha[:12]))
iflen(revs) ==1:
eprint('Try running: llvm/utils/git/arcfilter.sh')
die('Aborting (force push by adding "--no-verify")')
return
if__name__=='__main__':
ifnotshutil.which('git'):
die('error: cannot find git command')
argv=sys.argv[1:]
p=argparse.ArgumentParser(
prog='pre-push', formatter_class=argparse.RawDescriptionHelpFormatter,
description=__doc__)
verbosity_group=p.add_mutually_exclusive_group()
verbosity_group.add_argument('-q', '--quiet', action='store_true',
help='print less information')
verbosity_group.add_argument('-v', '--verbose', action='store_true',
help='print more information')
p.add_argument('remote', type=str, help='Name of the remote')
p.add_argument('url', type=str, help='URL for the remote')
args=p.parse_args(argv)
VERBOSE=args.verbose
QUIET=args.quiet
lines=sys.stdin.readlines()
sys.stdin=open('/dev/tty', 'r')
forlineinlines:
local_ref, local_sha, remote_ref, remote_sha=line.split()
handle_push(args, local_ref, local_sha, remote_ref, remote_sha)