Skip to content

Commit 3ba0b24

Browse files
authored
Merge pull request #2 from Rohan5commit/fix/all-bugs
fix: resolve all bugs across 6 source modules
2 parents 6c8fdac + 0cbd6f1 commit 3ba0b24

9 files changed

Lines changed: 355 additions & 273 deletions

File tree

‎roast/analyzer.py‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import re
88
from typing import Literal
99

10-
from roast.scanner import FileResult
10+
from roast.scanner import FileResult, is_test_file
1111
from roast.custom_rules import load_custom_rules, CustomRule
1212

1313
Severity = Literal["low", "medium", "high"]
@@ -85,9 +85,7 @@ def _add_issue(
8585
)
8686

8787

88-
def _is_test_file(path: str) -> bool:
89-
lowered = path.lower()
90-
return "test" in lowered or "/tests/" in lowered or lowered.startswith("tests/")
88+
# _is_test_file is now imported from roast.scanner as is_test_file
9189

9290

9391
def _module_from_import(import_name: str) -> str:
@@ -281,7 +279,7 @@ def _detect_python_medium_severity(file: FileResult, issues: list[Issue], tree:
281279
)
282280

283281
lines = file.content.splitlines()
284-
if not _is_test_file(file.path):
282+
if not is_test_file(file.path):
285283
for idx, line in enumerate(lines, start=1):
286284
for rule in custom_rules:
287285
if re.search(rule.pattern, line):
@@ -367,7 +365,7 @@ def _detect_js_medium_severity(file: FileResult, issues: list[Issue]) -> None:
367365
)
368366

