DEV Community

墨抒颖
墨抒颖

Posted on

🚀 From Zero to One: Building Your VSCode Cyclomatic Complexity Analysis Plugin

Must-read for developers: How to build a professional-grade code quality analysis tool

The plugin has been published to the VSCode marketplace, welcome to download and use: Code Cyclomatic Complexity

📖 Preface

In the fast-paced world of frontend development, code quality is often overlooked. Complex functions, nested conditional statements, lengthy logic chains... These "technical debts" accumulate as projects grow, ultimately affecting development efficiency and code maintainability.

Today, we will dive deep into how to build a VSCode Cyclomatic Complexity Analysis Plugin from scratch, which not only helps developers monitor code quality in real-time but also provides visual code health indicators for team collaboration.

🎯 What is Cyclomatic Complexity?

Cyclomatic Complexity is an important metric for measuring code complexity:

  • Base complexity: Each function starts with a value of 1
  • Conditional branches: Each if, for, while, case, etc. adds 1
  • Logical operators: &&, ||, ? :, etc. add 1
  • Exception handling: catch, finally, etc. add 1

Complexity levels:

  • 🟢 1-5: Simple, easy to understand and maintain
  • 🟡 6-10: Moderate, needs attention
  • 🔴 11+: Complex, recommended for refactoring

🛠️ Technical Architecture Design

Core Module Division

src/
├── extension.ts              # Plugin entry point, lifecycle management
├── complexityAnalyzer.ts     # Core analysis engine
├── fileTreeProvider.ts       # Tree view data provider
├── fileDecoratorProvider.ts  # File decorator (display complexity numbers)
└── fileTypeHandlers.ts       # Multi-language file type handlers
Enter fullscreen mode Exit fullscreen mode

Key Technology Stack

  • TypeScript: Type-safe JavaScript superset
  • VSCode API: Core interfaces for plugin development
  • AST Parsing: Abstract Syntax Tree analysis
  • File System: Recursive project file traversal
  • Caching Mechanism: Improve analysis performance

🔧 Core Implementation Analysis

1. Plugin Activation and Lifecycle Management

export function activate(context: vscode.ExtensionContext) {
  // Create core components
  const complexityAnalyzer = new ComplexityAnalyzer();
  const fileTreeProvider = new FileTreeProvider(complexityAnalyzer);
  const fileDecoratorProvider = new FileDecoratorProvider(complexityAnalyzer);

  // Register commands and views
  registerCommands(context, complexityAnalyzer, fileTreeProvider);
  registerViews(context, fileTreeProvider, fileDecoratorProvider);

  // Auto-analyze workspace
  initializeAnalysis(complexityAnalyzer, fileTreeProvider);
}
Enter fullscreen mode Exit fullscreen mode

2. Multi-language File Type Support

export class FileTypeManager {
  private handlers = new Map<string, FileTypeHandler>();

  constructor() {
    this.registerHandler('javascript', new JavaScriptHandler());
    this.registerHandler('typescript', new TypeScriptHandler());
    this.registerHandler('vue', new VueHandler());
    this.registerHandler('html', new HTMLHandler());
    this.registerHandler('css', new CSSHandler());
  }

  analyzeFile(filePath: string, content: string): number {
    const handler = this.getHandler(filePath);
    return handler ? handler.calculateComplexity(content) : 0;
  }
}
Enter fullscreen mode Exit fullscreen mode

3. Intelligent File Filtering System

private async loadGitignoreRules(folderPath: string): Promise<GitignoreRule[]> {
  // Read .gitignore file
  const gitignorePath = path.join(folderPath, '.gitignore');

  // Get VSCode configuration exclusion rules
  const config = vscode.workspace.getConfiguration('codeComplexity');
  const excludeFolders = config.get<string[]>('excludeFolders', []);

  // Merge rules and parse
  return this.parseGitignoreRules(rules);
}
Enter fullscreen mode Exit fullscreen mode

4. Performance Optimization Strategies

  • Incremental Analysis: Only analyze modified files
  • Caching Mechanism: Avoid duplicate calculations
  • Async Processing: Don't block UI thread
  • Progress Feedback: Real-time analysis status display

🎨 User Experience Design

1. Explorer Integration

Display complexity numbers next to files with color coding:

  • 🟢 Green: Complexity ≤ 5
  • 🟡 Yellow: Complexity 6-10
  • 🔴 Red: Complexity > 10

2. Dedicated Analysis Panel

  • Tree View: Organized by folders, supports sorting
  • Quick Actions: Right-click menu, one-click file opening
  • Real-time Updates: Auto re-analyze after file modifications

