UNPKG

@regele/devtools

Version:

A collection of developer utilities for code processing and text analysis

87 lines (86 loc) 2.71 kB
import * as parser from '@babel/parser'; import * as t from '@babel/types'; import { Rule } from '../rule'; import { CategoryType, CodeFinding, SeverityLevel } from '../../types'; /** * Rule to detect duplicated code */ export declare class DuplicatedCodeRule extends Rule { readonly id = "maint-duplicated-code"; readonly name = "Duplicated Code"; readonly description = "Detects duplicated code blocks that should be refactored"; readonly category = CategoryType.Maintainability; readonly defaultSeverity = SeverityLevel.Warning; readonly requiresAST = true; private readonly MIN_BLOCK_SIZE; private readonly SIMILARITY_THRESHOLD; /** * Apply the rule to the given code * * @param code - Source code * @param ast - Parsed AST * @param filePath - Path to the file * @returns Array of findings */ apply(code: string, ast: parser.ParseResult<t.File>, filePath: string): CodeFinding[]; /** * Get the body of a function-like node * * @param node - Function-like node * @returns Body node or undefined */ private getFunctionBody; /** * Find duplicated code blocks * * @param blocks - Array of code blocks * @returns Array of duplicate groups */ private findDuplicates; /** * Calculate similarity between two code blocks * * @param code1 - First code block * @param code2 - Second code block * @returns Similarity score (0-1) */ private calculateSimilarity; /** * Normalize code by removing whitespace and comments * * @param code - Code to normalize * @returns Normalized code */ private normalizeCode; /** * Calculate Levenshtein distance between two strings * * @param s1 - First string * @param s2 - Second string * @returns Levenshtein distance */ private levenshteinDistance; /** * Generate a suggestion for refactoring duplicated code * * @param code - Duplicated code * @param originalName - Name of the original function * @param duplicateName - Name of the duplicate function * @returns Suggested code */ protected generateSuggestion(code: string, _originalName?: string, _duplicateName?: string): string; /** * Get the name of the function * * @param path - AST path * @returns Function name or undefined */ protected getFunctionName(path: any): string | undefined; /** * Get the name of the class containing a method * * @param path - AST path * @returns Class name or undefined */ protected getClassName(path: any): string | undefined; }