Skip to content

hew/cog-and-complexity-code-analyzer

Repository files navigation

Complexity Analyzer 🧠

A modern code complexity analyzer that helps developers write maintainable code through actionable insights. Unlike traditional tools, it measures both cyclomatic and cognitive complexity, showing you not just that code is complex, but why and how to fix it.

Why This Tool Exists

We've all seen this function:

function processUserData(user, settings, permissions) {
  if (user.active) {
    if (user.verified) {
      if (settings.advanced) {
        if (permissions.includes('admin')) {
          // ... 50 more lines of nested logic
        }
      }
    }
  }
}

This tool doesn't just say "complexity: 15" - it explains why it's hard to understand and how to refactor it.

Features

  • 🎯 Dual Complexity Metrics
    • Cyclomatic: Counts code paths (traditional)
    • Cognitive: Measures human understanding difficulty (innovative)
  • 🚦 Actionable Feedback - Explains why functions are complex
  • πŸ”’ Git Hooks - Prevent complex code from being committed
  • πŸ€– CI/CD Integration - Automated PR checks with GitHub Actions
  • πŸ§‘β€πŸ’» Claude Code Support - Works as a Claude Code hook
  • ⚑ Fast - Built with Bun and TypeScript
  • 🎨 Beautiful Output - Color-coded terminal output with helpful indicators

Quick Start

Installation

Install directly from GitHub:

npm install -D git+https://github.com/hew/claude-code-complexity-analyzer.git
# or
yarn add -D git+https://github.com/hew/claude-code-complexity-analyzer.git
# or
bun add -D git+https://github.com/hew/claude-code-complexity-analyzer.git

# Or clone and link locally:
git clone https://github.com/hew/claude-code-complexity-analyzer.git
cd claude-code-complexity-analyzer
bun install
bun run build
npm link

Basic Usage

# Analyze your source code
npx complexity-analyzer analyze src

# Set up git hooks (recommended)
npx complexity-analyzer setup-hooks

# Check specific files
npx complexity-analyzer analyze src/components --max-complexity 15

Real-World Usage Flow

1. Daily Development

When you try to commit complex code:

git commit -m "feat: add user processing"

πŸ” Running complexity analysis on staged files...
⚠️  High complexity in src/UserService.ts:
   processUser:45 | Cyclo: 12 | Cogn: 24
    ↳ High nesting or logical complexity

❌ Commit blocked: High complexity detected

Options:
  1. Refactor the complex functions
  2. Override with: git commit --no-verify
  3. Increase limit: MAX_COMPLEXITY=15 git commit

2. Understanding the Feedback

The tool shows both metrics side-by-side:

getUserData:23    | Cyclo: 14 | Cogn:  6
    ↳ Linear control flow (e.g., else-if chains)

processPayment:89 | Cyclo:  8 | Cogn: 22
    ↳ High nesting or logical complexity

This tells you:

  • getUserData has many branches but they're linear (less problematic)
  • processPayment has deeply nested logic (needs refactoring)

3. CI/CD Integration

On every pull request:

PR Comment Example

## βœ… Complexity Analysis Results

High Complexity Functions:
- fetchUserData:34 | Cyclo: 11 | Cogn: 18

Summary:
Total functions analyzed: 47
Functions exceeding threshold: 1

πŸ’‘ Tip: Functions with high cognitive complexity are harder to understand than those with high cyclomatic complexity.

4. With Claude Code

Claude sees complexity warnings before editing:

πŸ” Analyzing complexity for src/api.ts...
⚠️  Complex functions detected:
   handleRequest:67 | Cyclo: 9 | Cogn: 15

πŸ’‘ Consider refactoring before adding new features.

Understanding the Metrics

Cyclomatic Complexity

Traditional metric that counts decision points:

  • Each if, for, while, case adds +1
  • Linear and predictable
  • Good for measuring test coverage needs

Cognitive Complexity

Modern metric that measures human understanding:

  • Penalizes nesting (deeper = harder)
  • Ignores linear else-if chains
  • Considers logical operator sequences
  • Better represents actual maintainability

Example Comparison

// HIGH Cyclomatic (7), LOW Cognitive (1)
function getStatus(code: number) {
  if (code === 200) return 'success';
  else if (code === 201) return 'created';
  else if (code === 400) return 'bad request';
  else if (code === 401) return 'unauthorized';
  else if (code === 404) return 'not found';
  else if (code === 500) return 'server error';
  else return 'unknown';
}

// LOW Cyclomatic (4), HIGH Cognitive (9)
function processRequest(user: User, request: Request) {
  if (user.authenticated) {                    // +1
    if (request.method === 'POST') {          // +2 (nested)
      if (user.permissions.includes('write')) { // +3 (deeper)
        if (request.body.valid) {              // +4 (even deeper)
          // process...
        }
      }
    }
  }
}

Configuration

Git Hooks Setup

# Automatic setup
npx complexity-analyzer setup-hooks

# Manual setup
ln -sf node_modules/@hew/complexity-analyzer/hooks/pre-commit .git/hooks/pre-commit

Customization

In package.json:

{
  "complexity-analyzer": {
    "maxCyclomatic": 10,
    "maxCognitive": 15,
    "exclude": ["**/*.test.ts", "**/*.spec.ts"],
    "failOn": "error"
  }
}

Or via environment variables:

MAX_COMPLEXITY=15 git commit
COMPLEXITY_EXCLUDE="test/**" npx complexity-analyzer analyze

GitHub Actions

Add to .github/workflows/complexity.yml:

name: Complexity Check
on: [push, pull_request]

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: oven-sh/setup-bun@v1
      - run: bun install
      - run: npx complexity-analyzer analyze src --max-complexity 10

Programmatic API

import { 
  calculateCyclomaticComplexity,
  calculateCognitiveComplexity 
} from 'claude-code-complexity-analyzer';

const code = `
  function example(x: number) {
    if (x > 0) return 'positive';
    return 'negative';
  }
`;

const cyclomatic = calculateCyclomaticComplexity(code);  // 2
const cognitive = calculateCognitiveComplexity(code);    // 1

Recommended Thresholds

Complexity Cyclomatic Cognitive Action
βœ… Simple 1-5 0-5 Good!
🟑 Moderate 6-10 6-10 Consider refactoring
🟠 Complex 11-20 11-20 Should refactor
πŸ”΄ Very Complex 21+ 21+ Must refactor

Development

# Clone the repo
git clone https://github.com/hew/claude-code-complexity-analyzer
cd claude-code-complexity-analyzer

# Install dependencies
bun install

# Run tests
bun test

# Analyze the analyzer itself!
bun run analyze:self

# Set up git hooks
bun run setup-hooks

Contributing

We welcome contributions! Please ensure:

  1. All tests pass (bun test)
  2. Complexity thresholds are met (bun run analyze)
  3. Code follows existing patterns

License

MIT

Roadmap

  • VSCode extension with inline hints
  • Historical tracking with git integration
  • HTML reports with charts
  • More metrics (Halstead, Maintainability Index)
  • Language support beyond JS/TS

Built with ❀️ using Bun and ts-morph

About

Don't vibe code yourself into a corner

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published