Claude
Skills
Sign in
Back

when-auditing-code-style-use-style-audit

Included with Lifetime
$97 forever

Code style and conventions audit with auto-fix capabilities for comprehensive style enforcement

testing-quality

What this skill does


# Code Style Audit with Auto-Fix

## Purpose

Perform comprehensive code style and conventions audit across the entire codebase with automated fix capabilities. Identifies style violations, enforces naming conventions, validates formatting, and applies automated corrections to ensure consistent code quality.

## Core Principles

- **Automated Enforcement**: Auto-fix for style violations where possible
- **Comprehensive Coverage**: ESLint, Prettier, TypeScript, naming conventions
- **Evidence-Based**: Measurable style compliance metrics
- **Non-Breaking**: Only applies safe, non-destructive fixes
- **Continuous Compliance**: Style validation at every commit

## Phase 1: Scan Codebase

### Objective
Identify all style violations, formatting issues, and convention inconsistencies across the codebase.

### Agent Configuration
```yaml
agent: code-analyzer
specialization: style-scanning
tools: ESLint, Prettier, TypeScript
```

### Execution Steps

**1. Initialize Style Scan**
```bash
# Pre-task setup
npx claude-flow@alpha hooks pre-task \
  --agent-id "code-analyzer" \
  --description "Comprehensive code style scanning" \
  --task-type "style-scan"

# Restore session context
npx claude-flow@alpha hooks session-restore \
  --session-id "style-audit-${AUDIT_ID}" \
  --agent-id "code-analyzer"
```

**2. ESLint Comprehensive Scan**
```bash
# Run ESLint with all rules
npx eslint . \
  --ext .js,.jsx,.ts,.tsx \
  --format json \
  --output-file eslint-report.json \
  --max-warnings 0

# Separate auto-fixable vs manual issues
npx eslint . \
  --ext .js,.jsx,.ts,.tsx \
  --format json \
  --fix-dry-run > eslint-fixable-report.json
```

**3. Prettier Formatting Check**
```bash
# Check all supported file types
npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}" \
  --list-different > prettier-violations.txt

# Check configuration consistency
npx prettier --find-config-path . > prettier-config-check.txt
```

**4. TypeScript Style Validation**
```bash
# Strict type checking
npx tsc --noEmit --strict --pretty false 2> typescript-strict-errors.txt

# Check for any types
grep -r ": any" src/ --include="*.ts" --include="*.tsx" > any-types.txt

# Check for implicit any
npx tsc --noImplicitAny --noEmit 2> implicit-any-errors.txt
```

**5. Naming Convention Analysis**
```javascript
// Naming patterns validation
const namingConventions = {
  // File naming
  files: {
    pattern: /^[a-z][a-z0-9-]*\.(js|ts|jsx|tsx)$/,
    examples: ['user-service.js', 'api-client.ts'],
    violations: []
  },

  // Directory naming
  directories: {
    pattern: /^[a-z][a-z0-9-]*$/,
    examples: ['user-api', 'auth-service'],
    violations: []
  },

  // Class naming (PascalCase)
  classes: {
    pattern: /^[A-Z][a-zA-Z0-9]*$/,
    examples: ['UserService', 'ApiClient'],
    violations: []
  },

  // Function naming (camelCase)
  functions: {
    pattern: /^[a-z][a-zA-Z0-9]*$/,
    examples: ['getUserById', 'calculateTotal'],
    violations: []
  },

  // Constant naming (UPPER_SNAKE_CASE)
  constants: {
    pattern: /^[A-Z][A-Z0-9_]*$/,
    examples: ['MAX_RETRIES', 'API_BASE_URL'],
    violations: []
  },

  // React component naming (PascalCase)
  components: {
    pattern: /^[A-Z][a-zA-Z0-9]*$/,
    examples: ['UserProfile', 'LoginForm'],
    violations: []
  },

  // Private methods (leading underscore)
  privateMethods: {
    pattern: /^_[a-z][a-zA-Z0-9]*$/,
    examples: ['_validateInput', '_processData'],
    violations: []
  }
};

// Scan for naming violations
function scanNamingViolations(ast) {
  ast.walk((node) => {
    if (node.type === 'ClassDeclaration') {
      if (!namingConventions.classes.pattern.test(node.id.name)) {
        namingConventions.classes.violations.push({
          file: node.loc.source,
          line: node.loc.start.line,
          found: node.id.name,
          expected: toPascalCase(node.id.name)
        });
      }
    }
    // Similar checks for other node types...
  });
}
```

