rk147 commited on
Commit
cf28cad
·
verified ·
1 Parent(s): a269447

Update app/modules/analyzer_javascript.py

Browse files
Files changed (1) hide show
  1. app/modules/analyzer_javascript.py +28 -42
app/modules/analyzer_javascript.py CHANGED
@@ -4,19 +4,16 @@ import subprocess
4
  import tempfile
5
  import json
6
  import os
7
- import sys
8
  from app.modules.analyzer_base import CodeAnalyzer, AnalysisResult
9
 
10
 
11
  class JavaScriptAnalyzer(CodeAnalyzer):
12
- """Analyzer for JavaScript/TypeScript code using ESLint."""
13
-
14
  def __init__(self, language: str = "javascript"):
15
  super().__init__(language)
16
  self.eslint_available = self._check_eslint()
17
-
18
  def _check_eslint(self) -> bool:
19
- """Check if ESLint is available."""
20
  try:
21
  result = subprocess.run(
22
  ["npx", "eslint", "--version"],
@@ -25,93 +22,82 @@ class JavaScriptAnalyzer(CodeAnalyzer):
25
  return result.returncode == 0
26
  except Exception:
27
  return False
28
-
29
  def analyze(self, code: str) -> AnalysisResult:
30
- """Analyze JavaScript/TypeScript code."""
31
  if not self.eslint_available:
32
  return self._analyze_fallback(code)
33
-
34
  ext = ".ts" if self.language == "typescript" else ".js"
35
  with tempfile.NamedTemporaryFile(mode="w", suffix=ext, delete=False, encoding="utf-8") as f:
36
  f.write(code)
37
  temp_path = f.name
38
-
39
  try:
40
  result = subprocess.run(
41
  ["npx", "eslint", "--format=json", temp_path],
42
  capture_output=True, text=True, timeout=15
43
  )
44
-
 
45
  if result.stdout.strip():
46
  try:
47
  raw_data = json.loads(result.stdout)
48
  raw_issues = raw_data[0].get("messages", []) if raw_data else []
49
  except json.JSONDecodeError:
50
- raw_issues = []
51
- else:
52
- raw_issues = []
53
-
54
- # Convert ESLint format to standardized format
55
  issues = []
56
- for issue in raw_issues[:5]: # Limit to top 5
57
- severity_map = {
58
- 2: "high", # error
59
- 1: "medium", # warning
60
- }
61
-
62
  severity = severity_map.get(issue.get("severity", 1), "low")
63
-
64
- formatted_issue = self.format_issue(
65
  line=issue.get("line", 0),
66
  symbol=issue.get("ruleId", ""),
67
  message=issue.get("message", ""),
68
  category="style",
69
- severity=severity
70
- )
71
- issues.append(formatted_issue)
72
-
73
  return AnalysisResult(self.language, issues)
74
-
75
  except Exception as e:
76
  return AnalysisResult(self.language, error=str(e))
77
-
78
  finally:
79
  if os.path.exists(temp_path):
80
  os.unlink(temp_path)
81
-
82
  def _analyze_fallback(self, code: str) -> AnalysisResult:
83
- """Fallback analysis when ESLint is not available."""
84
- # Basic linting without external tool
85
  issues = []
86
  lines = code.split("\n")
87
-
88
  for i, line in enumerate(lines, 1):
89
- # Check for common JS issues
90
  if "var " in line and "var" in line.split(";")[0]:
91
  issues.append(self.format_issue(
92
  line=i,
93
  symbol="no-var",
94
  message="Use 'let' or 'const' instead of 'var'",
95
  category="style",
96
- severity="low"
97
  ))
98
-
99
- if "== " in line:
 
100
  issues.append(self.format_issue(
101
  line=i,
102
  symbol="eqeqeq",
103
  message="Use '===' instead of '=='",
104
  category="correctness",
105
- severity="medium"
106
  ))
107
-
108
  if line.rstrip() != line:
109
  issues.append(self.format_issue(
110
  line=i,
111
  symbol="trailing-spaces",
112
  message="Trailing whitespace",
113
  category="style",
114
- severity="low"
115
  ))
116
-
117
- return AnalysisResult(self.language, issues[:5])
 
4
  import tempfile
5
  import json
6
  import os
 
7
  from app.modules.analyzer_base import CodeAnalyzer, AnalysisResult
8
 
9
 
10
  class JavaScriptAnalyzer(CodeAnalyzer):
11
+
 
12
  def __init__(self, language: str = "javascript"):
13
  super().__init__(language)
14
  self.eslint_available = self._check_eslint()
15
+
16
  def _check_eslint(self) -> bool:
 
17
  try:
18
  result = subprocess.run(
19
  ["npx", "eslint", "--version"],
 
22
  return result.returncode == 0
23
  except Exception:
24
  return False
25
+
26
  def analyze(self, code: str) -> AnalysisResult:
 
27
  if not self.eslint_available:
28
  return self._analyze_fallback(code)
29
+
30
  ext = ".ts" if self.language == "typescript" else ".js"
31
  with tempfile.NamedTemporaryFile(mode="w", suffix=ext, delete=False, encoding="utf-8") as f:
32
  f.write(code)
33
  temp_path = f.name
34
+
35
  try:
36
  result = subprocess.run(
37
  ["npx", "eslint", "--format=json", temp_path],
38
  capture_output=True, text=True, timeout=15
39
  )
40
+
41
+ raw_issues = []
42
  if result.stdout.strip():
43
  try:
44
  raw_data = json.loads(result.stdout)
45
  raw_issues = raw_data[0].get("messages", []) if raw_data else []
46
  except json.JSONDecodeError:
47
+ pass
48
+
 
 
 
49
  issues = []
50
+ for issue in raw_issues[:5]:
51
+ severity_map = {2: "high", 1: "medium"}
 
 
 
 
52
  severity = severity_map.get(issue.get("severity", 1), "low")
53
+ issues.append(self.format_issue(
 
54
  line=issue.get("line", 0),
55
  symbol=issue.get("ruleId", ""),
56
  message=issue.get("message", ""),
57
  category="style",
58
+ severity=severity,
59
+ ))
60
+
 
61
  return AnalysisResult(self.language, issues)
62
+
63
  except Exception as e:
64
  return AnalysisResult(self.language, error=str(e))
65
+
66
  finally:
67
  if os.path.exists(temp_path):
68
  os.unlink(temp_path)
69
+
70
  def _analyze_fallback(self, code: str) -> AnalysisResult:
 
 
71
  issues = []
72
  lines = code.split("\n")
73
+
74
  for i, line in enumerate(lines, 1):
 
75
  if "var " in line and "var" in line.split(";")[0]:
76
  issues.append(self.format_issue(
77
  line=i,
78
  symbol="no-var",
79
  message="Use 'let' or 'const' instead of 'var'",
80
  category="style",
81
+ severity="low",
82
  ))
83
+
84
+ # FIX: use " == " with spaces to avoid matching === and !==
85
+ if " == " in line and " === " not in line:
86
  issues.append(self.format_issue(
87
  line=i,
88
  symbol="eqeqeq",
89
  message="Use '===' instead of '=='",
90
  category="correctness",
91
+ severity="medium",
92
  ))
93
+
94
  if line.rstrip() != line:
95
  issues.append(self.format_issue(
96
  line=i,
97
  symbol="trailing-spaces",
98
  message="Trailing whitespace",
99
  category="style",
100
+ severity="low",
101
  ))
102
+
103
+ return AnalysisResult(self.language, issues[:5])