git-slopcheck 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,173 @@
1
+ Metadata-Version: 2.4
2
+ Name: git-slopcheck
3
+ Version: 0.1.0
4
+ Summary: 100% offline CLI tool scanning staged git diffs for AI code smells using Tree-sitter.
5
+ Author: Raja
6
+ License: MIT
7
+ Keywords: linter,git,tree-sitter,ast,cli,static-analysis
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Environment :: Console
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Topic :: Software Development :: Quality Assurance
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: tree-sitter>=0.25.0
22
+ Requires-Dist: tree-sitter-python>=0.25.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # slopcheck
28
+
29
+ A 100% offline, zero-cost Python CLI tool that scans `git diff --cached` using Tree-sitter AST analysis to catch AI-generated code slop before you commit.
30
+
31
+ ## Features & Detection Rules
32
+
33
+ `slopcheck` analyzes only your staged changes across four distinct code smells:
34
+
35
+ ### 1. `obvious-comment` (Captain Obvious Comments)
36
+ Flags comments that repeat $>70\%$ of the words from the identifier defined on the immediately following line (skipping pragmas like `# type: ignore` and `# noqa`).
37
+
38
+ ```python
39
+ # Bad: repeats the next-line function name
40
+ # Calculate total
41
+ def calculate_total():
42
+ return 100
43
+
44
+ # Good: explains why or provides architectural context
45
+ # Cache result for 5 minutes to reduce database read load
46
+ def calculate_total():
47
+ return 100
48
+ ```
49
+
50
+ ### 2. `swallowed-exception` (Swallowed Exceptions)
51
+ Flags broad catches (`except:`, `except Exception`, `except BaseException`, `except* Exception`) whose body only consists of `pass`, `...`, `print(...)`, or contextless `raise`.
52
+
53
+ ```python
54
+ # Bad: silently swallows errors or only prints
55
+ try:
56
+ process_order()
57
+ except Exception as e:
58
+ print(e)
59
+
60
+ # Good: proper logging, context re-raising, or specific catch
61
+ try:
62
+ process_order()
63
+ except ValueError:
64
+ handle_invalid_order()
65
+ except Exception as e:
66
+ logger.exception("Order processing failed")
67
+ raise OrderProcessingError("Order failure") from e
68
+ ```
69
+
70
+ ### 3. `micro-wrapper` (Single-Use Micro-Wrappers)
71
+ Flags newly added functions of 1–2 statements that are only invoked once across the entire repository (skipping `@property`, `@abstractmethod`, dunders like `__init__`, and `test_*` functions).
72
+
73
+ ```python
74
+ # Bad: single-use helper that adds indirection without reuse
75
+ def _fetch_user_raw(user_id: int):
76
+ return db.query(User).get(user_id)
77
+
78
+ def get_user_profile(user_id: int):
79
+ user = _fetch_user_raw(user_id) # Only call in the whole repo
80
+ return user.to_dict()
81
+ ```
82
+
83
+ ### 4. `filler-docstring` (AI Filler Docstrings)
84
+ Flags boilerplate docstrings filled with common LLM introductory phrases like *"This function is responsible for..."* or *"Helper method to..."*.
85
+
86
+ ```python
87
+ # Bad: LLM boilerplate filler
88
+ def parse_config(path: str):
89
+ """This function is responsible for parsing configuration files."""
90
+ ...
91
+
92
+ # Good: concise and domain-specific
93
+ def parse_config(path: str):
94
+ """Parse YAML settings into application configuration options."""
95
+ ...
96
+ ```
97
+
98
+ ---
99
+
100
+ ## Installation
101
+
102
+ Install from PyPI:
103
+ ```bash
104
+ pip install git-slopcheck
105
+ ```
106
+
107
+ Or install locally for development:
108
+ ```bash
109
+ git clone https://github.com/complex-day/Slopcheck.git
110
+ cd Slopcheck
111
+ pip install -e ".[dev]"
112
+ ```
113
+
114
+ ---
115
+
116
+ ## Usage
117
+
118
+ Run `slopcheck` against currently staged changes in your git repository:
119
+
120
+ ```bash
121
+ # Scan staged changes in current working tree
122
+ slopcheck
123
+
124
+ # Scan staged changes in a specific repository root
125
+ slopcheck --repo /path/to/repo
126
+
127
+ # Check version
128
+ slopcheck --version
129
+ ```
130
+
131
+ ### Sample Output
132
+
133
+ ```
134
+ app.py:1: [filler-docstring] AI filler docstring detected: contains boilerplate phrase 'this module is responsible for'
135
+ app.py:3: [obvious-comment] Obvious comment duplicates identifier 'calculate_total'
136
+ app.py:8: [micro-wrapper] Single-use micro-wrapper '_tiny_helper' has 1 statement(s) and is only called once
137
+ app.py:16: [swallowed-exception] Swallowed exception caught without proper logging or handling
138
+
139
+ slopcheck: Found 4 violation(s) across 1 staged file(s).
140
+ ```
141
+
142
+ When no violations are found:
143
+ ```
144
+ slopcheck: Clean! Scanned 2 staged file(s) with 0 violations.
145
+ ```
146
+
147
+ ### Exit Codes
148
+
149
+ | Exit Code | Meaning |
150
+ | :---: | :--- |
151
+ | `0` | Clean: No violations detected, or no staged Python files to check. |
152
+ | `1` | Violations: One or more code smell violations detected in staged diff. |
153
+ | `2` | Error: Git execution failed or directory is not a Git repository. |
154
+
155
+ ---
156
+
157
+ ## Pre-commit Integration
158
+
159
+ Add `slopcheck` as a pre-commit hook in your `.pre-commit-config.yaml`:
160
+
161
+ ```yaml
162
+ repos:
163
+ - repo: https://github.com/complex-day/Slopcheck
164
+ rev: v0.1.0
165
+ hooks:
166
+ - id: slopcheck
167
+ ```
168
+
169
+ ---
170
+
171
+ ## License
172
+
173
+ MIT License. See [LICENSE](LICENSE) for details.
@@ -0,0 +1,17 @@
1
+ git_slopcheck-0.1.0.dist-info/licenses/LICENSE,sha256=DHciHoxbBvUcg8B-X9KPFGoRy5a2M6XLU6aYSC2S9xQ,1061
2
+ slopcheck/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
3
+ slopcheck/cli.py,sha256=CFfrB2ByGswbMNfury6kLJJZSb9NmPKV9gIrKP9ly8E,1431
4
+ slopcheck/diff_parser.py,sha256=C8j4uwoRDgbXphY-mqba7zOlu5tINPyIYKwYZqaQL2s,2873
5
+ slopcheck/parser.py,sha256=kMTNbVgUikFFtdAPLXEcltzIPVqyaWlTjvdha0Ay9yM,1184
6
+ slopcheck/runner.py,sha256=nVgq_iAqUrvfp5uwdiNcIudj03cOCOpo7hl1WU_iHAw,2567
7
+ slopcheck/rules/__init__.py,sha256=VpjvTkkd7epQ9F-LexuvGaYs4rbNf9D1-cfYKCf1Xr0,531
8
+ slopcheck/rules/base.py,sha256=xE975Bp0YI3mzOg_XULFfbxCgPWhB--lAf_0UoEDr3A,144
9
+ slopcheck/rules/filler_docstrings.py,sha256=aVFUGHclDLo2O0u0N1ZDA1_cJ57z5efVIGplD60_M98,4037
10
+ slopcheck/rules/micro_wrappers.py,sha256=41SMsXM8R3Q1erJHjm27HyLMkolrbcSH_p6SBin1wDE,5527
11
+ slopcheck/rules/obvious_comments.py,sha256=qLosH98WMeLJLOJ2QpRZXbE4uog5haavp99CRt-zAWg,4374
12
+ slopcheck/rules/swallowed_exceptions.py,sha256=Xt0VFP3PHy4jiPKwhOPyzpWXK4bgeVNvZ6wbw2hM7sg,4163
13
+ git_slopcheck-0.1.0.dist-info/METADATA,sha256=koDlj22T1e6coa9sWJfGfY8fMeFSaRqP0c0ZYOL9yZk,5219
14
+ git_slopcheck-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
15
+ git_slopcheck-0.1.0.dist-info/entry_points.txt,sha256=g64cuhZxBk-hcNcs1vtBMK5f13YoaL7eXMmmsH1cY3U,49
16
+ git_slopcheck-0.1.0.dist-info/top_level.txt,sha256=ygq40r1CChmmNxkJGeTtmabzI8ClLuid2C4LOTzA_5w,10
17
+ git_slopcheck-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ slopcheck = slopcheck.cli:main
@@ -0,0 +1,17 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Raja
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ slopcheck
slopcheck/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
slopcheck/cli.py ADDED
@@ -0,0 +1,53 @@
1
+ import argparse
2
+ import sys
3
+ from slopcheck import __version__
4
+ from slopcheck.diff_parser import GitDiffError
5
+ from slopcheck.runner import scan_staged
6
+
7
+
8
+ def main(argv: list[str] | None = None) -> int:
9
+ parser = argparse.ArgumentParser(
10
+ prog="slopcheck",
11
+ description="A 100% offline CLI tool to detect AI-generated code slop in staged git changes.",
12
+ )
13
+ parser.add_argument(
14
+ "--version",
15
+ action="version",
16
+ version=f"%(prog)s {__version__}",
17
+ )
18
+ parser.add_argument(
19
+ "--repo",
20
+ type=str,
21
+ default=None,
22
+ help="Path to the Git repository root (defaults to current working directory).",
23
+ )
24
+
25
+ args = parser.parse_args(argv)
26
+
27
+ try:
28
+ violations, files_scanned = scan_staged(repo_root=args.repo)
29
+ except GitDiffError as err:
30
+ print(f"slopcheck error: {err}", file=sys.stderr)
31
+ return 2
32
+
33
+ if files_scanned == 0:
34
+ print("slopcheck: No staged Python files to check.")
35
+ return 0
36
+
37
+ if not violations:
38
+ print(
39
+ f"slopcheck: Clean! Scanned {files_scanned} staged file(s) with 0 violations."
40
+ )
41
+ return 0
42
+
43
+ for v in violations:
44
+ print(f"{v.file_path}:{v.line}: [{v.rule_id}] {v.message}")
45
+
46
+ print(
47
+ f"\nslopcheck: Found {len(violations)} violation(s) across {files_scanned} staged file(s)."
48
+ )
49
+ return 1
50
+
51
+
52
+ if __name__ == "__main__":
53
+ sys.exit(main())
@@ -0,0 +1,96 @@
1
+ from pathlib import Path
2
+ import re
3
+ import subprocess
4
+
5
+
6
+ class GitDiffError(Exception):
7
+ """Raised when git diff execution fails."""
8
+
9
+
10
+ HUNK_HEADER_RE = re.compile(
11
+ r"^@@\s+-[0-9]+(?:,[0-9]+)?\s+\+([0-9]+)(?:,([0-9]+))?\s+@@"
12
+ )
13
+
14
+
15
+ def get_staged_diff_text(cwd: str | Path | None = None) -> str:
16
+ cmd = [
17
+ "git",
18
+ "-c",
19
+ "core.quotepath=false",
20
+ "diff",
21
+ "--cached",
22
+ "--unified=0",
23
+ "--diff-filter=ACM",
24
+ ]
25
+ try:
26
+ result = subprocess.run(
27
+ cmd,
28
+ capture_output=True,
29
+ text=True,
30
+ encoding="utf-8",
31
+ errors="replace",
32
+ check=True,
33
+ cwd=cwd,
34
+ )
35
+ return result.stdout
36
+ except (subprocess.CalledProcessError, FileNotFoundError) as err:
37
+ err_msg = (
38
+ err.stderr.strip()
39
+ if isinstance(err, subprocess.CalledProcessError) and err.stderr
40
+ else str(err)
41
+ )
42
+ raise GitDiffError(f"Git diff failed: {err_msg}") from err
43
+
44
+
45
+ def parse_diff_output(diff_text: str) -> dict[str, set[int]]:
46
+ diff_map: dict[str, set[int]] = {}
47
+ current_file: str | None = None
48
+
49
+ for line in diff_text.splitlines():
50
+ if line.startswith("diff --git "):
51
+ current_file = None
52
+ continue
53
+
54
+ if line.startswith("Binary files ") or line.startswith("GIT binary patch"):
55
+ if current_file is not None:
56
+ diff_map.pop(current_file, None)
57
+ current_file = None
58
+ continue
59
+
60
+ if line.startswith("+++ "):
61
+ raw_path = line[4:].strip()
62
+ if raw_path.startswith('"') and raw_path.endswith('"'):
63
+ raw_path = raw_path[1:-1]
64
+ if raw_path == "/dev/null":
65
+ current_file = None
66
+ continue
67
+ if raw_path.startswith("b/"):
68
+ raw_path = raw_path[2:]
69
+
70
+ normalized_path = raw_path.replace("\\", "/")
71
+ if normalized_path.endswith(".py"):
72
+ current_file = normalized_path
73
+ diff_map.setdefault(current_file, set())
74
+ else:
75
+ current_file = None
76
+ continue
77
+
78
+ if current_file is not None:
79
+ match = HUNK_HEADER_RE.match(line)
80
+ if match:
81
+ new_start = int(match.group(1))
82
+ new_count = int(match.group(2)) if match.group(2) is not None else 1
83
+ if new_count > 0:
84
+ diff_map[current_file].update(
85
+ range(new_start, new_start + new_count)
86
+ )
87
+
88
+ return {path: lines for path, lines in diff_map.items() if lines}
89
+
90
+
91
+ def parse_staged_diff(cwd: str | Path | None = None) -> dict[str, set[int]]:
92
+ diff_text = get_staged_diff_text(cwd=cwd)
93
+ return parse_diff_output(diff_text)
94
+
95
+
96
+ get_staged_diff = parse_staged_diff
slopcheck/parser.py ADDED
@@ -0,0 +1,41 @@
1
+ from pathlib import Path
2
+ from tree_sitter import Language, Node, Parser, Query, QueryCursor, Tree
3
+ import tree_sitter_python as tspython
4
+
5
+ PY_LANGUAGE = Language(tspython.language())
6
+ PARSER = Parser(PY_LANGUAGE)
7
+
8
+
9
+ def parse_source(source: str | bytes) -> tuple[Tree, bytes]:
10
+ source_bytes = source.encode("utf-8") if isinstance(source, str) else source
11
+ tree = PARSER.parse(source_bytes)
12
+ return tree, source_bytes
13
+
14
+
15
+ def parse_file(file_path: str | Path) -> tuple[Tree, bytes]:
16
+ path = Path(file_path)
17
+ return parse_source(path.read_bytes())
18
+
19
+
20
+ def run_query(tree: Tree, query_str: str) -> dict[str, list[Node]]:
21
+ query = Query(PY_LANGUAGE, query_str)
22
+ cursor = QueryCursor(query)
23
+ return cursor.captures(tree.root_node)
24
+
25
+
26
+ def run_matches(
27
+ tree: Tree, query_str: str
28
+ ) -> list[tuple[int, dict[str, list[Node]]]]:
29
+ query = Query(PY_LANGUAGE, query_str)
30
+ cursor = QueryCursor(query)
31
+ return cursor.matches(tree.root_node)
32
+
33
+
34
+ def node_line(node: Node) -> int:
35
+ return node.start_point[0] + 1
36
+
37
+
38
+ def node_text(node: Node, source_bytes: bytes) -> str:
39
+ return source_bytes[node.start_byte:node.end_byte].decode(
40
+ "utf-8", errors="replace"
41
+ )
@@ -0,0 +1,17 @@
1
+ from slopcheck.rules.base import Violation
2
+ from slopcheck.rules.filler_docstrings import check_filler_docstrings
3
+ from slopcheck.rules.micro_wrappers import (
4
+ check_micro_wrappers,
5
+ count_repo_calls,
6
+ )
7
+ from slopcheck.rules.obvious_comments import check_obvious_comments
8
+ from slopcheck.rules.swallowed_exceptions import check_swallowed_exceptions
9
+
10
+ __all__ = [
11
+ "Violation",
12
+ "check_filler_docstrings",
13
+ "check_micro_wrappers",
14
+ "check_obvious_comments",
15
+ "check_swallowed_exceptions",
16
+ "count_repo_calls",
17
+ ]
@@ -0,0 +1,9 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass(frozen=True)
5
+ class Violation:
6
+ file_path: str
7
+ line: int
8
+ rule_id: str
9
+ message: str
@@ -0,0 +1,113 @@
1
+ import re
2
+ from slopcheck.parser import node_line, node_text, parse_source, run_query
3
+ from slopcheck.rules.base import Violation
4
+ from tree_sitter import Node
5
+
6
+ QUERY_DEFINITIONS = "(class_definition) @cls (function_definition) @func"
7
+
8
+ FILLER_PATTERNS = [
9
+ re.compile(r"\bthis function is responsible for\b", re.IGNORECASE),
10
+ re.compile(r"\bthis method is responsible for\b", re.IGNORECASE),
11
+ re.compile(r"\bthis class is responsible for\b", re.IGNORECASE),
12
+ re.compile(r"\bthis module is responsible for\b", re.IGNORECASE),
13
+ re.compile(r"\bhelper function to\b", re.IGNORECASE),
14
+ re.compile(r"\bhelper function that\b", re.IGNORECASE),
15
+ re.compile(r"\bhelper method to\b", re.IGNORECASE),
16
+ re.compile(r"\bhelper method that\b", re.IGNORECASE),
17
+ re.compile(r"\butility function to\b", re.IGNORECASE),
18
+ re.compile(r"\butility method to\b", re.IGNORECASE),
19
+ re.compile(r"\ba simple function to\b", re.IGNORECASE),
20
+ re.compile(r"\ba simple helper\b", re.IGNORECASE),
21
+ re.compile(r"\bthis function takes\b", re.IGNORECASE),
22
+ re.compile(r"\bthis method takes\b", re.IGNORECASE),
23
+ re.compile(r"\bas the name suggests\b", re.IGNORECASE),
24
+ re.compile(r"\bprovides a convenient way to\b", re.IGNORECASE),
25
+ ]
26
+
27
+
28
+ def extract_docstring_node(body_node: Node | None) -> Node | None:
29
+ if not body_node:
30
+ return None
31
+
32
+ for child in body_node.children:
33
+ if child.is_named and child.type != "comment":
34
+ if child.type == "expression_statement":
35
+ named = [c for c in child.children if c.is_named]
36
+ if len(named) == 1 and named[0].type == "string":
37
+ return named[0]
38
+ return None
39
+
40
+ return None
41
+
42
+
43
+ def normalize_docstring(raw_text: str) -> str:
44
+ text = raw_text.strip()
45
+ match = re.match(r"^[rRuUfFbB]{0,2}(\"\"\"|'''|\"|')", text)
46
+ if match:
47
+ quote = match.group(1)
48
+ text = text[match.end():]
49
+ if text.endswith(quote):
50
+ text = text[:-len(quote)]
51
+
52
+ return " ".join(text.split()).lower()
53
+
54
+
55
+ def find_matching_filler_phrase(normalized_text: str) -> str | None:
56
+ for pattern in FILLER_PATTERNS:
57
+ match = pattern.search(normalized_text)
58
+ if match:
59
+ return match.group(0)
60
+ return None
61
+
62
+
63
+ def check_filler_docstrings(
64
+ file_path: str,
65
+ source: str | bytes,
66
+ changed_lines: set[int] | None = None,
67
+ ) -> list[Violation]:
68
+ tree, source_bytes = parse_source(source)
69
+
70
+ docstring_nodes: list[Node] = []
71
+ seen_ids: set[int] = set()
72
+
73
+ # 1. Module-level docstring
74
+ module_doc = extract_docstring_node(tree.root_node)
75
+ if module_doc is not None:
76
+ docstring_nodes.append(module_doc)
77
+ seen_ids.add(module_doc.id)
78
+
79
+ # 2. Class and function docstrings
80
+ caps = run_query(tree, QUERY_DEFINITIONS)
81
+ for target in caps.get("cls", []) + caps.get("func", []):
82
+ body_node = target.child_by_field_name("body")
83
+ doc_node = extract_docstring_node(body_node)
84
+ if doc_node is not None and doc_node.id not in seen_ids:
85
+ docstring_nodes.append(doc_node)
86
+ seen_ids.add(doc_node.id)
87
+
88
+ violations: list[Violation] = []
89
+
90
+ for doc_node in docstring_nodes:
91
+ start_line = node_line(doc_node)
92
+ end_line = doc_node.end_point[0] + 1
93
+ covered_lines = set(range(start_line, end_line + 1))
94
+
95
+ if changed_lines is not None and not (covered_lines & changed_lines):
96
+ continue
97
+
98
+ raw_text = node_text(doc_node, source_bytes)
99
+ normalized = normalize_docstring(raw_text)
100
+ matched_phrase = find_matching_filler_phrase(normalized)
101
+
102
+ if matched_phrase:
103
+ violations.append(
104
+ Violation(
105
+ file_path=file_path,
106
+ line=start_line,
107
+ rule_id="filler-docstring",
108
+ message=f"AI filler docstring detected: contains boilerplate phrase '{matched_phrase}'",
109
+ )
110
+ )
111
+ violations.sort(key=lambda v: v.line)
112
+
113
+ return violations
@@ -0,0 +1,179 @@
1
+ import os
2
+ from pathlib import Path
3
+ from slopcheck.parser import node_line, node_text, parse_source, run_query
4
+ from slopcheck.rules.base import Violation
5
+ from tree_sitter import Node
6
+
7
+ QUERY_CALLS = "(call) @call"
8
+ QUERY_FUNCTIONS = "(function_definition) @func"
9
+
10
+ SKIP_DIRS = {
11
+ ".venv",
12
+ "venv",
13
+ ".git",
14
+ "__pycache__",
15
+ ".pytest_cache",
16
+ ".mypy_cache",
17
+ "build",
18
+ "dist",
19
+ }
20
+
21
+ COMPOUND_BLOCKS = {
22
+ "if_statement",
23
+ "elif_clause",
24
+ "else_clause",
25
+ "for_statement",
26
+ "while_statement",
27
+ "with_statement",
28
+ "try_statement",
29
+ "except_clause",
30
+ "finally_clause",
31
+ "match_statement",
32
+ "case_clause",
33
+ }
34
+
35
+
36
+ def should_skip_dir(name: str) -> bool:
37
+ return name in SKIP_DIRS or name.endswith(".egg-info")
38
+
39
+
40
+ def count_repo_calls(repo_root: str | Path) -> dict[str, int]:
41
+ root_path = Path(repo_root)
42
+ call_counts: dict[str, int] = {}
43
+ if not root_path.exists():
44
+ return call_counts
45
+
46
+ for root, dirs, files in os.walk(root_path):
47
+ dirs[:] = [d for d in dirs if not should_skip_dir(d)]
48
+ for file in files:
49
+ if file.endswith(".py"):
50
+ file_path = Path(root) / file
51
+ try:
52
+ source_bytes = file_path.read_bytes()
53
+ except OSError:
54
+ continue
55
+
56
+ tree, _ = parse_source(source_bytes)
57
+ caps = run_query(tree, QUERY_CALLS)
58
+ for call_node in caps.get("call", []):
59
+ fn_node = call_node.child_by_field_name("function")
60
+ name = None
61
+ if fn_node:
62
+ if fn_node.type == "identifier":
63
+ name = node_text(fn_node, source_bytes)
64
+ elif fn_node.type == "attribute":
65
+ attr_node = fn_node.child_by_field_name("attribute")
66
+ if attr_node:
67
+ name = node_text(attr_node, source_bytes)
68
+ if name:
69
+ call_counts[name] = call_counts.get(name, 0) + 1
70
+
71
+ return call_counts
72
+
73
+
74
+ def is_skipped_function(
75
+ func_node: Node,
76
+ func_name: str,
77
+ source_bytes: bytes,
78
+ ) -> bool:
79
+ if func_name.startswith("__") and func_name.endswith("__"):
80
+ return True
81
+
82
+ if func_name.startswith("test_") or func_name == "main":
83
+ return True
84
+
85
+ parent = func_node.parent
86
+ if parent and parent.type == "decorated_definition":
87
+ for child in parent.children:
88
+ if child.type == "decorator":
89
+ dec_text = node_text(child, source_bytes).lstrip("@").strip()
90
+ base_name = dec_text.split("(")[0].strip()
91
+ if base_name in (
92
+ "property",
93
+ "abstractmethod",
94
+ "abc.abstractmethod",
95
+ ) or base_name.endswith((".setter", ".deleter")):
96
+ return True
97
+
98
+ return False
99
+
100
+
101
+ def _count_nested_statements(node: Node) -> int:
102
+ total = 0
103
+ for child in node.children:
104
+ if not child.is_named or child.type == "comment":
105
+ continue
106
+ if child.type == "block":
107
+ total += _count_block_statements(child, strip_docstring=False)
108
+ elif child.type in COMPOUND_BLOCKS:
109
+ total += _count_nested_statements(child)
110
+ return total
111
+
112
+
113
+ def _count_block_statements(block_node: Node, strip_docstring: bool = False) -> int:
114
+ stmts = [c for c in block_node.children if c.is_named and c.type != "comment"]
115
+ if not stmts:
116
+ return 0
117
+
118
+ if strip_docstring:
119
+ first = stmts[0]
120
+ if first.type == "expression_statement":
121
+ named_children = [c for c in first.children if c.is_named]
122
+ if len(named_children) == 1 and named_children[0].type == "string":
123
+ stmts = stmts[1:]
124
+
125
+ total = 0
126
+ for stmt in stmts:
127
+ total += 1
128
+ if stmt.type in COMPOUND_BLOCKS:
129
+ total += _count_nested_statements(stmt)
130
+ return total
131
+
132
+
133
+ def count_executable_statements(body_node: Node) -> int:
134
+ return _count_block_statements(body_node, strip_docstring=True)
135
+
136
+
137
+ def check_micro_wrappers(
138
+ file_path: str,
139
+ source: str | bytes,
140
+ call_counts: dict[str, int],
141
+ changed_lines: set[int] | None = None,
142
+ ) -> list[Violation]:
143
+ tree, source_bytes = parse_source(source)
144
+ caps = run_query(tree, QUERY_FUNCTIONS)
145
+
146
+ violations: list[Violation] = []
147
+
148
+ for func_node in caps.get("func", []):
149
+ def_line = node_line(func_node)
150
+ if changed_lines is not None and def_line not in changed_lines:
151
+ continue
152
+
153
+ name_node = func_node.child_by_field_name("name")
154
+ if not name_node:
155
+ continue
156
+
157
+ func_name = node_text(name_node, source_bytes)
158
+ if is_skipped_function(func_node, func_name, source_bytes):
159
+ continue
160
+
161
+ body_node = func_node.child_by_field_name("body")
162
+ if not body_node:
163
+ continue
164
+
165
+ stmt_count = count_executable_statements(body_node)
166
+ if 1 <= stmt_count < 3 and call_counts.get(func_name, 0) == 1:
167
+ violations.append(
168
+ Violation(
169
+ file_path=file_path,
170
+ line=def_line,
171
+ rule_id="micro-wrapper",
172
+ message=(
173
+ f"Single-use micro-wrapper '{func_name}' has "
174
+ f"{stmt_count} statement(s) and is only called once"
175
+ ),
176
+ )
177
+ )
178
+
179
+ return violations
@@ -0,0 +1,132 @@
1
+ import re
2
+ from slopcheck.parser import node_line, node_text, parse_source, run_query
3
+ from slopcheck.rules.base import Violation
4
+
5
+ QUERY_STATEMENTS = """
6
+ (comment) @comment
7
+ (function_definition) @func_def
8
+ (class_definition) @class_def
9
+ (assignment) @assign_def
10
+ (decorated_definition) @dec_def
11
+ """
12
+
13
+ DIRECTIVE_PREFIXES = (
14
+ "type: ignore",
15
+ "type:ignore",
16
+ "noqa",
17
+ "pragma:",
18
+ "fmt:",
19
+ "isort:",
20
+ "pylint:",
21
+ )
22
+
23
+
24
+ def is_pragma_or_directive(comment_text: str, line: int) -> bool:
25
+ stripped = comment_text.strip()
26
+ if stripped.startswith("#!"):
27
+ return True
28
+
29
+ clean = stripped.lstrip("#").strip().lower()
30
+ if line <= 2 and ("coding:" in clean or "coding=" in clean):
31
+ return True
32
+
33
+ for prefix in DIRECTIVE_PREFIXES:
34
+ if clean.startswith(prefix):
35
+ return True
36
+
37
+ return False
38
+
39
+
40
+ def is_standalone_comment(start_byte: int, source_bytes: bytes) -> bool:
41
+ line_start = source_bytes.rfind(b"\n", 0, start_byte) + 1
42
+ return source_bytes[line_start:start_byte].strip() == b""
43
+
44
+
45
+ def extract_words(text: str) -> set[str]:
46
+ cleaned = re.sub(r"[^a-zA-Z0-9]+", " ", text)
47
+ cleaned = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", cleaned)
48
+ cleaned = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1 \2", cleaned)
49
+ return {w.lower() for w in cleaned.split() if w}
50
+
51
+
52
+ def check_obvious_comments(
53
+ file_path: str,
54
+ source: str | bytes,
55
+ changed_lines: set[int] | None = None,
56
+ ) -> list[Violation]:
57
+ tree, source_bytes = parse_source(source)
58
+ captures = run_query(tree, QUERY_STATEMENTS)
59
+
60
+ line_to_identifiers: dict[int, list[str]] = {}
61
+
62
+ def add_identifier(line: int, identifier: str) -> None:
63
+ if identifier:
64
+ line_to_identifiers.setdefault(line, []).append(identifier)
65
+
66
+ for func in captures.get("func_def", []):
67
+ name_node = func.child_by_field_name("name")
68
+ if name_node:
69
+ add_identifier(node_line(func), node_text(name_node, source_bytes))
70
+
71
+ for cls in captures.get("class_def", []):
72
+ name_node = cls.child_by_field_name("name")
73
+ if name_node:
74
+ add_identifier(node_line(cls), node_text(name_node, source_bytes))
75
+
76
+ for assign in captures.get("assign_def", []):
77
+ left_node = assign.child_by_field_name("left")
78
+ line = node_line(assign)
79
+ if left_node and left_node.type == "identifier":
80
+ add_identifier(line, node_text(left_node, source_bytes))
81
+ elif left_node and left_node.type == "attribute":
82
+ attr = left_node.child_by_field_name("attribute")
83
+ if attr:
84
+ add_identifier(line, node_text(attr, source_bytes))
85
+
86
+ for dec in captures.get("dec_def", []):
87
+ inner = dec.child_by_field_name("definition")
88
+ if inner and inner.type in ("function_definition", "class_definition"):
89
+ name_node = inner.child_by_field_name("name")
90
+ if name_node:
91
+ add_identifier(node_line(dec), node_text(name_node, source_bytes))
92
+
93
+ violations: list[Violation] = []
94
+
95
+ for comment_node in captures.get("comment", []):
96
+ comment_line = node_line(comment_node)
97
+ if changed_lines is not None and comment_line not in changed_lines:
98
+ continue
99
+
100
+ if not is_standalone_comment(comment_node.start_byte, source_bytes):
101
+ continue
102
+
103
+ comment_raw = node_text(comment_node, source_bytes)
104
+ if is_pragma_or_directive(comment_raw, comment_line):
105
+ continue
106
+
107
+ comment_body = comment_raw.lstrip("#")
108
+ comment_words = extract_words(comment_body)
109
+ if len(comment_words) < 2:
110
+ continue
111
+
112
+ next_line = comment_line + 1
113
+ target_identifiers = line_to_identifiers.get(next_line, [])
114
+
115
+ for identifier in target_identifiers:
116
+ identifier_words = extract_words(identifier)
117
+ if not identifier_words:
118
+ continue
119
+
120
+ overlap = len(comment_words & identifier_words) / len(comment_words)
121
+ if overlap > 0.70:
122
+ violations.append(
123
+ Violation(
124
+ file_path=file_path,
125
+ line=comment_line,
126
+ rule_id="obvious-comment",
127
+ message=f"Obvious comment duplicates identifier '{identifier}'",
128
+ )
129
+ )
130
+ break
131
+
132
+ return violations
@@ -0,0 +1,137 @@
1
+ from slopcheck.parser import node_line, node_text, parse_source, run_query
2
+ from slopcheck.rules.base import Violation
3
+ from tree_sitter import Node
4
+
5
+ QUERY_EXCEPT = "(except_clause) @clause"
6
+
7
+
8
+ def is_broad_catch(clause: Node, source_bytes: bytes) -> tuple[bool, str | None]:
9
+ val = clause.child_by_field_name("value")
10
+ if val is None:
11
+ return True, None
12
+
13
+ caught_var: str | None = None
14
+ expr_node = val
15
+ if val.type == "as_pattern":
16
+ alias_node = val.child_by_field_name("alias")
17
+ if alias_node:
18
+ caught_var = node_text(alias_node, source_bytes).strip()
19
+ if val.named_children:
20
+ expr_node = val.named_children[0]
21
+
22
+ def get_identifiers(node: Node) -> list[str]:
23
+ if node.type == "identifier":
24
+ return [node_text(node, source_bytes)]
25
+ ids: list[str] = []
26
+ for child in node.children:
27
+ ids.extend(get_identifiers(child))
28
+ return ids
29
+
30
+ caught_types = set(get_identifiers(expr_node))
31
+ is_broad = bool(caught_types & {"Exception", "BaseException"})
32
+ return is_broad, caught_var
33
+
34
+
35
+ def is_pass_or_ellipsis(stmt: Node) -> bool:
36
+ if stmt.type == "pass_statement":
37
+ return True
38
+ if stmt.type == "expression_statement":
39
+ named = [c for c in stmt.children if c.is_named]
40
+ if len(named) == 1 and named[0].type == "ellipsis":
41
+ return True
42
+ return False
43
+
44
+
45
+ def is_print_call(stmt: Node, source_bytes: bytes) -> bool:
46
+ if stmt.type == "expression_statement":
47
+ named = [c for c in stmt.children if c.is_named]
48
+ if len(named) == 1 and named[0].type == "call":
49
+ func_node = named[0].child_by_field_name("function")
50
+ if func_node and func_node.type == "identifier":
51
+ return node_text(func_node, source_bytes) == "print"
52
+ return False
53
+
54
+
55
+ def is_contextless_raise(
56
+ stmt: Node,
57
+ caught_var: str | None,
58
+ source_bytes: bytes,
59
+ ) -> bool:
60
+ if stmt.type != "raise_statement":
61
+ return False
62
+
63
+ if any(child.type == "from" for child in stmt.children):
64
+ return False
65
+
66
+ named_children = [c for c in stmt.children if c.is_named]
67
+ if not named_children:
68
+ return True
69
+
70
+ if len(named_children) == 1:
71
+ child = named_children[0]
72
+ if child.type == "identifier" and caught_var is not None:
73
+ return node_text(child, source_bytes) == caught_var
74
+
75
+ return False
76
+
77
+
78
+ def is_swallowed_body(
79
+ stmts: list[Node],
80
+ caught_var: str | None,
81
+ source_bytes: bytes,
82
+ ) -> bool:
83
+ if not stmts:
84
+ return True
85
+
86
+ if all(is_pass_or_ellipsis(s) or is_print_call(s, source_bytes) for s in stmts):
87
+ return True
88
+
89
+ if len(stmts) == 1 and is_contextless_raise(stmts[0], caught_var, source_bytes):
90
+ return True
91
+
92
+ return False
93
+
94
+
95
+ def check_swallowed_exceptions(
96
+ file_path: str,
97
+ source: str | bytes,
98
+ changed_lines: set[int] | None = None,
99
+ ) -> list[Violation]:
100
+ tree, source_bytes = parse_source(source)
101
+ captures = run_query(tree, QUERY_EXCEPT)
102
+
103
+ violations: list[Violation] = []
104
+
105
+ for clause in captures.get("clause", []):
106
+ clause_line = node_line(clause)
107
+ clause_span_lines = set(
108
+ range(clause.start_point[0] + 1, clause.end_point[0] + 2)
109
+ )
110
+
111
+ if changed_lines is not None and not (clause_span_lines & changed_lines):
112
+ continue
113
+
114
+ is_broad, caught_var = is_broad_catch(clause, source_bytes)
115
+ if not is_broad:
116
+ continue
117
+
118
+ block_nodes = [c for c in clause.children if c.type == "block"]
119
+ if not block_nodes:
120
+ continue
121
+
122
+ block = block_nodes[0]
123
+ executable_stmts = [
124
+ c for c in block.children if c.is_named and c.type != "comment"
125
+ ]
126
+
127
+ if is_swallowed_body(executable_stmts, caught_var, source_bytes):
128
+ violations.append(
129
+ Violation(
130
+ file_path=file_path,
131
+ line=clause_line,
132
+ rule_id="swallowed-exception",
133
+ message="Swallowed exception caught without proper logging or handling",
134
+ )
135
+ )
136
+
137
+ return violations
slopcheck/runner.py ADDED
@@ -0,0 +1,82 @@
1
+ from pathlib import Path
2
+ import subprocess
3
+ from slopcheck.diff_parser import GitDiffError, parse_staged_diff
4
+ from slopcheck.rules import (
5
+ Violation,
6
+ check_filler_docstrings,
7
+ check_micro_wrappers,
8
+ check_obvious_comments,
9
+ check_swallowed_exceptions,
10
+ count_repo_calls,
11
+ )
12
+
13
+
14
+ def get_git_toplevel(cwd: Path) -> Path:
15
+ try:
16
+ result = subprocess.run(
17
+ ["git", "rev-parse", "--show-toplevel"],
18
+ capture_output=True,
19
+ text=True,
20
+ encoding="utf-8",
21
+ errors="replace",
22
+ check=True,
23
+ cwd=cwd,
24
+ )
25
+ return Path(result.stdout.strip()).resolve()
26
+ except (subprocess.CalledProcessError, FileNotFoundError) as err:
27
+ err_msg = (
28
+ err.stderr.strip()
29
+ if isinstance(err, subprocess.CalledProcessError) and err.stderr
30
+ else str(err)
31
+ )
32
+ raise GitDiffError(f"Git diff failed: {err_msg}") from err
33
+
34
+
35
+ def read_staged_file_bytes(repo_root: Path, rel_path: str) -> bytes | None:
36
+ try:
37
+ result = subprocess.run(
38
+ ["git", "show", f":{rel_path}"],
39
+ capture_output=True,
40
+ check=True,
41
+ cwd=repo_root,
42
+ )
43
+ return result.stdout
44
+ except (subprocess.CalledProcessError, FileNotFoundError):
45
+ file_path = repo_root / rel_path
46
+ try:
47
+ return file_path.read_bytes()
48
+ except OSError:
49
+ return None
50
+
51
+
52
+ def scan_staged(repo_root: str | Path | None = None) -> tuple[list[Violation], int]:
53
+ start_dir = Path(repo_root).resolve() if repo_root else Path.cwd().resolve()
54
+ root = get_git_toplevel(start_dir)
55
+ staged_map = parse_staged_diff(cwd=root)
56
+
57
+ if not staged_map:
58
+ return [], 0
59
+
60
+ call_counts = count_repo_calls(root)
61
+ violations: list[Violation] = []
62
+
63
+ for rel_path, changed_lines in staged_map.items():
64
+ source_bytes = read_staged_file_bytes(root, rel_path)
65
+ if source_bytes is None:
66
+ continue
67
+
68
+ violations.extend(
69
+ check_obvious_comments(rel_path, source_bytes, changed_lines)
70
+ )
71
+ violations.extend(
72
+ check_swallowed_exceptions(rel_path, source_bytes, changed_lines)
73
+ )
74
+ violations.extend(
75
+ check_micro_wrappers(rel_path, source_bytes, call_counts, changed_lines)
76
+ )
77
+ violations.extend(
78
+ check_filler_docstrings(rel_path, source_bytes, changed_lines)
79
+ )
80
+
81
+ violations.sort(key=lambda v: (v.file_path, v.line, v.rule_id))
82
+ return violations, len(staged_map)