3 A script that runs clang-format on changes detected via git. It will 4 report if running clang-format generated any changes. 6 In CI, the script considers it a failure if running clang-format makes a change. 7 In the pre-commit hook, the user is prompted to apply any clang-format changes. 8 Running tools/clang_format.py manually with no arguments should replicate the pre-commit hook behavior. 10 Only files that are in CLANG_FORMAT_WHITELIST are checked. 23 CLANG_FORMAT_WHITELIST = [
"torch/csrc/jit/",
"test/cpp/jit/"]
25 CPP_FILE_REGEX = re.compile(
"^.*\\.(h|cpp|cc|c|hpp)$")
29 parser = argparse.ArgumentParser(
30 description=
"Execute clang-format on your working copy changes." 36 help=
"Git revision to diff against to get changes",
43 "If true, apply whatever changes clang-format creates. " 44 "Otherwise, just print the changes and exit" 51 help=
"If true, check all whitelisted files instead of just working copy changes",
53 parser.add_argument(
"--verbose",
"-v", action=
"store_true", default=
False)
54 return parser.parse_args()
59 Parse CLANG_FORMAT_WHITELIST and resolve all directories. 60 Returns the set of whitelist cpp source files. 63 for dir
in CLANG_FORMAT_WHITELIST:
64 for root, dirnames, filenames
in os.walk(dir):
65 for filename
in filenames:
66 if CPP_FILE_REGEX.match(filename):
67 matches.append(os.path.join(root, filename))
73 Get all changed files between the working tree and `rev` 76 subprocess.check_output(
77 [
"git",
"diff-index",
"--diff-filter=AMU",
"--name-only", rev]
82 return set(changed_files)
87 Run clang-format on all `files` and report if it changed anything. 88 Returns a mapping of filename => diff generator 92 formatted_text = subprocess.check_output([
"clang-format", f]).decode()
94 orig_text = orig.read()
95 if formatted_text != orig_text:
96 orig_lines = orig_text.split(
"\n")
97 formatted_lines = formatted_text.split(
"\n")
98 diff = difflib.unified_diff(
99 orig_lines, formatted_lines,
"original",
"formatted" 101 name_to_diffs[f] = diff
112 files_to_check = whitelisted_files
115 files_to_check = changed_files & whitelisted_files
118 print(
"Running clang-format on whitelisted files: ")
119 for f
in files_to_check:
122 name_to_diffs =
get_diffs(files_to_check)
124 if len(name_to_diffs) == 0:
127 if args.accept_changes:
129 args = [
"clang-format",
"-i"]
130 args.extend(name_to_diffs.keys())
131 subprocess.check_output(args)
134 args = [
"git",
"add"]
135 args.extend(name_to_diffs.keys())
136 subprocess.check_output(args)
138 print(
"ERROR: Running clang-format created changes: ")
139 for name, diff
in name_to_diffs.items():
146 if __name__ ==
"__main__":
Module caffe2.python.layers.split.