Utilizing AI to Detect and Correct Code Formatting Inconsistencies

Apply AI tools to identify and automatically fix formatting inconsistencies in codebases.

0 likes
9 views

Rule Content

---
title: Utilizing AI to Detect and Correct Code Formatting Inconsistencies
description: Apply AI tools to identify and automatically fix formatting inconsistencies in codebases.
category: Code Formatting
category_context: Ensures consistent style in code by handling indentation, spacing, line breaks, and overall structure to keep code clean and readable.
---

# AI-Assisted Code Formatting Rule

## Context
- **When to Apply**: This rule is triggered upon saving any source code file.
- **Prerequisites**: Ensure that AI-based code formatting tools (e.g., Prettier, Black, ClangFormat) are installed and configured in the development environment.

## Requirements
- **Indentation**: Maintain consistent indentation across all files.
  - *JavaScript/TypeScript*: Use 2 spaces.
  - *Python*: Use 4 spaces.
  - *C/C++*: Use 4 spaces.
- **Line Length**: Limit lines to a maximum of 80 characters to enhance readability.
- **Spacing**: Ensure proper spacing around operators and after commas.
- **Braces and Brackets**: Place opening braces on the same line as the statement and closing braces aligned with the start of the statement.
- **Trailing Whitespace**: Remove any trailing whitespace at the end of lines.
- **File Endings**: Ensure files end with a single newline character.

## Implementation
- **Trigger**: On file save.
- **Action**: Automatically run the appropriate AI-based code formatter for the file type.
  - *JavaScript/TypeScript*: Run `prettier --write <filename>`.
  - *Python*: Run `black <filename>`.
  - *C/C++*: Run `clang-format -i <filename>`.

## Examples

### Before Formatting (JavaScript)
function add(a,b){
return a+b;}
### After Formatting
function add(a, b) {
  return a + b;
}
### Before Formatting (Python)
def greet(name):print(f"Hello, {name}!")
### After Formatting
def greet(name):
    print(f"Hello, {name}!")
## Notes
- Ensure that the AI-based formatters are integrated into the development workflow to enforce these standards consistently.
- Regularly update the formatting tools to benefit from the latest improvements and language support.