ballpython 2.0.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.
ballpython/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """ballpython - alias and entrypoint wrapper for pycleaner."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pycleaner
6
+ from pycleaner import *
7
+
8
+ __version__ = pycleaner.__version__
9
+ __all__ = pycleaner.__all__
ballpython/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Entrypoint for python -m ballpython."""
2
+
3
+ import sys
4
+
5
+ from pycleaner.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
ballpython/cli.py ADDED
@@ -0,0 +1,7 @@
1
+ """CLI entrypoint for ballpython."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pycleaner.cli import main
6
+
7
+ __all__ = ["main"]
@@ -0,0 +1,322 @@
1
+ Metadata-Version: 2.4
2
+ Name: ballpython
3
+ Version: 2.0.0
4
+ Summary: The Ultimate Static Python Intelligence, Healing, Type Verification, and Security Suite
5
+ Author: Developer
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: ruff>=0.1.0
10
+ Requires-Dist: rich>=13.0.0
11
+ Requires-Dist: tomli>=1.1.0; python_version < "3.11"
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
14
+ Requires-Dist: black>=24.0.0; extra == "dev"
15
+ Requires-Dist: isort>=5.13.0; extra == "dev"
16
+ Provides-Extra: security
17
+ Requires-Dist: cryptography>=41.0.0; extra == "security"
18
+ Requires-Dist: defusedxml>=0.7.1; extra == "security"
19
+
20
+ # pycleaner — Ultimate Static Python Code Quality Suite
21
+
22
+ A production-grade, offline Python static analysis, syntax healing, linting, formatting, security scanning, complexity evaluation, dead code detection, and dependency auditing suite.
23
+
24
+ Zero external LLM dependencies, zero mock modes, and built for deterministic developer workflows and CI/CD pipelines.
25
+
26
+ ---
27
+
28
+ ## Key Capabilities
29
+
30
+ 1. **Syntax Healer (`SyntaxHealer`)**:
31
+ - Statically repairs missing colons on compound statement headers (`def`, `class`, `if`, `elif`, `else`, `for`, `while`, `try`, `except`, `finally`, `with`, `async def`, `match`, `case`).
32
+ - Corrects accidental single `=` assignments in conditionals (`if x = 1:` $\to$ `if x == 1:`) without corrupting keyword arguments (`func(x=1)`), augmented assignments, or walrus expressions (`x := 1`).
33
+ - Modernizes legacy Python 2 statements (`print "..."` $\to$ `print(...)`, `except Error, e:` $\to$ `except Error as e:`, and multi-exception tuples `except (E1, E2), e:` on Python 3.12+).
34
+ - Automatically closes unclosed parentheses, brackets, and braces.
35
+ - Normalizes mixed tab characters into 4 spaces.
36
+
37
+ 2. **Missing Import Resolver (`ImportResolver`)**:
38
+ - Walks Python AST to extract undefined loaded symbols across local, function, class, and comprehension scopes.
39
+ - Resolves undefined identifiers to standard library modules (`os`, `sys`, `json`, `re`, `subprocess`, `pathlib`, etc.), collections, typing constructs, dataclasses, concurrent primitives (`ThreadPoolExecutor`, `ProcessPoolExecutor`, `Lock`, `Queue`), and popular aliases (`np`, `pd`, `plt`, `sns`, `tf`, `nn`).
40
+ - **`TYPE_CHECKING` Awareness**: Injects typing-only imports into `if TYPE_CHECKING:` guards and adds `from __future__ import annotations` when symbols are used strictly in type annotations.
41
+ - **Custom Import Mapping**: Configurable mapping from symbol names to exact import statements.
42
+
43
+ 3. **Linter & Formatter (`LinterFormatter`)**:
44
+ - Integrates Rust-based `ruff` via in-memory stream processing (`--stdin-filename`).
45
+ - Automatically removes unused imports (`F401`) and unused variables (`F841`).
46
+ - Sorts and groups imports via `isort` / `ruff` or an internal pure-Python 3-tier sorter (stdlib $\to$ third-party $\to$ local).
47
+ - Modernizes deprecated syntax via `pyupgrade` (`UP`).
48
+ - Applies deterministic PEP 8 formatting (`ruff format` / `black` / pure-Python formatter).
49
+ - Wraps long `from ... import (...)` statements exceeding configured `line-length`.
50
+
51
+ 4. **Dead Code Detector (`DeadCodeDetector`)**:
52
+ - Builds a cross-file symbol definition and reference graph across a project.
53
+ - Identifies unused functions, methods, classes, module-level constants, and class attributes.
54
+ - Respects public exports in `__all__` and framework decorators (`@app.route`, `@pytest.fixture`, `@abstractmethod`, etc.).
55
+ - Detects unreachable code following unconditional `return`, `raise`, `break`, `continue`, or `sys.exit()`.
56
+ - Identifies empty pass blocks with no comments.
57
+
58
+ 5. **Static Security Scanner (`SecurityScanner`)**:
59
+ - Detects dangerous function calls: `eval()`, `exec()`, `compile()`, `pickle.loads()`, `os.system()`, and unsafe `yaml.load()` lacking `SafeLoader`.
60
+ - Flags SQL injection patterns (string concatenation, f-strings, `%`-formatting, or `.format()` inside `cursor.execute()`).
61
+ - Flags subprocess command injection (`shell=True`).
62
+ - Flags insecure transport (`verify=False` in `requests` or `httpx`).
63
+ - Scans for hardcoded secrets: AWS access/secret keys, GitHub tokens, Slack tokens, JWT tokens, private key headers, and generic passwords/API keys.
64
+ - Flags production `assert` statements used for input validation (which get stripped under `python -O`).
65
+
66
+ 6. **Complexity Analyzer (`ComplexityAnalyzer`)**:
67
+ - McCabe Cyclomatic Complexity per function ($E - N + 2$).
68
+ - Sonar-style Cognitive Complexity scoring (penalizing nested control flow, compound boolean conditions, and break in linear flow).
69
+ - Metrics tracked: line count, argument count, return statement count, and maximum nesting depth.
70
+ - Configurable thresholds with tabular and JSON reporting.
71
+
72
+ 7. **Dependency Auditor (`DependencyAuditor`)**:
73
+ - Statically scans all `.py` files across a repository to discover external third-party imports.
74
+ - Maps module import names to PyPI distribution package names (e.g., `yaml` $\to$ `PyYAML`, `PIL` $\to$ `pillow`, `cv2` $\to$ `opencv-python`).
75
+ - Compares imported dependencies against `requirements.txt` and `pyproject.toml`.
76
+ - Synchronizes `requirements.txt` with `--fix-deps` and prunes unused packages with `--prune-deps`.
77
+
78
+ 8. **Safety & Concurrency**:
79
+ - Backup creation (`.pycleaner.bak`) before overwriting files (enabled by default).
80
+ - Parallel multi-core file processing via `ProcessPoolExecutor`.
81
+ - Continuous file watching (`watch` mode) with automatic re-healing on save.
82
+ - Pre-commit configuration generator (`hook` subcommand).
83
+
84
+ ---
85
+
86
+ ## Installation
87
+
88
+ ```bash
89
+ # Editable install
90
+ pip install -e .
91
+
92
+ # Core dependencies
93
+ pip install ruff rich
94
+
95
+ # Optional security and development packages
96
+ pip install -e ".[dev,security]"
97
+ ```
98
+
99
+ ---
100
+
101
+ ## CLI Usage
102
+
103
+ ### Subcommands
104
+
105
+ #### `fix` (Default Action)
106
+ Heals syntax, resolves imports, prunes unused imports/variables, fixes lint violations, and formats code:
107
+ ```bash
108
+ py -m pycleaner fix src/
109
+ py -m pycleaner fix --diff path/to/script.py
110
+ py -m pycleaner fix --no-backup src/
111
+ py -m pycleaner fix --parallel --workers 4 src/
112
+ ```
113
+
114
+ #### `check` (Dry-Run CI Verification)
115
+ Inspects files without writing modifications to disk. Exits with code `1` if changes or errors are detected:
116
+ ```bash
117
+ py -m pycleaner check src/
118
+ py -m pycleaner check --diff src/
119
+ ```
120
+
121
+ #### `scan` (Security Vulnerability Audit)
122
+ Scans Python files for hardcoded secrets, dangerous calls, and injection vulnerabilities:
123
+ ```bash
124
+ py -m pycleaner scan .
125
+ py -m pycleaner scan --severity HIGH .
126
+ py -m pycleaner scan --json .
127
+ ```
128
+
129
+ #### `complexity` (Function Complexity Metrics)
130
+ Calculates Cyclomatic Complexity, Cognitive Complexity, and architectural metrics:
131
+ ```bash
132
+ py -m pycleaner complexity .
133
+ py -m pycleaner complexity --max-cyclomatic 10 --max-cognitive 15 .
134
+ py -m pycleaner complexity --json .
135
+ ```
136
+
137
+ #### `dead-code` (Unused Symbols & Unreachable Branches)
138
+ Finds unused functions, unused classes, empty pass branches, and dead code:
139
+ ```bash
140
+ py -m pycleaner dead-code .
141
+ py -m pycleaner dead-code --json .
142
+ ```
143
+
144
+ #### `audit` (Project Dependency Verification)
145
+ Audits imported third-party libraries against `requirements.txt`:
146
+ ```bash
147
+ # Audit only
148
+ py -m pycleaner audit .
149
+
150
+ # Automatically append missing dependencies
151
+ py -m pycleaner audit --fix-deps .
152
+
153
+ # Append missing and remove unimported dependencies
154
+ py -m pycleaner audit --fix-deps --prune-deps .
155
+ ```
156
+
157
+ #### `all` (Complete Quality Sweep)
158
+ Executes all engines in one command (fix + dependency audit + security scan + complexity + dead code):
159
+ ```bash
160
+ py -m pycleaner all .
161
+ ```
162
+
163
+ #### `watch` (Continuous File Watcher)
164
+ Watches files for filesystem modifications and auto-cleans on save:
165
+ ```bash
166
+ py -m pycleaner watch src/ --interval 1.0
167
+ ```
168
+
169
+ #### `hook` (Pre-Commit Integration)
170
+ Outputs a ready-to-use `.pre-commit-hooks.yaml` configuration block:
171
+ ```bash
172
+ py -m pycleaner hook
173
+ ```
174
+
175
+ ---
176
+
177
+ ### Backward-Compatible Flat Invocations
178
+
179
+ Legacy invocations continue to work seamlessly:
180
+ ```bash
181
+ pycleaner -a . # Equivalent to: pycleaner all .
182
+ pycleaner --check --diff src/ # Equivalent to: pycleaner check --diff src/
183
+ pycleaner --deps-only . # Equivalent to: pycleaner audit .
184
+ pycleaner path/to/file.py # Equivalent to: pycleaner fix path/to/file.py
185
+ ```
186
+
187
+ ---
188
+
189
+ ## Configuration
190
+
191
+ `pycleaner` automatically reads configuration from `pyproject.toml` under `[tool.pycleaner]` or from `.pycleaner.toml`.
192
+
193
+ ### `pyproject.toml` Example
194
+
195
+ ```toml
196
+ [tool.pycleaner]
197
+ # File targeting
198
+ exclude = ["migrations/", "generated/", "*_pb2.py", "*_pb2_grpc.py"]
199
+ include = ["src/", "tests/"]
200
+
201
+ # Syntax healing
202
+ fix-py2-syntax = true
203
+ fix-conditional-assignments = true
204
+
205
+ # Import resolution
206
+ custom-import-map = { "logger" = "from myapp.core.logging import logger" }
207
+ auto-add-future-annotations = false
208
+
209
+ # Linting & formatting
210
+ line-length = 88
211
+ select-rules = "F401,F841,I,UP,E,W,B,SIM,RUF"
212
+
213
+ # Dead code
214
+ ignore-decorators = ["@app.route", "@pytest.fixture", "@override"]
215
+ ignore-names = ["_*", "test_*"]
216
+
217
+ # Security
218
+ security-severity-threshold = "LOW"
219
+ ignore-security-rules = []
220
+
221
+ # Complexity thresholds
222
+ max-cyclomatic-complexity = 10
223
+ max-cognitive-complexity = 15
224
+ max-function-length = 50
225
+ max-arguments = 5
226
+
227
+ # Behavior
228
+ backup = true
229
+ parallel = false
230
+ max-workers = 4
231
+ ```
232
+
233
+ ---
234
+
235
+ ## Programmatic API
236
+
237
+ ### 1. Cleaning Source Code or Files
238
+ ```python
239
+ from pathlib import Path
240
+ from pycleaner import CleanPipeline, load_config
241
+
242
+ # Load config with project overrides
243
+ config = load_config(project_root=".")
244
+ pipeline = CleanPipeline(config=config)
245
+
246
+ # In-memory code processing
247
+ dirty_code = """
248
+ import math
249
+
250
+ def calculate(x)
251
+ if x = 0
252
+ return Path('.')
253
+ return Path(str(x))
254
+ """
255
+ result = pipeline.process_source(dirty_code, filename="example.py")
256
+ print("Cleaned code:\n", result.cleaned_code)
257
+ print("Repairs applied:", result.syntax_repairs)
258
+ print("Imports added:", result.resolved_imports)
259
+
260
+ # File processing with automatic backup
261
+ file_result = pipeline.process_file("example.py", apply_changes=True, backup=True)
262
+ ```
263
+
264
+ ### 2. Security Vulnerability Scanning
265
+ ```python
266
+ from pycleaner import SecurityScanner
267
+
268
+ scanner = SecurityScanner(severity_threshold="MEDIUM")
269
+ report = scanner.scan_project("src/")
270
+
271
+ for finding in report.findings:
272
+ print(f"[{finding.severity}] {finding.category} at {finding.filepath}:{finding.lineno}")
273
+ print(f" Message: {finding.message}")
274
+ print(f" Fix: {finding.suggestion}")
275
+ ```
276
+
277
+ ### 3. Complexity Analysis
278
+ ```python
279
+ from pycleaner import ComplexityAnalyzer
280
+
281
+ analyzer = ComplexityAnalyzer()
282
+ report = analyzer.analyze_project("src/")
283
+
284
+ print(f"Scanned {report.files_scanned} files, {report.count} functions.")
285
+ print(f"Average Cyclomatic: {report.average_cyclomatic:.2f}")
286
+
287
+ violations = report.above_threshold(max_cyclomatic=10, max_cognitive=15)
288
+ for func in violations:
289
+ print(f"{func.qualified_name} (CC={func.cyclomatic}, Cog={func.cognitive})")
290
+ ```
291
+
292
+ ### 4. Dead Code Detection
293
+ ```python
294
+ from pycleaner import DeadCodeDetector
295
+
296
+ detector = DeadCodeDetector()
297
+ report = detector.analyze_project("src/")
298
+
299
+ for item in report.unused_symbols:
300
+ print(f"Unused {item.kind} '{item.name}' at {item.filepath}:{item.lineno}")
301
+
302
+ for item in report.unreachable_code:
303
+ print(f"Unreachable code at {item.filepath}:{item.lineno} ({item.reason})")
304
+ ```
305
+
306
+ ---
307
+
308
+ ## Exit Codes
309
+
310
+ | Exit Code | Meaning |
311
+ |:---:|:---|
312
+ | `0` | Clean run: all files valid, no errors, or changes cleanly written |
313
+ | `1` | Issues found: check mode detected modifications, errors occurred, or critical security findings flagged |
314
+ | `2` | Configuration error: invalid TOML syntax, invalid configuration keys, or mismatched types |
315
+
316
+ ---
317
+
318
+ ## License
319
+
320
+ MIT License.
321
+ # ball-python
322
+ # ball-python
@@ -0,0 +1,24 @@
1
+ ballpython/__init__.py,sha256=d8ONxgaz9jml_fHPVvg867Vt5jGRhGTqzWPtux3WJOc,206
2
+ ballpython/__main__.py,sha256=aCRr0vnZfKYHDrPHBsYSjX5xTxtFJpTTSPVUSZTBK-I,136
3
+ ballpython/cli.py,sha256=LllCLRAQQ-fRR_lIXwmd2e3Q7DLCIvf-5jHBXsAhJWs,125
4
+ pycleaner/__init__.py,sha256=MfmUvfwNaguO_pYaRVKYAXHHKYgPpZmc6n0DPEzMOXA,1940
5
+ pycleaner/__main__.py,sha256=8QBFrPyxId563F6cipPMNVEBTG8TIZUgxQfp8gk1VSI,135
6
+ pycleaner/cli.py,sha256=1lmOLOiQz7AEABcV2WwcS_5UHkfaSlyjSqX-KHz64tg,50779
7
+ pycleaner/complexity_analyzer.py,sha256=esmBAwoC5XDgTKG_HVIXu82kFnJw6LYdbNJIShueSV8,15176
8
+ pycleaner/config.py,sha256=Mcp_1uTkIvxQtKKD1Y1xZeUmQVaHKf9PmqB6mqmMzCc,8401
9
+ pycleaner/dead_code_detector.py,sha256=yIa_RRCWyQMZLGweJsl41MGbqDE_j0teXoFW5ir8uNE,17598
10
+ pycleaner/dependency_auditor.py,sha256=wep0KcLYpHPy0bnuunMgkaIA9HODHTH6WQ8UhSX8oAQ,11589
11
+ pycleaner/import_resolver.py,sha256=JnAysZeYtXlmmM0LEnb9HBdkHnEsNwwp4QlxebRxGNE,32189
12
+ pycleaner/linter_formatter.py,sha256=LB5j66OCASU8WG8QgRFpSX7C2c7_UNMBgkJh2hSWxAY,20857
13
+ pycleaner/pipeline.py,sha256=o9rQUF4Jf8pcLicCPvAjAYHUTgCSAs2rzo_3FM8U-kY,12753
14
+ pycleaner/security_scanner.py,sha256=Ycz61UEuvSXcBZ49p5RwQXnBzS7x4NJMCrK8pWZeJBY,20630
15
+ pycleaner/syntax_healer.py,sha256=5yJ2WHjHjZ4i_046Xu_F5syDixf4J69ZrlofUHBVeXw,19823
16
+ pycleaner/taint_engine.py,sha256=bQc_nT63SgTMKIr7YsgbpW3USRNmw33AUiclzGlqb3c,26483
17
+ pycleaner/test_generator.py,sha256=Nu2i7qZtMZHz30h7lk-tef3VT-jAI6m4_jyheo2Abh0,16127
18
+ pycleaner/type_checker.py,sha256=CgnYRBTxDCaj2isGaFUdZQb0YxIATrEpElgSTg-Hwgc,33793
19
+ pycleaner/typeshed_resolver.py,sha256=N-kWU_CI5DG59lQMkt7wMW9sHYjNCBdfFS42b4y2Kr4,12742
20
+ ballpython-2.0.0.dist-info/METADATA,sha256=_gm1hvFBL42IWw8wkloJ7XJ7GWg2bxs4c2mUy6B_sRM,11728
21
+ ballpython-2.0.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
22
+ ballpython-2.0.0.dist-info/entry_points.txt,sha256=6ux-5UxoVSmlK5p9M-GDVt24sCdwTQq9wgRDkpMIYU8,81
23
+ ballpython-2.0.0.dist-info/top_level.txt,sha256=u6lmy8RWZ_saxCZAQTL7EijB4sunegOiVyk5fHjpwLk,21
24
+ ballpython-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ ballpython = pycleaner.cli:main
3
+ pycleaner = pycleaner.cli:main
@@ -0,0 +1,2 @@
1
+ ballpython
2
+ pycleaner
pycleaner/__init__.py ADDED
@@ -0,0 +1,53 @@
1
+ """
2
+ pycleaner - The Ultimate Static Python Intelligence, Healing, and Verification Suite.
3
+
4
+ Automatically heals syntax errors, resolves missing imports, prunes unused imports,
5
+ fixes linting violations, applies canonical formatting, audits project dependencies,
6
+ detects dead code, scans for security vulnerabilities, analyzes code complexity,
7
+ performs bidirectional type inference against Typeshed stubs, traces interprocedural
8
+ dataflow taint vulnerabilities, and synthesizes automated behavioral test suites.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ __version__ = "2.0.0"
14
+ __all__ = [
15
+ "CleanPipeline",
16
+ "CleanResult",
17
+ "ComplexityAnalyzer",
18
+ "ComplexityReport",
19
+ "DeadCodeDetector",
20
+ "DeadCodeReport",
21
+ "DependencyAuditor",
22
+ "GeneratedTestSuite",
23
+ "ImportResolver",
24
+ "LinterFormatter",
25
+ "PyCleanerConfig",
26
+ "SecurityReport",
27
+ "SecurityScanner",
28
+ "SyntaxHealer",
29
+ "TaintEngine",
30
+ "TaintFinding",
31
+ "TaintReport",
32
+ "TestCase",
33
+ "TestGenerator",
34
+ "TypeChecker",
35
+ "TypeFinding",
36
+ "TypeReport",
37
+ "TypeshedResolver",
38
+ "load_config",
39
+ ]
40
+
41
+ from pycleaner.complexity_analyzer import ComplexityAnalyzer, ComplexityReport
42
+ from pycleaner.config import PyCleanerConfig, load_config
43
+ from pycleaner.dead_code_detector import DeadCodeDetector, DeadCodeReport
44
+ from pycleaner.dependency_auditor import DependencyAuditor
45
+ from pycleaner.import_resolver import ImportResolver
46
+ from pycleaner.linter_formatter import LinterFormatter
47
+ from pycleaner.pipeline import CleanPipeline, CleanResult
48
+ from pycleaner.security_scanner import SecurityReport, SecurityScanner
49
+ from pycleaner.syntax_healer import SyntaxHealer
50
+ from pycleaner.taint_engine import TaintEngine, TaintFinding, TaintReport
51
+ from pycleaner.test_generator import GeneratedTestSuite, TestCase, TestGenerator
52
+ from pycleaner.type_checker import TypeChecker, TypeFinding, TypeReport
53
+ from pycleaner.typeshed_resolver import TypeshedResolver
pycleaner/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Entrypoint for python -m pycleaner."""
2
+
3
+ import sys
4
+
5
+ from pycleaner.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())