369367
lines = file.content.splitlines()
370-
if not _is_test_file(file.path):
368+
if not is_test_file(file.path):
371369
for idx, line in enumerate(lines, start=1):
372370
if "console.log(" in line:
373371
_add_issue(
@@ -522,8 +520,9 @@ def analyze(files: list[FileResult]) -> AnalysisReport:
522520
issues: list[Issue] = []
523521
custom_rules = load_custom_rules()
524522

525-
# Lazy import to avoid circular dependency
526-
from roast.security import detect_security_issues
523+
# Import here to avoid circular dependency at module level.
524+
# security.py imports from analyzer.py, so we defer this import.
525+
from roast.security import detect_security_issues # noqa: E402
527526

528527
for file in files:
529528
tree: ast.AST | None = None

‎roast/cli.py‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,25 @@ def _github_headers() -> dict[str, str]:
6767

6868

6969
def _extract_archive_root(temp_dir_path: Path) -> Path:
70-
extracted_dirs = [child for child in temp_dir_path.iterdir() if child.is_dir()]
71-
if len(extracted_dirs) != 1:
72-
raise RuntimeError("GitHub archive had an unexpected layout.")
73-
return extracted_dirs[0]
70+
"""Return the single top-level directory inside the extracted archive.
71+
72+
GitHub zipball archives always contain one root directory. If the layout
73+
is unexpected we raise with a helpful diagnostic instead of crashing with
74+
an opaque ``iterdir`` list.
75+
"""
76+
entries = list(temp_dir_path.iterdir())
77+
dirs = [e for e in entries if e.is_dir()]
78+
if len(dirs) == 1:
79+
return dirs[0]
80+
if not entries:
81+
raise RuntimeError(
82+
"GitHub archive was extracted but the directory is empty."
83+
)
84+
names = ", ".join(e.name for e in entries[:10])
85+
raise RuntimeError(
86+
f"GitHub archive had an unexpected layout "
87+
f"({len(dirs)} directories, {len(entries)} total entries: {names})."
88+
)
7489

7590

7691
def _download_github_archive(
@@ -238,8 +253,9 @@ def roast(
238253
console.print(Panel(str(exc), title="Configuration Error", border_style="red"))
239254
raise typer.Exit(code=1)
240255

256+
# "--provider none" is an explicit way to disable LLM, equivalent to --no-llm.
241257
if provider == "none":
242-
provider = "auto"
258+
no_llm = True
243259

244260
if not no_llm and not _has_any_configured_llm_key(provider, backup_provider):
245261
console.print(
@@ -309,8 +325,8 @@ def roast(
309325
"overall_score": report.scores.get("Overall", 0),
310326
"verdict": roast_result.verdict,
311327
})
312-
except Exception:
313-
pass
328+
except Exception as exc: # noqa: BLE001
329+
LOGGER.debug("Failed to save scan history: %s", exc)
314330

315331
if json_output:
316332
console.print(f"[bold cyan]JSON report saved to: {Path(json_output).expanduser()}[/]")

‎roast/custom_rules.py‎

Lines changed: 66 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,78 @@
1-
import yaml
1+
"""Custom linting rules loaded from a .roast.yaml config file."""
2+
3+
from __future__ import annotations
4+
5+
import logging
26
import re
3-
import os
47
from dataclasses import dataclass
5-
from typing import List, Optional
8+
from pathlib import Path
9+
from typing import Any
10+
11+
import yaml
12+
13+
LOGGER = logging.getLogger(__name__)
614

7-
@dataclass
15+
16+
@dataclass(slots=True)
817
class CustomRule:
918
name: str
1019
pattern: str
1120
severity: str
1221
message: str
1322
category: str = "Code Quality"
1423

15-
def load_custom_rules(config_path: str = ".roast.yaml") -> List[CustomRule]:
24+
25+
def load_custom_rules(config_path: str | Path = ".roast.yaml") -> list[CustomRule]:
26+
"""Load custom rules from a YAML config file.
27+
28+
Returns an empty list if the file does not exist, is invalid, or
29+
encounters an error.
30+
"""
31+
path = Path(config_path)
32+
if not path.exists():
33+
return []
34+
1635
try:
17-
if not os.path.exists(config_path):
18-
return []
19-
with open(config_path, "r") as f:
20-
config = yaml.safe_load(f)
21-
if not config or "rules" not in config:
22-
return []
23-
24-
rules = []
25-
for r in config["rules"]:
26-
rules.append(CustomRule(
27-
name=r["name"],
28-
pattern=r["pattern"],
29-
severity=r.get("severity", "medium"),
30-
message=r["message"],
31-
category=r.get("category", "Code Quality")
32-
))
33-
return rules
34-
except Exception as e:
35-
print(f"Error loading custom rules: {e}")
36+
with path.open("r", encoding="utf-8") as fh:
37+
config: dict[str, Any] | None = yaml.safe_load(fh)
38+
except (yaml.YAMLError, OSError) as exc:
39+
LOGGER.warning("Failed to read custom rules from %s: %s", path, exc)
3640
return []
41+
42+
if not config or "rules" not in config:
43+
return []
44+
45+
rules: list[CustomRule] = []
46+
for idx, rule in enumerate(config["rules"]):
47+
try:
48+
rules.append(
49+
CustomRule(
50+
name=rule["name"],
51+
pattern=rule["pattern"],
52+
severity=rule.get("severity", "medium"),
53+
message=rule["message"],
54+
category=rule.get("category", "Code Quality"),
55+
)
56+
)
57+
except KeyError as exc:
58+
LOGGER.warning(
59+
"Skipping malformed custom rule #%d in %s (missing key: %s)",
60+
idx + 1,
61+
path,
62+
exc,
63+
)
64+
continue
65+
# Validate the regex pattern at load time rather than at scan time.
66+
try:
67+
re.compile(rule["pattern"])
68+
except re.error as exc:
69+
LOGGER.warning(
70+
"Skipping custom rule %r in %s (invalid regex: %s)",
71+
rule.get("name", f"#{idx + 1}"),
72+
path,
73+
exc,
74+
)
75+
rules.pop() # Remove the rule we just added
76+
continue
77+
78+
return rules

‎roast/history.py‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,40 @@
1+
"""Scan history for trend tracking across multiple runs."""
2+
3+
from __future__ import annotations
4+
15
import json
26
import os
37
from datetime import datetime
48
from pathlib import Path
5-
from typing import Dict, List
9+
610

711
def _get_history_dir() -> Path:
812
cache_dir = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
913
return Path(cache_dir) / "roast-my-code" / "history"
1014

15+
1116
HISTORY_DIR = _get_history_dir()
1217

13-
def save_history(report_data: Dict):
18+
19+
def save_history(report_data: dict) -> None:
20+
"""Persist a scan result for later trend comparison."""
1421
HISTORY_DIR.mkdir(parents=True, exist_ok=True)
1522
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1623
filepath = HISTORY_DIR / f"scan_{timestamp}.json"
17-
with open(filepath, "w", encoding="utf-8") as f:
18-
json.dump(report_data, f)
24+
with filepath.open("w", encoding="utf-8") as fh:
25+
json.dump(report_data, fh)
26+
1927

20-
def get_history() -> List[Dict]:
28+
def get_history() -> list[dict]:
29+
"""Return all previously saved scan results, newest last."""
2130
if not HISTORY_DIR.exists():
2231
return []
23-
24-
history = []
32+
33+
history: list[dict] = []
2534
for filepath in sorted(HISTORY_DIR.glob("scan_*.json")):
2635
try:
27-
with open(filepath, "r", encoding="utf-8") as f:
28-
history.append(json.load(f))
36+
with filepath.open("r", encoding="utf-8") as fh:
37+
history.append(json.load(fh))
2938
except (json.JSONDecodeError, OSError):
3039
continue
3140
return history

‎roast/scanner.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,12 @@ def _should_skip_path(path: Path) -> bool:
9393
return name == ".env" or name.startswith(".env.")
9494

9595

96+
def is_test_file(path: str) -> bool:
97+
"""Return True if *path* looks like a test file or lives in a tests dir."""
98+
lowered = path.lower()
99+
return "test" in lowered or "/tests/" in lowered or lowered.startswith("tests/")
100+
101+
96102
def scan_repo(
97103
path: str | Path,
98104
extensions: Iterable[str],

‎roast/security.py‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import re
77

88
from roast.analyzer import Issue, SECURITY, _add_issue
9-
from roast.scanner import FileResult
9+
from roast.scanner import FileResult, is_test_file
1010

1111
# ---------------------------------------------------------------------------
1212
# Regex patterns (language-agnostic)
@@ -143,7 +143,7 @@ def _detect_python_security_ast(
143143

144144
# assert used for validation in non-test files
145145
if isinstance(node, ast.Assert):
146-
if not _is_test_file(file.path):
146+
if not is_test_file(file.path):
147147
_add_issue(
148148
issues,
149149
file.path,
@@ -253,11 +253,6 @@ def _has_loader_argument(node: ast.Call) -> bool:
253253
return False
254254

255255

256-
def _is_test_file(path: str) -> bool:
257-
lowered = path.lower()
258-
return "test" in lowered or "/tests/" in lowered or lowered.startswith("tests/")
259-
260-
261256
# ---------------------------------------------------------------------------
262257
# Public entry point
263258
# ---------------------------------------------------------------------------

‎web/next.config.mjs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ const securityHeaders = [
33
{ key: "X-Frame-Options", value: "DENY" },
44
{ key: "X-Content-Type-Options", value: "nosniff" },
55
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
6+
{
7+
key: "Strict-Transport-Security",
8+
value: "max-age=63072000; includeSubDomains; preload",
9+
},
610
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
711
{ key: "X-DNS-Prefetch-Control", value: "on" },
812
{

0 commit comments

Comments
 (0)