git-clang-format 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. #!/usr/bin/env python
  2. #
  3. #===- git-clang-format - ClangFormat Git 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. r"""
  11. clang-format git integration
  12. ============================
  13. This file provides a clang-format integration for git. Put it somewhere in your
  14. path and ensure that it is executable. Then, "git clang-format" will invoke
  15. clang-format on the changes in current files or a specific commit.
  16. For further details, run:
  17. git clang-format -h
  18. Requires Python 2.7 or Python 3
  19. """
  20. from __future__ import absolute_import, division, print_function
  21. import argparse
  22. import collections
  23. import contextlib
  24. import errno
  25. import os
  26. import re
  27. import subprocess
  28. import sys
  29. usage = 'git clang-format [OPTIONS] [<commit>] [<commit>] [--] [<file>...]'
  30. desc = '''
  31. If zero or one commits are given, run clang-format on all lines that differ
  32. between the working directory and <commit>, which defaults to HEAD. Changes are
  33. only applied to the working directory.
  34. If two commits are given (requires --diff), run clang-format on all lines in the
  35. second <commit> that differ from the first <commit>.
  36. The following git-config settings set the default of the corresponding option:
  37. clangFormat.binary
  38. clangFormat.commit
  39. clangFormat.extensions
  40. clangFormat.style
  41. '''
  42. # Name of the temporary index file in which save the output of clang-format.
  43. # This file is created within the .git directory.
  44. temp_index_basename = 'clang-format-index'
  45. Range = collections.namedtuple('Range', 'start, count')
  46. def main():
  47. config = load_git_config()
  48. # In order to keep '--' yet allow options after positionals, we need to
  49. # check for '--' ourselves. (Setting nargs='*' throws away the '--', while
  50. # nargs=argparse.REMAINDER disallows options after positionals.)
  51. argv = sys.argv[1:]
  52. try:
  53. idx = argv.index('--')
  54. except ValueError:
  55. dash_dash = []
  56. else:
  57. dash_dash = argv[idx:]
  58. argv = argv[:idx]
  59. default_extensions = ','.join([
  60. # From clang/lib/Frontend/FrontendOptions.cpp, all lower case
  61. 'c', 'h', # C
  62. 'm', # ObjC
  63. 'mm', # ObjC++
  64. 'cc', 'cp', 'cpp', 'c++', 'cxx', 'hh', 'hpp', 'hxx', # C++
  65. 'cu', 'cuh', # CUDA
  66. # Other languages that clang-format supports
  67. 'proto', 'protodevel', # Protocol Buffers
  68. 'java', # Java
  69. 'js', # JavaScript
  70. 'ts', # TypeScript
  71. 'cs', # C Sharp
  72. ])
  73. p = argparse.ArgumentParser(
  74. usage=usage, formatter_class=argparse.RawDescriptionHelpFormatter,
  75. description=desc)
  76. p.add_argument('--binary',
  77. default=config.get('clangformat.binary', 'clang-format'),
  78. help='path to clang-format'),
  79. p.add_argument('--commit',
  80. default=config.get('clangformat.commit', 'HEAD'),
  81. help='default commit to use if none is specified'),
  82. p.add_argument('--diff', action='store_true',
  83. help='print a diff instead of applying the changes')
  84. p.add_argument('--extensions',
  85. default=config.get('clangformat.extensions',
  86. default_extensions),
  87. help=('comma-separated list of file extensions to format, '
  88. 'excluding the period and case-insensitive')),
  89. p.add_argument('-f', '--force', action='store_true',
  90. help='allow changes to unstaged files')
  91. p.add_argument('-p', '--patch', action='store_true',
  92. help='select hunks interactively')
  93. p.add_argument('-q', '--quiet', action='count', default=0,
  94. help='print less information')
  95. p.add_argument('--style',
  96. default=config.get('clangformat.style', None),
  97. help='passed to clang-format'),
  98. p.add_argument('-v', '--verbose', action='count', default=0,
  99. help='print extra information')
  100. # We gather all the remaining positional arguments into 'args' since we need
  101. # to use some heuristics to determine whether or not <commit> was present.
  102. # However, to print pretty messages, we make use of metavar and help.
  103. p.add_argument('args', nargs='*', metavar='<commit>',
  104. help='revision from which to compute the diff')
  105. p.add_argument('ignored', nargs='*', metavar='<file>...',
  106. help='if specified, only consider differences in these files')
  107. opts = p.parse_args(argv)
  108. opts.verbose -= opts.quiet
  109. del opts.quiet
  110. commits, files = interpret_args(opts.args, dash_dash, opts.commit)
  111. if len(commits) > 1:
  112. if not opts.diff:
  113. die('--diff is required when two commits are given')
  114. else:
  115. if len(commits) > 2:
  116. die('at most two commits allowed; %d given' % len(commits))
  117. changed_lines = compute_diff_and_extract_lines(commits, files)
  118. if opts.verbose >= 1:
  119. ignored_files = set(changed_lines)
  120. filter_by_extension(changed_lines, opts.extensions.lower().split(','))
  121. # The computed diff outputs absolute paths, so we must cd before accessing
  122. # those files.
  123. cd_to_toplevel()
  124. filter_symlinks(changed_lines)
  125. if opts.verbose >= 1:
  126. ignored_files.difference_update(changed_lines)
  127. if ignored_files:
  128. print(
  129. 'Ignoring changes in the following files (wrong extension or symlink):')
  130. for filename in ignored_files:
  131. print(' %s' % filename)
  132. if changed_lines:
  133. print('Running clang-format on the following files:')
  134. for filename in changed_lines:
  135. print(' %s' % filename)
  136. if not changed_lines:
  137. if opts.verbose >= 0:
  138. print('no modified files to format')
  139. return
  140. if len(commits) > 1:
  141. old_tree = commits[1]
  142. new_tree = run_clang_format_and_save_to_tree(changed_lines,
  143. revision=commits[1],
  144. binary=opts.binary,
  145. style=opts.style)
  146. else:
  147. old_tree = create_tree_from_workdir(changed_lines)
  148. new_tree = run_clang_format_and_save_to_tree(changed_lines,
  149. binary=opts.binary,
  150. style=opts.style)
  151. if opts.verbose >= 1:
  152. print('old tree: %s' % old_tree)
  153. print('new tree: %s' % new_tree)
  154. if old_tree == new_tree:
  155. if opts.verbose >= 0:
  156. print('clang-format did not modify any files')
  157. elif opts.diff:
  158. print_diff(old_tree, new_tree)
  159. else:
  160. changed_files = apply_changes(old_tree, new_tree, force=opts.force,
  161. patch_mode=opts.patch)
  162. if (opts.verbose >= 0 and not opts.patch) or opts.verbose >= 1:
  163. print('changed files:')
  164. for filename in changed_files:
  165. print(' %s' % filename)
  166. def load_git_config(non_string_options=None):
  167. """Return the git configuration as a dictionary.
  168. All options are assumed to be strings unless in `non_string_options`, in which
  169. is a dictionary mapping option name (in lower case) to either "--bool" or
  170. "--int"."""
  171. if non_string_options is None:
  172. non_string_options = {}
  173. out = {}
  174. for entry in run('git', 'config', '--list', '--null').split('\0'):
  175. if entry:
  176. if '\n' in entry:
  177. name, value = entry.split('\n', 1)
  178. else:
  179. # A setting with no '=' ('\n' with --null) is implicitly 'true'
  180. name = entry
  181. value = 'true'
  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 filter_symlinks(dictionary):
  299. """Delete every key in `dictionary` that is a symlink."""
  300. for filename in list(dictionary.keys()):
  301. if os.path.islink(filename):
  302. del dictionary[filename]
  303. def cd_to_toplevel():
  304. """Change to the top level of the git repository."""
  305. toplevel = run('git', 'rev-parse', '--show-toplevel')
  306. os.chdir(toplevel)
  307. def create_tree_from_workdir(filenames):
  308. """Create a new git tree with the given files from the working directory.
  309. Returns the object ID (SHA-1) of the created tree."""
  310. return create_tree(filenames, '--stdin')
  311. def run_clang_format_and_save_to_tree(changed_lines, revision=None,
  312. binary='clang-format', style=None):
  313. """Run clang-format on each file and save the result to a git tree.
  314. Returns the object ID (SHA-1) of the created tree."""
  315. def iteritems(container):
  316. try:
  317. return container.iteritems() # Python 2
  318. except AttributeError:
  319. return container.items() # Python 3
  320. def index_info_generator():
  321. for filename, line_ranges in iteritems(changed_lines):
  322. if revision:
  323. git_metadata_cmd = ['git', 'ls-tree',
  324. '%s:%s' % (revision, os.path.dirname(filename)),
  325. os.path.basename(filename)]
  326. git_metadata = subprocess.Popen(git_metadata_cmd, stdin=subprocess.PIPE,
  327. stdout=subprocess.PIPE)
  328. stdout = git_metadata.communicate()[0]
  329. mode = oct(int(stdout.split()[0], 8))
  330. else:
  331. mode = oct(os.stat(filename).st_mode)
  332. # Adjust python3 octal format so that it matches what git expects
  333. if mode.startswith('0o'):
  334. mode = '0' + mode[2:]
  335. blob_id = clang_format_to_blob(filename, line_ranges,
  336. revision=revision,
  337. binary=binary,
  338. style=style)
  339. yield '%s %s\t%s' % (mode, blob_id, filename)
  340. return create_tree(index_info_generator(), '--index-info')
  341. def create_tree(input_lines, mode):
  342. """Create a tree object from the given input.
  343. If mode is '--stdin', it must be a list of filenames. If mode is
  344. '--index-info' is must be a list of values suitable for "git update-index
  345. --index-info", such as "<mode> <SP> <sha1> <TAB> <filename>". Any other mode
  346. is invalid."""
  347. assert mode in ('--stdin', '--index-info')
  348. cmd = ['git', 'update-index', '--add', '-z', mode]
  349. with temporary_index_file():
  350. p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
  351. for line in input_lines:
  352. p.stdin.write(to_bytes('%s\0' % line))
  353. p.stdin.close()
  354. if p.wait() != 0:
  355. die('`%s` failed' % ' '.join(cmd))
  356. tree_id = run('git', 'write-tree')
  357. return tree_id
  358. def clang_format_to_blob(filename, line_ranges, revision=None,
  359. binary='clang-format', style=None):
  360. """Run clang-format on the given file and save the result to a git blob.
  361. Runs on the file in `revision` if not None, or on the file in the working
  362. directory if `revision` is None.
  363. Returns the object ID (SHA-1) of the created blob."""
  364. clang_format_cmd = [binary]
  365. if style:
  366. clang_format_cmd.extend(['-style='+style])
  367. clang_format_cmd.extend([
  368. '-lines=%s:%s' % (start_line, start_line+line_count-1)
  369. for start_line, line_count in line_ranges])
  370. if revision:
  371. clang_format_cmd.extend(['-assume-filename='+filename])
  372. git_show_cmd = ['git', 'cat-file', 'blob', '%s:%s' % (revision, filename)]
  373. git_show = subprocess.Popen(git_show_cmd, stdin=subprocess.PIPE,
  374. stdout=subprocess.PIPE)
  375. git_show.stdin.close()
  376. clang_format_stdin = git_show.stdout
  377. else:
  378. clang_format_cmd.extend([filename])
  379. git_show = None
  380. clang_format_stdin = subprocess.PIPE
  381. try:
  382. clang_format = subprocess.Popen(clang_format_cmd, stdin=clang_format_stdin,
  383. stdout=subprocess.PIPE)
  384. if clang_format_stdin == subprocess.PIPE:
  385. clang_format_stdin = clang_format.stdin
  386. except OSError as e:
  387. if e.errno == errno.ENOENT:
  388. die('cannot find executable "%s"' % binary)
  389. else:
  390. raise
  391. clang_format_stdin.close()
  392. hash_object_cmd = ['git', 'hash-object', '-w', '--path='+filename, '--stdin']
  393. hash_object = subprocess.Popen(hash_object_cmd, stdin=clang_format.stdout,
  394. stdout=subprocess.PIPE)
  395. clang_format.stdout.close()
  396. stdout = hash_object.communicate()[0]
  397. if hash_object.returncode != 0:
  398. die('`%s` failed' % ' '.join(hash_object_cmd))
  399. if clang_format.wait() != 0:
  400. die('`%s` failed' % ' '.join(clang_format_cmd))
  401. if git_show and git_show.wait() != 0:
  402. die('`%s` failed' % ' '.join(git_show_cmd))
  403. return convert_string(stdout).rstrip('\r\n')
  404. @contextlib.contextmanager
  405. def temporary_index_file(tree=None):
  406. """Context manager for setting GIT_INDEX_FILE to a temporary file and deleting
  407. the file afterward."""
  408. index_path = create_temporary_index(tree)
  409. old_index_path = os.environ.get('GIT_INDEX_FILE')
  410. os.environ['GIT_INDEX_FILE'] = index_path
  411. try:
  412. yield
  413. finally:
  414. if old_index_path is None:
  415. del os.environ['GIT_INDEX_FILE']
  416. else:
  417. os.environ['GIT_INDEX_FILE'] = old_index_path
  418. os.remove(index_path)
  419. def create_temporary_index(tree=None):
  420. """Create a temporary index file and return the created file's path.
  421. If `tree` is not None, use that as the tree to read in. Otherwise, an
  422. empty index is created."""
  423. gitdir = run('git', 'rev-parse', '--git-dir')
  424. path = os.path.join(gitdir, temp_index_basename)
  425. if tree is None:
  426. tree = '--empty'
  427. run('git', 'read-tree', '--index-output='+path, tree)
  428. return path
  429. def print_diff(old_tree, new_tree):
  430. """Print the diff between the two trees to stdout."""
  431. # We use the porcelain 'diff' and not plumbing 'diff-tree' because the output
  432. # is expected to be viewed by the user, and only the former does nice things
  433. # like color and pagination.
  434. #
  435. # We also only print modified files since `new_tree` only contains the files
  436. # that were modified, so unmodified files would show as deleted without the
  437. # filter.
  438. subprocess.check_call(['git', 'diff', '--diff-filter=M', old_tree, new_tree,
  439. '--'])
  440. def apply_changes(old_tree, new_tree, force=False, patch_mode=False):
  441. """Apply the changes in `new_tree` to the working directory.
  442. Bails if there are local changes in those files and not `force`. If
  443. `patch_mode`, runs `git checkout --patch` to select hunks interactively."""
  444. changed_files = run('git', 'diff-tree', '--diff-filter=M', '-r', '-z',
  445. '--name-only', old_tree,
  446. new_tree).rstrip('\0').split('\0')
  447. if not force:
  448. unstaged_files = run('git', 'diff-files', '--name-status', *changed_files)
  449. if unstaged_files:
  450. print('The following files would be modified but '
  451. 'have unstaged changes:', file=sys.stderr)
  452. print(unstaged_files, file=sys.stderr)
  453. print('Please commit, stage, or stash them first.', file=sys.stderr)
  454. sys.exit(2)
  455. if patch_mode:
  456. # In patch mode, we could just as well create an index from the new tree
  457. # and checkout from that, but then the user will be presented with a
  458. # message saying "Discard ... from worktree". Instead, we use the old
  459. # tree as the index and checkout from new_tree, which gives the slightly
  460. # better message, "Apply ... to index and worktree". This is not quite
  461. # right, since it won't be applied to the user's index, but oh well.
  462. with temporary_index_file(old_tree):
  463. subprocess.check_call(['git', 'checkout', '--patch', new_tree])
  464. index_tree = old_tree
  465. else:
  466. with temporary_index_file(new_tree):
  467. run('git', 'checkout-index', '-a', '-f')
  468. return changed_files
  469. def run(*args, **kwargs):
  470. stdin = kwargs.pop('stdin', '')
  471. verbose = kwargs.pop('verbose', True)
  472. strip = kwargs.pop('strip', True)
  473. for name in kwargs:
  474. raise TypeError("run() got an unexpected keyword argument '%s'" % name)
  475. p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  476. stdin=subprocess.PIPE)
  477. stdout, stderr = p.communicate(input=stdin)
  478. stdout = convert_string(stdout)
  479. stderr = convert_string(stderr)
  480. if p.returncode == 0:
  481. if stderr:
  482. if verbose:
  483. print('`%s` printed to stderr:' % ' '.join(args), file=sys.stderr)
  484. print(stderr.rstrip(), file=sys.stderr)
  485. if strip:
  486. stdout = stdout.rstrip('\r\n')
  487. return stdout
  488. if verbose:
  489. print('`%s` returned %s' % (' '.join(args), p.returncode), file=sys.stderr)
  490. if stderr:
  491. print(stderr.rstrip(), file=sys.stderr)
  492. sys.exit(2)
  493. def die(message):
  494. print('error:', message, file=sys.stderr)
  495. sys.exit(2)
  496. def to_bytes(str_input):
  497. # Encode to UTF-8 to get binary data.
  498. if isinstance(str_input, bytes):
  499. return str_input
  500. return str_input.encode('utf-8')
  501. def to_string(bytes_input):
  502. if isinstance(bytes_input, str):
  503. return bytes_input
  504. return bytes_input.encode('utf-8')
  505. def convert_string(bytes_input):
  506. try:
  507. return to_string(bytes_input.decode('utf-8'))
  508. except AttributeError: # 'str' object has no attribute 'decode'.
  509. return str(bytes_input)
  510. except UnicodeError:
  511. return str(bytes_input)
  512. if __name__ == '__main__':
  513. main()