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

Pre-commit hooks #589

Merged
merged 7 commits into from
Feb 3, 2025
Merged

Pre-commit hooks #589

merged 7 commits into from
Feb 3, 2025

Conversation

kongzii
Copy link
Contributor

@kongzii kongzii commented Jan 23, 2025

No description provided.

Copy link

coderabbitai bot commented Jan 23, 2025

Walkthrough

This pull request updates the contributing guidelines by adding instructions for installing and using pre-commit hooks. It introduces a new script for automating hook installation and makes several comment modifications across source and test files by appending the marker # web3-private-key-ok to improve clarity. Additionally, some multi-line variable assignments were condensed into single-line assignments with inline comments. Overall, the changes focus on documentation clarity and minor formatting updates without affecting functional behavior.

Changes

File(s) Change Summary
README.md, install_hooks.sh Updated contributing guidelines to include pre-commit and added a shell script that automates the installation of pre-commit hooks.
prediction_market_agent_tooling/gtypes.py, prediction_market_agent_tooling/markets/omen/data_models.py, prediction_market_agent_tooling/markets/omen/omen.py, prediction_market_agent_tooling/tools/hexbytes_custom.py, scripts/store_prediction.py Appended # web3-private-key-ok to comments for clarity and simplified multi-line assignments to single-line statements where applicable.
tests/markets/omen/test_omen_subgraph_handler.py, tests/tools/test_web3_utils.py, tests_integration_with_local_chain/markets/omen/test_omen.py, tests_integration_with_local_chain/safe/test_constants.py Added inline # web3-private-key-ok annotations and adjusted variable assignment formatting in test files to enhance readability without affecting test logic.

Sequence Diagram(s)

sequenceDiagram
    participant D as Developer
    participant S as install_hooks.sh
    participant PC as pre-commit
    participant BH as Homebrew

    D->>S: Run install_hooks.sh
    S->>PC: Check if pre-commit is installed
    alt pre-commit not installed
        S->>BH: Install pre-commit
        BH-->>S: pre-commit installed
    end
    S->>PC: Execute "pre-commit install"
    PC-->>S: Hooks successfully installed
    S->>D: Display success message
Loading

Suggested reviewers

  • evangriffiths

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5d95de2 and c92b7d6.

