Integrating Code Formatting with Version Control Systems

Set up hooks and tools to enforce code formatting rules within version control workflows.

0 likes
8 views

Rule Content

---
description: Enforce code formatting rules within version control workflows by setting up pre-commit hooks and integrating formatting tools.
globs: ['**/*.{js,ts,jsx,tsx,py,java,go,rb,php}']
tags: [code-formatting, version-control, pre-commit-hooks]
priority: 3
version: 1.0.0
---

# Integrating Code Formatting with Version Control Systems

## Context
- **When to Apply**: This rule applies to all code repositories to ensure consistent code formatting across the team.
- **Prerequisites**: Ensure that all team members have the necessary code formatting tools installed and that the version control system supports pre-commit hooks.

## Requirements
- **Pre-Commit Hooks**: Implement pre-commit hooks to automatically check and enforce code formatting before commits.
- **Formatting Tools**: Utilize language-specific formatting tools (e.g., Prettier for JavaScript/TypeScript, Black for Python) to standardize code style.
- **Configuration Files**: Maintain a shared configuration file for the formatting tool to ensure consistency across the team.
- **Automated Enforcement**: Configure the version control system to reject commits that do not pass the formatting checks.

## Implementation Steps
1. **Install Formatting Tools**: Ensure that all developers have the appropriate formatting tools installed for the project's programming languages.
2. **Set Up Configuration Files**: Create and maintain a shared configuration file (e.g., `.prettierrc`, `pyproject.toml`) in the repository root.
3. **Configure Pre-Commit Hooks**:
   - Create a `.pre-commit-config.yaml` file in the repository root with the necessary hooks.
   - Install the `pre-commit` package and set up the hooks by running `pre-commit install`.
4. **Enforce Hooks**: Ensure that the pre-commit hooks are executed before each commit to enforce code formatting rules.

## Examples

<example>
**Good Example**: Setting up a pre-commit hook with Prettier for a JavaScript project.

1. Install Prettier and pre-commit:
   ```bash
   npm install --save-dev prettier
   pip install pre-commit
   ```

2. Create a `.prettierrc` configuration file:
   ```json
   {
     "semi": true,
     "singleQuote": true,
     "trailingComma": "es5"
   }
   ```

3. Create a `.pre-commit-config.yaml` file:
   ```yaml
   repos:
     - repo: https://github.com/pre-commit/mirrors-prettier
       rev: v2.3.2
       hooks:
         - id: prettier
   ```

4. Install the pre-commit hook:
   ```bash
   pre-commit install
   ```

Now, every time a commit is made, Prettier will automatically format the code.
</example>

<example type="invalid">
**Bad Example**: Committing code without enforcing formatting rules, leading to inconsistent code styles across the project.
</example>