clang-format-diff.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #!/usr/bin/env python
  2. #
  3. #===- clang-format-diff.py - ClangFormat Diff Reformatter ----*- python -*--===#
  4. #
  5. # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  6. # See https://llvm.org/LICENSE.txt for license information.
  7. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  8. #
  9. #===------------------------------------------------------------------------===#
  10. """
  11. This script reads input from a unified diff and reformats all the changed
  12. lines. This is useful to reformat all the lines touched by a specific patch.
  13. Example usage for git/svn users:
  14. git diff -U0 --no-color HEAD^ | clang-format-diff.py -p1 -i
  15. svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
  16. """
  17. from __future__ import absolute_import, division, print_function
  18. import argparse
  19. import difflib
  20. import re
  21. import subprocess
  22. import sys
  23. if sys.version_info.major >= 3:
  24. from io import StringIO
  25. else:
  26. from io import BytesIO as StringIO
  27. def main():
  28. parser = argparse.ArgumentParser(description=__doc__,
  29. formatter_class=
  30. argparse.RawDescriptionHelpFormatter)
  31. parser.add_argument('-i', action='store_true', default=False,
  32. help='apply edits to files instead of displaying a diff')
  33. parser.add_argument('-p', metavar='NUM', default=0,
  34. help='strip the smallest prefix containing P slashes')
  35. parser.add_argument('-regex', metavar='PATTERN', default=None,
  36. help='custom pattern selecting file paths to reformat '
  37. '(case sensitive, overrides -iregex)')
  38. parser.add_argument('-iregex', metavar='PATTERN', default=
  39. r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc|js|ts|proto'
  40. r'|protodevel|java)',
  41. help='custom pattern selecting file paths to reformat '
  42. '(case insensitive, overridden by -regex)')
  43. parser.add_argument('-sort-includes', action='store_true', default=False,
  44. help='let clang-format sort include blocks')
  45. parser.add_argument('-v', '--verbose', action='store_true',
  46. help='be more verbose, ineffective without -i')
  47. parser.add_argument('-style',
  48. help='formatting style to apply (LLVM, Google, Chromium, '
  49. 'Mozilla, WebKit)')
  50. parser.add_argument('-binary', default='clang-format',
  51. help='location of binary to use for clang-format')
  52. args = parser.parse_args()
  53. # Extract changed lines for each file.
  54. filename = None
  55. lines_by_file = {}
  56. for line in sys.stdin:
  57. match = re.search(r'^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
  58. if match:
  59. filename = match.group(2)
  60. if filename == None:
  61. continue
  62. if args.regex is not None:
  63. if not re.match('^%s$' % args.regex, filename):
  64. continue
  65. else:
  66. if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
  67. continue
  68. match = re.search(r'^@@.*\+(\d+)(,(\d+))?', line)
  69. if match:
  70. start_line = int(match.group(1))
  71. line_count = 1
  72. if match.group(3):
  73. line_count = int(match.group(3))
  74. if line_count == 0:
  75. continue
  76. end_line = start_line + line_count - 1
  77. lines_by_file.setdefault(filename, []).extend(
  78. ['-lines', str(start_line) + ':' + str(end_line)])
  79. # Reformat files containing changes in place.
  80. for filename, lines in lines_by_file.items():
  81. if args.i and args.verbose:
  82. print('Formatting {}'.format(filename))
  83. command = [args.binary, filename]
  84. if args.i:
  85. command.append('-i')
  86. if args.sort_includes:
  87. command.append('-sort-includes')
  88. command.extend(lines)
  89. if args.style:
  90. command.extend(['-style', args.style])
  91. p = subprocess.Popen(command,
  92. stdout=subprocess.PIPE,
  93. stderr=None,
  94. stdin=subprocess.PIPE,
  95. universal_newlines=True)
  96. stdout, stderr = p.communicate()
  97. if p.returncode != 0:
  98. sys.exit(p.returncode)
  99. if not args.i:
  100. with open(filename) as f:
  101. code = f.readlines()
  102. formatted_code = StringIO(stdout).readlines()
  103. diff = difflib.unified_diff(code, formatted_code,
  104. filename, filename,
  105. '(before formatting)', '(after formatting)')
  106. diff_string = ''.join(diff)
  107. if len(diff_string) > 0:
  108. sys.stdout.write(diff_string)
  109. if __name__ == '__main__':
  110. main()