Skip to content

Integrate format code script#759

Merged
elazarg merged 3 commits into
vbpf:mainfrom
Alan-Jowett:format_code
Nov 5, 2024
Merged

Integrate format code script#759
elazarg merged 3 commits into
vbpf:mainfrom
Alan-Jowett:format_code

Conversation

@Alan-Jowett

@Alan-Jowett Alan-Jowett commented Oct 24, 2024

Copy link
Copy Markdown
Contributor

This pull request introduces two new scripts, format-code and format-code.ps1, to format C/C++ source files based on .clang-format rules. Additionally, it updates the pre-commit script to include a formatting check. Here are the most important changes:

New Formatting Scripts:

  • scripts/format-code: Added a Bash script to format C/C++ source files. It includes options for verbose output, quiet mode, staged files, and what-if scenarios. It also checks for an acceptable version of clang-format and processes command-line options.
  • scripts/format-code.ps1: Added a PowerShell script with similar functionality to the Bash script, including handling of command-line options and checking for clang-format. It also includes verbose and what-if modes.

Pre-commit Hook Update:

  • scripts/pre-commit: Updated to include a call to the new format-code script to check for formatting issues before committing. If formatting issues are found, the commit is aborted with instructions to fix the formatting.

Summary by CodeRabbit

  • New Features

    • Introduced format-code scripts for formatting C/C++ source files according to .clang-format rules, available in both Bash and PowerShell.
    • Added a pre-commit hook to validate code formatting before commits, ensuring adherence to formatting standards.
  • Bug Fixes

    • Enhanced error handling in the formatting scripts to manage failures and unknown options effectively.

Signed-off-by: Alan Jowett <alan.jowett@microsoft.com>
@coderabbitai

coderabbitai Bot commented Oct 24, 2024

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Alan-Jowett has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 18 minutes and 50 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c933dc0 and aa49c3b.

Walkthrough

The changes introduce a new format-code script in both Bash and PowerShell, designed to format C/C++ source files according to .clang-format rules. These scripts include various command-line options for user interaction, error handling, and logging. Additionally, the scripts/pre-commit hook is updated to validate code formatting before commits by executing the format-code script, ensuring adherence to formatting standards.

Changes

File Change Summary
scripts/format-code New Bash script added to format C/C++ files, includes logging, command-line options, and error handling.
scripts/format-code.ps1 New PowerShell script added with similar functionality as the Bash script, including logging and command-line options.
scripts/pre-commit Updated to execute the format-code script with --quiet and --whatif options for staged files, ensuring formatting standards before commits.

Poem

In the land of code, so neat and bright,
A script was born to set things right.
With clang-format, it takes a stand,
Formatting files, oh so grand!
Pre-commit checks, no mess in sight,
Hopping along, our code takes flight! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 13

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 6f944ff and c933dc0.

📒 Files selected for processing (3)
  • scripts/format-code (1 hunks)
  • scripts/format-code.ps1 (1 hunks)
  • scripts/pre-commit (1 hunks)
🔇 Additional comments (4)
scripts/pre-commit (2)

40-43: LGTM! Well-structured integration of the formatting check.

The implementation:

  • Maintains consistent error handling with existing checks
  • Provides clear, actionable error messages
  • Includes cross-platform support with both bash and powershell commands
  • Preserves the ability to skip checks with --no-verify

40-42: 🛠️ Refactor suggestion

Verify the format-code script path and improve error handling.

While the implementation looks good, there are a few considerations:

Let's verify the script path and permissions:

Consider these improvements:

  1. Add error handling for the case when format-code script is not found
  2. Use array expansion for files to handle paths with spaces:
-if ! "$scripts/format-code" --quiet --whatif --files="${files[*]}"; then
+if [[ ! -x "$scripts/format-code" ]]; then
+    exit_ "Commit failed: format-code script not found or not executable"
+fi
+if ! "$scripts/format-code" --quiet --whatif --files="${files[@]}"; then
scripts/format-code (1)

