clang-format-diff.py 4.5 KB

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