Skip to content

Commit b697a3e

Browse files
committed
Add formatting helper tool for clang format
Signed-off-by: Ian <[email protected]>
1 parent c25cd87 commit b697a3e

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

tools/format.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import os
2+
import subprocess
3+
import argparse
4+
5+
6+
def format_files(starting_folder, file_extensions):
7+
"""
8+
Recursively format files in the given folder and its subdirectories using clang-format.
9+
"""
10+
for root, _, files in os.walk(starting_folder):
11+
for file in files:
12+
if file.endswith(tuple(file_extensions)):
13+
file_path = os.path.join(root, file)
14+
try:
15+
print(f"Formatting: {file_path}")
16+
subprocess.run(["clang-format", "-i", file_path], check=True)
17+
except subprocess.CalledProcessError as e:
18+
print(f"Error formatting {file_path}: {e}")
19+
20+
21+
def main():
22+
parser = argparse.ArgumentParser(description="Recursively run clang-format on a project.")
23+
parser.add_argument("starting_folder", type=str, help="Starting folder to recursively search for files.")
24+
parser.add_argument("--extensions", type=str, default=".cpp,.h,.hpp,.c",
25+
help="Comma-separated list of file extensions to format. Default: .cpp,.h,.hpp,.c")
26+
args = parser.parse_args()
27+
28+
file_extensions = args.extensions.split(",")
29+
if not os.path.exists(args.starting_folder):
30+
print(f"Error: Starting folder '{args.starting_folder}' does not exist.")
31+
return
32+
33+
print(f"Starting clang-format in folder: {args.starting_folder}")
34+
format_files(args.starting_folder, file_extensions)
35+
print("Formatting complete!")
36+
37+
38+
if __name__ == "__main__":
39+
main()

tools/run_format.bat

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
@echo off
2+
REM Run the Python formatting script for the specified directory and extensions
3+
python format.py ../include/ccmath --extensions .h,.hpp
4+
5+
REM Check the exit code to display an appropriate message
6+
if %errorlevel% neq 0 (
7+
echo Error: Failed to run the format script.
8+
exit /b %errorlevel%
9+
) else (
10+
echo Format script ran successfully.
11+
)

tools/run_format.sh

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#!/bin/bash
2+
# Run the Python formatting script for the specified directory and extensions
3+
4+
python format.py ../include/ccmath --extensions .h,.hpp
5+
6+
# Check the exit code to display an appropriate message
7+
if [ $? -ne 0 ]; then
8+
echo "Error: Failed to run the format script."
9+
exit 1
10+
else
11+
echo "Format script ran successfully."
12+
fi

0 commit comments

Comments
 (0)