clang-format-diff.py 4.3 KB

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