clang-format-diff.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #!/usr/bin/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 users:
  17. git diff -U0 HEAD^ | clang-format-diff.py -p1 -i
  18. """
  19. import argparse
  20. import difflib
  21. import re
  22. import string
  23. import subprocess
  24. import StringIO
  25. import sys
  26. # Change this to the full path if clang-format is not on the path.
  27. binary = 'clang-format'
  28. def main():
  29. parser = argparse.ArgumentParser(description=
  30. 'Reformat changed lines in diff. Without -i '
  31. 'option just output the diff that would be '
  32. 'introduced.')
  33. parser.add_argument('-i', action='store_true', default=False,
  34. help='apply edits to files instead of displaying a diff')
  35. parser.add_argument('-p', metavar='NUM', default=0,
  36. help='strip the smallest prefix containing P slashes')
  37. parser.add_argument('-regex', metavar='PATTERN', default=None,
  38. help='custom pattern selecting file paths to reformat '
  39. '(case sensitive, overrides -iregex)')
  40. parser.add_argument('-iregex', metavar='PATTERN', default=
  41. r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc|js|proto'
  42. r'|protodevel)',
  43. help='custom pattern selecting file paths to reformat '
  44. '(case insensitive, overridden by -regex)')
  45. parser.add_argument(
  46. '-style',
  47. help=
  48. 'formatting style to apply (LLVM, Google, Chromium, Mozilla, WebKit)')
  49. args = parser.parse_args()
  50. # Extract changed lines for each file.
  51. filename = None
  52. lines_by_file = {}
  53. for line in sys.stdin:
  54. match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
  55. if match:
  56. filename = match.group(2)
  57. if filename == None:
  58. continue
  59. if args.regex is not None:
  60. if not re.match('^%s$' % args.regex, filename):
  61. continue
  62. else:
  63. if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
  64. continue
  65. match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
  66. if match:
  67. start_line = int(match.group(1))
  68. line_count = 1
  69. if match.group(3):
  70. line_count = int(match.group(3))
  71. if line_count == 0:
  72. continue
  73. end_line = start_line + line_count - 1;
  74. lines_by_file.setdefault(filename, []).extend(
  75. ['-lines', str(start_line) + ':' + str(end_line)])
  76. # Reformat files containing changes in place.
  77. for filename, lines in lines_by_file.iteritems():
  78. command = [binary, filename]
  79. if args.i:
  80. command.append('-i')
  81. command.extend(lines)
  82. if args.style:
  83. command.extend(['-style', args.style])
  84. p = subprocess.Popen(command, stdout=subprocess.PIPE,
  85. stderr=None, stdin=subprocess.PIPE)
  86. stdout, stderr = p.communicate()
  87. if p.returncode != 0:
  88. sys.exit(p.returncode);
  89. if not args.i:
  90. with open(filename) as f:
  91. code = f.readlines()
  92. formatted_code = StringIO.StringIO(stdout).readlines()
  93. diff = difflib.unified_diff(code, formatted_code,
  94. filename, filename,
  95. '(before formatting)', '(after formatting)')
  96. diff_string = string.join(diff, '')
  97. if len(diff_string) > 0:
  98. sys.stdout.write(diff_string)
  99. if __name__ == '__main__':
  100. main()