repolens-scan 0.1.0__tar.gz
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.
- repolens_scan-0.1.0/LICENSE +21 -0
- repolens_scan-0.1.0/PKG-INFO +100 -0
- repolens_scan-0.1.0/README.md +84 -0
- repolens_scan-0.1.0/pyproject.toml +26 -0
- repolens_scan-0.1.0/repolens/__init__.py +1 -0
- repolens_scan-0.1.0/repolens/__main__.py +10 -0
- repolens_scan-0.1.0/repolens/analyze.py +38 -0
- repolens_scan-0.1.0/repolens/cli.py +147 -0
- repolens_scan-0.1.0/repolens/jsanalyzer.py +239 -0
- repolens_scan-0.1.0/repolens/models.py +55 -0
- repolens_scan-0.1.0/repolens/pyanalyzer.py +110 -0
- repolens_scan-0.1.0/repolens/report.py +69 -0
- repolens_scan-0.1.0/repolens/scanner.py +168 -0
- repolens_scan-0.1.0/repolens/secrets.py +118 -0
- repolens_scan-0.1.0/repolens_scan.egg-info/PKG-INFO +100 -0
- repolens_scan-0.1.0/repolens_scan.egg-info/SOURCES.txt +20 -0
- repolens_scan-0.1.0/repolens_scan.egg-info/dependency_links.txt +1 -0
- repolens_scan-0.1.0/repolens_scan.egg-info/entry_points.txt +2 -0
- repolens_scan-0.1.0/repolens_scan.egg-info/top_level.txt +1 -0
- repolens_scan-0.1.0/setup.cfg +4 -0
- repolens_scan-0.1.0/tests/test_checks.py +139 -0
- repolens_scan-0.1.0/tests/test_cli.py +45 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Prabhat Yadav
|
|
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
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: repolens-scan
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Summarize a source tree: size, code problems and leaked secrets.
|
|
5
|
+
Author: Prabhat Yadav
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Prabhatyadav92/repolens
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# repolens
|
|
18
|
+
|
|
19
|
+
A small command line tool that looks through a project folder and tells you how big it is, which functions have grown out of hand, and whether anyone committed a password.
|
|
20
|
+
|
|
21
|
+
It only uses the Python standard library, works offline, and reads files without running or importing any of your code.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
pip install repolens-scan
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Or from a clone:
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
git clone https://github.com/Prabhatyadav92/repolens
|
|
33
|
+
cd repolens
|
|
34
|
+
pip install .
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Python 3.9 or newer.
|
|
38
|
+
|
|
39
|
+
## Use
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
repolens . # summary and findings
|
|
43
|
+
repolens secrets . # only secrets, exit code 1 if any are found
|
|
44
|
+
repolens report . # write repolens-report.md
|
|
45
|
+
repolens rules # list every check
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Example:
|
|
49
|
+
|
|
50
|
+
```
|
|
51
|
+
$ repolens src/
|
|
52
|
+
Scanning /home/me/newspulse/src
|
|
53
|
+
|
|
54
|
+
Languages
|
|
55
|
+
JavaScript 41 files 7,204 lines
|
|
56
|
+
Python 22 files 3,118 lines
|
|
57
|
+
|
|
58
|
+
Total 63 files 10,322 lines
|
|
59
|
+
|
|
60
|
+
Secrets (1)
|
|
61
|
+
config.js:7 aws-access-key AWS access key: AKIA********
|
|
62
|
+
|
|
63
|
+
Findings (9)
|
|
64
|
+
server.js:10 long-function anonymous function is 112 lines (limit 60)
|
|
65
|
+
...
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Useful options:
|
|
69
|
+
|
|
70
|
+
| Option | What it does |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `-x GLOB`, `--exclude GLOB` | Skip matching files or folders. Repeatable. |
|
|
73
|
+
| `--max-function-lines N` | Length before `long-function` fires (default 60). |
|
|
74
|
+
| `--max-complexity N` | Branch count before `complexity` fires (default 15). |
|
|
75
|
+
| `--fail-on LEVEL` | Exit 1 if something at `low`, `medium` or `high` is found. Handy in CI. |
|
|
76
|
+
| `--all` | Print every finding instead of the first 20. |
|
|
77
|
+
|
|
78
|
+
Files matched by `.gitignore` are skipped, along with `node_modules`, virtualenvs and build folders. To silence a single line, put `repolens: ignore` in a comment on it.
|
|
79
|
+
|
|
80
|
+
## What it checks
|
|
81
|
+
|
|
82
|
+
- **Python** (via `ast`): long or complex functions, too many parameters, mutable default arguments, bare `except`, `eval`/`exec`, unused imports.
|
|
83
|
+
- **JavaScript** (regex, no parser): long or complex functions, unused imports and requires, `var`, loose equality, empty `catch`, `eval`, leftover `console.log`.
|
|
84
|
+
- **Any text file**: TODO / FIXME / HACK / XXX in comments.
|
|
85
|
+
- **Secrets**: private keys, AWS, GitHub, Slack, Google and Stripe keys, JWTs, database URLs with passwords, `password = "..."` style assignments, and `.env` files. Secret values are always masked in output.
|
|
86
|
+
|
|
87
|
+
## Limits
|
|
88
|
+
|
|
89
|
+
The JavaScript checks are approximate. Regex literals and unusual formatting can confuse the function-length counting, and TypeScript is counted but not analyzed. `.gitignore` negation rules (`!pattern`) are ignored. The secret scanner will miss secrets it has no pattern for and will sometimes flag test fixtures; use `repolens: ignore` for those. It is not a replacement for a tool like gitleaks if you need serious coverage.
|
|
90
|
+
|
|
91
|
+
## Development
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
pip install pytest
|
|
95
|
+
pytest
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## License
|
|
99
|
+
|
|
100
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# repolens
|
|
2
|
+
|
|
3
|
+
A small command line tool that looks through a project folder and tells you how big it is, which functions have grown out of hand, and whether anyone committed a password.
|
|
4
|
+
|
|
5
|
+
It only uses the Python standard library, works offline, and reads files without running or importing any of your code.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
pip install repolens-scan
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or from a clone:
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
git clone https://github.com/Prabhatyadav92/repolens
|
|
17
|
+
cd repolens
|
|
18
|
+
pip install .
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Python 3.9 or newer.
|
|
22
|
+
|
|
23
|
+
## Use
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
repolens . # summary and findings
|
|
27
|
+
repolens secrets . # only secrets, exit code 1 if any are found
|
|
28
|
+
repolens report . # write repolens-report.md
|
|
29
|
+
repolens rules # list every check
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Example:
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
$ repolens src/
|
|
36
|
+
Scanning /home/me/newspulse/src
|
|
37
|
+
|
|
38
|
+
Languages
|
|
39
|
+
JavaScript 41 files 7,204 lines
|
|
40
|
+
Python 22 files 3,118 lines
|
|
41
|
+
|
|
42
|
+
Total 63 files 10,322 lines
|
|
43
|
+
|
|
44
|
+
Secrets (1)
|
|
45
|
+
config.js:7 aws-access-key AWS access key: AKIA********
|
|
46
|
+
|
|
47
|
+
Findings (9)
|
|
48
|
+
server.js:10 long-function anonymous function is 112 lines (limit 60)
|
|
49
|
+
...
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Useful options:
|
|
53
|
+
|
|
54
|
+
| Option | What it does |
|
|
55
|
+
| --- | --- |
|
|
56
|
+
| `-x GLOB`, `--exclude GLOB` | Skip matching files or folders. Repeatable. |
|
|
57
|
+
| `--max-function-lines N` | Length before `long-function` fires (default 60). |
|
|
58
|
+
| `--max-complexity N` | Branch count before `complexity` fires (default 15). |
|
|
59
|
+
| `--fail-on LEVEL` | Exit 1 if something at `low`, `medium` or `high` is found. Handy in CI. |
|
|
60
|
+
| `--all` | Print every finding instead of the first 20. |
|
|
61
|
+
|
|
62
|
+
Files matched by `.gitignore` are skipped, along with `node_modules`, virtualenvs and build folders. To silence a single line, put `repolens: ignore` in a comment on it.
|
|
63
|
+
|
|
64
|
+
## What it checks
|
|
65
|
+
|
|
66
|
+
- **Python** (via `ast`): long or complex functions, too many parameters, mutable default arguments, bare `except`, `eval`/`exec`, unused imports.
|
|
67
|
+
- **JavaScript** (regex, no parser): long or complex functions, unused imports and requires, `var`, loose equality, empty `catch`, `eval`, leftover `console.log`.
|
|
68
|
+
- **Any text file**: TODO / FIXME / HACK / XXX in comments.
|
|
69
|
+
- **Secrets**: private keys, AWS, GitHub, Slack, Google and Stripe keys, JWTs, database URLs with passwords, `password = "..."` style assignments, and `.env` files. Secret values are always masked in output.
|
|
70
|
+
|
|
71
|
+
## Limits
|
|
72
|
+
|
|
73
|
+
The JavaScript checks are approximate. Regex literals and unusual formatting can confuse the function-length counting, and TypeScript is counted but not analyzed. `.gitignore` negation rules (`!pattern`) are ignored. The secret scanner will miss secrets it has no pattern for and will sometimes flag test fixtures; use `repolens: ignore` for those. It is not a replacement for a tool like gitleaks if you need serious coverage.
|
|
74
|
+
|
|
75
|
+
## Development
|
|
76
|
+
|
|
77
|
+
```
|
|
78
|
+
pip install pytest
|
|
79
|
+
pytest
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## License
|
|
83
|
+
|
|
84
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "repolens-scan"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Summarize a source tree: size, code problems and leaked secrets."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Prabhat Yadav" }]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"License :: OSI Approved :: MIT License",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Environment :: Console",
|
|
17
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.scripts]
|
|
21
|
+
repolens = "repolens.cli:main"
|
|
22
|
+
|
|
23
|
+
[tool.setuptools]
|
|
24
|
+
packages = ["repolens"]
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://github.com/Prabhatyadav92/repolens"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from . import jsanalyzer, pyanalyzer
|
|
6
|
+
from .models import Finding, Limits
|
|
7
|
+
|
|
8
|
+
COMMENTED_LANGS = {
|
|
9
|
+
"Python", "JavaScript", "TypeScript", "Java", "Go", "Rust", "Ruby", "PHP", "C", "C++",
|
|
10
|
+
"C#", "Shell", "SQL", "HTML", "CSS", "SCSS", "YAML", "TOML",
|
|
11
|
+
}
|
|
12
|
+
MARKER = re.compile(r"(?:#|//|/\*|<!--|^\s*\*)[^\n]*?\b(TODO|FIXME|HACK|XXX)\b[:\s(-]*(.*)") # repolens: ignore
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def run(files, limits: Limits) -> list[Finding]:
|
|
16
|
+
findings = []
|
|
17
|
+
for f in files:
|
|
18
|
+
if f.generated:
|
|
19
|
+
continue
|
|
20
|
+
if f.language == "Python":
|
|
21
|
+
findings.extend(pyanalyzer.check(f, limits))
|
|
22
|
+
elif f.language == "JavaScript":
|
|
23
|
+
findings.extend(jsanalyzer.check(f, limits))
|
|
24
|
+
if f.language in COMMENTED_LANGS:
|
|
25
|
+
findings.extend(_markers(f))
|
|
26
|
+
return findings
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _markers(f):
|
|
30
|
+
out = []
|
|
31
|
+
for number, line in enumerate(f.text.splitlines(), 1):
|
|
32
|
+
if "repolens: ignore" in line:
|
|
33
|
+
continue
|
|
34
|
+
m = MARKER.search(line)
|
|
35
|
+
if m:
|
|
36
|
+
note = m.group(2).strip().rstrip("*/-> ").strip()[:60]
|
|
37
|
+
out.append(Finding(f.path, number, "todo", f"{m.group(1)} {note}".strip()))
|
|
38
|
+
return out
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from . import __version__, analyze, report, secrets
|
|
8
|
+
from .models import RULES, SEVERITY_ORDER, Limits
|
|
9
|
+
from .scanner import scan
|
|
10
|
+
|
|
11
|
+
COMMANDS = {"scan", "secrets", "report", "rules"}
|
|
12
|
+
SHOW_LIMIT = 20
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
16
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
17
|
+
common.add_argument("path", nargs="?", default=".", help="directory to look at (default: .)")
|
|
18
|
+
common.add_argument("-x", "--exclude", action="append", default=[], metavar="GLOB",
|
|
19
|
+
help="skip files or directories matching GLOB; may be given more than once")
|
|
20
|
+
common.add_argument("--max-function-lines", type=int, default=60, metavar="N")
|
|
21
|
+
common.add_argument("--max-complexity", type=int, default=15, metavar="N")
|
|
22
|
+
common.add_argument("--max-args", type=int, default=7, metavar="N")
|
|
23
|
+
|
|
24
|
+
parser = argparse.ArgumentParser(
|
|
25
|
+
prog="repolens",
|
|
26
|
+
description="Summarize a source tree: size, code problems and leaked secrets.",
|
|
27
|
+
)
|
|
28
|
+
parser.add_argument("--version", action="version", version=f"repolens {__version__}")
|
|
29
|
+
sub = parser.add_subparsers(dest="command", metavar="command")
|
|
30
|
+
|
|
31
|
+
p = sub.add_parser("scan", parents=[common], help="print a summary and the findings (default)")
|
|
32
|
+
p.add_argument("--all", action="store_true", help=f"show every finding, not just the first {SHOW_LIMIT}")
|
|
33
|
+
p.add_argument("--fail-on", choices=list(SEVERITY_ORDER), metavar="LEVEL",
|
|
34
|
+
help="exit 1 if there is a finding at LEVEL (low, medium, high) or above")
|
|
35
|
+
|
|
36
|
+
sub.add_parser("secrets", parents=[common], help="only look for secrets; exit 1 if any are found")
|
|
37
|
+
|
|
38
|
+
p = sub.add_parser("report", parents=[common], help="write a Markdown report")
|
|
39
|
+
p.add_argument("-o", "--output", default="repolens-report.md", metavar="FILE")
|
|
40
|
+
|
|
41
|
+
sub.add_parser("rules", help="list what is checked")
|
|
42
|
+
return parser
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main(argv=None) -> int:
|
|
46
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
47
|
+
if not argv or (argv[0] not in COMMANDS and argv[0] not in ("-h", "--help", "--version")):
|
|
48
|
+
argv.insert(0, "scan")
|
|
49
|
+
args = build_parser().parse_args(argv)
|
|
50
|
+
|
|
51
|
+
if args.command == "rules":
|
|
52
|
+
return _print_rules()
|
|
53
|
+
|
|
54
|
+
root = Path(args.path)
|
|
55
|
+
if not root.is_dir():
|
|
56
|
+
print(f"repolens: {args.path}: not a directory", file=sys.stderr)
|
|
57
|
+
return 2
|
|
58
|
+
|
|
59
|
+
limits = Limits(args.max_function_lines, args.max_complexity, args.max_args)
|
|
60
|
+
result = scan(root, args.exclude)
|
|
61
|
+
leaks = secrets.scan(result)
|
|
62
|
+
|
|
63
|
+
if args.command == "secrets":
|
|
64
|
+
_print_findings("Secrets", leaks, show_all=True)
|
|
65
|
+
if not leaks:
|
|
66
|
+
print("No secrets found.")
|
|
67
|
+
return 1 if leaks else 0
|
|
68
|
+
|
|
69
|
+
quality = analyze.run(result.files, limits)
|
|
70
|
+
|
|
71
|
+
if args.command == "report":
|
|
72
|
+
Path(args.output).write_text(report.render(result, quality, leaks), encoding="utf-8")
|
|
73
|
+
print(f"Wrote {args.output} ({len(quality)} findings, {len(leaks)} possible secrets)")
|
|
74
|
+
return 0
|
|
75
|
+
|
|
76
|
+
_print_scan(result, quality, leaks, show_all=args.all)
|
|
77
|
+
if args.fail_on:
|
|
78
|
+
bar = SEVERITY_ORDER[args.fail_on]
|
|
79
|
+
if any(SEVERITY_ORDER[x.severity] >= bar for x in quality + leaks):
|
|
80
|
+
return 1
|
|
81
|
+
return 0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _print_scan(result, quality, leaks, show_all):
|
|
85
|
+
print(f"Scanning {result.root}\n")
|
|
86
|
+
_print_languages(result)
|
|
87
|
+
_print_project(result)
|
|
88
|
+
_print_findings("Secrets", leaks, show_all=True)
|
|
89
|
+
_print_findings("Findings", quality, show_all=show_all)
|
|
90
|
+
print(f"{len(quality)} findings, {len(leaks)} possible secrets. Run `repolens report` for a file.")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _print_languages(result):
|
|
94
|
+
rows = sorted(result.languages().items(), key=lambda kv: -kv[1][1])
|
|
95
|
+
if not rows:
|
|
96
|
+
print("No source files found.\n")
|
|
97
|
+
return
|
|
98
|
+
rows.append(("Total", (sum(v[0] for _, v in rows), sum(v[1] for _, v in rows))))
|
|
99
|
+
files = [f"{n} file" + ("" if n == 1 else "s") for _, (n, _) in rows]
|
|
100
|
+
lines = [f"{n:,} line" + ("" if n == 1 else "s") for _, (_, n) in rows]
|
|
101
|
+
width = max(len(name) for name, _ in rows)
|
|
102
|
+
fw, lw = max(map(len, files)), max(map(len, lines))
|
|
103
|
+
print("Languages")
|
|
104
|
+
for (name, _), fcol, lcol in zip(rows, files, lines):
|
|
105
|
+
if name == "Total":
|
|
106
|
+
print()
|
|
107
|
+
print(f" {name:<{width}} {fcol:>{fw}} {lcol:>{lw}}")
|
|
108
|
+
print()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _print_project(result):
|
|
112
|
+
lines = []
|
|
113
|
+
if result.manifests():
|
|
114
|
+
lines.append("dependency files: " + ", ".join(result.manifests()[:6]))
|
|
115
|
+
if result.missing():
|
|
116
|
+
lines.append("not found: " + ", ".join(result.missing()))
|
|
117
|
+
hidden = len(result.files) - len(result.counted)
|
|
118
|
+
if hidden:
|
|
119
|
+
lines.append(f"{hidden} generated/minified files not counted")
|
|
120
|
+
if lines:
|
|
121
|
+
print("Project")
|
|
122
|
+
for line in lines:
|
|
123
|
+
print(" " + line)
|
|
124
|
+
print()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _print_findings(title, findings, show_all):
|
|
128
|
+
if not findings:
|
|
129
|
+
return
|
|
130
|
+
ordered = report.sort_findings(findings)
|
|
131
|
+
shown = ordered if show_all else ordered[:SHOW_LIMIT]
|
|
132
|
+
print(f"{title} ({len(findings)})")
|
|
133
|
+
loc_w = min(max(len(x.location) for x in shown), 44)
|
|
134
|
+
rule_w = max(len(x.rule) for x in shown)
|
|
135
|
+
for x in shown:
|
|
136
|
+
loc = x.location if len(x.location) <= loc_w else "..." + x.location[-(loc_w - 3):]
|
|
137
|
+
print(f" {loc:<{loc_w}} {x.rule:<{rule_w}} {x.message}")
|
|
138
|
+
if len(shown) < len(ordered):
|
|
139
|
+
print(f" ... {len(ordered) - len(shown)} more (use --all)")
|
|
140
|
+
print()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _print_rules() -> int:
|
|
144
|
+
width = max(map(len, RULES))
|
|
145
|
+
for name, text in RULES.items():
|
|
146
|
+
print(f"{name:<{width}} {text}")
|
|
147
|
+
return 0
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Regex based checks for JavaScript.
|
|
2
|
+
|
|
3
|
+
There is no real parser here. Comments and strings are blanked out first so
|
|
4
|
+
braces inside them don't throw off the function-length counting, but regex
|
|
5
|
+
literals can still fool it. When braces don't balance, a function is skipped
|
|
6
|
+
rather than guessed at.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import bisect
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
from .models import Finding, Limits
|
|
14
|
+
|
|
15
|
+
_NON_NEWLINE = re.compile(r"[^\n]")
|
|
16
|
+
_SPECIAL = re.compile(r"[/'\"`]")
|
|
17
|
+
_KEYWORDS = {"if", "for", "while", "switch", "catch", "function", "return", "with"}
|
|
18
|
+
|
|
19
|
+
_PATTERNS = [
|
|
20
|
+
(re.compile(r"\bfunction\s*\*?\s*([A-Za-z_$][\w$]*)\s*(?=\()"), "fn"),
|
|
21
|
+
(re.compile(r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?function\b"), "fn"),
|
|
22
|
+
(re.compile(r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?"
|
|
23
|
+
r"(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>"), "arrow"),
|
|
24
|
+
(re.compile(r"\bfunction\s*\*?\s*(?=\()"), "fn"),
|
|
25
|
+
(re.compile(r"(?:\([^()]*\)|\b[A-Za-z_$][\w$]*)\s*=>"), "arrow"),
|
|
26
|
+
(re.compile(r"^[ \t]*(?:(?:static|async|get|set)\s+)*([A-Za-z_$][\w$]*)\s*\([^()]*\)\s*\{", re.M), "method"),
|
|
27
|
+
]
|
|
28
|
+
_DECISIONS = re.compile(r"\b(?:if|for|while|case|catch)\b|&&|\|\||(?<!\?)\?(?![?.])")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _mask(text):
|
|
32
|
+
return _NON_NEWLINE.sub(" ", text)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _mask_template(body):
|
|
36
|
+
"""Blank template literal text but keep the code inside ${ ... }."""
|
|
37
|
+
out = []
|
|
38
|
+
depth = 0
|
|
39
|
+
i = 0
|
|
40
|
+
while i < len(body):
|
|
41
|
+
ch = body[i]
|
|
42
|
+
if depth == 0:
|
|
43
|
+
if body.startswith("${", i):
|
|
44
|
+
out.append("${")
|
|
45
|
+
depth = 1
|
|
46
|
+
i += 2
|
|
47
|
+
continue
|
|
48
|
+
out.append(ch if ch == "\n" else " ")
|
|
49
|
+
else:
|
|
50
|
+
depth += (ch == "{") - (ch == "}")
|
|
51
|
+
out.append(ch)
|
|
52
|
+
i += 1
|
|
53
|
+
return "".join(out)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _string_end(src, start):
|
|
57
|
+
quote = src[start]
|
|
58
|
+
j = start + 1
|
|
59
|
+
while j < len(src):
|
|
60
|
+
ch = src[j]
|
|
61
|
+
if ch == "\\":
|
|
62
|
+
j += 2
|
|
63
|
+
continue
|
|
64
|
+
if ch == quote:
|
|
65
|
+
return j + 1, True
|
|
66
|
+
if ch == "\n" and quote != "`":
|
|
67
|
+
break
|
|
68
|
+
j += 1
|
|
69
|
+
return min(j, len(src)), False
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def strip_source(src):
|
|
73
|
+
"""Blank out comments and string contents, keeping offsets and newlines."""
|
|
74
|
+
out = []
|
|
75
|
+
i, n = 0, len(src)
|
|
76
|
+
while i < n:
|
|
77
|
+
m = _SPECIAL.search(src, i)
|
|
78
|
+
if not m:
|
|
79
|
+
out.append(src[i:])
|
|
80
|
+
break
|
|
81
|
+
out.append(src[i:m.start()])
|
|
82
|
+
i = m.start()
|
|
83
|
+
c = src[i]
|
|
84
|
+
two = src[i:i + 2]
|
|
85
|
+
if two == "//":
|
|
86
|
+
j = src.find("\n", i)
|
|
87
|
+
j = n if j == -1 else j
|
|
88
|
+
out.append(_mask(src[i:j]))
|
|
89
|
+
i = j
|
|
90
|
+
elif two == "/*":
|
|
91
|
+
j = src.find("*/", i + 2)
|
|
92
|
+
j = n if j == -1 else j + 2
|
|
93
|
+
out.append(_mask(src[i:j]))
|
|
94
|
+
i = j
|
|
95
|
+
elif c == "/":
|
|
96
|
+
out.append(c)
|
|
97
|
+
i += 1
|
|
98
|
+
else:
|
|
99
|
+
j, closed = _string_end(src, i)
|
|
100
|
+
if not closed and c != "`":
|
|
101
|
+
out.append(c) # e.g. the apostrophe in JSX text
|
|
102
|
+
i += 1
|
|
103
|
+
continue
|
|
104
|
+
seg = src[i:j]
|
|
105
|
+
if closed:
|
|
106
|
+
inner = _mask_template(seg[1:-1]) if c == "`" else _mask(seg[1:-1])
|
|
107
|
+
out.append(c + inner + c)
|
|
108
|
+
else:
|
|
109
|
+
out.append(_mask(seg))
|
|
110
|
+
i = j
|
|
111
|
+
return "".join(out)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _match(code, start, opener, closer):
|
|
115
|
+
depth = 0
|
|
116
|
+
for k in range(start, len(code)):
|
|
117
|
+
ch = code[k]
|
|
118
|
+
if ch == opener:
|
|
119
|
+
depth += 1
|
|
120
|
+
elif ch == closer:
|
|
121
|
+
depth -= 1
|
|
122
|
+
if depth == 0:
|
|
123
|
+
return k
|
|
124
|
+
return -1
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _skip_space(code, k):
|
|
128
|
+
while k < len(code) and code[k].isspace():
|
|
129
|
+
k += 1
|
|
130
|
+
return k
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _functions(code):
|
|
134
|
+
seen = set()
|
|
135
|
+
found = []
|
|
136
|
+
for rx, kind in _PATTERNS:
|
|
137
|
+
for m in rx.finditer(code):
|
|
138
|
+
name = m.group(1) if m.lastindex else "(anonymous)"
|
|
139
|
+
if kind == "method":
|
|
140
|
+
if name in _KEYWORDS:
|
|
141
|
+
continue
|
|
142
|
+
body = m.end() - 1
|
|
143
|
+
elif kind == "arrow":
|
|
144
|
+
body = _skip_space(code, m.end())
|
|
145
|
+
else:
|
|
146
|
+
paren = code.find("(", m.end())
|
|
147
|
+
if paren == -1:
|
|
148
|
+
continue
|
|
149
|
+
close = _match(code, paren, "(", ")")
|
|
150
|
+
if close == -1:
|
|
151
|
+
continue
|
|
152
|
+
body = _skip_space(code, close + 1)
|
|
153
|
+
if body >= len(code) or code[body] != "{" or body in seen:
|
|
154
|
+
continue
|
|
155
|
+
seen.add(body)
|
|
156
|
+
end = _match(code, body, "{", "}")
|
|
157
|
+
if end != -1:
|
|
158
|
+
found.append((name, m.start(), body, end))
|
|
159
|
+
return found
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def check(f, limits: Limits) -> list[Finding]:
|
|
163
|
+
skeleton = strip_source(f.text)
|
|
164
|
+
starts = [0] + [i + 1 for i, ch in enumerate(f.text) if ch == "\n"]
|
|
165
|
+
|
|
166
|
+
def line_of(offset):
|
|
167
|
+
return bisect.bisect_right(starts, offset)
|
|
168
|
+
|
|
169
|
+
out = []
|
|
170
|
+
for name, start, body, end in _functions(skeleton):
|
|
171
|
+
label = "anonymous function" if name == "(anonymous)" else f"{name}()"
|
|
172
|
+
length = line_of(end) - line_of(start) + 1
|
|
173
|
+
if length > limits.max_function_lines:
|
|
174
|
+
out.append(Finding(f.path, line_of(start), "long-function",
|
|
175
|
+
f"{label} is {length} lines (limit {limits.max_function_lines})"))
|
|
176
|
+
score = 1 + len(_DECISIONS.findall(skeleton, body, end))
|
|
177
|
+
if score > limits.max_complexity:
|
|
178
|
+
out.append(Finding(f.path, line_of(start), "complexity",
|
|
179
|
+
f"{label} has complexity about {score} (limit {limits.max_complexity})"))
|
|
180
|
+
|
|
181
|
+
out.extend(_unused_imports(f, skeleton, line_of))
|
|
182
|
+
|
|
183
|
+
for m in re.finditer(r"\beval\s*\(", skeleton):
|
|
184
|
+
out.append(Finding(f.path, line_of(m.start()), "eval-call", "call to eval()", "medium"))
|
|
185
|
+
for m in re.finditer(r"\bcatch\s*(?:\([^)]*\))?\s*\{\s*\}", f.text):
|
|
186
|
+
out.append(Finding(f.path, line_of(m.start()), "empty-catch", "empty catch block", "medium"))
|
|
187
|
+
|
|
188
|
+
out.extend(_counted(f.path, skeleton, line_of, r"\bvar\s+[A-Za-z_$\[{]", "use-var",
|
|
189
|
+
"var used {n} {times}", 1))
|
|
190
|
+
out.extend(_counted(f.path, skeleton, line_of, r"(?<![=!<>])(?:==|!=)(?!=)(?!\s*null\b)", "loose-equality",
|
|
191
|
+
"== or != used {n} {times}", 1))
|
|
192
|
+
out.extend(_counted(f.path, skeleton, line_of, r"\bconsole\.log\s*\(", "console-log",
|
|
193
|
+
"console.log called {n} {times}", 5))
|
|
194
|
+
return out
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _counted(path, code, line_of, pattern, rule, template, minimum):
|
|
198
|
+
hits = list(re.finditer(pattern, code))
|
|
199
|
+
if len(hits) < minimum:
|
|
200
|
+
return []
|
|
201
|
+
return [Finding(path, line_of(hits[0].start()), rule, template.format(n=len(hits), times="time" if len(hits) == 1 else "times"))]
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
_IMPORT_FORMS = [
|
|
205
|
+
re.compile(r"\bimport\s+([A-Za-z_$][\w$]*)\s*(?:,\s*\{([^}]*)\})?\s*from\b"),
|
|
206
|
+
re.compile(r"\bimport\s*\{([^}]*)\}\s*from\b"),
|
|
207
|
+
re.compile(r"\bimport\s*\*\s*as\s+([A-Za-z_$][\w$]*)\s*from\b"),
|
|
208
|
+
re.compile(r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*require\s*\("),
|
|
209
|
+
re.compile(r"\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\s*\("),
|
|
210
|
+
]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _unused_imports(f, skeleton, line_of):
|
|
214
|
+
names = [] # (name, offset)
|
|
215
|
+
for rx in _IMPORT_FORMS:
|
|
216
|
+
for m in rx.finditer(skeleton):
|
|
217
|
+
for group in m.groups():
|
|
218
|
+
if not group:
|
|
219
|
+
continue
|
|
220
|
+
for part in group.split(","):
|
|
221
|
+
part = part.strip()
|
|
222
|
+
if not part:
|
|
223
|
+
continue
|
|
224
|
+
part = re.split(r"\s+as\s+|:", part)[-1]
|
|
225
|
+
part = part.split("=")[0].strip()
|
|
226
|
+
if re.fullmatch(r"[A-Za-z_$][\w$]*", part):
|
|
227
|
+
names.append((part, m.start()))
|
|
228
|
+
|
|
229
|
+
out = []
|
|
230
|
+
seen = set()
|
|
231
|
+
for name, offset in names:
|
|
232
|
+
if name in seen or (name == "React" and f.path.endswith(".jsx")):
|
|
233
|
+
continue
|
|
234
|
+
seen.add(name)
|
|
235
|
+
uses = len(re.findall(r"(?<![\w$.])" + re.escape(name) + r"(?![\w$])", skeleton))
|
|
236
|
+
uses += len(re.findall(r"</?" + re.escape(name) + r"(?![\w$])", f.text))
|
|
237
|
+
if uses <= 1:
|
|
238
|
+
out.append(Finding(f.path, line_of(offset), "unused-import", f"'{name}' imported but never used"))
|
|
239
|
+
return out
|