File size: 8,847 Bytes
4fea3ee | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | // Code Quality Scanner
// Analyzes code quality metrics and patterns
// Multi-language support for JavaScript, Python, Java, C#, Go, PHP, Ruby, SQL
const LanguageDetector = require('../analyzers/language-detector');
class CodeQualityScanner {
constructor(options = {}) {
this.options = options;
this.issues = [];
this.languageDetector = new LanguageDetector();
}
scan(content, filePath) {
// Detect language
const langInfo = this.languageDetector.detectFromPath(filePath);
const metrics = {
filePath,
language: langInfo.language,
linesOfCode: this.countLines(content, langInfo),
codeSmells: this.detectCodeSmells(content, langInfo),
duplications: this.detectDuplication(content),
longFunctions: this.detectLongFunctions(content, langInfo),
deepNesting: this.detectDeepNesting(content),
magicNumbers: this.detectMagicNumbers(content)
};
return metrics;
}
countLines(content, langInfo) {
const lines = content.split('\n');
const config = langInfo.config;
const commentStarts = config.comments ? [config.comments.line, config.comments.blockStart].filter(Boolean) : ['//'];
const codeLines = lines.filter(line => {
const trimmed = line.trim();
if (trimmed.length === 0) return false;
// Check if line starts with any comment syntax
return !commentStarts.some(c => trimmed.startsWith(c));
});
return {
total: lines.length,
code: codeLines.length,
comments: lines.length - codeLines.length
};
}
detectCodeSmells(content, langInfo) {
const smells = [];
const config = langInfo.config;
// Long parameter lists (language-agnostic)
const longParams = content.match(/\([^)]{100,}\)/g);
if (longParams) {
smells.push({
type: 'long-parameter-list',
count: longParams.length,
severity: 'MEDIUM'
});
}
// Multiple return statements
const returnKeyword = config.keywords?.control?.includes('return') ? 'return' : 'return';
const returns = content.match(new RegExp(`\\b${returnKeyword}\\s+`, 'g')) || [];
if (returns.length > 10) {
smells.push({
type: 'multiple-returns',
count: returns.length,
severity: 'LOW'
});
}
// Console/print logs in production code (multi-language)
const logPatterns = [
/console\.(log|warn|error|debug)/g, // JavaScript
/print\(/g, // Python
/System\.out\.println/g, // Java
/Console\.WriteLine/g, // C#
/fmt\.Println/g, // Go
/echo\s/g, // PHP
/puts\s/g // Ruby
];
let totalLogs = 0;
logPatterns.forEach(pattern => {
const matches = content.match(pattern);
if (matches) totalLogs += matches.length;
});
if (totalLogs > 5) {
smells.push({
type: 'excessive-debug-logs',
count: totalLogs,
severity: 'MEDIUM'
});
}
return smells;
}
detectDuplication(content) {
const lines = content.split('\n');
const duplicates = [];
const seen = new Map();
lines.forEach((line, index) => {
const trimmed = line.trim();
if (trimmed.length > 20) { // Only check substantial lines
if (seen.has(trimmed)) {
seen.get(trimmed).push(index + 1);
} else {
seen.set(trimmed, [index + 1]);
}
}
});
seen.forEach((lineNumbers, line) => {
if (lineNumbers.length > 1) {
duplicates.push({
line: line.substring(0, 50),
occurrences: lineNumbers.length,
lines: lineNumbers
});
}
});
return duplicates;
}
detectLongFunctions(content, langInfo) {
const longFunctions = [];
const config = langInfo.config;
// Language-specific function patterns
const patterns = {
javascript: /(?:function\s+(\w+)|const\s+(\w+)\s*=\s*(?:async\s+)?\([^)]*\)\s*=>)\s*\{/g,
python: /def\s+(\w+)\s*\([^)]*\):/g,
java: /(?:public|private|protected)?\s*(?:static)?\s*\w+\s+(\w+)\s*\([^)]*\)\s*\{/g,
csharp: /(?:public|private|protected)?\s*(?:static)?\s*\w+\s+(\w+)\s*\([^)]*\)\s*\{/g,
go: /func\s+(?:\(\w+\s+\*?\w+\)\s+)?(\w+)\s*\([^)]*\)\s*(?:\([^)]*\))?\s*\{/g,
php: /function\s+(\w+)\s*\([^)]*\)\s*\{/g,
ruby: /def\s+(\w+)(?:\([^)]*\))?/g
};
const functionPattern = patterns[langInfo.language] || patterns.javascript;
let match;
while ((match = functionPattern.exec(content)) !== null) {
const funcName = match[1] || match[2];
const startPos = match.index;
// Find end of function (simplified - use braces or indentation)
let endPos = startPos + match[0].length;
if (langInfo.language === 'python' || langInfo.language === 'ruby') {
// Indentation-based
const lines = content.substring(startPos).split('\n');
const startIndent = lines[0].search(/\S/);
let funcLines = 1;
for (let i = 1; i < lines.length; i++) {
const lineIndent = lines[i].search(/\S/);
if (lineIndent >= 0 && lineIndent <= startIndent && lines[i].trim().length > 0) break;
funcLines++;
}
if (funcLines > 50) {
longFunctions.push({
name: funcName,
lines: funcLines,
severity: funcLines > 100 ? 'HIGH' : 'MEDIUM'
});
}
} else {
// Brace-based
let braceCount = 1;
for (let i = endPos; i < content.length && braceCount > 0; i++) {
if (content[i] === '{') braceCount++;
if (content[i] === '}') braceCount--;
if (braceCount === 0) {
endPos = i;
break;
}
}
const funcContent = content.substring(startPos, endPos);
const lines = funcContent.split('\n').length;
if (lines > 50) {
longFunctions.push({
name: funcName,
lines: lines,
severity: lines > 100 ? 'HIGH' : 'MEDIUM'
});
}
}
}
return longFunctions;
}
detectDeepNesting(content) {
const lines = content.split('\n');
const deepNesting = [];
lines.forEach((line, index) => {
const indentLevel = line.search(/\S/) / 2; // Assuming 2 spaces per indent
if (indentLevel > 5) {
deepNesting.push({
line: index + 1,
level: Math.floor(indentLevel),
severity: indentLevel > 8 ? 'HIGH' : 'MEDIUM'
});
}
});
return deepNesting;
}
detectMagicNumbers(content) {
const magicNumbers = [];
const numberPattern = /(?<![a-zA-Z0-9_])([0-9]+)(?![a-zA-Z0-9_])/g;
let match;
while ((match = numberPattern.exec(content)) !== null) {
const num = parseInt(match[1]);
// Ignore common numbers
if (num > 1 && num !== 100 && num !== 1000) {
const lineNumber = content.substring(0, match.index).split('\n').length;
magicNumbers.push({
number: num,
line: lineNumber
});
}
}
return magicNumbers.slice(0, 10); // Limit to first 10
}
}
module.exports = CodeQualityScanner;
|