1
0

git-clang-format 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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.extension
  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', # 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. if opts.verbose >= 1:
  122. ignored_files.difference_update(changed_lines)
  123. if ignored_files:
  124. print('Ignoring changes in the following files (wrong extension):')
  125. for filename in ignored_files:
  126. print(' %s' % filename)
  127. if changed_lines:
  128. print('Running clang-format on the following files:')
  129. for filename in changed_lines:
  130. print(' %s' % filename)
  131. if not changed_lines:
  132. print('no modified files to format')
  133. return
  134. # The computed diff outputs absolute paths, so we must cd before accessing
  135. # those files.
  136. cd_to_toplevel()
  137. if len(commits) > 1:
  138. old_tree = commits[1]
  139. new_tree = run_clang_format_and_save_to_tree(changed_lines,
  140. revision=commits[1],
  141. binary=opts.binary,
  142. style=opts.style)
  143. else:
  144. old_tree = create_tree_from_workdir(changed_lines)
  145. new_tree = run_clang_format_and_save_to_tree(changed_lines,
  146. binary=opts.binary,
  147. style=opts.style)
  148. if opts.verbose >= 1:
  149. print('old tree: %s' % old_tree)
  150. print('new tree: %s' % new_tree)
  151. if old_tree == new_tree:
  152. if opts.verbose >= 0:
  153. print('clang-format did not modify any files')
  154. elif opts.diff:
  155. print_diff(old_tree, new_tree)
  156. else:
  157. changed_files = apply_changes(old_tree, new_tree, force=opts.force,
  158. patch_mode=opts.patch)
  159. if (opts.verbose >= 0 and not opts.patch) or opts.verbose >= 1:
  160. print('changed files:')
  161. for filename in changed_files:
  162. print(' %s' % filename)
  163. def load_git_config(non_string_options=None):
  164. """Return the git configuration as a dictionary.
  165. All options are assumed to be strings unless in `non_string_options`, in which
  166. is a dictionary mapping option name (in lower case) to either "--bool" or
  167. "--int"."""
  168. if non_string_options is None:
  169. non_string_options = {}
  170. out = {}
  171. for entry in run('git', 'config', '--list', '--null').split('\0'):
  172. if entry:
  173. name, value = entry.split('\n', 1)
  174. if name in non_string_options:
  175. value = run('git', 'config', non_string_options[name], name)
  176. out[name] = value
  177. return out
  178. def interpret_args(args, dash_dash, default_commit):
  179. """Interpret `args` as "[commits] [--] [files]" and return (commits, files).
  180. It is assumed that "--" and everything that follows has been removed from
  181. args and placed in `dash_dash`.
  182. If "--" is present (i.e., `dash_dash` is non-empty), the arguments to its
  183. left (if present) are taken as commits. Otherwise, the arguments are checked
  184. from left to right if they are commits or files. If commits are not given,
  185. a list with `default_commit` is used."""
  186. if dash_dash:
  187. if len(args) == 0:
  188. commits = [default_commit]
  189. else:
  190. commits = args
  191. for commit in commits:
  192. object_type = get_object_type(commit)
  193. if object_type not in ('commit', 'tag'):
  194. if object_type is None:
  195. die("'%s' is not a commit" % commit)
  196. else:
  197. die("'%s' is a %s, but a commit was expected" % (commit, object_type))
  198. files = dash_dash[1:]
  199. elif args:
  200. commits = []
  201. while args:
  202. if not disambiguate_revision(args[0]):
  203. break
  204. commits.append(args.pop(0))
  205. if not commits:
  206. commits = [default_commit]
  207. files = args
  208. else:
  209. commits = [default_commit]
  210. files = []
  211. return commits, files
  212. def disambiguate_revision(value):
  213. """Returns True if `value` is a revision, False if it is a file, or dies."""
  214. # If `value` is ambiguous (neither a commit nor a file), the following
  215. # command will die with an appropriate error message.
  216. run('git', 'rev-parse', value, verbose=False)
  217. object_type = get_object_type(value)
  218. if object_type is None:
  219. return False
  220. if object_type in ('commit', 'tag'):
  221. return True
  222. die('`%s` is a %s, but a commit or filename was expected' %
  223. (value, object_type))
  224. def get_object_type(value):
  225. """Returns a string description of an object's type, or None if it is not
  226. a valid git object."""
  227. cmd = ['git', 'cat-file', '-t', value]
  228. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  229. stdout, stderr = p.communicate()
  230. if p.returncode != 0:
  231. return None
  232. return convert_string(stdout.strip())
  233. def compute_diff_and_extract_lines(commits, files):
  234. """Calls compute_diff() followed by extract_lines()."""
  235. diff_process = compute_diff(commits, files)
  236. changed_lines = extract_lines(diff_process.stdout)
  237. diff_process.stdout.close()
  238. diff_process.wait()
  239. if diff_process.returncode != 0:
  240. # Assume error was already printed to stderr.
  241. sys.exit(2)
  242. return changed_lines
  243. def compute_diff(commits, files):
  244. """Return a subprocess object producing the diff from `commits`.
  245. The return value's `stdin` file object will produce a patch with the
  246. differences between the working directory and the first commit if a single
  247. one was specified, or the difference between both specified commits, filtered
  248. on `files` (if non-empty). Zero context lines are used in the patch."""
  249. git_tool = 'diff-index'
  250. if len(commits) > 1:
  251. git_tool = 'diff-tree'
  252. cmd = ['git', git_tool, '-p', '-U0'] + commits + ['--']
  253. cmd.extend(files)
  254. p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  255. p.stdin.close()
  256. return p
  257. def extract_lines(patch_file):
  258. """Extract the changed lines in `patch_file`.
  259. The return value is a dictionary mapping filename to a list of (start_line,
  260. line_count) pairs.
  261. The input must have been produced with ``-U0``, meaning unidiff format with
  262. zero lines of context. The return value is a dict mapping filename to a
  263. list of line `Range`s."""
  264. matches = {}
  265. for line in patch_file:
  266. line = convert_string(line)
  267. match = re.search(r'^\+\+\+\ [^/]+/(.*)', line)
  268. if match:
  269. filename = match.group(1).rstrip('\r\n')
  270. match = re.search(r'^@@ -[0-9,]+ \+(\d+)(,(\d+))?', line)
  271. if match:
  272. start_line = int(match.group(1))
  273. line_count = 1
  274. if match.group(3):
  275. line_count = int(match.group(3))
  276. if line_count > 0:
  277. matches.setdefault(filename, []).append(Range(start_line, line_count))
  278. return matches
  279. def filter_by_extension(dictionary, allowed_extensions):
  280. """Delete every key in `dictionary` that doesn't have an allowed extension.
  281. `allowed_extensions` must be a collection of lowercase file extensions,
  282. excluding the period."""
  283. allowed_extensions = frozenset(allowed_extensions)
  284. for filename in list(dictionary.keys()):
  285. base_ext = filename.rsplit('.', 1)
  286. if len(base_ext) == 1 and '' in allowed_extensions:
  287. continue
  288. if len(base_ext) == 1 or base_ext[1].lower() not in allowed_extensions:
  289. del dictionary[filename]
  290. def cd_to_toplevel():
  291. """Change to the top level of the git repository."""
  292. toplevel = run('git', 'rev-parse', '--show-toplevel')
  293. os.chdir(toplevel)
  294. def create_tree_from_workdir(filenames):
  295. """Create a new git tree with the given files from the working directory.
  296. Returns the object ID (SHA-1) of the created tree."""
  297. return create_tree(filenames, '--stdin')
  298. def run_clang_format_and_save_to_tree(changed_lines, revision=None,
  299. binary='clang-format', style=None):
  300. """Run clang-format on each file and save the result to a git tree.
  301. Returns the object ID (SHA-1) of the created tree."""
  302. def iteritems(container):
  303. try:
  304. return container.iteritems() # Python 2
  305. except AttributeError:
  306. return container.items() # Python 3
  307. def index_info_generator():
  308. for filename, line_ranges in iteritems(changed_lines):
  309. if revision:
  310. git_metadata_cmd = ['git', 'ls-tree',
  311. '%s:%s' % (revision, os.path.dirname(filename)),
  312. os.path.basename(filename)]
  313. git_metadata = subprocess.Popen(git_metadata_cmd, stdin=subprocess.PIPE,
  314. stdout=subprocess.PIPE)
  315. stdout = git_metadata.communicate()[0]
  316. mode = oct(int(stdout.split()[0], 8))
  317. else:
  318. mode = oct(os.stat(filename).st_mode)
  319. # Adjust python3 octal format so that it matches what git expects
  320. if mode.startswith('0o'):
  321. mode = '0' + mode[2:]
  322. blob_id = clang_format_to_blob(filename, line_ranges,
  323. revision=revision,
  324. binary=binary,
  325. style=style)
  326. yield '%s %s\t%s' % (mode, blob_id, filename)
  327. return create_tree(index_info_generator(), '--index-info')
  328. def create_tree(input_lines, mode):
  329. """Create a tree object from the given input.
  330. If mode is '--stdin', it must be a list of filenames. If mode is
  331. '--index-info' is must be a list of values suitable for "git update-index
  332. --index-info", such as "<mode> <SP> <sha1> <TAB> <filename>". Any other mode
  333. is invalid."""
  334. assert mode in ('--stdin', '--index-info')
  335. cmd = ['git', 'update-index', '--add', '-z', mode]
  336. with temporary_index_file():
  337. p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
  338. for line in input_lines:
  339. p.stdin.write(to_bytes('%s\0' % line))
  340. p.stdin.close()
  341. if p.wait() != 0:
  342. die('`%s` failed' % ' '.join(cmd))
  343. tree_id = run('git', 'write-tree')
  344. return tree_id
  345. def clang_format_to_blob(filename, line_ranges, revision=None,
  346. binary='clang-format', style=None):
  347. """Run clang-format on the given file and save the result to a git blob.
  348. Runs on the file in `revision` if not None, or on the file in the working
  349. directory if `revision` is None.
  350. Returns the object ID (SHA-1) of the created blob."""
  351. clang_format_cmd = [binary]
  352. if style:
  353. clang_format_cmd.extend(['-style='+style])
  354. clang_format_cmd.extend([
  355. '-lines=%s:%s' % (start_line, start_line+line_count-1)
  356. for start_line, line_count in line_ranges])
  357. if revision:
  358. clang_format_cmd.extend(['-assume-filename='+filename])
  359. git_show_cmd = ['git', 'cat-file', 'blob', '%s:%s' % (revision, filename)]
  360. git_show = subprocess.Popen(git_show_cmd, stdin=subprocess.PIPE,
  361. stdout=subprocess.PIPE)
  362. git_show.stdin.close()
  363. clang_format_stdin = git_show.stdout
  364. else:
  365. clang_format_cmd.extend([filename])
  366. git_show = None
  367. clang_format_stdin = subprocess.PIPE
  368. try:
  369. clang_format = subprocess.Popen(clang_format_cmd, stdin=clang_format_stdin,
  370. stdout=subprocess.PIPE)
  371. if clang_format_stdin == subprocess.PIPE:
  372. clang_format_stdin = clang_format.stdin
  373. except OSError as e:
  374. if e.errno == errno.ENOENT:
  375. die('cannot find executable "%s"' % binary)
  376. else:
  377. raise
  378. clang_format_stdin.close()
  379. hash_object_cmd = ['git', 'hash-object', '-w', '--path='+filename, '--stdin']
  380. hash_object = subprocess.Popen(hash_object_cmd, stdin=clang_format.stdout,
  381. stdout=subprocess.PIPE)
  382. clang_format.stdout.close()
  383. stdout = hash_object.communicate()[0]
  384. if hash_object.returncode != 0:
  385. die('`%s` failed' % ' '.join(hash_object_cmd))
  386. if clang_format.wait() != 0:
  387. die('`%s` failed' % ' '.join(clang_format_cmd))
  388. if git_show and git_show.wait() != 0:
  389. die('`%s` failed' % ' '.join(git_show_cmd))
  390. return convert_string(stdout).rstrip('\r\n')
  391. @contextlib.contextmanager
  392. def temporary_index_file(tree=None):
  393. """Context manager for setting GIT_INDEX_FILE to a temporary file and deleting
  394. the file afterward."""
  395. index_path = create_temporary_index(tree)
  396. old_index_path = os.environ.get('GIT_INDEX_FILE')
  397. os.environ['GIT_INDEX_FILE'] = index_path
  398. try:
  399. yield
  400. finally:
  401. if old_index_path is None:
  402. del os.environ['GIT_INDEX_FILE']
  403. else:
  404. os.environ['GIT_INDEX_FILE'] = old_index_path
  405. os.remove(index_path)
  406. def create_temporary_index(tree=None):
  407. """Create a temporary index file and return the created file's path.
  408. If `tree` is not None, use that as the tree to read in. Otherwise, an
  409. empty index is created."""
  410. gitdir = run('git', 'rev-parse', '--git-dir')
  411. path = os.path.join(gitdir, temp_index_basename)
  412. if tree is None:
  413. tree = '--empty'
  414. run('git', 'read-tree', '--index-output='+path, tree)
  415. return path
  416. def print_diff(old_tree, new_tree):
  417. """Print the diff between the two trees to stdout."""
  418. # We use the porcelain 'diff' and not plumbing 'diff-tree' because the output
  419. # is expected to be viewed by the user, and only the former does nice things
  420. # like color and pagination.
  421. #
  422. # We also only print modified files since `new_tree` only contains the files
  423. # that were modified, so unmodified files would show as deleted without the
  424. # filter.
  425. subprocess.check_call(['git', 'diff', '--diff-filter=M', old_tree, new_tree,
  426. '--'])
  427. def apply_changes(old_tree, new_tree, force=False, patch_mode=False):
  428. """Apply the changes in `new_tree` to the working directory.
  429. Bails if there are local changes in those files and not `force`. If
  430. `patch_mode`, runs `git checkout --patch` to select hunks interactively."""
  431. changed_files = run('git', 'diff-tree', '--diff-filter=M', '-r', '-z',
  432. '--name-only', old_tree,
  433. new_tree).rstrip('\0').split('\0')
  434. if not force:
  435. unstaged_files = run('git', 'diff-files', '--name-status', *changed_files)
  436. if unstaged_files:
  437. print('The following files would be modified but '
  438. 'have unstaged changes:', file=sys.stderr)
  439. print(unstaged_files, file=sys.stderr)
  440. print('Please commit, stage, or stash them first.', file=sys.stderr)
  441. sys.exit(2)
  442. if patch_mode:
  443. # In patch mode, we could just as well create an index from the new tree
  444. # and checkout from that, but then the user will be presented with a
  445. # message saying "Discard ... from worktree". Instead, we use the old
  446. # tree as the index and checkout from new_tree, which gives the slightly
  447. # better message, "Apply ... to index and worktree". This is not quite
  448. # right, since it won't be applied to the user's index, but oh well.
  449. with temporary_index_file(old_tree):
  450. subprocess.check_call(['git', 'checkout', '--patch', new_tree])
  451. index_tree = old_tree
  452. else:
  453. with temporary_index_file(new_tree):
  454. run('git', 'checkout-index', '-a', '-f')
  455. return changed_files
  456. def run(*args, **kwargs):
  457. stdin = kwargs.pop('stdin', '')
  458. verbose = kwargs.pop('verbose', True)
  459. strip = kwargs.pop('strip', True)
  460. for name in kwargs:
  461. raise TypeError("run() got an unexpected keyword argument '%s'" % name)
  462. p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  463. stdin=subprocess.PIPE)
  464. stdout, stderr = p.communicate(input=stdin)
  465. stdout = convert_string(stdout)
  466. stderr = convert_string(stderr)
  467. if p.returncode == 0:
  468. if stderr:
  469. if verbose:
  470. print('`%s` printed to stderr:' % ' '.join(args), file=sys.stderr)
  471. print(stderr.rstrip(), file=sys.stderr)
  472. if strip:
  473. stdout = stdout.rstrip('\r\n')
  474. return stdout
  475. if verbose:
  476. print('`%s` returned %s' % (' '.join(args), p.returncode), file=sys.stderr)
  477. if stderr:
  478. print(stderr.rstrip(), file=sys.stderr)
  479. sys.exit(2)
  480. def die(message):
  481. print('error:', message, file=sys.stderr)
  482. sys.exit(2)
  483. def to_bytes(str_input):
  484. # Encode to UTF-8 to get binary data.
  485. if isinstance(str_input, bytes):
  486. return str_input
  487. return str_input.encode('utf-8')
  488. def to_string(bytes_input):
  489. if isinstance(bytes_input, str):
  490. return bytes_input
  491. return bytes_input.encode('utf-8')
  492. def convert_string(bytes_input):
  493. try:
  494. return to_string(bytes_input.decode('utf-8'))
  495. except AttributeError: # 'str' object has no attribute 'decode'.
  496. return str(bytes_input)
  497. except UnicodeError:
  498. return str(bytes_input)
  499. if __name__ == '__main__':
  500. main()