git-clang-format 22 KB

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