git-llvm 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. #!/usr/bin/env python
  2. #
  3. # ======- git-llvm - LLVM Git Help Integration ---------*- python -*--========#
  4. #
  5. # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  6. # See https://llvm.org/LICENSE.txt for license information.
  7. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  8. #
  9. # ==------------------------------------------------------------------------==#
  10. """
  11. git-llvm integration
  12. ====================
  13. This file provides integration for git.
  14. """
  15. from __future__ import print_function
  16. import argparse
  17. import collections
  18. import os
  19. import re
  20. import shutil
  21. import subprocess
  22. import sys
  23. import time
  24. assert sys.version_info >= (2, 7)
  25. try:
  26. dict.iteritems
  27. except AttributeError:
  28. # Python 3
  29. def iteritems(d):
  30. return iter(d.items())
  31. else:
  32. # Python 2
  33. def iteritems(d):
  34. return d.iteritems()
  35. try:
  36. # Python 3
  37. from shlex import quote
  38. except ImportError:
  39. # Python 2
  40. from pipes import quote
  41. # It's *almost* a straightforward mapping from the monorepo to svn...
  42. LLVM_MONOREPO_SVN_MAPPING = {
  43. d: (d + '/trunk')
  44. for d in [
  45. 'clang-tools-extra',
  46. 'compiler-rt',
  47. 'debuginfo-tests',
  48. 'dragonegg',
  49. 'klee',
  50. 'libc',
  51. 'libclc',
  52. 'libcxx',
  53. 'libcxxabi',
  54. 'libunwind',
  55. 'lld',
  56. 'lldb',
  57. 'llgo',
  58. 'llvm',
  59. 'openmp',
  60. 'parallel-libs',
  61. 'polly',
  62. 'pstl',
  63. ]
  64. }
  65. LLVM_MONOREPO_SVN_MAPPING.update({'clang': 'cfe/trunk'})
  66. LLVM_MONOREPO_SVN_MAPPING.update({'': 'monorepo-root/trunk'})
  67. SPLIT_REPO_NAMES = {'llvm-' + d: d + '/trunk'
  68. for d in ['www', 'zorg', 'test-suite', 'lnt']}
  69. VERBOSE = False
  70. QUIET = False
  71. dev_null_fd = None
  72. def eprint(*args, **kwargs):
  73. print(*args, file=sys.stderr, **kwargs)
  74. def log(*args, **kwargs):
  75. if QUIET:
  76. return
  77. print(*args, **kwargs)
  78. def log_verbose(*args, **kwargs):
  79. if not VERBOSE:
  80. return
  81. print(*args, **kwargs)
  82. def die(msg):
  83. eprint(msg)
  84. sys.exit(1)
  85. def ask_confirm(prompt):
  86. # Python 2/3 compatibility
  87. try:
  88. read_input = raw_input
  89. except NameError:
  90. read_input = input
  91. while True:
  92. query = read_input('%s (y/N): ' % (prompt))
  93. if query.lower() not in ['y','n', '']:
  94. print('Expect y or n!')
  95. continue
  96. return query.lower() == 'y'
  97. def split_first_path_component(d):
  98. # Assuming we have a git path, it'll use slashes even on windows...I hope.
  99. if '/' in d:
  100. return d.split('/', 1)
  101. else:
  102. return (d, None)
  103. def get_dev_null():
  104. """Lazily create a /dev/null fd for use in shell()"""
  105. global dev_null_fd
  106. if dev_null_fd is None:
  107. dev_null_fd = open(os.devnull, 'w')
  108. return dev_null_fd
  109. def shell(cmd, strip=True, cwd=None, stdin=None, die_on_failure=True,
  110. ignore_errors=False, text=True):
  111. # Escape args when logging for easy repro.
  112. quoted_cmd = [quote(arg) for arg in cmd]
  113. log_verbose('Running in %s: %s' % (cwd, ' '.join(quoted_cmd)))
  114. err_pipe = subprocess.PIPE
  115. if ignore_errors:
  116. # Silence errors if requested.
  117. err_pipe = get_dev_null()
  118. start = time.time()
  119. p = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=err_pipe,
  120. stdin=subprocess.PIPE,
  121. universal_newlines=text)
  122. stdout, stderr = p.communicate(input=stdin)
  123. elapsed = time.time() - start
  124. log_verbose('Command took %0.1fs' % elapsed)
  125. if p.returncode == 0 or ignore_errors:
  126. if stderr and not ignore_errors:
  127. eprint('`%s` printed to stderr:' % ' '.join(quoted_cmd))
  128. eprint(stderr.rstrip())
  129. if strip:
  130. if text:
  131. stdout = stdout.rstrip('\r\n')
  132. else:
  133. stdout = stdout.rstrip(b'\r\n')
  134. if VERBOSE:
  135. for l in stdout.splitlines():
  136. log_verbose("STDOUT: %s" % l)
  137. return stdout
  138. err_msg = '`%s` returned %s' % (' '.join(quoted_cmd), p.returncode)
  139. eprint(err_msg)
  140. if stderr:
  141. eprint(stderr.rstrip())
  142. if die_on_failure:
  143. sys.exit(2)
  144. raise RuntimeError(err_msg)
  145. def git(*cmd, **kwargs):
  146. return shell(['git'] + list(cmd), **kwargs)
  147. def svn(cwd, *cmd, **kwargs):
  148. return shell(['svn'] + list(cmd), cwd=cwd, **kwargs)
  149. def program_exists(cmd):
  150. if sys.platform == 'win32' and not cmd.endswith('.exe'):
  151. cmd += '.exe'
  152. for path in os.environ["PATH"].split(os.pathsep):
  153. if os.access(os.path.join(path, cmd), os.X_OK):
  154. return True
  155. return False
  156. def get_default_rev_range():
  157. # Get the newest common ancestor between HEAD and our upstream branch.
  158. upstream_rev = git('merge-base', 'HEAD', '@{upstream}', ignore_errors=True)
  159. if not upstream_rev:
  160. eprint("Warning: git-llvm assumes that origin/master is the upstream "
  161. "branch but git does not.")
  162. eprint("To make this warning go away: git branch -u origin/master")
  163. eprint("To avoid this warning when creating branches: "
  164. "git checkout -b MyBranchName origin/master")
  165. upstream_rev = git('merge-base', 'HEAD', 'origin/master')
  166. return '%s..' % upstream_rev
  167. def get_revs_to_push(rev_range):
  168. if not rev_range:
  169. rev_range = get_default_rev_range()
  170. # Use git show rather than some plumbing command to figure out which revs
  171. # are in rev_range because it handles single revs (HEAD^) and ranges
  172. # (foo..bar) like we want.
  173. return git('show', '--reverse', '--quiet',
  174. '--pretty=%h', rev_range).splitlines()
  175. def clean_svn(svn_repo):
  176. svn(svn_repo, 'revert', '-R', '.')
  177. # Unfortunately it appears there's no svn equivalent for git clean, so we
  178. # have to do it ourselves.
  179. for line in svn(svn_repo, 'status', '--no-ignore').split('\n'):
  180. if not line.startswith('?'):
  181. continue
  182. filename = line[1:].strip()
  183. filepath = os.path.abspath(os.path.join(svn_repo, filename))
  184. abs_svn_repo = os.path.abspath(svn_repo)
  185. # Safety check that the directory we are about to delete is
  186. # actually within our svn staging dir.
  187. if not filepath.startswith(abs_svn_repo):
  188. die("Path to clean (%s) is not in svn staging dir (%s)"
  189. % (filepath, abs_svn_repo))
  190. if os.path.isdir(filepath):
  191. shutil.rmtree(filepath)
  192. else:
  193. os.remove(filepath)
  194. def svn_init(svn_root):
  195. if not os.path.exists(svn_root):
  196. log('Creating svn staging directory: (%s)' % (svn_root))
  197. os.makedirs(svn_root)
  198. svn(svn_root, 'checkout', '--depth=empty',
  199. 'https://llvm.org/svn/llvm-project/', '.')
  200. log("svn staging area ready in '%s'" % svn_root)
  201. if not os.path.isdir(svn_root):
  202. die("Can't initialize svn staging dir (%s)" % svn_root)
  203. def fix_eol_style_native(rev, svn_sr_path, files):
  204. """Fix line endings before applying patches with Unix endings
  205. SVN on Windows will check out files with CRLF for files with the
  206. svn:eol-style property set to "native". This breaks `git apply`, which
  207. typically works with Unix-line ending patches. Work around the problem here
  208. by doing a dos2unix up front for files with svn:eol-style set to "native".
  209. SVN will not commit a mass line ending re-doing because it detects the line
  210. ending format for files with this property.
  211. """
  212. # 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))]
  214. # 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,
  217. ignore_errors=True)
  218. crlf_files = []
  219. if len(files) == 1:
  220. # No need to split propget output on ' - ' when we have one file.
  221. if eol_props.strip() in ['native', 'CRLF']:
  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)
  237. if crlf_files:
  238. # Reformat all files with native SVN line endings to Unix format. SVN
  239. # knows files with native line endings are text files. It will commit
  240. # just the diff, and not a mass line ending change.
  241. shell(['dos2unix'] + crlf_files, ignore_errors=True, cwd=svn_sr_path)
  242. def split_subrepo(f, git_to_svn_mapping):
  243. # Given a path, splits it into (subproject, rest-of-path). If the path is
  244. # not in a subproject, returns ('', full-path).
  245. subproject, remainder = split_first_path_component(f)
  246. if subproject in git_to_svn_mapping:
  247. return subproject, remainder
  248. else:
  249. return '', f
  250. def get_all_parent_dirs(name):
  251. parts = []
  252. head, tail = os.path.split(name)
  253. while head:
  254. parts.append(head)
  255. head, tail = os.path.split(head)
  256. return parts
  257. def svn_push_one_rev(svn_repo, rev, git_to_svn_mapping, dry_run):
  258. def split_status(x):
  259. x = x.split('\t')
  260. return x[1], x[0]
  261. files_status = [split_status(x) for x in
  262. git('diff-tree', '--no-commit-id', '--name-status',
  263. '--no-renames', '-r', rev).split('\n')]
  264. if not files_status:
  265. raise RuntimeError('Empty diff for rev %s?' % rev)
  266. # Split files by subrepo
  267. subrepo_files = collections.defaultdict(list)
  268. for f, st in files_status:
  269. subrepo, remainder = split_subrepo(f, git_to_svn_mapping)
  270. subrepo_files[subrepo].append((remainder, st))
  271. status = svn(svn_repo, 'status', '--no-ignore')
  272. if status:
  273. die("Can't push git rev %s because status in svn staging dir (%s) is "
  274. "not empty:\n%s" % (rev, svn_repo, status))
  275. svn_dirs_to_update = set()
  276. for sr, files_status in iteritems(subrepo_files):
  277. svn_sr_path = git_to_svn_mapping[sr]
  278. for f, _ in files_status:
  279. svn_dirs_to_update.add(
  280. os.path.dirname(os.path.join(svn_sr_path, f)))
  281. # We also need to svn update any parent directories which are not yet
  282. # present
  283. parent_dirs = set()
  284. for dir in svn_dirs_to_update:
  285. parent_dirs.update(get_all_parent_dirs(dir))
  286. parent_dirs = set(dir for dir in parent_dirs
  287. if not os.path.exists(os.path.join(svn_repo, dir)))
  288. svn_dirs_to_update.update(parent_dirs)
  289. # Sort by length to ensure that the parent directories are passed to svn
  290. # before child directories.
  291. sorted_dirs_to_update = sorted(svn_dirs_to_update, key=len)
  292. # SVN update only in the affected directories.
  293. svn(svn_repo, 'update', '--depth=files', *sorted_dirs_to_update)
  294. for sr, files_status in iteritems(subrepo_files):
  295. svn_sr_path = os.path.join(svn_repo, git_to_svn_mapping[sr])
  296. if os.name == 'nt':
  297. fix_eol_style_native(rev, svn_sr_path,
  298. [f for f, _ in files_status])
  299. # We use text=False (and pass '--binary') so that we can get an exact
  300. # diff that can be passed as-is to 'git apply' without any line ending,
  301. # encoding, or other mangling.
  302. diff = git('show', '--binary', rev, '--',
  303. *(os.path.join(sr, f) for f, _ in files_status),
  304. strip=False, text=False)
  305. # git is the only thing that can handle its own patches...
  306. if sr == '':
  307. prefix_strip = '-p1'
  308. else:
  309. prefix_strip = '-p2'
  310. try:
  311. shell(['git', 'apply', prefix_strip, '-'], cwd=svn_sr_path,
  312. stdin=diff, die_on_failure=False, text=False)
  313. except RuntimeError as e:
  314. eprint("Patch doesn't apply: maybe you should try `git pull -r` "
  315. "first?")
  316. sys.exit(2)
  317. # Handle removed files and directories. We need to be careful not to
  318. # remove directories just because they _look_ empty in the svn tree, as
  319. # we might be missing sibling directories in the working copy. So, only
  320. # remove parent directories if they're empty on both the git and svn
  321. # sides.
  322. maybe_dirs_to_remove = set()
  323. for f, st in files_status:
  324. if st == 'D':
  325. maybe_dirs_to_remove.update(get_all_parent_dirs(f))
  326. svn(svn_sr_path, 'remove', f)
  327. elif not (st == 'A' or st == 'M' or st == 'T'):
  328. # Add is handled below, and nothing needs to be done for Modify.
  329. # (FIXME: Type-change between symlink and file might need some
  330. # special handling, but let's ignore that for now.)
  331. die("Unexpected git status for %r: %r" % (f, st))
  332. maybe_dirs_to_remove = sorted(maybe_dirs_to_remove, key=len)
  333. for f in maybe_dirs_to_remove:
  334. if(not os.path.exists(os.path.join(svn_sr_path, f)) and
  335. git('ls-tree', '-d', rev, os.path.join(sr, f)) == ''):
  336. svn(svn_sr_path, 'remove', f)
  337. status_lines = svn(svn_repo, 'status', '--no-ignore').split('\n')
  338. for l in status_lines:
  339. f = l[1:].strip()
  340. if l.startswith('?') or l.startswith('I'):
  341. svn(svn_repo, 'add', '--no-ignore', f)
  342. # Now we're ready to commit.
  343. commit_msg = git('show', '--pretty=%B', '--quiet', rev)
  344. if not dry_run:
  345. commit_args = ['commit', '-m', commit_msg]
  346. if '--force-interactive' in svn(svn_repo, 'commit', '--help'):
  347. commit_args.append('--force-interactive')
  348. log(svn(svn_repo, *commit_args))
  349. log('Committed %s to svn.' % rev)
  350. else:
  351. log("Would have committed %s to svn, if this weren't a dry run." % rev)
  352. def cmd_push(args):
  353. '''Push changes back to SVN: this is extracted from Justin Lebar's script
  354. available here: https://github.com/jlebar/llvm-repo-tools/
  355. Note: a current limitation is that git does not track file rename, so they
  356. will show up in SVN as delete+add.
  357. '''
  358. # Get the git root
  359. git_root = git('rev-parse', '--show-toplevel')
  360. if not os.path.isdir(git_root):
  361. die("Can't find git root dir")
  362. # Push from the root of the git repo
  363. os.chdir(git_root)
  364. # Get the remote URL, and check if it's one of the standalone repos.
  365. git_remote_url = git('ls-remote', '--get-url', 'origin')
  366. git_remote_url = git_remote_url.rstrip('.git').rstrip('/')
  367. git_remote_repo_name = git_remote_url.rsplit('/', 1)[-1]
  368. split_repo_path = SPLIT_REPO_NAMES.get(git_remote_repo_name)
  369. if split_repo_path:
  370. git_to_svn_mapping = {'': split_repo_path}
  371. else:
  372. # Default to the monorepo mapping
  373. git_to_svn_mapping = LLVM_MONOREPO_SVN_MAPPING
  374. # We need a staging area for SVN, let's hide it in the .git directory.
  375. dot_git_dir = git('rev-parse', '--git-common-dir')
  376. # Not all versions of git support --git-common-dir and just print the
  377. # unknown command back. If this happens, fall back to --git-dir
  378. if dot_git_dir == '--git-common-dir':
  379. dot_git_dir = git('rev-parse', '--git-dir')
  380. svn_root = os.path.join(dot_git_dir, 'llvm-upstream-svn')
  381. svn_init(svn_root)
  382. rev_range = args.rev_range
  383. dry_run = args.dry_run
  384. revs = get_revs_to_push(rev_range)
  385. if not args.force and not revs:
  386. die('Nothing to push: No revs in range %s.' % rev_range)
  387. log('%sPushing %d %s commit%s:\n%s' %
  388. ('[DryRun] ' if dry_run else '', len(revs),
  389. 'split-repo (%s)' % split_repo_path
  390. if split_repo_path else 'monorepo',
  391. 's' if len(revs) != 1 else '',
  392. '\n'.join(' ' + git('show', '--oneline', '--quiet', c)
  393. for c in revs)))
  394. # Ask confirmation if multiple commits are about to be pushed
  395. if not args.force and len(revs) > 1:
  396. if not ask_confirm("Are you sure you want to create %d commits?" % len(revs)):
  397. die("Aborting")
  398. for r in revs:
  399. clean_svn(svn_root)
  400. svn_push_one_rev(svn_root, r, git_to_svn_mapping, dry_run)
  401. def lookup_llvm_svn_id(git_commit_hash):
  402. # Use --format=%b to get the raw commit message, without any extra
  403. # whitespace.
  404. commit_msg = git('log', '-1', '--format=%b', git_commit_hash,
  405. ignore_errors=True)
  406. if len(commit_msg) == 0:
  407. die("Can't find git commit " + git_commit_hash)
  408. # If a commit has multiple "llvm-svn:" lines (e.g. if the commit is
  409. # reverting/quoting a previous commit), choose the last one, which should
  410. # be the authoritative one.
  411. svn_match_iter = re.finditer('^llvm-svn: (\d{5,7})$', commit_msg,
  412. re.MULTILINE)
  413. svn_match = None
  414. for m in svn_match_iter:
  415. svn_match = m.group(1)
  416. if svn_match:
  417. return int(svn_match)
  418. die("Can't find svn revision in git commit " + git_commit_hash)
  419. def cmd_svn_lookup(args):
  420. '''Find the SVN revision id for a given git commit hash.
  421. This is identified by 'llvm-svn: NNNNNN' in the git commit message.'''
  422. # Get the git root
  423. git_root = git('rev-parse', '--show-toplevel')
  424. if not os.path.isdir(git_root):
  425. die("Can't find git root dir")
  426. # Run commands from the root
  427. os.chdir(git_root)
  428. log('r' + str(lookup_llvm_svn_id(args.git_commit_hash)))
  429. def git_hash_by_svn_rev(svn_rev):
  430. '''Find the git hash for a given svn revision.
  431. This check is paranoid: 'llvm-svn: NNNNNN' could exist on its own line
  432. somewhere else in the commit message. Look in the full log message to see
  433. if it's actually on the last line.
  434. Since this check is expensive (we're searching every single commit), limit
  435. to the past 10k commits (about 5 months).
  436. '''
  437. possible_hashes = git(
  438. 'log', '--format=%H', '--grep', '^llvm-svn: %d$' % svn_rev,
  439. 'HEAD~10000...HEAD').split('\n')
  440. matching_hashes = [h for h in possible_hashes
  441. if lookup_llvm_svn_id(h) == svn_rev]
  442. if len(matching_hashes) > 1:
  443. die("svn revision r%d has ambiguous commits: %s" % (
  444. svn_rev, ', '.join(matching_hashes)))
  445. elif len(matching_hashes) < 1:
  446. die("svn revision r%d matches no commits" % svn_rev)
  447. return matching_hashes[0]
  448. def cmd_revert(args):
  449. '''Revert a commit by either SVN id (rNNNNNN) or git hash. This also
  450. populates the git commit message with both the SVN revision and git hash of
  451. the change being reverted.'''
  452. # Get the git root
  453. git_root = git('rev-parse', '--show-toplevel')
  454. if not os.path.isdir(git_root):
  455. die("Can't find git root dir")
  456. # Run commands from the root
  457. os.chdir(git_root)
  458. # Check for a client branch first.
  459. open_files = git('status', '-uno', '-s', '--porcelain')
  460. if len(open_files) > 0:
  461. die("Found open files. Please stash and then revert.\n" + open_files)
  462. # If the revision looks like rNNNNNN (or with a callsign, e.g. rLLDNNNNNN),
  463. # use that. Otherwise, look for it in the git commit.
  464. svn_match = re.match('^r[A-Z]*(\d{5,7})$', args.revision)
  465. if svn_match:
  466. # If the revision looks like rNNNNNN, use that as the svn revision, and
  467. # grep through git commits to find which one corresponds to that svn
  468. # revision.
  469. svn_rev = int(svn_match.group(1))
  470. git_hash = git_hash_by_svn_rev(svn_rev)
  471. else:
  472. # Otherwise, this looks like a git hash, so we just need to grab the
  473. # svn revision from the end of the commit message. Get the actual git
  474. # hash in case the revision is something like "HEAD~1"
  475. git_hash = git('rev-parse', '--verify', args.revision + '^{commit}')
  476. svn_rev = lookup_llvm_svn_id(git_hash)
  477. msg = git('log', '-1', '--format=%s', git_hash)
  478. log_verbose('Ready to revert r%d (%s): "%s"' % (svn_rev, git_hash, msg))
  479. revert_args = ['revert', '--no-commit', git_hash]
  480. # TODO: Running --edit doesn't seem to work, with errors that stdin is not
  481. # a tty.
  482. commit_args = [
  483. 'commit', '-m', 'Revert ' + msg,
  484. '-m', 'This reverts r%d (git commit %s)' % (svn_rev, git_hash)]
  485. if args.dry_run:
  486. log("Would have run the following commands, if this weren't a"
  487. "dry run:\n"
  488. '1) git %s\n2) git %s' % (
  489. ' '.join(quote(arg) for arg in revert_args),
  490. ' '.join(quote(arg) for arg in commit_args)))
  491. return
  492. git(*revert_args)
  493. commit_log = git(*commit_args)
  494. log('Created revert of r%d: %s' % (svn_rev, commit_log))
  495. log("Run 'git llvm push -n' to inspect your changes and "
  496. "run 'git llvm push' when ready")
  497. if __name__ == '__main__':
  498. if not program_exists('svn'):
  499. die('error: git-llvm needs svn command, but svn is not installed.')
  500. argv = sys.argv[1:]
  501. p = argparse.ArgumentParser(
  502. prog='git llvm', formatter_class=argparse.RawDescriptionHelpFormatter,
  503. description=__doc__)
  504. subcommands = p.add_subparsers(title='subcommands',
  505. description='valid subcommands',
  506. help='additional help')
  507. verbosity_group = p.add_mutually_exclusive_group()
  508. verbosity_group.add_argument('-q', '--quiet', action='store_true',
  509. help='print less information')
  510. verbosity_group.add_argument('-v', '--verbose', action='store_true',
  511. help='print more information')
  512. parser_push = subcommands.add_parser(
  513. 'push', description=cmd_push.__doc__,
  514. help='push changes back to the LLVM SVN repository')
  515. parser_push.add_argument(
  516. '-n',
  517. '--dry-run',
  518. dest='dry_run',
  519. action='store_true',
  520. help='Do everything other than commit to svn. Leaves junk in the svn '
  521. 'repo, so probably will not work well if you try to commit more '
  522. 'than one rev.')
  523. parser_push.add_argument(
  524. '-f',
  525. '--force',
  526. action='store_true',
  527. help='Do not ask for confirmation when pushing multiple commits.')
  528. parser_push.add_argument(
  529. 'rev_range',
  530. metavar='GIT_REVS',
  531. type=str,
  532. nargs='?',
  533. help="revs to push (default: everything not in the branch's "
  534. 'upstream, or not in origin/master if the branch lacks '
  535. 'an explicit upstream)')
  536. parser_push.set_defaults(func=cmd_push)
  537. parser_revert = subcommands.add_parser(
  538. 'revert', description=cmd_revert.__doc__,
  539. help='Revert a commit locally.')
  540. parser_revert.add_argument(
  541. 'revision',
  542. help='Revision to revert. Can either be an SVN revision number '
  543. "(rNNNNNN) or a git commit hash (anything that doesn't look "
  544. 'like an SVN revision number).')
  545. parser_revert.add_argument(
  546. '-n',
  547. '--dry-run',
  548. dest='dry_run',
  549. action='store_true',
  550. help='Do everything other than perform a revert. Prints the git '
  551. 'revert command it would have run.')
  552. parser_revert.set_defaults(func=cmd_revert)
  553. parser_svn_lookup = subcommands.add_parser(
  554. 'svn-lookup', description=cmd_svn_lookup.__doc__,
  555. help='Find the llvm-svn revision for a given commit.')
  556. parser_svn_lookup.add_argument(
  557. 'git_commit_hash',
  558. help='git_commit_hash for which we will look up the svn revision id.')
  559. parser_svn_lookup.set_defaults(func=cmd_svn_lookup)
  560. args = p.parse_args(argv)
  561. VERBOSE = args.verbose
  562. QUIET = args.quiet
  563. # Python3 workaround, for when not arguments are provided.
  564. # See https://bugs.python.org/issue16308
  565. try:
  566. func = args.func
  567. except AttributeError:
  568. # No arguments or subcommands were given.
  569. parser.print_help()
  570. parser.exit()
  571. # Dispatch to the right subcommand
  572. args.func(args)