Created
July 14, 2025 17:45
-
-
Save lassoan/0d42031ec1ea6a90d56ebedc25cce230 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
""" | |
Run clang-format on modified files, on files modified in the last commit, or all files in the source tree | |
(that match the valid file extensions .h and .cxx). | |
Example use: | |
cd /d C:\D\S4 | |
c:\Users\andra\AppData\Local\Programs\Python\Python313\python.exe autoformat.py | |
""" | |
import subprocess | |
import os | |
import pathlib | |
# Extensions to format | |
valid_exts = {'.h', '.cxx'} | |
def get_modified_files(commit_range=0): | |
try: | |
result = subprocess.run( | |
['git', 'diff', '--name-only', '--diff-filter=ACM', f'HEAD~{commit_range}'], | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE, | |
text=True, | |
check=True | |
) | |
return result.stdout.strip().splitlines() | |
except subprocess.CalledProcessError as e: | |
print("Error getting git diff:", e.stderr) | |
return [] | |
def is_valid_file(path): | |
ext = pathlib.Path(path).suffix.lower() | |
return ext in valid_exts and os.path.isfile(path) | |
def format_file(path): | |
print(f"Formatting {path}") | |
subprocess.run([r'c:\Program Files\LLVM\bin\clang-format.exe', '-i', '--style=file', path]) | |
def main(): | |
"""Main function to format modified files. | |
If --all is passed, format all files with valid extensions. | |
If --last is passed, format files modified in the last commit. | |
""" | |
import sys | |
if len(sys.argv) > 1 and sys.argv[1] == '--all': | |
files = [f for f in pathlib.Path('.').rglob('*') if is_valid_file(f)] | |
if len(sys.argv) > 1 and sys.argv[1] == '--last': | |
files = get_modified_files(1) | |
else: | |
files = get_modified_files() | |
for f in files: | |
if is_valid_file(f): | |
format_file(f) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment