Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a git hook #7605

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open

Added a git hook #7605

wants to merge 1 commit into from

Conversation

ClementBouvierN
Copy link
Contributor

Nothing in release notes

Signed-off-by: ClementBouvierN <[email protected]>
Copy link

coderabbitai bot commented Nov 28, 2024

📝 Walkthrough

Walkthrough

This pull request introduces a new Bash script located in bin/hook/pre-commit, designed to serve as a pre-commit hook for Git repositories. The script automatically updates copyright years in modified and staged files of specific types, including Java, TypeScript, HTML, SCSS, CSS, and AsciiDoc. It determines the current year and uses a regular expression to identify copyright year formats in the files. The script checks each file for a copyright header and performs actions based on its contents: if the header specifies only the current year, it skips further processing; if it contains a year range, it updates the end year; and if it has a single year, it converts it into a range by appending the current year. After making the necessary updates, the script stages the modified files for commit. Additionally, the documentation in src/docs/asciidoc/dev_env/scripts.adoc has been updated to reflect the new copyright year and to provide instructions on using the pre-commit hook.

Possibly related PRs

  • Specified link to github actions #7438: This PR includes updates to documentation that references the new pre-commit hook located in bin/hook/pre-commit, which is directly related to the changes made in the main PR.

Suggested reviewers

  • freddidierRTE: Suggested as a reviewer for their expertise related to the changes made in the pre-commit hook.

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.

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (1)
bin/hook/pre-commit (1)

1-14: Add error handling and improve documentation

While the basic structure is good, consider enhancing the script's robustness and documentation:

  1. Add command dependency checks
  2. Include usage instructions
  3. Document the expected file structure requirements

Add these improvements at the start of the script:

 #!/bin/bash

+# Verify required commands
+for cmd in date grep sed git; do
+    if ! command -v "$cmd" >/dev/null 2>&1; then
+        echo "Error: Required command '$cmd' not found"
+        exit 1
+    fi
+done
+
+# Usage instructions
+if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
+    echo "Usage: pre-commit"
+    echo "Updates copyright years in modified files before commit."
+    echo "Supported files: .java, .ts, .html, .scss, .css, .adoc"
+    echo "Files must contain a copyright header in the format:"
+    echo "Copyright (c) YYYY, RTE (..."
+    exit 0
+fi
+
 # Copyright (c) 2024, RTE (http://www.rte-france.com)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ff867a4 and b4f4fb0.