36-76: ⚠️ Potential issue

Initialize flag variables

The script uses several flag variables (usage, verbose, quiet, whatif) but doesn't initialize them. This could lead to undefined behavior.

Add these initializations at the start of the script:

+# Initialize flags
+usage=0
+verbose=0
+quiet=0
+whatif=0

Validate option values

The script doesn't validate the values provided to --exclude-dirs and --include-exts.

Consider adding validation:

     --exclude-dirs=*)
         userExcludeDirs="${opt#*=}"
+        if [[ -z "$userExcludeDirs" ]]; then
+            echo "Error: --exclude-dirs requires a value"
+            exit 1
+        fi
         ;;
scripts/format-code.ps1 (1)

105-157: LGTM! Well-documented help message.

The help message is comprehensive, well-structured, and includes clear examples.

Comment thread scripts/format-code
Comment thread scripts/format-code
Comment on lines +18 to +28
##==============================================================================
##
## Echo if whatif flag is specified but not quiet flag
##
##==============================================================================
log_whatif()
{
if [[ ${whatif} -eq 1 && ${quiet} -ne 1 ]]; then
echo "$1"
fi
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Enhance function documentation clarity

The comment for log_whatif could be more precise about the condition logic.

Consider updating the comment to:

-## Echo if whatif flag is specified but not quiet flag
+## Echo if both conditions are met:
+## 1. whatif flag is specified (whatif=1)
+## 2. quiet flag is not specified (quiet!=1)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
##==============================================================================
##
## Echo if whatif flag is specified but not quiet flag
##
##==============================================================================
log_whatif()
{
if [[ ${whatif} -eq 1 && ${quiet} -ne 1 ]]; then
echo "$1"
fi
}
##==============================================================================
##
## Echo if both conditions are met:
## 1. whatif flag is specified (whatif=1)
## 2. quiet flag is not specified (quiet!=1)
##
##==============================================================================
log_whatif()
{
if [[ ${whatif} -eq 1 && ${quiet} -ne 1 ]]; then
echo "$1"
fi
}

Comment thread scripts/format-code
Comment on lines +160 to +181
check_clang-format()
{
# First check explicitly for the clang-format-7 executable.
cf=$(command -v clang-format-7 2> /dev/null)

if [[ -x ${cf} ]]; then
cf="clang-format-7"
return
else
cf=$(command -v clang-format 2> /dev/null)
if [[ ! -x ${cf} ]]; then
echo "clang-format is not installed"
exit 1
fi
cf="clang-format"
fi

local required_cfver='17.0.3'
# shellcheck disable=SC2155
local cfver=$(${cf} --version | grep -o -E '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
check_version "${required_cfver}" "${cfver}"
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Revise clang-format version handling

Several issues with the version checking:

  1. The script preferentially looks for clang-format-7 but requires version 17.0.3
  2. The version comparison only warns but continues execution
  3. Function name check_clang-format uses a hyphen which is unconventional in Bash

Consider these changes:

-check_clang-format()
+check_clang_format()
 {
-    # First check explicitly for the clang-format-7 executable.
-    cf=$(command -v clang-format-7 2> /dev/null)
-
-    if [[ -x ${cf} ]]; then
-        cf="clang-format-7"
-        return
-    else
-        cf=$(command -v clang-format 2> /dev/null)
-        if [[ ! -x ${cf} ]]; then
-            echo "clang-format is not installed"
-            exit 1
-        fi
-        cf="clang-format"
-    fi
+    cf=$(command -v clang-format 2> /dev/null)
+    if [[ ! -x ${cf} ]]; then
+        echo "clang-format is not installed"
+        exit 1
+    fi
+    cf="clang-format"

     local required_cfver='17.0.3'
     # shellcheck disable=SC2155
     local cfver=$(${cf} --version | grep -o -E '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-    check_version "${required_cfver}" "${cfver}"
+    if ! check_version "${required_cfver}" "${cfver}"; then
+        exit 1
+    fi
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
check_clang-format()
{
# First check explicitly for the clang-format-7 executable.
cf=$(command -v clang-format-7 2> /dev/null)
if [[ -x ${cf} ]]; then
cf="clang-format-7"
return
else
cf=$(command -v clang-format 2> /dev/null)
if [[ ! -x ${cf} ]]; then
echo "clang-format is not installed"
exit 1
fi
cf="clang-format"
fi
local required_cfver='17.0.3'
# shellcheck disable=SC2155
local cfver=$(${cf} --version | grep -o -E '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
check_version "${required_cfver}" "${cfver}"
}
check_clang_format()
{
cf=$(command -v clang-format 2> /dev/null)
if [[ ! -x ${cf} ]]; then
echo "clang-format is not installed"
exit 1
fi
cf="clang-format"
local required_cfver='17.0.3'
# shellcheck disable=SC2155
local cfver=$(${cf} --version | grep -o -E '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
if ! check_version "${required_cfver}" "${cfver}"; then
exit 1
fi
}

Comment thread scripts/format-code
Comment on lines +84 to +128
if [[ ${usage} -eq 1 ]]; then
cat<<EOF

OVERVIEW:

Formats all C/C++ source files based on the .clang-format rules

$ format-code [-h] [-q] [-s] [-v] [-w] [--exclude-dirs="..."] [--include-exts="..."] [--files="..."]

OPTIONS:
-h, --help Print this help message.
-q, --quiet Display only clang-format output and errors.
-s, --staged Only format files which are staged to be committed.
-v, --verbose Display verbose output.
-w, --whatif Run the script without actually modifying the files
and display the diff of expected changes, if any.
--exclude-dirs Subdirectories to exclude. If unspecified, then
./external, ./packages and ./x64 are excluded.
All subdirectories are relative to the current path.
--include-exts File extensions to include for formatting. If
unspecified, then *.h, *.hpp, *.c, *.cpp, *idl, and
*.acf are included.
--files Only run the script against the specified files from
the current directory.

EXAMPLES:

To determine what lines of each file in the default configuration would be
modified by format-code, you can run from the root folder:

$ ./scripts/format-code -w

To update only all .c and .cpp files in src/ except for src/tools/netsh, you
can run from the src folder:

src$ ../scripts/format-code --exclude-dirs="tools/netsh" \
--include-exts="c cpp"

To run only against a specified set of comma separated files in the current directory:

$ ./scripts/format-code -w --files="file1 file2"

EOF
exit 0
fi

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Add version requirement to help message

The help message should mention the required clang-format version (17.0.3) to help users understand compatibility requirements.

Add to the overview section:

 OVERVIEW:
 
 Formats all C/C++ source files based on the .clang-format rules
+
+Requires clang-format version 17.0.3
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if [[ ${usage} -eq 1 ]]; then
cat<<EOF
OVERVIEW:
Formats all C/C++ source files based on the .clang-format rules
$ format-code [-h] [-q] [-s] [-v] [-w] [--exclude-dirs="..."] [--include-exts="..."] [--files="..."]
OPTIONS:
-h, --help Print this help message.
-q, --quiet Display only clang-format output and errors.
-s, --staged Only format files which are staged to be committed.
-v, --verbose Display verbose output.
-w, --whatif Run the script without actually modifying the files
and display the diff of expected changes, if any.
--exclude-dirs Subdirectories to exclude. If unspecified, then
./external, ./packages and ./x64 are excluded.
All subdirectories are relative to the current path.
--include-exts File extensions to include for formatting. If
unspecified, then *.h, *.hpp, *.c, *.cpp, *idl, and
*.acf are included.
--files Only run the script against the specified files from
the current directory.
EXAMPLES:
To determine what lines of each file in the default configuration would be
modified by format-code, you can run from the root folder:
$ ./scripts/format-code -w
To update only all .c and .cpp files in src/ except for src/tools/netsh, you
can run from the src folder:
src$ ../scripts/format-code --exclude-dirs="tools/netsh" \
--include-exts="c cpp"
To run only against a specified set of comma separated files in the current directory:
$ ./scripts/format-code -w --files="file1 file2"
EOF
exit 0
fi
if [[ ${usage} -eq 1 ]]; then
cat<<EOF
OVERVIEW:
Formats all C/C++ source files based on the .clang-format rules
Requires clang-format version 17.0.3
$ format-code [-h] [-q] [-s] [-v] [-w] [--exclude-dirs="..."] [--include-exts="..."] [--files="..."]
OPTIONS:
-h, --help Print this help message.
-q, --quiet Display only clang-format output and errors.
-s, --staged Only format files which are staged to be committed.
-v, --verbose Display verbose output.
-w, --whatif Run the script without actually modifying the files
and display the diff of expected changes, if any.
--exclude-dirs Subdirectories to exclude. If unspecified, then
./external, ./packages and ./x64 are excluded.
All subdirectories are relative to the current path.
--include-exts File extensions to include for formatting. If
unspecified, then *.h, *.hpp, *.c, *.cpp, *idl, and
*.acf are included.
--files Only run the script against the specified files from
the current directory.
EXAMPLES:
To determine what lines of each file in the default configuration would be
modified by format-code, you can run from the root folder:
$ ./scripts/format-code -w
To update only all .c and .cpp files in src/ except for src/tools/netsh, you
can run from the src folder:
src$ ../scripts/format-code --exclude-dirs="tools/netsh" \
--include-exts="c cpp"
To run only against a specified set of comma separated files in the current directory:
$ ./scripts/format-code -w --files="file1 file2"
EOF
exit 0
fi

Comment thread scripts/format-code
Comment on lines +191 to +234
findargs='find .'

get_find_args()
{
local defaultExcludeDirs='./.git ./external ./packages ./x64'
local defaultIncludeExts='h hpp c cpp idl acf'

if [[ -z ${userExcludeDirs} ]]; then
read -r -a excludeDirs <<< "${defaultExcludeDirs}"
else
log_verbose "Using user directory exclusions: ${userExcludeDirs}"
read -r -a excludeDirs <<< "${userExcludeDirs}"
fi

for exc in "${excludeDirs[@]}"
do
findargs="${findargs} ! \( -path '${exc}' -prune \)"
done

if [[ -z ${userIncludeExts} ]]; then
# not local as this is used in get_file_list() too
read -r -a includeExts <<< "${defaultIncludeExts}"
else
log_verbose "Using user extension inclusions: ${userIncludeExts}"
read -r -a includeExts <<< "${userIncludeExts}"
fi

findargs="${findargs} \("
for ((i=0; i<${#includeExts[@]}; i++));
do
findargs="${findargs} -iname '*.${includeExts[$i]}'"
if [[ $((i + 1)) -lt ${#includeExts[@]} ]]; then
findargs="${findargs} -o"
fi
done
findargs="${findargs} \)"
}

get_find_args

log_verbose "Query for files for format:"
log_verbose "${findargs}"
log_verbose ""

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve file finding security and validation

The current implementation has potential security and robustness issues:

  1. Command injection possible through userExcludeDirs
  2. No validation that found files exist and are readable

Consider these improvements:

 for exc in "${excludeDirs[@]}"
 do
+    # Validate directory name
+    if [[ "$exc" =~ [^a-zA-Z0-9_./-] ]]; then
+        echo "Invalid directory name: $exc"
+        exit 1
+    fi
     findargs="${findargs} ! \( -path '${exc}' -prune \)"
 done

Also add file validation:

 get_file_list()
 {
     if [[ -z "${userFiles[*]}" ]]; then
         mapfile -t file_list < <(eval "$findargs")
         if [[ ${#file_list[@]} -eq 0 ]]; then
             echo "No files were found to format!"
             exit 1
         fi
+        # Validate files
+        for file in "${file_list[@]}"; do
+            if [[ ! -r "$file" ]]; then
+                echo "Cannot read file: $file"
+                exit 1
+            fi
+        done
     else

Committable suggestion was skipped due to low confidence.

Comment thread scripts/format-code.ps1
Comment on lines +179 to +190

$findargs+=" -Include @( "
foreach ($ext in $includeExts)
{
$findargs+=("'*."+"$ext'")
if ($includeExts.IndexOf($ext) -lt $includeExts.count-1)
{
$findargs+=", "
}
}
$findargs+=") "

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Simplify string concatenation using array join.

The current string concatenation could be simplified using array join for better readability and maintainability.

-    $findargs+=" -Include @( "
-    foreach ($ext in $includeExts)
-    {
-        $findargs+=("'*."+"$ext'")
-        if ($includeExts.IndexOf($ext) -lt $includeExts.count-1)
-        {
-            $findargs+=", "
-        }
-    }
-    $findargs+=") "
+    $findargs += " -Include @('" + ($includeExts | ForEach-Object { "*.$_" } | Join-String -Separator "', '") + "') "
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$findargs+=" -Include @( "
foreach ($ext in $includeExts)
{
$findargs+=("'*."+"$ext'")
if ($includeExts.IndexOf($ext) -lt $includeExts.count-1)
{
$findargs+=", "
}
}
$findargs+=") "
$findargs += " -Include @('" + ($includeExts | ForEach-Object { "*.$_" } | Join-String -Separator "', '") + "') "

Comment thread scripts/format-code.ps1
Comment on lines +84 to +92
"--exclude-dirs=*" {
$userExcludeDirs=($opt -split "=")[1];
break;
}

"--include-exts=*" {
$userIncludeExts=($opt -split "=")[1];
break;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add input validation for exclude-dirs and include-exts.

The script should validate the user input for these parameters to ensure they contain valid directory names and file extensions.

     "--exclude-dirs=*" {
-        $userExcludeDirs=($opt -split "=")[1];
+        $dirs = ($opt -split "=")[1]
+        if ($dirs -match '^[a-zA-Z0-9_/.-]+(\s+[a-zA-Z0-9_/.-]+)*$') {
+            $userExcludeDirs = $dirs
+        } else {
+            Write-Error "Invalid directory names in --exclude-dirs"
+            exit 1
+        }
         break;
     }

     "--include-exts=*" {
-        $userIncludeExts=($opt -split "=")[1];
+        $exts = ($opt -split "=")[1]
+        if ($exts -match '^[a-zA-Z0-9]+(\s+[a-zA-Z0-9]+)*$') {
+            $userIncludeExts = $exts
+        } else {
+            Write-Error "Invalid file extensions in --include-exts"
+            exit 1
+        }
         break;
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"--exclude-dirs=*" {
$userExcludeDirs=($opt -split "=")[1];
break;
}
"--include-exts=*" {
$userIncludeExts=($opt -split "=")[1];
break;
}
"--exclude-dirs=*" {
$dirs = ($opt -split "=")[1]
if ($dirs -match '^[a-zA-Z0-9_/.-]+(\s+[a-zA-Z0-9_/.-]+)*$') {
$userExcludeDirs = $dirs
} else {
Write-Error "Invalid directory names in --exclude-dirs"
exit 1
}
break;
}
"--include-exts=*" {
$exts = ($opt -split "=")[1]
if ($exts -match '^[a-zA-Z0-9]+(\s+[a-zA-Z0-9]+)*$') {
$userIncludeExts = $exts
} else {
Write-Error "Invalid file extensions in --include-exts"
exit 1
}
break;
}

Comment thread scripts/format-code.ps1
Comment on lines +226 to +236
foreach ( $file_name in $userfiles ) {
$user_file_name = get-ChildItem -Path '.' -Name $file_name
$file = New-Object System.IO.FileInfo($user_file_name)
foreach ( $ext in $includeExts ) {
if ( $file.Extension -eq ".$ext" ) {
$file_list += $file_name
log_verbose "Checking user file: $file_name"
break;
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for non-existent files and fix potential path traversal.

The script should validate file existence and sanitize file paths to prevent path traversal attacks.

     foreach ( $file_name in $userfiles ) {
-        $user_file_name = get-ChildItem -Path '.' -Name $file_name
-        $file = New-Object System.IO.FileInfo($user_file_name)
+        try {
+            # Resolve full path and ensure it's under current directory
+            $full_path = Resolve-Path -Path $file_name -ErrorAction Stop
+            if (-not $full_path.Path.StartsWith((Get-Location).Path)) {
+                Write-Error "File path '$file_name' is outside current directory"
+                continue
+            }
+            $file = Get-Item -Path $full_path -ErrorAction Stop
+        } catch {
+            Write-Error "Invalid or inaccessible file: $file_name"
+            continue
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
foreach ( $file_name in $userfiles ) {
$user_file_name = get-ChildItem -Path '.' -Name $file_name
$file = New-Object System.IO.FileInfo($user_file_name)
foreach ( $ext in $includeExts ) {
if ( $file.Extension -eq ".$ext" ) {
$file_list += $file_name
log_verbose "Checking user file: $file_name"
break;
}
}
}
foreach ( $file_name in $userfiles ) {
try {
# Resolve full path and ensure it's under current directory
$full_path = Resolve-Path -Path $file_name -ErrorAction Stop
if (-not $full_path.Path.StartsWith((Get-Location).Path)) {
Write-Error "File path '$file_name' is outside current directory"
continue
}
$file = Get-Item -Path $full_path -ErrorAction Stop
} catch {
Write-Error "Invalid or inaccessible file: $file_name"
continue
}
foreach ( $ext in $includeExts ) {
if ( $file.Extension -eq ".$ext" ) {
$file_list += $file_name
log_verbose "Checking user file: $file_name"
break;
}
}
}

Comment thread scripts/format-code.ps1
Comment thread scripts/format-code.ps1
@coveralls

coveralls commented Oct 24, 2024

Copy link
Copy Markdown

Coverage Status

coverage: 90.542% (+0.1%) from 90.403%
when pulling aa49c3b on Alan-Jowett:format_code
into 3308618 on vbpf:main.

@elazarg elazarg left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple of questions:

  1. Why specifically release 17.0.3? I now see that BreakAfterAttributes: Always was introduced in v16.
  2. Can you check that the version is at least required_cfver, not equivalent to it?
  3. How about using git-clang-format? I've just find out about it, and it has the benefit of not bloating the diff when some previous commit was not properly formatted.

@Alan-Jowett

Copy link
Copy Markdown
Contributor Author

A couple of questions:

  1. Why specifically release 17.0.3? I now see that BreakAfterAttributes: Always was introduced in v16.
  2. Can you check that the version is at least required_cfver, not equivalent to it?
  3. How about using git-clang-format? I've just find out about it, and it has the benefit of not bloating the diff when some previous commit was not properly formatted.

This code was taken from eBPF for Windows repo, so may need some tweaks.

17.0.3 was selected as that's the version that eBPF for Windows mandates (or rather that's the version that ships with Visual Studio and is compiled by MSFT and hence is considered safer from supply chain attacks).

Follow-ups:

  1. Make this a minimum version.
  2. Investigate git-clang-format.

Note:
This script only checks changes files, but will reformat prior commits in the current files.

Comment thread scripts/format-code Outdated
Comment thread scripts/format-code.ps1 Outdated
Signed-off-by: Alan Jowett <alan.jowett@microsoft.com>

Co-authored-by: Dave Thaler <dthaler1968@gmail.com>
@elazarg elazarg merged commit 076ae86 into vbpf:main Nov 5, 2024
@Alan-Jowett Alan-Jowett deleted the format_code branch November 12, 2024 00:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants