blob: 975b8480601b2cf666d300c96bfe0392f9a377f4 [file] [log] [blame]
Mehdi Amini7b484632016-11-07 20:00:47 +00001#!/usr/bin/env python
2#
3# ======- git-llvm - LLVM Git Help Integration ---------*- python -*--========#
4#
5# The LLVM Compiler Infrastructure
6#
7# This file is distributed under the University of Illinois Open Source
8# License. See LICENSE.TXT for details.
9#
10# ==------------------------------------------------------------------------==#
11
12"""
13git-llvm integration
14====================
15
16This file provides integration for git.
17"""
18
19from __future__ import print_function
20import argparse
21import collections
22import contextlib
23import errno
24import os
25import re
26import subprocess
27import sys
28import tempfile
29import time
30assert sys.version_info >= (2, 7)
31
32
33# It's *almost* a straightforward mapping from the monorepo to svn...
34GIT_TO_SVN_DIR = {
35 d: (d + '/trunk')
36 for d in [
37 'clang-tools-extra',
38 'compiler-rt',
39 'dragonegg',
40 'klee',
41 'libclc',
42 'libcxx',
43 'libcxxabi',
44 'lld',
45 'lldb',
46 'llvm',
47 'polly',
48 ]
49}
50GIT_TO_SVN_DIR.update({'clang': 'cfe/trunk'})
51
52VERBOSE = False
53QUIET = False
Reid Kleckner45340972017-04-24 22:09:08 +000054dev_null_fd = None
Mehdi Amini7b484632016-11-07 20:00:47 +000055
56
57def eprint(*args, **kwargs):
58 print(*args, file=sys.stderr, **kwargs)
59
60
61def log(*args, **kwargs):
62 if QUIET:
63 return
64 print(*args, **kwargs)
65
66
67def log_verbose(*args, **kwargs):
68 if not VERBOSE:
69 return
70 print(*args, **kwargs)
71
72
73def die(msg):
74 eprint(msg)
75 sys.exit(1)
76
77
78def first_dirname(d):
79 while True:
80 (head, tail) = os.path.split(d)
81 if not head or head == '/':
82 return tail
83 d = head
84
85
Reid Kleckner45340972017-04-24 22:09:08 +000086def get_dev_null():
87 """Lazily create a /dev/null fd for use in shell()"""
88 global dev_null_fd
89 if dev_null_fd is None:
90 dev_null_fd = open(os.devnull, 'w')
91 return dev_null_fd
92
93
94def shell(cmd, strip=True, cwd=None, stdin=None, die_on_failure=True,
95 ignore_errors=False):
Mehdi Amini7b484632016-11-07 20:00:47 +000096 log_verbose('Running: %s' % ' '.join(cmd))
97
Reid Kleckner45340972017-04-24 22:09:08 +000098 err_pipe = subprocess.PIPE
99 if ignore_errors:
100 # Silence errors if requested.
101 err_pipe = get_dev_null()
102
Mehdi Amini7b484632016-11-07 20:00:47 +0000103 start = time.time()
Reid Kleckner45340972017-04-24 22:09:08 +0000104 p = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=err_pipe,
105 stdin=subprocess.PIPE)
Mehdi Amini7b484632016-11-07 20:00:47 +0000106 stdout, stderr = p.communicate(input=stdin)
107 elapsed = time.time() - start
108
109 log_verbose('Command took %0.1fs' % elapsed)
110
Reid Kleckner45340972017-04-24 22:09:08 +0000111 if p.returncode == 0 or ignore_errors:
112 if stderr and not ignore_errors:
Mehdi Amini7b484632016-11-07 20:00:47 +0000113 eprint('`%s` printed to stderr:' % ' '.join(cmd))
114 eprint(stderr.rstrip())
115 if strip:
116 stdout = stdout.rstrip('\r\n')
117 return stdout
Mehdi Aminifbd26852016-11-12 01:17:59 +0000118 err_msg = '`%s` returned %s' % (' '.join(cmd), p.returncode)
119 eprint(err_msg)
Mehdi Amini7b484632016-11-07 20:00:47 +0000120 if stderr:
121 eprint(stderr.rstrip())
Mehdi Aminifbd26852016-11-12 01:17:59 +0000122 if die_on_failure:
123 sys.exit(2)
124 raise RuntimeError(err_msg)
Mehdi Amini7b484632016-11-07 20:00:47 +0000125
126
127def git(*cmd, **kwargs):
128 return shell(['git'] + list(cmd), kwargs.get('strip', True))
129
130
131def svn(cwd, *cmd, **kwargs):
132 # TODO: Better way to do default arg when we have *cmd?
Reid Kleckner45340972017-04-24 22:09:08 +0000133 return shell(['svn'] + list(cmd), cwd=cwd, stdin=kwargs.get('stdin', None),
134 ignore_errors=kwargs.get('ignore_errors', None))
Mehdi Amini7b484632016-11-07 20:00:47 +0000135
Rui Ueyama2f8db1d2017-05-23 21:50:40 +0000136def program_exists(cmd):
Zachary Turnerdc4cbc02017-05-24 00:28:46 +0000137 if sys.platform == 'win32' and not cmd.endswith('.exe'):
138 cmd += '.exe'
Rui Ueyama2f8db1d2017-05-23 21:50:40 +0000139 for path in os.environ["PATH"].split(os.pathsep):
140 if os.access(os.path.join(path, cmd), os.X_OK):
141 return True
142 return False
Mehdi Amini7b484632016-11-07 20:00:47 +0000143
144def get_default_rev_range():
145 # Get the branch tracked by the current branch, as set by
146 # git branch --set-upstream-to See http://serverfault.com/a/352236/38694.
147 cur_branch = git('rev-parse', '--symbolic-full-name', 'HEAD')
148 upstream_branch = git('for-each-ref', '--format=%(upstream:short)',
149 cur_branch)
150 if not upstream_branch:
151 upstream_branch = 'origin/master'
152
153 # Get the newest common ancestor between HEAD and our upstream branch.
154 upstream_rev = git('merge-base', 'HEAD', upstream_branch)
155 return '%s..' % upstream_rev
156
157
158def get_revs_to_push(rev_range):
159 if not rev_range:
160 rev_range = get_default_rev_range()
161 # Use git show rather than some plumbing command to figure out which revs
162 # are in rev_range because it handles single revs (HEAD^) and ranges
163 # (foo..bar) like we want.
164 revs = git('show', '--reverse', '--quiet',
165 '--pretty=%h', rev_range).splitlines()
166 if not revs:
167 die('Nothing to push: No revs in range %s.' % rev_range)
168 return revs
169
170
171def clean_and_update_svn(svn_repo):
172 svn(svn_repo, 'revert', '-R', '.')
173
174 # Unfortunately it appears there's no svn equivalent for git clean, so we
175 # have to do it ourselves.
176 for line in svn(svn_repo, 'status').split('\n'):
177 if not line.startswith('?'):
178 continue
179 filename = line[1:].strip()
180 os.remove(os.path.join(svn_repo, filename))
181
182 svn(svn_repo, 'update', *list(GIT_TO_SVN_DIR.values()))
183
184
185def svn_init(svn_root):
186 if not os.path.exists(svn_root):
187 log('Creating svn staging directory: (%s)' % (svn_root))
188 os.makedirs(svn_root)
Rui Ueyama62839f02016-12-20 05:49:56 +0000189 log('This is a one-time initialization, please be patient for a few'
Mehdi Amini7b484632016-11-07 20:00:47 +0000190 ' minutes...')
191 svn(svn_root, 'checkout', '--depth=immediates',
192 'https://llvm.org/svn/llvm-project/', '.')
193 svn(svn_root, 'update', *list(GIT_TO_SVN_DIR.values()))
194 log("svn staging area ready in '%s'" % svn_root)
195 if not os.path.isdir(svn_root):
196 die("Can't initialize svn staging dir (%s)" % svn_root)
197
198
Reid Kleckner45340972017-04-24 22:09:08 +0000199def fix_eol_style_native(rev, sr, svn_sr_path):
200 """Fix line endings before applying patches with Unix endings
201
202 SVN on Windows will check out files with CRLF for files with the
203 svn:eol-style property set to "native". This breaks `git apply`, which
204 typically works with Unix-line ending patches. Work around the problem here
205 by doing a dos2unix up front for files with svn:eol-style set to "native".
206 SVN will not commit a mass line ending re-doing because it detects the line
207 ending format for files with this property.
208 """
209 files = git('diff-tree', '--no-commit-id', '--name-only', '-r', rev, '--',
210 sr).split('\n')
211 files = [f.split('/', 1)[1] for f in files]
Reid Kleckner162c5cd2017-05-18 17:17:17 +0000212 # Skip files that don't exist in SVN yet.
213 files = [f for f in files if os.path.exists(os.path.join(svn_sr_path, f))]
Reid Kleckner45340972017-04-24 22:09:08 +0000214 # Use ignore_errors because 'svn propget' prints errors if the file doesn't
215 # have the named property. There doesn't seem to be a way to suppress that.
216 eol_props = svn(svn_sr_path, 'propget', 'svn:eol-style', *files,
Reid Kleckner0f442bc2017-05-12 00:10:19 +0000217 ignore_errors=True)
Reid Kleckner45340972017-04-24 22:09:08 +0000218 crlf_files = []
Reid Kleckner0f442bc2017-05-12 00:10:19 +0000219 if len(files) == 1:
220 # No need to split propget output on ' - ' when we have one file.
221 if eol_props.strip() == 'native':
222 crlf_files = files
223 else:
224 for eol_prop in eol_props.split('\n'):
225 # Remove spare CR.
226 eol_prop = eol_prop.strip('\r')
227 if not eol_prop:
228 continue
229 prop_parts = eol_prop.rsplit(' - ', 1)
230 if len(prop_parts) != 2:
231 eprint("unable to parse svn propget line:")
232 eprint(eol_prop)
233 continue
234 (f, eol_style) = prop_parts
235 if eol_style == 'native':
236 crlf_files.append(f)
Reid Kleckner45340972017-04-24 22:09:08 +0000237 # Reformat all files with native SVN line endings to Unix format. SVN knows
238 # files with native line endings are text files. It will commit just the
239 # diff, and not a mass line ending change.
240 shell(['dos2unix', '-q'] + crlf_files, cwd=svn_sr_path)
241
242
Mehdi Amini7b484632016-11-07 20:00:47 +0000243def svn_push_one_rev(svn_repo, rev, dry_run):
244 files = git('diff-tree', '--no-commit-id', '--name-only', '-r',
245 rev).split('\n')
246 subrepos = {first_dirname(f) for f in files}
247 if not subrepos:
248 raise RuntimeError('Empty diff for rev %s?' % rev)
249
250 status = svn(svn_repo, 'status')
251 if status:
252 die("Can't push git rev %s because svn status is not empty:\n%s" %
253 (rev, status))
254
255 for sr in subrepos:
Mehdi Amini7b484632016-11-07 20:00:47 +0000256 svn_sr_path = os.path.join(svn_repo, GIT_TO_SVN_DIR[sr])
Reid Kleckner45340972017-04-24 22:09:08 +0000257 if os.name == 'nt':
258 fix_eol_style_native(rev, sr, svn_sr_path)
259 diff = git('show', '--binary', rev, '--', sr, strip=False)
Mehdi Amini7b484632016-11-07 20:00:47 +0000260 # git is the only thing that can handle its own patches...
261 log_verbose('Apply patch: %s' % diff)
Mehdi Aminifbd26852016-11-12 01:17:59 +0000262 try:
263 shell(['git', 'apply', '-p2', '-'], cwd=svn_sr_path, stdin=diff,
264 die_on_failure=False)
265 except RuntimeError as e:
266 eprint("Patch doesn't apply: maybe you should try `git pull -r` "
267 "first?")
268 sys.exit(2)
Mehdi Amini7b484632016-11-07 20:00:47 +0000269
270 status_lines = svn(svn_repo, 'status').split('\n')
271
272 for l in (l for l in status_lines if l.startswith('?')):
273 svn(svn_repo, 'add', l[1:].strip())
274 for l in (l for l in status_lines if l.startswith('!')):
275 svn(svn_repo, 'remove', l[1:].strip())
276
277 # Now we're ready to commit.
278 commit_msg = git('show', '--pretty=%B', '--quiet', rev)
279 if not dry_run:
Mehdi Amini5c289b72016-11-30 19:12:53 +0000280 log(svn(svn_repo, 'commit', '-m', commit_msg, '--force-interactive'))
Mehdi Amini7b484632016-11-07 20:00:47 +0000281 log('Committed %s to svn.' % rev)
282 else:
283 log("Would have committed %s to svn, if this weren't a dry run." % rev)
284
285
286def cmd_push(args):
287 '''Push changes back to SVN: this is extracted from Justin Lebar's script
288 available here: https://github.com/jlebar/llvm-repo-tools/
289
290 Note: a current limitation is that git does not track file rename, so they
291 will show up in SVN as delete+add.
292 '''
293 # Get the git root
294 git_root = git('rev-parse', '--show-toplevel')
295 if not os.path.isdir(git_root):
296 die("Can't find git root dir")
297
298 # Push from the root of the git repo
299 os.chdir(git_root)
300
301 # We need a staging area for SVN, let's hide it in the .git directory.
Mehdi Aminif95a4592016-11-07 20:35:02 +0000302 dot_git_dir = git('rev-parse', '--git-common-dir')
303 svn_root = os.path.join(dot_git_dir, 'llvm-upstream-svn')
Mehdi Amini7b484632016-11-07 20:00:47 +0000304 svn_init(svn_root)
305
306 rev_range = args.rev_range
307 dry_run = args.dry_run
308 revs = get_revs_to_push(rev_range)
309 log('Pushing %d commit%s:\n%s' %
310 (len(revs), 's' if len(revs) != 1
311 else '', '\n'.join(' ' + git('show', '--oneline', '--quiet', c)
312 for c in revs)))
313 for r in revs:
314 clean_and_update_svn(svn_root)
315 svn_push_one_rev(svn_root, r, dry_run)
316
317
318if __name__ == '__main__':
Rui Ueyama2f8db1d2017-05-23 21:50:40 +0000319 if not program_exists('svn'):
320 die('error: git-llvm needs svn command, but svn is not installed.')
321
Mehdi Amini7b484632016-11-07 20:00:47 +0000322 argv = sys.argv[1:]
323 p = argparse.ArgumentParser(
324 prog='git llvm', formatter_class=argparse.RawDescriptionHelpFormatter,
325 description=__doc__)
326 subcommands = p.add_subparsers(title='subcommands',
327 description='valid subcommands',
328 help='additional help')
329 verbosity_group = p.add_mutually_exclusive_group()
330 verbosity_group.add_argument('-q', '--quiet', action='store_true',
331 help='print less information')
332 verbosity_group.add_argument('-v', '--verbose', action='store_true',
333 help='print more information')
334
335 parser_push = subcommands.add_parser(
336 'push', description=cmd_push.__doc__,
337 help='push changes back to the LLVM SVN repository')
338 parser_push.add_argument(
339 '-n',
340 '--dry-run',
341 dest='dry_run',
342 action='store_true',
343 help='Do everything other than commit to svn. Leaves junk in the svn '
344 'repo, so probably will not work well if you try to commit more '
345 'than one rev.')
346 parser_push.add_argument(
347 'rev_range',
348 metavar='GIT_REVS',
349 type=str,
350 nargs='?',
351 help="revs to push (default: everything not in the branch's "
352 'upstream, or not in origin/master if the branch lacks '
353 'an explicit upstream)')
354 parser_push.set_defaults(func=cmd_push)
355 args = p.parse_args(argv)
356 VERBOSE = args.verbose
357 QUIET = args.quiet
358
359 # Dispatch to the right subcommand
360 args.func(args)