**6. Code Organization Violations**
```javascript
// File organization rules
const organizationRules = {
  max_file_length: {
    threshold: 500,
    unit: 'lines',
    violations: []
  },

  max_function_length: {
    threshold: 50,
    unit: 'lines',
    violations: []
  },

  max_function_parameters: {
    threshold: 4,
    unit: 'parameters',
    violations: []
  },

  max_nesting_depth: {
    threshold: 4,
    unit: 'levels',
    violations: []
  },

  import_organization: {
    rules: [
      'External imports first',
      'Internal imports second',
      'Relative imports last',
      'Alphabetically sorted within groups'
    ],
    violations: []
  },

  export_organization: {
    rules: [
      'Named exports grouped',
      'Default export last',
      'No mixed inline and end-of-file exports'
    ],
    violations: []
  }
};

// Check file length
function checkFileLength(filePath) {
  const lines = fs.readFileSync(filePath, 'utf8').split('\n').length;
  if (lines > organizationRules.max_file_length.threshold) {
    organizationRules.max_file_length.violations.push({
      file: filePath,
      lines: lines,
      excess: lines - organizationRules.max_file_length.threshold
    });
  }
}
```

**7. Generate Scan Report**
```markdown
## Code Style Audit - Scan Results

### ESLint Violations
**Total: 247 issues (189 errors, 58 warnings)**

#### By Category
| Category | Count | Auto-Fixable |
|----------|-------|--------------|
| Formatting | 123 | 123 ✅ |
| Best Practices | 45 | 28 ✅ |
| Possible Errors | 34 | 12 ✅ |
| Variables | 28 | 18 ✅ |
| ES6 | 17 | 8 ✅ |

#### Top Violations
1. `indent` (2 spaces): 67 occurrences
2. `no-unused-vars`: 34 occurrences
3. `prefer-const`: 28 occurrences
4. `no-console`: 23 occurrences
5. `quotes` (single): 19 occurrences

### Prettier Violations
**Total: 147 files need formatting**

- Inconsistent quote style (single vs double): 89 files
- Missing trailing commas: 67 files
- Incorrect indentation: 45 files
- Line length exceeded (>100 chars): 34 files

### TypeScript Issues
**Total: 67 issues**

- Explicit `any` types: 23 occurrences
- Implicit `any` warnings: 31 occurrences
- Strict null checks: 13 occurrences

### Naming Convention Violations
**Total: 89 violations**

| Convention | Violations | Examples |
|------------|------------|----------|
| File naming | 23 | `UserService.js` → `user-service.js` |
| Class naming | 12 | `apiClient` → `ApiClient` |
| Function naming | 18 | `GetUserById` → `getUserById` |
| Constant naming | 15 | `maxRetries` → `MAX_RETRIES` |
| Variable naming | 21 | `user_id` → `userId` |

### Code Organization Issues
**Total: 56 violations**

- Files exceeding 500 lines: 12 files
- Functions exceeding 50 lines: 28 functions
- Functions with >4 parameters: 8 functions
- Nesting depth >4 levels: 8 occurrences

### Summary
- **Auto-fixable**: 189/247 ESLint issues (76.5%)
- **Manual fixes required**: 58 ESLint issues
- **Prettier auto-fixable**: 147 files (100%)
- **Naming convention fixes**: 89 (requires refactoring)
```

**8. Store Scan Results**
```bash
npx claude-flow@alpha hooks post-edit \
  --file "style-scan-report.json" \
  --memory-key "swarm/code-analyzer/scan-results" \
  --metadata "{\"total_violations\": ${TOTAL_VIOLATIONS}, \"auto_fixable\": ${AUTO_FIXABLE}}"
```

### Validation Gates
- ✅ Complete codebase scanned
- ✅ All violation types identified
- ✅ Auto-fixable issues flagged
- ✅ Manual issues documented

### Expected Outputs
- `eslint-report.json` - ESLint violations
- `prettier-violations.txt` - Formatting issues
- `typescript-strict-errors.txt` - Type issues
- `naming-violations.json` - Naming convention issues
- `style-scan-report.json` - Comprehensive scan results

---

## Phase 2: Compare to Standards

### Objective
Compare scanned violations against project coding standards and industry best practices.

### Agent Configuration
```yaml
agent: reviewer
specialization: standards-comparison
standards: Airbnb, Google, StandardJS
```

### Execution Steps

**1. Initialize Standa

Related in testing-quality