3. Status Bar Feedback

$(sync~spin) Analyzing cyclomatic complexity (15/100) [src/components]
Enter fullscreen mode Exit fullscreen mode

📦 Plugin Configuration and Publishing

package.json Configuration

{
  "name": "vscode-cyclomatic-complexity",
  "displayName": "Code Cyclomatic Complexity",
  "description": "Display cyclomatic complexity of code files",
  "version": "0.0.6",
  "publisher": "your-publisher-name",
  "engines": {
    "vscode": "^1.74.0"
  },
  "categories": ["Other"],
  "activationEvents": ["onStartupFinished"],
  "contributes": {
    "commands": [...],
    "viewsContainers": [...],
    "views": [...],
    "menus": [...],
    "configuration": {...}
  }
}
Enter fullscreen mode Exit fullscreen mode

Publishing Process

# Install publishing tool
npm install -g @vscode/vsce

# Compile project
npm run compile

# Package plugin
vsce package

# Publish to marketplace
vsce publish
Enter fullscreen mode Exit fullscreen mode

🚀 Advanced Feature Implementation

1. Custom Complexity Rules

interface ComplexityRule {
  pattern: RegExp;
  weight: number;
  description: string;
}

const rules: ComplexityRule[] = [
  { pattern: /if\s*\(/, weight: 1, description: 'if statement' },
  { pattern: /for\s*\(/, weight: 1, description: 'for loop' },
  { pattern: /while\s*\(/, weight: 1, description: 'while loop' },
  { pattern: /catch\s*\(/, weight: 1, description: 'exception handling' },
  { pattern: /&&|\|\|/, weight: 1, description: 'logical operators' }
];
Enter fullscreen mode Exit fullscreen mode

2. Team Collaboration Support

  • Configuration Files: Unified configuration in .vscode/settings.json
  • CI/CD Integration: Command-line tool support
  • Report Generation: Export analysis results

3. Extensibility Design

  • Plugin Architecture: Support for custom file type handlers
  • Rule Engine: Configurable complexity calculation rules
  • Theme Adaptation: Support for VSCode dark/light themes

📊 Real-world Application Scenarios

1. Code Review

In Pull Requests, team members can quickly identify high-complexity files and focus on code that needs refactoring.

2. Technical Debt Management

Regular analysis runs generate complexity reports, helping teams plan refactoring work.

3. New Developer Training

Through visual indicators, help new developers understand the importance of code quality.

4. Performance Optimization

Identify complex functions to provide data support for performance optimization.

🎯 Best Practice Recommendations

1. Development Phase

  • Early Integration: Introduce complexity analysis at project inception
  • Continuous Monitoring: Set up CI/CD pipelines for automatic checking
  • Team Consensus: Establish complexity threshold standards

2. Refactoring Strategy

  • Priority Sorting: Start refactoring from high-complexity files
  • Incremental Improvement: Avoid large-scale rewrites
  • Test Coverage: Ensure adequate testing before refactoring

3. Tool Selection

  • VSCode Plugin: Real-time feedback during development
  • Command-line Tool: CI/CD integration
  • Web Dashboard: Team collaboration and reporting

🔮 Future Development Directions

1. Intelligent Analysis

  • AI Assistance: Machine learning-based complexity prediction
  • Auto Refactoring: Intelligent code simplification suggestions
  • Pattern Recognition: Identify common anti-patterns

2. Ecosystem Integration

  • Git Integration: Deep integration with GitHub/GitLab
  • Project Management: Integration with Jira, Trello, and other tools
  • Monitoring Alerts: Automatic notifications for complexity violations

3. Multi-language Support

  • Backend Languages: Java, Python, C#, etc.
  • Mobile Development: Swift, Kotlin, etc.
  • Emerging Languages: Rust, Go, etc.

💡 Summary

Building a professional code quality analysis tool requires not only solid technical skills but also a deep understanding of developer needs. Through this detailed analysis, you should now have mastered:

  • ✅ Core concepts and calculation methods of cyclomatic complexity
  • ✅ Complete process of VSCode plugin development
  • ✅ Technical implementation of multi-language file type handling
  • ✅ Best practices for user experience design
  • ✅ Performance optimization and extensibility design

Start your plugin development journey now! Make code quality visible, make development more efficient, and make team collaboration smoother.


This article is based on the open-source project vscode-cyclomatic-complexity, welcome to Star and contribute code!

The plugin has been published to the VSCode marketplace, welcome to download and use: Code Cyclomatic Complexity

🔗 Related Links

Top comments (0)