Skip to content

Commit

Permalink
Add script to format code locally
Browse files Browse the repository at this point in the history
Dry run:
>./utils/format.sh

Apply changes:
>./utils/format.sh apply
  • Loading branch information
tlifschitz committed Jun 25, 2024
1 parent 608d225 commit 49b0c75
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions utils/format.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#!/usr/bin/env bash

# Script to run clang-format locally and print differences using colordiff
# only for files that have changes.
#
# Dry run:
# >./format.sh
#
# Apply changes:
# >./format.sh apply


CLANG_FORMAT="clang-format"

# Check if colordiff is installed
if ! command -v colordiff &> /dev/null; then
echo "colordiff is required but not installed. Please install it and run the script again."
exit 1
fi


APPLY=false
# Check if the 'apply' argument is provided
if [ -n "$1" ]; then
if [ "$1" == "apply" ]; then
APPLY=true
else
# If the first argument is not 'apply', print usage and exit
echo "Invalid argument. Usage:"
echo "format.sh apply"
exit 1
fi
fi


if [ "$1" == "apply" ]; then
APPLY=true
fi

# Run clang-format and print differences only for files that have changes
echo "Running clang-format..."

# Excluded paths
EXCLUDED_PATHS=(
"./simplepyble/*"
"*CMakeFiles*"
"*_deps*"
"*build*"
"*external*"
)

FIND_CMD="find . -type f \( -name \"*.h\" -o -name \"*.hpp\" -o -name \"*.cpp\" -o -name \"*.c\" \)"
for path in "${EXCLUDED_PATHS[@]}"; do
FIND_CMD+=" ! -path \"$path\""
done

# Find all relevant source files, excluding specified paths, and process each file
eval "$FIND_CMD" | while read -r file; do

# Get the differences between the original file and the formatted file
diff_output=$($CLANG_FORMAT "$file" | diff -u "$file" - | colordiff)

# If differences are found, print the file name and the differences
if [ -n "$diff_output" ]; then
if [ "$APPLY" == true ]; then
$CLANG_FORMAT -i "$file"
echo "Applied changes to $file"
else
echo "Differences found in $file:"
echo "$diff_output"
fi
fi
done

echo "Format completed."

0 comments on commit 49b0c75

Please sign in to comment.