clang_format_merge_driver.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env python
  2. # Copyright 2016 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """clang-format 3-way merge driver.
  6. This is a custom merge driver for git that helps automatically resolves
  7. conflicts caused by clang-format changes. The conflict resolution
  8. strategy is extremely simple: it simply clang-formats the current,
  9. ancestor branch's, and other branch's version of the file and delegates
  10. the remaining work to git merge-file.
  11. See https://git-scm.com/docs/gitattributes ("Defining a custom merge
  12. driver") for more details.
  13. """
  14. from __future__ import print_function
  15. import subprocess
  16. import sys
  17. import clang_format
  18. def main():
  19. if len(sys.argv) < 5:
  20. print('usage: %s <base> <current> <others> <path in the tree>' %
  21. sys.argv[0])
  22. sys.exit(1)
  23. base, current, others, file_name_in_tree = sys.argv[1:5]
  24. if file_name_in_tree == '%P':
  25. print(file=sys.stderr)
  26. print('ERROR: clang-format merge driver needs git 2.5+', file=sys.stderr)
  27. if sys.platform == 'darwin':
  28. print('Upgrade to Xcode 7.2+', file=sys.stderr)
  29. print(file=sys.stderr)
  30. return 1
  31. print('Running clang-format 3-way merge driver on ' + file_name_in_tree)
  32. try:
  33. tool = clang_format.FindClangFormatToolInChromiumTree()
  34. for fpath in base, current, others:
  35. # Typically, clang-format is used with the -i option to rewrite files
  36. # in-place. However, merge files live in the repo root, so --style=file
  37. # will always pick up the root .clang-format.
  38. #
  39. # Instead, this tool uses --assume-filename so clang-format will pick up
  40. # the appropriate .clang-format. Unfortunately, --assume-filename only
  41. # works when the input is from stdin, so the file I/O portions are lifted
  42. # up into the script as well.
  43. with open(fpath, 'rb') as input_file:
  44. output = subprocess.check_output(
  45. [tool, '--assume-filename=%s' % file_name_in_tree, '--style=file'],
  46. stdin=input_file)
  47. with open(fpath, 'wb') as output_file:
  48. output_file.write(output)
  49. except clang_format.NotFoundError as e:
  50. print(e)
  51. print('Failed to find clang-format. Falling-back on standard 3-way merge')
  52. return subprocess.call(['git', 'merge-file', '-Lcurrent', '-Lbase', '-Lother',
  53. current, base, others])
  54. if __name__ == '__main__':
  55. sys.exit(main())