📒 Files selected for processing (2)
  • bin/hook/pre-commit (1 hunks)
  • src/docs/asciidoc/dev_env/scripts.adoc (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/docs/asciidoc/dev_env/scripts.adoc

Comment on lines +17 to +20
current_year=$(date +"%Y")

year_regex="([0-9]{4})(-[0-9]{4})?"

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve variable safety and regex precision

The variables should be protected against word splitting and globbing. Also, the regex could be more precise.

Apply these improvements:

-current_year=$(date +"%Y")
+current_year="$(date +"%Y")"
 
-year_regex="([0-9]{4})(-[0-9]{4})?"
+year_regex="(20[0-9]{2})(-20[0-9]{2})?"  # More precise: matches years 2000-2099
📝 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
current_year=$(date +"%Y")
year_regex="([0-9]{4})(-[0-9]{4})?"
current_year="$(date +"%Y")"
year_regex="(20[0-9]{2})(-20[0-9]{2})?" # More precise: matches years 2000-2099


year_regex="([0-9]{4})(-[0-9]{4})?"

modified_files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.java$|\.ts$|\.html$|\.scss$|\.css$|\.adoc$')
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve file handling and make extensions configurable

The current file selection logic needs improvements for robustness and maintainability.

Apply these improvements:

-modified_files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.java$|\.ts$|\.html$|\.scss$|\.css$|\.adoc$')
+# Define monitored extensions
+readonly MONITORED_EXTENSIONS=( "java" "ts" "html" "scss" "css" "adoc" )
+
+# Build the grep pattern
+extension_pattern=$(printf "\\%s$|" ".${MONITORED_EXTENSIONS[@]}")
+extension_pattern="${extension_pattern%|}"
+
+# Get modified files (handles spaces in filenames)
+readarray -t modified_files < <(git diff --cached --name-only --diff-filter=ACMR | grep -E "$extension_pattern" || true)
📝 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
modified_files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.java$|\.ts$|\.html$|\.scss$|\.css$|\.adoc$')
# Define monitored extensions
readonly MONITORED_EXTENSIONS=( "java" "ts" "html" "scss" "css" "adoc" )
# Build the grep pattern
extension_pattern=$(printf "\\%s$|" ".${MONITORED_EXTENSIONS[@]}")
extension_pattern="${extension_pattern%|}"
# Get modified files (handles spaces in filenames)
readarray -t modified_files < <(git diff --cached --name-only --diff-filter=ACMR | grep -E "$extension_pattern" || true)

Comment on lines +12 to +13
# This file needs to be placed in operatorfabric-core/git/hooks/pre-commit
# This file has no extension and should stay as plain text
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Pre-commit hook requires proper installation and permissions

The verification revealed several issues that need to be addressed:

  • The pre-commit hook is currently located at bin/hook/pre-commit but needs to be moved to .git/hooks/pre-commit
  • The file permissions are -rw-r--r-- but the hook needs to be executable (+x)
  • There are no documented installation instructions in the README files

Required actions:

  1. Move the hook to .git/hooks/pre-commit
  2. Make the hook executable: chmod +x .git/hooks/pre-commit
  3. Add installation instructions to the repository documentation
🔗 Analysis chain

Verify hook installation process

The installation process for this git hook needs to be documented and verified:

  1. The hook needs to be executable
  2. The path needs to be corrected
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the hook installation instructions

# Check if there's a script to install the hook
if fd -t f "install.*hooks.*" || fd -t f "setup.*hooks.*"; then
  echo "Found potential hook installation script"
fi

# Check if there's documentation about hook installation
rg -i "git.*hooks.*install" || rg -i "pre-commit.*hook.*install"

Length of output: 185


Script:

#!/bin/bash
# Let's verify the current state of the hook and related files

# Check the actual location and content of the pre-commit hook
echo "=== Checking pre-commit hook location ==="
fd -t f "pre-commit" .git/hooks/
fd -t f "pre-commit" bin/

# Check if there are any installation or setup instructions in README files
echo -e "\n=== Checking README files for hook setup instructions ==="
fd -t f "README" -E "*.md" -X cat {}

# Check file permissions of the pre-commit hook
echo -e "\n=== Checking pre-commit hook permissions ==="
fd -t f "pre-commit" -X ls -l {}

Length of output: 11151

Comment on lines +23 to +43
for file in $modified_files; do
# Check if the file contains the copyright header
if grep -q "Copyright (c)" "$file"; then
# Check if the header has a single year equal to the current year (e.g., 2024)
if grep -qE "Copyright \(c\) $current_year, RTE \(" "$file"; then
continue
fi

# Check if the header already has a year range (e.g., 2018-2023)
if grep -qE "Copyright \(c\) $year_regex, RTE \(" "$file"; then
# Replace the second year in the range with the current year (e.g., 2018-2023 becomes 2018-2024)
sed -i -E "s/Copyright \(c\) ([0-9]{4})(-[0-9]{4})?, RTE \(/Copyright \(c\) \1-$current_year, RTE \(/" "$file"
else
# If there's no year range, convert the single year to a range (e.g., 2023 becomes 2023-2024)
sed -i -E "s/Copyright \(c\) ([0-9]{4}), RTE \(/Copyright \(c\) \1-$current_year, RTE \(/" "$file"
fi
fi

# Add the file to the staging area after the modification
git add "$file"
done
Copy link

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 and improve file processing safety

The main processing loop needs several improvements for better reliability and safety:

  1. Handle sed failures
  2. Safe file iteration
  3. Backup files before modification
  4. Validate copyright format

Apply these improvements:

-for file in $modified_files; do
+for file in "${modified_files[@]}"; do
+  # Skip if file doesn't exist or isn't readable
+  if [ ! -r "$file" ]; then
+    echo "Warning: Cannot read file: $file"
+    continue
+  fi
+
+  # Create backup
+  cp "$file" "$file.bak"
+
   # Check if the file contains the copyright header
   if grep -q "Copyright (c)" "$file"; then
+    # Validate copyright format
+    if ! grep -qE "Copyright \(c\) ($year_regex), RTE \(" "$file"; then
+      echo "Warning: Invalid copyright format in $file"
+      continue
+    fi
+
     # Check if the header has a single year equal to the current year
-    if grep -qE "Copyright \(c\) $current_year, RTE \(" "$file"; then
+    if grep -qE "Copyright \(c\) ${current_year}, RTE \(" "$file"; then
+      rm -f "$file.bak"  # Clean up backup
       continue
     fi

     # Check if the header already has a year range
-    if grep -qE "Copyright \(c\) $year_regex, RTE \(" "$file"; then
+    if grep -qE "Copyright \(c\) ${year_regex}, RTE \(" "$file"; then
       # Replace the second year in the range with the current year
-      sed -i -E "s/Copyright \(c\) ([0-9]{4})(-[0-9]{4})?, RTE \(/Copyright \(c\) \1-$current_year, RTE \(/" "$file"
+      if ! sed -i.tmp -E "s/Copyright \(c\) ([0-9]{4})(-[0-9]{4})?, RTE \(/Copyright \(c\) \1-${current_year}, RTE \(/" "$file"; then
+        echo "Error: Failed to update copyright in $file"
+        mv "$file.bak" "$file"  # Restore backup
+        continue
+      fi
     else
       # If there's no year range, convert the single year to a range
-      sed -i -E "s/Copyright \(c\) ([0-9]{4}), RTE \(/Copyright \(c\) \1-$current_year, RTE \(/" "$file"
+      if ! sed -i.tmp -E "s/Copyright \(c\) ([0-9]{4}), RTE \(/Copyright \(c\) \1-${current_year}, RTE \(/" "$file"; then
+        echo "Error: Failed to update copyright in $file"
+        mv "$file.bak" "$file"  # Restore backup
+        continue
+      fi
     fi
+    rm -f "$file.tmp"  # Clean up sed temporary file
   fi
 
+  # Clean up backup
+  rm -f "$file.bak"
+
   # Add the file to the staging area after the modification
-  git add "$file"
+  if ! git add "$file"; then
+    echo "Error: Failed to stage file: $file"
+  fi
 done
📝 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
for file in $modified_files; do
# Check if the file contains the copyright header
if grep -q "Copyright (c)" "$file"; then
# Check if the header has a single year equal to the current year (e.g., 2024)
if grep -qE "Copyright \(c\) $current_year, RTE \(" "$file"; then
continue
fi
# Check if the header already has a year range (e.g., 2018-2023)
if grep -qE "Copyright \(c\) $year_regex, RTE \(" "$file"; then
# Replace the second year in the range with the current year (e.g., 2018-2023 becomes 2018-2024)
sed -i -E "s/Copyright \(c\) ([0-9]{4})(-[0-9]{4})?, RTE \(/Copyright \(c\) \1-$current_year, RTE \(/" "$file"
else
# If there's no year range, convert the single year to a range (e.g., 2023 becomes 2023-2024)
sed -i -E "s/Copyright \(c\) ([0-9]{4}), RTE \(/Copyright \(c\) \1-$current_year, RTE \(/" "$file"
fi
fi
# Add the file to the staging area after the modification
git add "$file"
done
for file in "${modified_files[@]}"; do
# Skip if file doesn't exist or isn't readable
if [ ! -r "$file" ]; then
echo "Warning: Cannot read file: $file"
continue
fi
# Create backup
cp "$file" "$file.bak"
# Check if the file contains the copyright header
if grep -q "Copyright (c)" "$file"; then
# Validate copyright format
if ! grep -qE "Copyright \(c\) ($year_regex), RTE \(" "$file"; then
echo "Warning: Invalid copyright format in $file"
continue
fi
# Check if the header has a single year equal to the current year
if grep -qE "Copyright \(c\) ${current_year}, RTE \(" "$file"; then
rm -f "$file.bak" # Clean up backup
continue
fi
# Check if the header already has a year range
if grep -qE "Copyright \(c\) ${year_regex}, RTE \(" "$file"; then
# Replace the second year in the range with the current year
if ! sed -i.tmp -E "s/Copyright \(c\) ([0-9]{4})(-[0-9]{4})?, RTE \(/Copyright \(c\) \1-${current_year}, RTE \(/" "$file"; then
echo "Error: Failed to update copyright in $file"
mv "$file.bak" "$file" # Restore backup
continue
fi
else
# If there's no year range, convert the single year to a range
if ! sed -i.tmp -E "s/Copyright \(c\) ([0-9]{4}), RTE \(/Copyright \(c\) \1-${current_year}, RTE \(/" "$file"; then
echo "Error: Failed to update copyright in $file"
mv "$file.bak" "$file" # Restore backup
continue
fi
fi
rm -f "$file.tmp" # Clean up sed temporary file
fi
# Clean up backup
rm -f "$file.bak"
# Add the file to the staging area after the modification
if ! git add "$file"; then
echo "Error: Failed to stage file: $file"
fi
done

Copy link

sonarcloud bot commented Nov 28, 2024

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.

3 participants