⛔ Files ignored due to path filters (3)
  • .github/workflows/python_ci.yaml is excluded by !**/*.yaml
  • .pre-commit-config.yaml is excluded by !**/*.yaml
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (1)
  • tests/markets/omen/test_omen_subgraph_handler.py (9 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/markets/omen/test_omen_subgraph_handler.py
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: pytest - Python 3.12.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.12.x - Unit Tests
  • GitHub Check: pytest - Python 3.11.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.11.x - Unit Tests
  • GitHub Check: pytest - Python 3.10.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.10.x - Unit Tests

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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

🧹 Nitpick comments (1)
README.md (1)

136-136: Enhance pre-commit documentation.

Consider adding more detailed information about the pre-commit workflow:

 We use `mypy` for static type checking, and `isort`, `black` and `autoflake` for linting, and `pre-commit` to minimise unwanted pushes to the public repositories. These all run as steps in CI, but `pre-commit` also needs to be installed locally using the provided `install_hooks.sh` script.
+
+### Git Hooks
+
+The repository includes several Git hooks to ensure code quality:
+
+1. **Pre-commit**: Runs linting and type checking before each commit
+2. **Post-merge**: Automatically updates pre-commit hooks when configuration changes
+3. **Prepare-commit-msg**: Verifies pre-commit hooks are installed
+
+To set up the hooks:
+
+```bash
+# Install pre-commit and configure hooks
+./install_hooks.sh
+
+# Verify installation
+pre-commit run --all-files
+```
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d2d4566 and e7fabc7.

⛔ Files ignored due to path filters (2)
  • .github/workflows/python_ci.yaml is excluded by !**/*.yaml
  • .pre-commit-config.yaml is excluded by !**/*.yaml
📒 Files selected for processing (4)
  • .githooks/post-merge (1 hunks)
  • .githooks/prepare-commit-msg (1 hunks)
  • README.md (1 hunks)
  • install_hooks.sh (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: pytest - Python 3.12.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.12.x - Unit Tests
  • GitHub Check: pytest - Python 3.11.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.11.x - Unit Tests
  • GitHub Check: pytest - Python 3.10.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.10.x - Unit Tests
  • GitHub Check: mypy

Comment on lines +6 to +8
echo "pre-commit is not installed. Installing now..."
brew install pre-commit
fi
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 cross-platform support for pre-commit installation.

The script assumes brew is available, which is macOS specific. Consider adding support for other package managers:

 if ! command -v pre-commit &> /dev/null
 then
     echo "pre-commit is not installed. Installing now..."
-    brew install pre-commit
+    if command -v brew &> /dev/null; then
+        brew install pre-commit
+    elif command -v apt-get &> /dev/null; then
+        sudo apt-get install -y pre-commit
+    elif command -v pip &> /dev/null; then
+        pip install pre-commit
+    else
+        echo "Error: Could not find a package manager to install pre-commit"
+        exit 1
+    fi
 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
echo "pre-commit is not installed. Installing now..."
brew install pre-commit
fi
echo "pre-commit is not installed. Installing now..."
if command -v brew &> /dev/null; then
brew install pre-commit
elif command -v apt-get &> /dev/null; then
sudo apt-get install -y pre-commit
elif command -v pip &> /dev/null; then
pip install pre-commit
else
echo "Error: Could not find a package manager to install pre-commit"
exit 1
fi
fi

install_hooks.sh Outdated
Comment on lines 13 to 14
# Create a symlink for the hooks
ln -sfn .githooks .git/hooks
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for symlink creation.

The symlink creation lacks error handling and directory existence checks.

 # Create a symlink for the hooks
+if [ ! -d ".githooks" ]; then
+    echo "Error: .githooks directory not found"
+    exit 1
+fi
+
 ln -sfn .githooks .git/hooks
+if [ $? -ne 0 ]; then
+    echo "Error: Failed to create symlink"
+    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
# Create a symlink for the hooks
ln -sfn .githooks .git/hooks
# Create a symlink for the hooks
if [ ! -d ".githooks" ]; then
echo "Error: .githooks directory not found"
exit 1
fi
ln -sfn .githooks .git/hooks
if [ $? -ne 0 ]; then
echo "Error: Failed to create symlink"
exit 1
fi

Comment on lines 3 to 7
if [ ! -f .git/hooks/pre-commit ]; then
echo "Error: Pre-commit hooks are not installed."
echo "Please run 'pre-commit install' before committing."
exit 1
fi
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use absolute paths and check executable permissions.

The hook should use absolute paths and verify executable permissions.

-if [ ! -f .git/hooks/pre-commit ]; then
+HOOK_PATH="$(git rev-parse --git-dir)/hooks/pre-commit"
+if [ ! -f "$HOOK_PATH" ]; then
     echo "Error: Pre-commit hooks are not installed."
     echo "Please run 'pre-commit install' before committing."
     exit 1
+elif [ ! -x "$HOOK_PATH" ]; then
+    echo "Error: Pre-commit hook exists but is not executable."
+    echo "Please run 'chmod +x $HOOK_PATH' to fix."
+    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
if [ ! -f .git/hooks/pre-commit ]; then
echo "Error: Pre-commit hooks are not installed."
echo "Please run 'pre-commit install' before committing."
exit 1
fi
HOOK_PATH="$(git rev-parse --git-dir)/hooks/pre-commit"
if [ ! -f "$HOOK_PATH" ]; then
echo "Error: Pre-commit hooks are not installed."
echo "Please run 'pre-commit install' before committing."
exit 1
elif [ ! -x "$HOOK_PATH" ]; then
echo "Error: Pre-commit hook exists but is not executable."
echo "Please run 'chmod +x $HOOK_PATH' to fix."
exit 1
fi

Comment on lines 4 to 8
if git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD | grep -q ".pre-commit-config.yaml"; then
echo "Pre-commit config changed, updating hooks..."
pre-commit autoupdate
pre-commit install
fi
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and verbose output.

The hook should handle errors from pre-commit commands and provide clear feedback.

 if git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD | grep -q ".pre-commit-config.yaml"; then
     echo "Pre-commit config changed, updating hooks..."
-    pre-commit autoupdate
-    pre-commit install
+    if ! pre-commit autoupdate; then
+        echo "Error: Failed to update pre-commit hooks"
+        exit 1
+    fi
+    echo "Hooks updated successfully"
+
+    if ! pre-commit install; then
+        echo "Error: Failed to install pre-commit hooks"
+        exit 1
+    fi
+    echo "Hooks installed successfully"
 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
if git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD | grep -q ".pre-commit-config.yaml"; then
echo "Pre-commit config changed, updating hooks..."
pre-commit autoupdate
pre-commit install
fi
if git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD | grep -q ".pre-commit-config.yaml"; then
echo "Pre-commit config changed, updating hooks..."
if ! pre-commit autoupdate; then
echo "Error: Failed to update pre-commit hooks"
exit 1
fi
echo "Hooks updated successfully"
if ! pre-commit install; then
echo "Error: Failed to install pre-commit hooks"
exit 1
fi
echo "Hooks installed successfully"
fi

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: 1

🧹 Nitpick comments (4)
scripts/detect_web3_private_keys.py (3)

34-35: Log validation failures for debugging.

Consider logging the specific exception when key validation fails to help debug false positives.

-    except Exception:
+    except Exception as e:
+        if os.getenv("DEBUG"):
+            print(f"Key validation failed: {e}", file=sys.stderr)
         return False

44-54: Enhance error reporting and add batch processing capabilities.

The current implementation could be improved in several ways:

  1. Add line content to error messages for context
  2. Support batch reporting instead of immediate printing
  3. Add progress indication for large files

Would you like me to provide an enhanced implementation that addresses these points?


59-75: Add support for directory scanning and gitignore patterns.

The script could be more useful if it could:

  1. Recursively scan directories
  2. Respect .gitignore patterns
  3. Support exclusion patterns

Would you like me to provide an implementation that includes these features?

tests_integration_with_local_chain/safe/test_constants.py (1)

1-1: LGTM! Consider enhancing the comment.

The addition of the web3-private-key-ok comment is good as it explicitly marks this as an approved test key. To provide even more clarity for future developers, consider expanding the comment to indicate this is Anvil's default private key for local testing.

-ANVIL_PKEY1 = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"  # web3-private-key-ok
+ANVIL_PKEY1 = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"  # web3-private-key-ok: Anvil's default private key for local testing
🧰 Tools
🪛 Gitleaks (8.21.2)

1-1: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e7fabc7 and 5d95de2.

⛔ Files ignored due to path filters (3)
  • .pre-commit-config.yaml is excluded by !**/*.yaml
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (11)
  • install_hooks.sh (1 hunks)
  • prediction_market_agent_tooling/gtypes.py (1 hunks)
  • prediction_market_agent_tooling/markets/omen/data_models.py (1 hunks)
  • prediction_market_agent_tooling/markets/omen/omen.py (1 hunks)
  • prediction_market_agent_tooling/tools/hexbytes_custom.py (1 hunks)
  • scripts/detect_web3_private_keys.py (1 hunks)
  • scripts/store_prediction.py (1 hunks)
  • tests/markets/omen/test_omen_subgraph_handler.py (9 hunks)
  • tests/tools/test_web3_utils.py (1 hunks)
  • tests_integration_with_local_chain/markets/omen/test_omen.py (1 hunks)
  • tests_integration_with_local_chain/safe/test_constants.py (1 hunks)
✅ Files skipped from review due to trivial changes (5)
  • scripts/store_prediction.py
  • tests/markets/omen/test_omen_subgraph_handler.py
  • tests_integration_with_local_chain/markets/omen/test_omen.py
  • prediction_market_agent_tooling/markets/omen/omen.py
  • prediction_market_agent_tooling/markets/omen/data_models.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • install_hooks.sh
🧰 Additional context used
🪛 Gitleaks (8.21.2)
tests/tools/test_web3_utils.py

16-16: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

tests_integration_with_local_chain/safe/test_constants.py

1-1: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: pytest - Python 3.12.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.12.x - Unit Tests
  • GitHub Check: pytest - Python 3.11.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.11.x - Integration Tests
  • GitHub Check: pytest - Python 3.11.x - Unit Tests
  • GitHub Check: pytest - Python 3.10.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.10.x - Integration Tests
  • GitHub Check: pytest - Python 3.10.x - Unit Tests
  • GitHub Check: mypy
🔇 Additional comments (3)
tests/tools/test_web3_utils.py (1)

16-16: LGTM! Test uses appropriate annotation.

The added comment correctly indicates that this is an intentional test private key.

🧰 Tools
🪛 Gitleaks (8.21.2)

16-16: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

prediction_market_agent_tooling/tools/hexbytes_custom.py (1)

26-26: LGTM! Appropriate annotation for schema example.

The example is correctly annotated as a web3 private key example used for schema validation.

prediction_market_agent_tooling/gtypes.py (1)

85-85: LGTM! Clear example with appropriate annotation.

The example effectively demonstrates the padding behavior and is correctly annotated.

from eth_utils import decode_hex

# Regular expression to match Ethereum private keys
KEY_PATTERN = re.compile(r"\b(0x)?[a-fA-F0-9]{64}\b")
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Strengthen the private key regex pattern.

The current pattern might miss some edge cases. Consider using a more precise pattern that enforces length constraints.

-KEY_PATTERN = re.compile(r"\b(0x)?[a-fA-F0-9]{64}\b")
+KEY_PATTERN = re.compile(r"(?:^|[^a-fA-F0-9])(0x)?[a-fA-F0-9]{64}(?:$|[^a-fA-F0-9])")
📝 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
KEY_PATTERN = re.compile(r"\b(0x)?[a-fA-F0-9]{64}\b")
KEY_PATTERN = re.compile(r"(?:^|[^a-fA-F0-9])(0x)?[a-fA-F0-9]{64}(?:$|[^a-fA-F0-9])")

pip install pre-commit
- name: Run Pre-Commit
run: |
pre-commit run --all-files
Copy link
Contributor Author

Choose a reason for hiding this comment

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

pre-commit needs to be installed locally (see install_hooks.sh), but as a last resort, also run it in CI, so at least we won't miss it by accident if the key gets leaked.

hooks:
- id: detect-web3-private-key
name: Detect Web3 Private Key
entry: python scripts/detect_web3_private_keys.py
Copy link
Contributor Author

Choose a reason for hiding this comment

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

After review, I'll try to get this into https://github.com/pre-commit/pre-commit-hooks, if they don't accept, I'll create a separate repo for it, so we can share it across our repos

@@ -82,5 +82,5 @@ def secretstr_to_v1_secretstr(s: SecretStr | None) -> SecretStrV1 | None:


def int_to_hexbytes(v: int) -> HexBytes:
# Example: 1 -> HexBytes("0x0000000000000000000000000000000000000000000000000000000000000001").
# Example: 1 -> HexBytes("0x0000000000000000000000000000000000000000000000000000000000000001"). # web3-private-key-ok
Copy link
Contributor Author

Choose a reason for hiding this comment

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

It looks like private keys don't have any strong format. I had to add this # web3-private-key-ok so we can tell the script that these aren't real private keys.

@gabrielfior please check out scripts/detect_web3_private_keys.py, if you know a better way of how to detect private keys, I'll be happy 😄

@kongzii kongzii merged commit 3ce6ae0 into main Feb 3, 2025
14 of 17 checks passed
@kongzii kongzii deleted the peter/hooks branch February 3, 2025 10:21
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.

2 participants