@sun-asterisk/sunlint 1.1.7 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.sunlint.json +1 -1
- package/CHANGELOG.md +83 -0
- package/README.md +66 -4
- package/config/presets/all.json +125 -0
- package/config/presets/beginner.json +16 -8
- package/config/presets/ci.json +12 -4
- package/config/presets/maintainability.json +38 -0
- package/config/presets/performance.json +32 -0
- package/config/presets/quality.json +103 -0
- package/config/presets/recommended.json +36 -12
- package/config/presets/security.json +88 -0
- package/config/presets/strict.json +15 -5
- package/config/rules/rules-registry-generated.json +6312 -0
- package/config/rules-summary.json +1941 -0
- package/core/adapters/sunlint-rule-adapter.js +452 -0
- package/core/analysis-orchestrator.js +4 -4
- package/core/config-manager.js +28 -5
- package/core/rule-selection-service.js +52 -55
- package/docs/CONFIGURATION.md +111 -3
- package/docs/LANGUAGE-SPECIFIC-RULES.md +308 -0
- package/docs/README.md +3 -0
- package/docs/STANDARDIZED-CATEGORY-FILTERING.md +156 -0
- package/engines/eslint-engine.js +92 -2
- package/engines/heuristic-engine.js +8 -31
- package/origin-rules/common-en.md +1320 -0
- package/origin-rules/dart-en.md +289 -0
- package/origin-rules/java-en.md +60 -0
- package/origin-rules/kotlin-mobile-en.md +453 -0
- package/origin-rules/reactjs-en.md +102 -0
- package/origin-rules/security-en.md +1055 -0
- package/origin-rules/swift-en.md +449 -0
- package/origin-rules/typescript-en.md +136 -0
- package/package.json +6 -5
- package/scripts/copy-rules.js +86 -0
- package/rules/README.md +0 -252
- package/rules/common/C002_no_duplicate_code/analyzer.js +0 -65
- package/rules/common/C002_no_duplicate_code/config.json +0 -23
- package/rules/common/C003_no_vague_abbreviations/analyzer.js +0 -418
- package/rules/common/C003_no_vague_abbreviations/config.json +0 -35
- package/rules/common/C006_function_naming/analyzer.js +0 -349
- package/rules/common/C006_function_naming/config.json +0 -86
- package/rules/common/C010_limit_block_nesting/analyzer.js +0 -389
- package/rules/common/C013_no_dead_code/analyzer.js +0 -206
- package/rules/common/C014_dependency_injection/analyzer.js +0 -338
- package/rules/common/C017_constructor_logic/analyzer.js +0 -314
- package/rules/common/C019_log_level_usage/analyzer.js +0 -362
- package/rules/common/C019_log_level_usage/config.json +0 -121
- package/rules/common/C029_catch_block_logging/analyzer.js +0 -373
- package/rules/common/C029_catch_block_logging/config.json +0 -59
- package/rules/common/C031_validation_separation/analyzer.js +0 -186
- package/rules/common/C041_no_sensitive_hardcode/analyzer.js +0 -292
- package/rules/common/C042_boolean_name_prefix/analyzer.js +0 -300
- package/rules/common/C043_no_console_or_print/analyzer.js +0 -304
- package/rules/common/C047_no_duplicate_retry_logic/analyzer.js +0 -351
- package/rules/common/C075_explicit_return_types/analyzer.js +0 -103
- package/rules/common/C076_single_test_behavior/analyzer.js +0 -121
- package/rules/docs/C002_no_duplicate_code.md +0 -57
- package/rules/docs/C031_validation_separation.md +0 -72
- package/rules/index.js +0 -149
- package/rules/migration/converter.js +0 -385
- package/rules/migration/mapping.json +0 -164
- package/rules/security/S026_json_schema_validation/analyzer.js +0 -251
- package/rules/security/S026_json_schema_validation/config.json +0 -27
- package/rules/security/S027_no_hardcoded_secrets/analyzer.js +0 -263
- package/rules/security/S027_no_hardcoded_secrets/config.json +0 -29
- package/rules/security/S029_csrf_protection/analyzer.js +0 -264
- package/rules/tests/C002_no_duplicate_code.test.js +0 -50
- package/rules/universal/C010/generic.js +0 -0
- package/rules/universal/C010/tree-sitter-analyzer.js +0 -0
- package/rules/utils/ast-utils.js +0 -191
- package/rules/utils/base-analyzer.js +0 -98
- package/rules/utils/pattern-matchers.js +0 -239
- package/rules/utils/rule-helpers.js +0 -264
- package/rules/utils/severity-constants.js +0 -93
|
@@ -1,373 +0,0 @@
|
|
|
1
|
-
const fs = require('fs');
|
|
2
|
-
const path = require('path');
|
|
3
|
-
const { PatternMatcher } = require('../../utils/pattern-matchers');
|
|
4
|
-
const { RuleHelper } = require('../../utils/rule-helpers');
|
|
5
|
-
|
|
6
|
-
class C029Analyzer {
|
|
7
|
-
constructor() {
|
|
8
|
-
this.ruleId = 'C029';
|
|
9
|
-
this.ruleName = 'Enhanced Catch Block Error Logging';
|
|
10
|
-
this.description = 'Mọi catch block phải log nguyên nhân lỗi đầy đủ và bảo toàn context (enhanced version replacing ESLint C028)';
|
|
11
|
-
this.aiAnalyzer = null;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
async analyze(files, language, options = {}) {
|
|
15
|
-
const violations = [];
|
|
16
|
-
|
|
17
|
-
for (const filePath of files) {
|
|
18
|
-
if (options.verbose) {
|
|
19
|
-
console.log(`🔍 Running pattern analysis on ${path.basename(filePath)}`);
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
try {
|
|
23
|
-
const content = fs.readFileSync(filePath, 'utf8');
|
|
24
|
-
const fileViolations = await this.analyzeFile(filePath, content, language, options);
|
|
25
|
-
violations.push(...fileViolations);
|
|
26
|
-
} catch (error) {
|
|
27
|
-
console.warn(`⚠️ Failed to analyze ${filePath}: ${error.message}`);
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
return violations;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
async analyzeFile(filePath, content, language, config) {
|
|
35
|
-
switch (language) {
|
|
36
|
-
case 'typescript':
|
|
37
|
-
case 'javascript':
|
|
38
|
-
return this.analyzeTypeScript(filePath, content, config);
|
|
39
|
-
default:
|
|
40
|
-
return [];
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
async analyzeTypeScript(filePath, content, config) {
|
|
45
|
-
const violations = [];
|
|
46
|
-
const lines = content.split('\n');
|
|
47
|
-
|
|
48
|
-
// Focus on core functionality - only detect truly silent catch blocks
|
|
49
|
-
violations.push(...this.findSilentCatchBlocks(lines, filePath));
|
|
50
|
-
// Disabled strict checks to reduce false positives:
|
|
51
|
-
// violations.push(...this.findInadequateErrorLogging(lines, filePath));
|
|
52
|
-
// violations.push(...this.findMissingErrorContext(lines, filePath));
|
|
53
|
-
|
|
54
|
-
return violations;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Core functionality from ESLint C029 - detect silent catch blocks
|
|
59
|
-
*/
|
|
60
|
-
findSilentCatchBlocks(lines, filePath) {
|
|
61
|
-
const violations = [];
|
|
62
|
-
|
|
63
|
-
lines.forEach((line, index) => {
|
|
64
|
-
const lineNumber = index + 1;
|
|
65
|
-
const trimmedLine = line.trim();
|
|
66
|
-
|
|
67
|
-
// Detect catch block start
|
|
68
|
-
if (this.isCatchBlockStart(trimmedLine)) {
|
|
69
|
-
const catchBlockInfo = this.extractCatchBlockInfo(lines, index);
|
|
70
|
-
|
|
71
|
-
if (catchBlockInfo.isEmpty) {
|
|
72
|
-
violations.push({
|
|
73
|
-
ruleId: this.ruleId,
|
|
74
|
-
file: filePath,
|
|
75
|
-
line: lineNumber,
|
|
76
|
-
column: line.indexOf('catch') + 1,
|
|
77
|
-
message: 'Empty catch block - error is silently ignored',
|
|
78
|
-
severity: 'error',
|
|
79
|
-
code: trimmedLine,
|
|
80
|
-
type: 'empty_catch_block',
|
|
81
|
-
confidence: 1.0,
|
|
82
|
-
suggestion: 'Add error logging or rethrowing in catch block'
|
|
83
|
-
});
|
|
84
|
-
} else if (!catchBlockInfo.hasLoggingOrRethrow) {
|
|
85
|
-
violations.push({
|
|
86
|
-
ruleId: this.ruleId,
|
|
87
|
-
file: filePath,
|
|
88
|
-
line: lineNumber,
|
|
89
|
-
column: line.indexOf('catch') + 1,
|
|
90
|
-
message: 'Catch block must log error or rethrow - silent error handling hides bugs',
|
|
91
|
-
severity: 'error',
|
|
92
|
-
code: trimmedLine,
|
|
93
|
-
type: 'silent_catch_block',
|
|
94
|
-
confidence: 0.9,
|
|
95
|
-
suggestion: 'Add error logging (console.error, logger.error) or rethrow the error'
|
|
96
|
-
});
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
});
|
|
100
|
-
|
|
101
|
-
return violations;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* SunLint enhanced functionality - detect inadequate error logging
|
|
106
|
-
*/
|
|
107
|
-
findInadequateErrorLogging(lines, filePath) {
|
|
108
|
-
const violations = [];
|
|
109
|
-
|
|
110
|
-
lines.forEach((line, index) => {
|
|
111
|
-
const lineNumber = index + 1;
|
|
112
|
-
const trimmedLine = line.trim();
|
|
113
|
-
|
|
114
|
-
if (this.isCatchBlockStart(trimmedLine)) {
|
|
115
|
-
const catchBlockInfo = this.extractCatchBlockInfo(lines, index);
|
|
116
|
-
|
|
117
|
-
if (catchBlockInfo.hasLoggingOrRethrow && !catchBlockInfo.hasAdequateLogging) {
|
|
118
|
-
violations.push({
|
|
119
|
-
ruleId: this.ruleId,
|
|
120
|
-
file: filePath,
|
|
121
|
-
line: lineNumber,
|
|
122
|
-
column: line.indexOf('catch') + 1,
|
|
123
|
-
message: 'Error logging should include error message, stack trace, and context',
|
|
124
|
-
severity: 'warning',
|
|
125
|
-
code: trimmedLine,
|
|
126
|
-
type: 'inadequate_error_logging',
|
|
127
|
-
confidence: 0.8,
|
|
128
|
-
suggestion: 'Include error.message, error.stack, and relevant context in error logging'
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
});
|
|
133
|
-
|
|
134
|
-
return violations;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* SunLint enhanced functionality - detect missing error context
|
|
139
|
-
* DISABLED: Too strict, causing false positives
|
|
140
|
-
*/
|
|
141
|
-
findMissingErrorContext(lines, filePath) {
|
|
142
|
-
// Disabled to reduce false positives
|
|
143
|
-
return [];
|
|
144
|
-
|
|
145
|
-
/* Original strict implementation:
|
|
146
|
-
const violations = [];
|
|
147
|
-
|
|
148
|
-
lines.forEach((line, index) => {
|
|
149
|
-
const lineNumber = index + 1;
|
|
150
|
-
const trimmedLine = line.trim();
|
|
151
|
-
|
|
152
|
-
if (this.isCatchBlockStart(trimmedLine)) {
|
|
153
|
-
const catchBlockInfo = this.extractCatchBlockInfo(lines, index);
|
|
154
|
-
|
|
155
|
-
if (catchBlockInfo.hasLoggingOrRethrow && !catchBlockInfo.hasContextualLogging) {
|
|
156
|
-
violations.push({
|
|
157
|
-
ruleId: this.ruleId,
|
|
158
|
-
file: filePath,
|
|
159
|
-
line: lineNumber,
|
|
160
|
-
column: line.indexOf('catch') + 1,
|
|
161
|
-
message: 'Error logging should include operational context (function name, input parameters)',
|
|
162
|
-
severity: 'info',
|
|
163
|
-
code: trimmedLine,
|
|
164
|
-
type: 'missing_error_context',
|
|
165
|
-
confidence: 0.7,
|
|
166
|
-
suggestion: 'Include function name, input parameters, and operational context in error logging'
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
});
|
|
171
|
-
|
|
172
|
-
return violations;
|
|
173
|
-
*/
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
isCatchBlockStart(line) {
|
|
177
|
-
return line.includes('catch (') || line.includes('catch(');
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
extractCatchBlockInfo(lines, startIndex) {
|
|
181
|
-
const catchBlockLines = [];
|
|
182
|
-
let braceDepth = 0;
|
|
183
|
-
let foundCatchBrace = false;
|
|
184
|
-
|
|
185
|
-
for (let i = startIndex; i < lines.length; i++) {
|
|
186
|
-
const line = lines[i];
|
|
187
|
-
catchBlockLines.push(line);
|
|
188
|
-
|
|
189
|
-
// Check if this is the catch line with opening brace
|
|
190
|
-
if (this.isCatchBlockStart(line.trim())) {
|
|
191
|
-
// Count braces in the catch line itself
|
|
192
|
-
for (const char of line) {
|
|
193
|
-
if (char === '{') {
|
|
194
|
-
foundCatchBrace = true;
|
|
195
|
-
braceDepth = 1; // Start counting from 1 for the catch block
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
} else if (foundCatchBrace) {
|
|
199
|
-
// Count braces in subsequent lines
|
|
200
|
-
for (const char of line) {
|
|
201
|
-
if (char === '{') {
|
|
202
|
-
braceDepth++;
|
|
203
|
-
} else if (char === '}') {
|
|
204
|
-
braceDepth--;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
// If we've closed all braces, we're done
|
|
209
|
-
if (braceDepth === 0) {
|
|
210
|
-
break;
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
const content = catchBlockLines.join('\n').toLowerCase();
|
|
216
|
-
const originalContent = catchBlockLines.join('\n');
|
|
217
|
-
|
|
218
|
-
return {
|
|
219
|
-
isEmpty: this.isCatchBlockEmpty(catchBlockLines),
|
|
220
|
-
hasLoggingOrRethrow: this.hasLoggingOrRethrow(content, originalContent),
|
|
221
|
-
hasAdequateLogging: this.hasAdequateErrorLogging(content, originalContent),
|
|
222
|
-
hasContextualLogging: this.hasContextualErrorLogging(content, originalContent)
|
|
223
|
-
};
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
isCatchBlockEmpty(catchBlockLines) {
|
|
227
|
-
if (catchBlockLines.length === 0) return true;
|
|
228
|
-
|
|
229
|
-
// Join all lines and find the content between braces
|
|
230
|
-
const fullContent = catchBlockLines.join('\n');
|
|
231
|
-
|
|
232
|
-
// Find the opening brace and closing brace
|
|
233
|
-
let openBraceIndex = fullContent.indexOf('{');
|
|
234
|
-
let closeBraceIndex = fullContent.lastIndexOf('}');
|
|
235
|
-
|
|
236
|
-
if (openBraceIndex === -1 || closeBraceIndex === -1) {
|
|
237
|
-
return true; // Malformed catch block
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
// Extract body content between braces
|
|
241
|
-
const bodyContent = fullContent.substring(openBraceIndex + 1, closeBraceIndex).trim();
|
|
242
|
-
|
|
243
|
-
// Remove comments and whitespace
|
|
244
|
-
const cleanedBody = bodyContent
|
|
245
|
-
.replace(/\/\*[\s\S]*?\*\//g, '') // Remove block comments
|
|
246
|
-
.replace(/\/\/.*$/gm, '') // Remove line comments
|
|
247
|
-
.replace(/\s+/g, ' ') // Normalize whitespace
|
|
248
|
-
.trim();
|
|
249
|
-
|
|
250
|
-
return cleanedBody.length === 0;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
hasLoggingOrRethrow(content, originalContent) {
|
|
254
|
-
// Check for throw statements
|
|
255
|
-
if (content.includes('throw ') || content.includes('throw;')) {
|
|
256
|
-
return true;
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
// Check for test assertions - valid form of error handling
|
|
260
|
-
const testPatterns = [
|
|
261
|
-
'expect(',
|
|
262
|
-
'assert(',
|
|
263
|
-
'tobeinstanceof',
|
|
264
|
-
'toequal(',
|
|
265
|
-
'tohavebeencalled',
|
|
266
|
-
'toBe(',
|
|
267
|
-
'toHaveBeenCalledWith'
|
|
268
|
-
];
|
|
269
|
-
|
|
270
|
-
const hasTestAssertions = testPatterns.some(pattern =>
|
|
271
|
-
content.includes(pattern.toLowerCase()) || originalContent.toLowerCase().includes(pattern.toLowerCase())
|
|
272
|
-
);
|
|
273
|
-
|
|
274
|
-
if (hasTestAssertions) {
|
|
275
|
-
return true;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
// Check for Redux/async thunk error handling
|
|
279
|
-
const reduxErrorHandlers = [
|
|
280
|
-
'handleaxioserror',
|
|
281
|
-
'rejectwithvalue',
|
|
282
|
-
'dispatch(',
|
|
283
|
-
'seterror(',
|
|
284
|
-
'return value',
|
|
285
|
-
'return rejectwithvalue'
|
|
286
|
-
];
|
|
287
|
-
|
|
288
|
-
const hasReduxHandling = reduxErrorHandlers.some(pattern =>
|
|
289
|
-
content.includes(pattern.toLowerCase()) || originalContent.toLowerCase().includes(pattern.toLowerCase())
|
|
290
|
-
);
|
|
291
|
-
|
|
292
|
-
if (hasReduxHandling) {
|
|
293
|
-
return true;
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
// Check for logging patterns (expanded from original)
|
|
297
|
-
const loggingPatterns = [
|
|
298
|
-
'console.error',
|
|
299
|
-
'console.log',
|
|
300
|
-
'console.warn',
|
|
301
|
-
'logger.error',
|
|
302
|
-
'log.error',
|
|
303
|
-
'logger.warn',
|
|
304
|
-
'log.warn',
|
|
305
|
-
'winston.error',
|
|
306
|
-
'bunyan.error',
|
|
307
|
-
'pino.error',
|
|
308
|
-
'.error(',
|
|
309
|
-
'.warn(',
|
|
310
|
-
'.log('
|
|
311
|
-
];
|
|
312
|
-
|
|
313
|
-
// Accept basic error logging - don't require context
|
|
314
|
-
const hasBasicLogging = loggingPatterns.some(pattern =>
|
|
315
|
-
content.includes(pattern) || originalContent.includes(pattern)
|
|
316
|
-
);
|
|
317
|
-
|
|
318
|
-
return hasBasicLogging;
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
hasAdequateErrorLogging(content, originalContent) {
|
|
322
|
-
// Check for error properties being logged
|
|
323
|
-
const errorProperties = [
|
|
324
|
-
'error.message',
|
|
325
|
-
'error.stack',
|
|
326
|
-
'err.message',
|
|
327
|
-
'err.stack',
|
|
328
|
-
'e.message',
|
|
329
|
-
'e.stack',
|
|
330
|
-
'error.name',
|
|
331
|
-
'error.cause'
|
|
332
|
-
];
|
|
333
|
-
|
|
334
|
-
const hasErrorProperties = errorProperties.some(prop =>
|
|
335
|
-
content.includes(prop) || originalContent.includes(prop)
|
|
336
|
-
);
|
|
337
|
-
|
|
338
|
-
// Check for comprehensive error logging
|
|
339
|
-
const hasLogging = this.hasLoggingOrRethrow(content, originalContent);
|
|
340
|
-
|
|
341
|
-
return hasLogging && hasErrorProperties;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
hasContextualErrorLogging(content, originalContent) {
|
|
345
|
-
// Check for contextual information in logging
|
|
346
|
-
const contextualPatterns = [
|
|
347
|
-
'function',
|
|
348
|
-
'method',
|
|
349
|
-
'operation',
|
|
350
|
-
'input',
|
|
351
|
-
'parameters',
|
|
352
|
-
'context',
|
|
353
|
-
'state',
|
|
354
|
-
'request',
|
|
355
|
-
'response',
|
|
356
|
-
'userId',
|
|
357
|
-
'sessionId',
|
|
358
|
-
'transactionId'
|
|
359
|
-
];
|
|
360
|
-
|
|
361
|
-
// Check if logging includes contextual information
|
|
362
|
-
const hasContextualInfo = contextualPatterns.some(pattern =>
|
|
363
|
-
content.includes(pattern) || originalContent.includes(pattern)
|
|
364
|
-
);
|
|
365
|
-
|
|
366
|
-
// Check for template literals or string concatenation (indicates contextual logging)
|
|
367
|
-
const hasTemplateLogging = originalContent.includes('${') || originalContent.includes('" + ') || originalContent.includes("' + ");
|
|
368
|
-
|
|
369
|
-
return hasContextualInfo || hasTemplateLogging;
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
module.exports = new C029Analyzer();
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"ruleId": "C029",
|
|
3
|
-
"name": "Catch Block Error Logging",
|
|
4
|
-
"description": "Mọi catch block phải log nguyên nhân lỗi đầy đủ",
|
|
5
|
-
"category": "error-handling",
|
|
6
|
-
"severity": "error",
|
|
7
|
-
"languages": ["typescript", "dart", "kotlin", "javascript"],
|
|
8
|
-
"version": "1.0.0",
|
|
9
|
-
"status": "activated",
|
|
10
|
-
"tags": ["error-handling", "logging", "debugging", "monitoring"],
|
|
11
|
-
"examples": {
|
|
12
|
-
"typescript": {
|
|
13
|
-
"violations": [
|
|
14
|
-
"try { riskyOperation(); } catch (error) { return null; }",
|
|
15
|
-
"catch (e) { /* empty */ }",
|
|
16
|
-
"catch (error) { throw new Error('Failed'); }"
|
|
17
|
-
],
|
|
18
|
-
"valid": [
|
|
19
|
-
"catch (error) { console.error('Operation failed:', error); }",
|
|
20
|
-
"catch (e) { logger.error('Error in process:', e); }",
|
|
21
|
-
"catch (error) { console.error(error); throw error; }"
|
|
22
|
-
]
|
|
23
|
-
},
|
|
24
|
-
"dart": {
|
|
25
|
-
"violations": [
|
|
26
|
-
"try { riskyOperation(); } catch (e) { return null; }",
|
|
27
|
-
"on Exception catch (e) { /* empty */ }"
|
|
28
|
-
],
|
|
29
|
-
"valid": [
|
|
30
|
-
"catch (e) { print('Error: $e'); }",
|
|
31
|
-
"on Exception catch (e) { log.severe('Failed:', e); }"
|
|
32
|
-
]
|
|
33
|
-
},
|
|
34
|
-
"kotlin": {
|
|
35
|
-
"violations": [
|
|
36
|
-
"try { riskyOperation() } catch (e: Exception) { return null }",
|
|
37
|
-
"catch (e: Exception) { /* empty */ }"
|
|
38
|
-
],
|
|
39
|
-
"valid": [
|
|
40
|
-
"catch (e: Exception) { Log.e(TAG, 'Error:', e) }",
|
|
41
|
-
"catch (e: Exception) { logger.error('Failed', e) }"
|
|
42
|
-
]
|
|
43
|
-
}
|
|
44
|
-
},
|
|
45
|
-
"configuration": {
|
|
46
|
-
"requiredLoggingMethods": [
|
|
47
|
-
"console.error",
|
|
48
|
-
"console.log",
|
|
49
|
-
"logger.error",
|
|
50
|
-
"log.error",
|
|
51
|
-
"print",
|
|
52
|
-
"log.severe",
|
|
53
|
-
"Log.e",
|
|
54
|
-
"timber.e"
|
|
55
|
-
],
|
|
56
|
-
"allowEmptyWhenRethrow": true,
|
|
57
|
-
"checkErrorParameter": true
|
|
58
|
-
}
|
|
59
|
-
}
|
|
@@ -1,186 +0,0 @@
|
|
|
1
|
-
const fs = require('fs');
|
|
2
|
-
const path = require('path');
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Rule C031 - Validation Logic Separation
|
|
6
|
-
* Kiểm tra logic validation có bị trộn lẫn với business logic không
|
|
7
|
-
*/
|
|
8
|
-
class ValidationSeparationAnalyzer {
|
|
9
|
-
constructor() {
|
|
10
|
-
this.ruleId = 'C031';
|
|
11
|
-
this.ruleName = 'Validation Logic Separation';
|
|
12
|
-
this.category = 'architecture';
|
|
13
|
-
this.severity = 'warning';
|
|
14
|
-
this.description = 'Logic kiểm tra dữ liệu (validate) phải nằm riêng biệt';
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
analyzeFile(filePath, options = {}) {
|
|
18
|
-
const violations = [];
|
|
19
|
-
|
|
20
|
-
try {
|
|
21
|
-
if (!fs.existsSync(filePath)) {
|
|
22
|
-
return violations;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
const content = fs.readFileSync(filePath, 'utf8');
|
|
26
|
-
const lines = content.split('\n');
|
|
27
|
-
|
|
28
|
-
// Detect functions with mixed validation and business logic
|
|
29
|
-
const functions = this.extractFunctions(content);
|
|
30
|
-
|
|
31
|
-
for (const func of functions) {
|
|
32
|
-
const validationCount = this.countValidationStatements(func.body);
|
|
33
|
-
const businessLogicCount = this.countBusinessLogicStatements(func.body);
|
|
34
|
-
|
|
35
|
-
// If both validation and business logic exist in same function
|
|
36
|
-
if (validationCount > 0 && businessLogicCount > 0) {
|
|
37
|
-
const maxValidationAllowed = options.maxValidationStatementsInFunction || 3;
|
|
38
|
-
|
|
39
|
-
if (validationCount > maxValidationAllowed) {
|
|
40
|
-
violations.push({
|
|
41
|
-
line: func.startLine,
|
|
42
|
-
column: 1,
|
|
43
|
-
message: `Function '${func.name}' has ${validationCount} validation statements mixed with business logic. Consider separating validation logic.`,
|
|
44
|
-
ruleId: this.ruleId,
|
|
45
|
-
severity: this.severity,
|
|
46
|
-
source: lines[func.startLine - 1]?.trim() || ''
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
} catch (error) {
|
|
53
|
-
console.error(`Error analyzing ${filePath}:`, error.message);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
return violations;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
extractFunctions(content) {
|
|
60
|
-
const functions = [];
|
|
61
|
-
const lines = content.split('\n');
|
|
62
|
-
|
|
63
|
-
// Simple function detection patterns
|
|
64
|
-
const functionPatterns = [
|
|
65
|
-
/function\s+(\w+)\s*\(/g,
|
|
66
|
-
/const\s+(\w+)\s*=\s*\(/g,
|
|
67
|
-
/(\w+)\s*\(\s*[^)]*\s*\)\s*=>/g,
|
|
68
|
-
/(\w+)\s*:\s*function\s*\(/g
|
|
69
|
-
];
|
|
70
|
-
|
|
71
|
-
for (let i = 0; i < lines.length; i++) {
|
|
72
|
-
const line = lines[i];
|
|
73
|
-
|
|
74
|
-
for (const pattern of functionPatterns) {
|
|
75
|
-
const matches = line.matchAll(pattern);
|
|
76
|
-
for (const match of matches) {
|
|
77
|
-
const functionName = match[1];
|
|
78
|
-
const startLine = i + 1;
|
|
79
|
-
|
|
80
|
-
// Extract function body (simple approach)
|
|
81
|
-
const body = this.extractFunctionBody(lines, i);
|
|
82
|
-
|
|
83
|
-
functions.push({
|
|
84
|
-
name: functionName,
|
|
85
|
-
startLine,
|
|
86
|
-
body
|
|
87
|
-
});
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
return functions;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
extractFunctionBody(lines, startIndex) {
|
|
96
|
-
let body = '';
|
|
97
|
-
let braceCount = 0;
|
|
98
|
-
let inFunction = false;
|
|
99
|
-
|
|
100
|
-
for (let i = startIndex; i < lines.length; i++) {
|
|
101
|
-
const line = lines[i];
|
|
102
|
-
|
|
103
|
-
if (line.includes('{')) {
|
|
104
|
-
braceCount += (line.match(/\{/g) || []).length;
|
|
105
|
-
inFunction = true;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
if (inFunction) {
|
|
109
|
-
body += line + '\n';
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
if (line.includes('}')) {
|
|
113
|
-
braceCount -= (line.match(/\}/g) || []).length;
|
|
114
|
-
if (braceCount <= 0 && inFunction) {
|
|
115
|
-
break;
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
return body;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
countValidationStatements(code) {
|
|
124
|
-
const validationPatterns = [
|
|
125
|
-
/if\s*\(\s*!.*\)\s*\{?\s*throw/g,
|
|
126
|
-
/if\s*\(.*\.\s*length\s*[<>=]\s*\d+\)/g,
|
|
127
|
-
/if\s*\(.*\s*==\s*null\s*\||\s*.*\s*==\s*undefined\)/g,
|
|
128
|
-
/if\s*\(.*\s*!\s*=\s*null\s*&&\s*.*\s*!\s*=\s*undefined\)/g,
|
|
129
|
-
/throw\s+new\s+Error\s*\(/g,
|
|
130
|
-
/assert\s*\(/g,
|
|
131
|
-
/validate\w*\s*\(/g,
|
|
132
|
-
/check\w*\s*\(/g
|
|
133
|
-
];
|
|
134
|
-
|
|
135
|
-
let count = 0;
|
|
136
|
-
for (const pattern of validationPatterns) {
|
|
137
|
-
const matches = code.match(pattern);
|
|
138
|
-
if (matches) {
|
|
139
|
-
count += matches.length;
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
return count;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
countBusinessLogicStatements(code) {
|
|
147
|
-
const businessLogicPatterns = [
|
|
148
|
-
/calculate\w*\s*\(/g,
|
|
149
|
-
/process\w*\s*\(/g,
|
|
150
|
-
/save\w*\s*\(/g,
|
|
151
|
-
/update\w*\s*\(/g,
|
|
152
|
-
/delete\w*\s*\(/g,
|
|
153
|
-
/send\w*\s*\(/g,
|
|
154
|
-
/return\s+\w+\s*\(/g,
|
|
155
|
-
/await\s+\w+\s*\(/g
|
|
156
|
-
];
|
|
157
|
-
|
|
158
|
-
let count = 0;
|
|
159
|
-
for (const pattern of businessLogicPatterns) {
|
|
160
|
-
const matches = code.match(pattern);
|
|
161
|
-
if (matches) {
|
|
162
|
-
count += matches.length;
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
return count;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
// Main analyze method expected by CLI
|
|
170
|
-
async analyze(files, language, config) {
|
|
171
|
-
const violations = [];
|
|
172
|
-
|
|
173
|
-
for (const filePath of files) {
|
|
174
|
-
try {
|
|
175
|
-
const fileViolations = this.analyzeFile(filePath, config);
|
|
176
|
-
violations.push(...fileViolations);
|
|
177
|
-
} catch (error) {
|
|
178
|
-
console.error(`Error analyzing file ${filePath}:`, error.message);
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
return violations;
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
module.exports = new ValidationSeparationAnalyzer();
|