Created
March 23, 2023 06:21
-
-
Save JulianKnodt/fee4da06b9ca860e65e7132bf91590fa to your computer and use it in GitHub Desktop.
pre-commit hook for linting only modified lines of cpp files with clang-format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# Author: julianknodt | |
# -- Description | |
# A git pre-commit hook that will run clang-format on only modified lines. | |
import subprocess | |
import os | |
def main(): | |
DRY = False | |
extensions = [".cpp", ".h", ".hpp", ".cxx"] | |
out = subprocess.check_output(["git", "diff", "--cached", "-U0"]) | |
out = out.decode('utf-8') | |
curr_file = None | |
result = 0 | |
for l in out.splitlines(): | |
if l.startswith("diff --git"): | |
file_path = l.split()[-1] | |
assert(file_path.startswith("b/")) | |
curr_file = file_path[2:] | |
if l.startswith("@@"): | |
assert(curr_file is not None) | |
if not any(curr_file.endswith(e) for e in extensions): continue | |
new = l.split()[2] | |
assert(new.startswith("+")) | |
start, count = new[1:].split(",") | |
cmds = [ | |
f"clang-format -i {curr_file} --lines={start}:{start+count}", | |
f"git add {curr_file}", | |
] | |
run = print if DRY else os.system | |
for c in cmds: result |= (run(c) or 0) | |
exit(result) | |
if __name__ == "__main__": main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment