git-clang-format-custom 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. #!/usr/bin/env python
  2. # Copy of https://github.com/llvm-mirror/clang/blob/master/tools/clang-format/git-clang-format
  3. # Adds a --diffstat option to show the files needing formatting.
  4. # This change will be upstreamed, but the current git-clang-format does not
  5. # have it yet. We use it in the internal scripts/clang-format.sh
  6. #
  7. #===- git-clang-format - ClangFormat Git Integration ---------*- python -*--===#
  8. #
  9. # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  10. # See https://llvm.org/LICENSE.txt for license information.
  11. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  12. #
  13. #===------------------------------------------------------------------------===#
  14. r"""
  15. clang-format git integration
  16. ============================
  17. This file provides a clang-format integration for git. Put it somewhere in your
  18. path and ensure that it is executable. Then, "git clang-format" will invoke
  19. clang-format on the changes in current files or a specific commit.
  20. For further details, run:
  21. git clang-format -h
  22. Requires Python 2.7 or Python 3
  23. """
  24. from __future__ import absolute_import, division, print_function
  25. import argparse
  26. import collections
  27. import contextlib
  28. import errno
  29. import os
  30. import re
  31. import subprocess
  32. import sys
  33. usage = 'git clang-format [OPTIONS] [<commit>] [<commit>] [--] [<file>...]'
  34. desc = '''
  35. If zero or one commits are given, run clang-format on all lines that differ
  36. between the working directory and <commit>, which defaults to HEAD. Changes are
  37. only applied to the working directory.
  38. If two commits are given (requires --diff), run clang-format on all lines in the
  39. second <commit> that differ from the first <commit>.
  40. The following git-config settings set the default of the corresponding option:
  41. clangFormat.binary
  42. clangFormat.commit
  43. clangFormat.extensions
  44. clangFormat.style
  45. '''
  46. # Name of the temporary index file in which save the output of clang-format.
  47. # This file is created within the .git directory.
  48. temp_index_basename = 'clang-format-index'
  49. Range = collections.namedtuple('Range', 'start, count')
  50. def main():
  51. config = load_git_config()
  52. # In order to keep '--' yet allow options after positionals, we need to
  53. # check for '--' ourselves. (Setting nargs='*' throws away the '--', while
  54. # nargs=argparse.REMAINDER disallows options after positionals.)
  55. argv = sys.argv[1:]
  56. try:
  57. idx = argv.index('--')
  58. except ValueError:
  59. dash_dash = []
  60. else:
  61. dash_dash = argv[idx:]
  62. argv = argv[:idx]
  63. default_extensions = ','.join([
  64. # From clang/lib/Frontend/FrontendOptions.cpp, all lower case
  65. 'c', 'h', # C
  66. 'm', # ObjC
  67. 'mm', # ObjC++
  68. 'cc', 'cp', 'cpp', 'c++', 'cxx', 'hh', 'hpp', 'hxx', # C++
  69. 'cu', # CUDA
  70. # Other languages that clang-format supports
  71. 'proto', 'protodevel', # Protocol Buffers
  72. 'java', # Java
  73. 'js', # JavaScript
  74. 'ts', # TypeScript
  75. 'cs', # C Sharp
  76. ])
  77. p = argparse.ArgumentParser(
  78. usage=usage, formatter_class=argparse.RawDescriptionHelpFormatter,
  79. description=desc)
  80. p.add_argument('--binary',
  81. default=config.get('clangformat.binary', 'clang-format'),
  82. help='path to clang-format'),
  83. p.add_argument('--commit',
  84. default=config.get('clangformat.commit', 'HEAD'),
  85. help='default commit to use if none is specified'),
  86. p.add_argument('--diff', action='store_true',
  87. help='print a diff instead of applying the changes')
  88. p.add_argument('--diffstat', action='store_true',
  89. help='print diffstat instead of applying the changes')
  90. p.add_argument('--extensions',
  91. default=config.get('clangformat.extensions',
  92. default_extensions),
  93. help=('comma-separated list of file extensions to format, '
  94. 'excluding the period and case-insensitive')),
  95. p.add_argument('-f', '--force', action='store_true',
  96. help='allow changes to unstaged files')
  97. p.add_argument('-p', '--patch', action='store_true',
  98. help='select hunks interactively')
  99. p.add_argument('-q', '--quiet', action='count', default=0,
  100. help='print less information')
  101. p.add_argument('--style',
  102. default=config.get('clangformat.style', None),
  103. help='passed to clang-format'),
  104. p.add_argument('-v', '--verbose', action='count', default=0,
  105. help='print extra information')
  106. # We gather all the remaining positional arguments into 'args' since we need
  107. # to use some heuristics to determine whether or not <commit> was present.
  108. # However, to print pretty messages, we make use of metavar and help.
  109. p.add_argument('args', nargs='*', metavar='<commit>',
  110. help='revision from which to compute the diff')
  111. p.add_argument('ignored', nargs='*', metavar='<file>...',
  112. help='if specified, only consider differences in these files')
  113. opts = p.parse_args(argv)
  114. opts.verbose -= opts.quiet
  115. del opts.quiet
  116. commits, files = interpret_args(opts.args, dash_dash, opts.commit)
  117. if len(commits) > 1:
  118. if not opts.diff:
  119. die('--diff is required when two commits are given')
  120. else:
  121. if len(commits) > 2:
  122. die('at most two commits allowed; %d given' % len(commits))
  123. changed_lines = compute_diff_and_extract_lines(commits, files)
  124. if opts.verbose >= 1:
  125. ignored_files = set(changed_lines)
  126. filter_by_extension(changed_lines, opts.extensions.lower().split(','))
  127. if opts.verbose >= 1:
  128. ignored_files.difference_update(changed_lines)
  129. if ignored_files:
  130. print('Ignoring changes in the following files (wrong extension):')
  131. for filename in ignored_files:
  132. print(' %s' % filename)
  133. if changed_lines:
  134. print('Running clang-format on the following files:')
  135. for filename in changed_lines:
  136. print(' %s' % filename)
  137. if not changed_lines:
  138. print('no modified files to format')
  139. return
  140. # The computed diff outputs absolute paths, so we must cd before accessing
  141. # those files.
  142. cd_to_toplevel()
  143. if len(commits) > 1:
  144. old_tree = commits[1]
  145. new_tree = run_clang_format_and_save_to_tree(changed_lines,
  146. revision=commits[1],
  147. binary=opts.binary,
  148. style=opts.style)
  149. else:
  150. old_tree = create_tree_from_workdir(changed_lines)
  151. new_tree = run_clang_format_and_save_to_tree(changed_lines,
  152. binary=opts.binary,
  153. style=opts.style)
  154. if opts.verbose >= 1:
  155. print('old tree: %s' % old_tree)
  156. print('new tree: %s' % new_tree)
  157. if old_tree == new_tree:
  158. if opts.verbose >= 0:
  159. print('clang-format did not modify any files')
  160. elif opts.diff:
  161. print_diff(old_tree, new_tree)
  162. elif opts.diffstat:
  163. print_diffstat(old_tree, new_tree)
  164. else:
  165. changed_files = apply_changes(old_tree, new_tree, force=opts.force,
  166. patch_mode=opts.patch)
  167. if (opts.verbose >= 0 and not opts.patch) or opts.verbose >= 1:
  168. print('changed files:')
  169. for filename in changed_files:
  170. print(' %s' % filename)
  171. def load_git_config(non_string_options=None):
  172. """Return the git configuration as a dictionary.
  173. All options are assumed to be strings unless in `non_string_options`, in which
  174. is a dictionary mapping option name (in lower case) to either "--bool" or
  175. "--int"."""
  176. if non_string_options is None:
  177. non_string_options = {}
  178. out = {}
  179. for entry in run('git', 'config', '--list', '--null').split('\0'):
  180. if entry:
  181. name, value = entry.split('\n', 1)
  182. if name in non_string_options:
  183. value = run('git', 'config', non_string_options[name], name)
  184. out[name] = value
  185. return out
  186. def interpret_args(args, dash_dash, default_commit):
  187. """Interpret `args` as "[commits] [--] [files]" and return (commits, files).
  188. It is assumed that "--" and everything that follows has been removed from
  189. args and placed in `dash_dash`.
  190. If "--" is present (i.e., `dash_dash` is non-empty), the arguments to its
  191. left (if present) are taken as commits. Otherwise, the arguments are checked
  192. from left to right if they are commits or files. If commits are not given,
  193. a list with `default_commit` is used."""
  194. if dash_dash:
  195. if len(args) == 0:
  196. commits = [default_commit]
  197. else:
  198. commits = args
  199. for commit in commits:
  200. object_type = get_object_type(commit)
  201. if object_type not in ('commit', 'tag'):
  202. if object_type is None:
  203. die("'%s' is not a commit" % commit)
  204. else:
  205. die("'%s' is a %s, but a commit was expected" % (commit, object_type))
  206. files = dash_dash[1:]
  207. elif args:
  208. commits = []
  209. while args:
  210. if not disambiguate_revision(args[0]):
  211. break
  212. commits.append(args.pop(0))
  213. if not commits:
  214. commits = [default_commit]
  215. files = args
  216. else:
  217. commits = [default_commit]
  218. files = []
  219. return commits, files
  220. def disambiguate_revision(value):
  221. """Returns True if `value` is a revision, False if it is a file, or dies."""
  222. # If `value` is ambiguous (neither a commit nor a file), the following
  223. # command will die with an appropriate error message.
  224. run('git', 'rev-parse', value, verbose=False)
  225. object_type = get_object_type(value)
  226. if object_type is None:
  227. return False
  228. if object_type in ('commit', 'tag'):
  229. return True
  230. die('`%s` is a %s, but a commit or filename was expected' %
  231. (value, object_type))
  232. def get_object_type(value):
  233. """Returns a string description of an object's type, or None if it is not
  234. a valid git object."""
  235. cmd = ['git', 'cat-file', '-t', value]
  236. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  237. stdout, stderr = p.communicate()
  238. if p.returncode != 0:
  239. return None
  240. return convert_string(stdout.strip())
  241. def compute_diff_and_extract_lines(commits, files):
  242. """Calls compute_diff() followed by extract_lines()."""
  243. diff_process = compute_diff(commits, files)
  244. changed_lines = extract_lines(diff_process.stdout)
  245. diff_process.stdout.close()
  246. diff_process.wait()
  247. if diff_process.returncode != 0:
  248. # Assume error was already printed to stderr.
  249. sys.exit(2)
  250. return changed_lines
  251. def compute_diff(commits, files):
  252. """Return a subprocess object producing the diff from `commits`.
  253. The return value's `stdin` file object will produce a patch with the
  254. differences between the working directory and the first commit if a single
  255. one was specified, or the difference between both specified commits, filtered
  256. on `files` (if non-empty). Zero context lines are used in the patch."""
  257. git_tool = 'diff-index'
  258. if len(commits) > 1:
  259. git_tool = 'diff-tree'
  260. cmd = ['git', git_tool, '-p', '-U0'] + commits + ['--']
  261. cmd.extend(files)
  262. p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  263. p.stdin.close()
  264. return p
  265. def extract_lines(patch_file):
  266. """Extract the changed lines in `patch_file`.
  267. The return value is a dictionary mapping filename to a list of (start_line,
  268. line_count) pairs.
  269. The input must have been produced with ``-U0``, meaning unidiff format with
  270. zero lines of context. The return value is a dict mapping filename to a
  271. list of line `Range`s."""
  272. matches = {}
  273. for line in patch_file:
  274. line = convert_string(line)
  275. match = re.search(r'^\+\+\+\ [^/]+/(.*)', line)
  276. if match:
  277. filename = match.group(1).rstrip('\r\n')
  278. match = re.search(r'^@@ -[0-9,]+ \+(\d+)(,(\d+))?', line)
  279. if match:
  280. start_line = int(match.group(1))
  281. line_count = 1
  282. if match.group(3):
  283. line_count = int(match.group(3))
  284. if line_count > 0:
  285. matches.setdefault(filename, []).append(Range(start_line, line_count))
  286. return matches
  287. def filter_by_extension(dictionary, allowed_extensions):
  288. """Delete every key in `dictionary` that doesn't have an allowed extension.
  289. `allowed_extensions` must be a collection of lowercase file extensions,
  290. excluding the period."""
  291. allowed_extensions = frozenset(allowed_extensions)
  292. for filename in list(dictionary.keys()):
  293. base_ext = filename.rsplit('.', 1)
  294. if len(base_ext) == 1 and '' in allowed_extensions:
  295. continue
  296. if len(base_ext) == 1 or base_ext[1].lower() not in allowed_extensions:
  297. del dictionary[filename]
  298. def cd_to_toplevel():
  299. """Change to the top level of the git repository."""
  300. toplevel = run('git', 'rev-parse', '--show-toplevel')
  301. os.chdir(toplevel)
  302. def create_tree_from_workdir(filenames):
  303. """Create a new git tree with the given files from the working directory.
  304. Returns the object ID (SHA-1) of the created tree."""
  305. return create_tree(filenames, '--stdin')
  306. def run_clang_format_and_save_to_tree(changed_lines, revision=None,
  307. binary='clang-format', style=None):
  308. """Run clang-format on each file and save the result to a git tree.
  309. Returns the object ID (SHA-1) of the created tree."""
  310. def iteritems(container):
  311. try:
  312. return container.iteritems() # Python 2
  313. except AttributeError:
  314. return container.items() # Python 3
  315. def index_info_generator():
  316. for filename, line_ranges in iteritems(changed_lines):
  317. if revision:
  318. git_metadata_cmd = ['git', 'ls-tree',
  319. '%s:%s' % (revision, os.path.dirname(filename)),
  320. os.path.basename(filename)]
  321. git_metadata = subprocess.Popen(git_metadata_cmd, stdin=subprocess.PIPE,
  322. stdout=subprocess.PIPE)
  323. stdout = git_metadata.communicate()[0]
  324. mode = oct(int(stdout.split()[0], 8))
  325. else:
  326. mode = oct(os.stat(filename).st_mode)
  327. # Adjust python3 octal format so that it matches what git expects
  328. if mode.startswith('0o'):
  329. mode = '0' + mode[2:]
  330. blob_id = clang_format_to_blob(filename, line_ranges,
  331. revision=revision,
  332. binary=binary,
  333. style=style)
  334. yield '%s %s\t%s' % (mode, blob_id, filename)
  335. return create_tree(index_info_generator(), '--index-info')
  336. def create_tree(input_lines, mode):
  337. """Create a tree object from the given input.
  338. If mode is '--stdin', it must be a list of filenames. If mode is
  339. '--index-info' is must be a list of values suitable for "git update-index
  340. --index-info", such as "<mode> <SP> <sha1> <TAB> <filename>". Any other mode
  341. is invalid."""
  342. assert mode in ('--stdin', '--index-info')
  343. cmd = ['git', 'update-index', '--add', '-z', mode]
  344. with temporary_index_file():
  345. p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
  346. for line in input_lines:
  347. p.stdin.write(to_bytes('%s\0' % line))
  348. p.stdin.close()
  349. if p.wait() != 0:
  350. die('`%s` failed' % ' '.join(cmd))
  351. tree_id = run('git', 'write-tree')
  352. return tree_id
  353. def clang_format_to_blob(filename, line_ranges, revision=None,
  354. binary='clang-format', style=None):
  355. """Run clang-format on the given file and save the result to a git blob.
  356. Runs on the file in `revision` if not None, or on the file in the working
  357. directory if `revision` is None.
  358. Returns the object ID (SHA-1) of the created blob."""
  359. clang_format_cmd = [binary]
  360. if style:
  361. clang_format_cmd.extend(['-style='+style])
  362. clang_format_cmd.extend([
  363. '-lines=%s:%s' % (start_line, start_line+line_count-1)
  364. for start_line, line_count in line_ranges])
  365. if revision:
  366. clang_format_cmd.extend(['-assume-filename='+filename])
  367. git_show_cmd = ['git', 'cat-file', 'blob', '%s:%s' % (revision, filename)]
  368. git_show = subprocess.Popen(git_show_cmd, stdin=subprocess.PIPE,
  369. stdout=subprocess.PIPE)
  370. git_show.stdin.close()
  371. clang_format_stdin = git_show.stdout
  372. else:
  373. clang_format_cmd.extend([filename])
  374. git_show = None
  375. clang_format_stdin = subprocess.PIPE
  376. try:
  377. clang_format = subprocess.Popen(clang_format_cmd, stdin=clang_format_stdin,
  378. stdout=subprocess.PIPE)
  379. if clang_format_stdin == subprocess.PIPE:
  380. clang_format_stdin = clang_format.stdin
  381. except OSError as e:
  382. if e.errno == errno.ENOENT:
  383. die('cannot find executable "%s"' % binary)
  384. else:
  385. raise
  386. clang_format_stdin.close()
  387. hash_object_cmd = ['git', 'hash-object', '-w', '--path='+filename, '--stdin']
  388. hash_object = subprocess.Popen(hash_object_cmd, stdin=clang_format.stdout,
  389. stdout=subprocess.PIPE)
  390. clang_format.stdout.close()
  391. stdout = hash_object.communicate()[0]
  392. if hash_object.returncode != 0:
  393. die('`%s` failed' % ' '.join(hash_object_cmd))
  394. if clang_format.wait() != 0:
  395. die('`%s` failed' % ' '.join(clang_format_cmd))
  396. if git_show and git_show.wait() != 0:
  397. die('`%s` failed' % ' '.join(git_show_cmd))
  398. return convert_string(stdout).rstrip('\r\n')
  399. @contextlib.contextmanager
  400. def temporary_index_file(tree=None):
  401. """Context manager for setting GIT_INDEX_FILE to a temporary file and deleting
  402. the file afterward."""
  403. index_path = create_temporary_index(tree)
  404. old_index_path = os.environ.get('GIT_INDEX_FILE')
  405. os.environ['GIT_INDEX_FILE'] = index_path
  406. try:
  407. yield
  408. finally:
  409. if old_index_path is None:
  410. del os.environ['GIT_INDEX_FILE']
  411. else:
  412. os.environ['GIT_INDEX_FILE'] = old_index_path
  413. os.remove(index_path)
  414. def create_temporary_index(tree=None):
  415. """Create a temporary index file and return the created file's path.
  416. If `tree` is not None, use that as the tree to read in. Otherwise, an
  417. empty index is created."""
  418. gitdir = run('git', 'rev-parse', '--git-dir')
  419. path = os.path.join(gitdir, temp_index_basename)
  420. if tree is None:
  421. tree = '--empty'
  422. run('git', 'read-tree', '--index-output='+path, tree)
  423. return path
  424. def print_diff(old_tree, new_tree):
  425. """Print the diff between the two trees to stdout."""
  426. # We use the porcelain 'diff' and not plumbing 'diff-tree' because the output
  427. # is expected to be viewed by the user, and only the former does nice things
  428. # like color and pagination.
  429. #
  430. # We also only print modified files since `new_tree` only contains the files
  431. # that were modified, so unmodified files would show as deleted without the
  432. # filter.
  433. subprocess.check_call(['git', 'diff', '--diff-filter=M', old_tree, new_tree,
  434. '--'])
  435. def print_diffstat(old_tree, new_tree):
  436. """Print the diffstat between the two trees to stdout."""
  437. # We use the porcelain 'diff' and not plumbing 'diff-tree' because the output
  438. # is expected to be viewed by the user, and only the former does nice things
  439. # like color and pagination.
  440. #
  441. # We also only print modified files since `new_tree` only contains the files
  442. # that were modified, so unmodified files would show as deleted without the
  443. # filter.
  444. subprocess.check_call(['git', 'diff', '--diff-filter=M', '--stat', old_tree, new_tree,
  445. '--'])
  446. def apply_changes(old_tree, new_tree, force=False, patch_mode=False):
  447. """Apply the changes in `new_tree` to the working directory.
  448. Bails if there are local changes in those files and not `force`. If
  449. `patch_mode`, runs `git checkout --patch` to select hunks interactively."""
  450. changed_files = run('git', 'diff-tree', '--diff-filter=M', '-r', '-z',
  451. '--name-only', old_tree,
  452. new_tree).rstrip('\0').split('\0')
  453. if not force:
  454. unstaged_files = run('git', 'diff-files', '--name-status', *changed_files)
  455. if unstaged_files:
  456. print('The following files would be modified but '
  457. 'have unstaged changes:', file=sys.stderr)
  458. print(unstaged_files, file=sys.stderr)
  459. print('Please commit, stage, or stash them first.', file=sys.stderr)
  460. sys.exit(2)
  461. if patch_mode:
  462. # In patch mode, we could just as well create an index from the new tree
  463. # and checkout from that, but then the user will be presented with a
  464. # message saying "Discard ... from worktree". Instead, we use the old
  465. # tree as the index and checkout from new_tree, which gives the slightly
  466. # better message, "Apply ... to index and worktree". This is not quite
  467. # right, since it won't be applied to the user's index, but oh well.
  468. with temporary_index_file(old_tree):
  469. subprocess.check_call(['git', 'checkout', '--patch', new_tree])
  470. index_tree = old_tree
  471. else:
  472. with temporary_index_file(new_tree):
  473. run('git', 'checkout-index', '-a', '-f')
  474. return changed_files
  475. def run(*args, **kwargs):
  476. stdin = kwargs.pop('stdin', '')
  477. verbose = kwargs.pop('verbose', True)
  478. strip = kwargs.pop('strip', True)
  479. for name in kwargs:
  480. raise TypeError("run() got an unexpected keyword argument '%s'" % name)
  481. p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  482. stdin=subprocess.PIPE)
  483. stdout, stderr = p.communicate(input=stdin)
  484. stdout = convert_string(stdout)
  485. stderr = convert_string(stderr)
  486. if p.returncode == 0:
  487. if stderr:
  488. if verbose:
  489. print('`%s` printed to stderr:' % ' '.join(args), file=sys.stderr)
  490. print(stderr.rstrip(), file=sys.stderr)
  491. if strip:
  492. stdout = stdout.rstrip('\r\n')
  493. return stdout
  494. if verbose:
  495. print('`%s` returned %s' % (' '.join(args), p.returncode), file=sys.stderr)
  496. if stderr:
  497. print(stderr.rstrip(), file=sys.stderr)
  498. sys.exit(2)
  499. def die(message):
  500. print('error:', message, file=sys.stderr)
  501. sys.exit(2)
  502. def to_bytes(str_input):
  503. # Encode to UTF-8 to get binary data.
  504. if isinstance(str_input, bytes):
  505. return str_input
  506. return str_input.encode('utf-8')
  507. def to_string(bytes_input):
  508. if isinstance(bytes_input, str):
  509. return bytes_input
  510. return bytes_input.encode('utf-8')
  511. def convert_string(bytes_input):
  512. try:
  513. return to_string(bytes_input.decode('utf-8'))
  514. except AttributeError: # 'str' object has no attribute 'decode'.
  515. return str(bytes_input)
  516. except UnicodeError:
  517. return str(bytes_input)
  518. if __name__ == '__main__':
  519. main()