codeintely-cli 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.
@@ -0,0 +1,193 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the
44
+ purposes of this License, Derivative Works shall not include works
45
+ that remain separable from, or merely link (or bind by name) to the
46
+ interfaces of, the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including the
49
+ original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright
52
+ owner or by an individual or Legal Entity authorized to submit on
53
+ behalf of the copyright owner. For the purposes of this definition,
54
+ "submitted" means any form of electronic, verbal, or written
55
+ communication sent to the Licensor or its representatives,
56
+ including but not limited to communication on electronic mailing
57
+ lists, source code control systems, and issue tracking systems that
58
+ are managed by, or on behalf of, the Licensor for the purpose of
59
+ discussing and improving the Work, but excluding communication that
60
+ is conspicuously marked or otherwise designated in writing by the
61
+ copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have
78
+ made, use, offer to sell, sell, import, and otherwise transfer the
79
+ Work, where such license applies only to those patent claims
80
+ licensable by such Contributor that are necessarily infringed by
81
+ their Contribution(s) alone or by combination of their
82
+ Contribution(s) with the Work to which such Contribution(s) was
83
+ submitted. If You institute patent litigation against any entity
84
+ (including a cross-claim or counterclaim in a lawsuit) alleging
85
+ that the Work or a Contribution incorporated within the Work
86
+ constitutes direct or contributory patent infringement, then any
87
+ patent licenses granted to You under this License for that Work
88
+ shall terminate as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing
142
+ the origin of the Work and reproducing the content of the NOTICE
143
+ file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this
154
+ License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as a
162
+ result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor
166
+ has been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. While redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ Copyright 2026 FNTN Consultancy Inc
182
+
183
+ Licensed under the Apache License, Version 2.0 (the "License");
184
+ you may not use this file except in compliance with the License.
185
+ You may obtain a copy of the License at
186
+
187
+ http://www.apache.org/licenses/LICENSE-2.0
188
+
189
+ Unless required by applicable law or agreed to in writing, software
190
+ distributed under the License is distributed on an "AS IS" BASIS,
191
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
192
+ See the License for the specific language governing permissions and
193
+ limitations under the License.
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.4
2
+ Name: codeintely-cli
3
+ Version: 0.1.0
4
+ Summary: CodeIntely local/pre-commit security scanner — the same custom rule pack (identity security, AppSec breadth, IaC/container config) the GitHub App and VS Code extension use, runnable before you ever push.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://codeintely.com
7
+ Project-URL: Repository, https://github.com/mdfaisalbe84/codeintely
8
+ Classifier: Environment :: Console
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Topic :: Security
11
+ Classifier: Topic :: Software Development :: Quality Assurance
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: semgrep>=1.90
17
+ Requires-Dist: pyyaml>=6.0
18
+ Dynamic: license-file
19
+
20
+ # codeintely-cli
21
+
22
+ Local security scanner for the [CodeIntely](https://codeintely.com) platform — the same rule pack the GitHub App and VS Code extension use, runnable before you ever push. No account, no network calls to CodeIntely's own servers, no Django project required.
23
+
24
+ ```bash
25
+ pip install codeintely-cli
26
+ codeintely scan .
27
+ ```
28
+
29
+ ## What it checks
30
+
31
+ - **Custom rule pack** (bundled, always runs) — identity security, tenant isolation/IDOR, mass assignment, and general AppSec breadth, via [Semgrep](https://semgrep.dev).
32
+ - **Secrets** — [Gitleaks](https://github.com/gitleaks/gitleaks).
33
+ - **Dependency CVEs** — [OSV-Scanner](https://github.com/google/osv-scanner).
34
+ - **IaC misconfiguration** (Terraform/Kubernetes/Dockerfile) — [Trivy](https://github.com/aquasecurity/trivy).
35
+
36
+ Gitleaks/OSV-Scanner/Trivy are auto-installed on first use if not already on `PATH` (downloaded once into `~/.codeintely/bin/`, reused after) — a plain `pip install` gets full coverage without separately installing three more tools by hand.
37
+
38
+ ## Usage
39
+
40
+ ```bash
41
+ codeintely scan [PATH] # defaults to the current directory
42
+ codeintely scan . --format json # machine-readable output
43
+ codeintely scan . --severity-threshold HIGH # exit non-zero only at/above this severity (default: HIGH)
44
+ codeintely scan . --no-color # disable ANSI color
45
+ ```
46
+
47
+ Exit code is `0` when nothing at or above `--severity-threshold` was found, `1` otherwise — safe to use directly in CI or a git hook.
48
+
49
+ ## Pre-commit hook
50
+
51
+ Add to your repo's `.pre-commit-config.yaml`:
52
+
53
+ ```yaml
54
+ repos:
55
+ - repo: https://github.com/mdfaisalbe84/codeintely
56
+ rev: main # pin to a tag once one exists
57
+ hooks:
58
+ - id: codeintely
59
+ ```
60
+
61
+ Then:
62
+
63
+ ```bash
64
+ pip install pre-commit
65
+ pre-commit install
66
+ ```
67
+
68
+ Every `git commit` now runs the scan first — a finding at or above `HIGH` blocks the commit before it ever reaches version control.
69
+
70
+ ## Why local, not just the GitHub App
71
+
72
+ The hosted GitHub App scans pull requests *after* they reach GitHub — it can block a merge, not a `git push`. This CLI runs the same rules entirely offline, before a commit is even made.
@@ -0,0 +1,53 @@
1
+ # codeintely-cli
2
+
3
+ Local security scanner for the [CodeIntely](https://codeintely.com) platform — the same rule pack the GitHub App and VS Code extension use, runnable before you ever push. No account, no network calls to CodeIntely's own servers, no Django project required.
4
+
5
+ ```bash
6
+ pip install codeintely-cli
7
+ codeintely scan .
8
+ ```
9
+
10
+ ## What it checks
11
+
12
+ - **Custom rule pack** (bundled, always runs) — identity security, tenant isolation/IDOR, mass assignment, and general AppSec breadth, via [Semgrep](https://semgrep.dev).
13
+ - **Secrets** — [Gitleaks](https://github.com/gitleaks/gitleaks).
14
+ - **Dependency CVEs** — [OSV-Scanner](https://github.com/google/osv-scanner).
15
+ - **IaC misconfiguration** (Terraform/Kubernetes/Dockerfile) — [Trivy](https://github.com/aquasecurity/trivy).
16
+
17
+ Gitleaks/OSV-Scanner/Trivy are auto-installed on first use if not already on `PATH` (downloaded once into `~/.codeintely/bin/`, reused after) — a plain `pip install` gets full coverage without separately installing three more tools by hand.
18
+
19
+ ## Usage
20
+
21
+ ```bash
22
+ codeintely scan [PATH] # defaults to the current directory
23
+ codeintely scan . --format json # machine-readable output
24
+ codeintely scan . --severity-threshold HIGH # exit non-zero only at/above this severity (default: HIGH)
25
+ codeintely scan . --no-color # disable ANSI color
26
+ ```
27
+
28
+ Exit code is `0` when nothing at or above `--severity-threshold` was found, `1` otherwise — safe to use directly in CI or a git hook.
29
+
30
+ ## Pre-commit hook
31
+
32
+ Add to your repo's `.pre-commit-config.yaml`:
33
+
34
+ ```yaml
35
+ repos:
36
+ - repo: https://github.com/mdfaisalbe84/codeintely
37
+ rev: main # pin to a tag once one exists
38
+ hooks:
39
+ - id: codeintely
40
+ ```
41
+
42
+ Then:
43
+
44
+ ```bash
45
+ pip install pre-commit
46
+ pre-commit install
47
+ ```
48
+
49
+ Every `git commit` now runs the scan first — a finding at or above `HIGH` blocks the commit before it ever reaches version control.
50
+
51
+ ## Why local, not just the GitHub App
52
+
53
+ The hosted GitHub App scans pull requests *after* they reach GitHub — it can block a merge, not a `git push`. This CLI runs the same rules entirely offline, before a commit is even made.
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,178 @@
1
+ """Auto-installs gitleaks/osv-scanner/trivy on first use, so a plain
2
+ `pip install codeintely-cli` gets full coverage (secrets, dependency CVEs,
3
+ IaC misconfig) without a user separately installing three more tools by
4
+ hand — the actual point of "include gitleaks/osv-scanner/trivy" rather
5
+ than just reporting them as skipped.
6
+
7
+ An existing PATH install is always preferred over downloading a second
8
+ copy (shutil.which() checked first) — this only downloads when nothing
9
+ is already available. Downloaded binaries are cached under
10
+ ~/.codeintely/bin/ and reused on every later run; only the very first
11
+ `codeintely scan` after install pays the download cost.
12
+
13
+ Versions are pinned to the exact same releases backend/Dockerfile uses
14
+ in production (gitleaks v8.21.2, osv-scanner v2.4.0, trivy v0.74.0) —
15
+ same detection behavior locally as the hosted GitHub App, not
16
+ independently-drifting versions. Asset names/archive layouts below were
17
+ confirmed against the real GitHub releases for these exact versions, not
18
+ assumed from a naming convention.
19
+
20
+ osv-scanner is pinned to v2.4.0 specifically, not the also-real v1.9.2:
21
+ confirmed live that scanners.py's `scan source ...` invocation has no
22
+ `source` subcommand in v1.9.2 (real syntax there is just `scan
23
+ [directory]`) — it silently produces zero findings instead of erroring,
24
+ since the failed run leaves the pre-created output file empty and the
25
+ caller reads "empty file" as "clean scan." v2.4.0 is what this was
26
+ actually written and tested against.
27
+ """
28
+
29
+ import io
30
+ import logging
31
+ import platform
32
+ import shutil
33
+ import stat
34
+ import sys
35
+ import tarfile
36
+ import urllib.error
37
+ import urllib.request
38
+ import zipfile
39
+ from pathlib import Path
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+ CACHE_DIR = Path.home() / ".codeintely" / "bin"
44
+ DOWNLOAD_TIMEOUT_SECONDS = 180 # trivy's Windows build alone is ~170MB
45
+
46
+ GITLEAKS_VERSION = "8.21.2"
47
+ OSV_SCANNER_VERSION = "2.4.0"
48
+ TRIVY_VERSION = "0.74.0"
49
+
50
+
51
+ def _os_arch() -> tuple[str | None, str | None]:
52
+ system = platform.system() # "Windows" | "Linux" | "Darwin"
53
+ machine = platform.machine().lower()
54
+ if machine in ("amd64", "x86_64"):
55
+ arch = "x64"
56
+ elif machine in ("arm64", "aarch64"):
57
+ arch = "arm64"
58
+ else:
59
+ arch = None # a real, if rare, unsupported case (e.g. 32-bit) — no asset built for it
60
+ return (system if system in ("Windows", "Linux", "Darwin") else None), arch
61
+
62
+
63
+ def _gitleaks_asset(system: str, arch: str) -> str | None:
64
+ os_name = {"Windows": "windows", "Linux": "linux", "Darwin": "darwin"}[system]
65
+ # Confirmed live: this exact pinned version has no windows_arm64 build
66
+ # (later releases added one) — a real, narrow gap, not a bug.
67
+ if system == "Windows" and arch == "arm64":
68
+ return None
69
+ ext = "zip" if system == "Windows" else "tar.gz"
70
+ return f"gitleaks_{GITLEAKS_VERSION}_{os_name}_{arch}.{ext}"
71
+
72
+
73
+ def _osv_scanner_asset(system: str, arch: str) -> str | None:
74
+ os_name = {"Windows": "windows", "Linux": "linux", "Darwin": "darwin"}[system]
75
+ arch_name = "amd64" if arch == "x64" else "arm64"
76
+ ext = ".exe" if system == "Windows" else ""
77
+ return f"osv-scanner_{os_name}_{arch_name}{ext}"
78
+
79
+
80
+ def _trivy_asset(system: str, arch: str) -> str | None:
81
+ # Confirmed live: real, inconsistent-but-real casing per OS — "Linux"
82
+ # and "macOS" are capitalized, "windows" isn't.
83
+ os_name = {"Windows": "windows", "Linux": "Linux", "Darwin": "macOS"}[system]
84
+ arch_name = "64bit" if arch == "x64" else "ARM64"
85
+ ext = "zip" if system == "Windows" else "tar.gz"
86
+ return f"trivy_{TRIVY_VERSION}_{os_name}-{arch_name}.{ext}"
87
+
88
+
89
+ # {tool_name: (release_base_url, asset_fn, is_raw_binary)} — is_raw_binary
90
+ # distinguishes osv-scanner (the GitHub asset itself IS the binary, no
91
+ # archive) from gitleaks/trivy (a .zip/.tar.gz to extract from).
92
+ _TOOLS = {
93
+ "gitleaks": (
94
+ f"https://github.com/gitleaks/gitleaks/releases/download/v{GITLEAKS_VERSION}",
95
+ _gitleaks_asset, False,
96
+ ),
97
+ "osv-scanner": (
98
+ f"https://github.com/google/osv-scanner/releases/download/v{OSV_SCANNER_VERSION}",
99
+ _osv_scanner_asset, True,
100
+ ),
101
+ "trivy": (
102
+ f"https://github.com/aquasecurity/trivy/releases/download/v{TRIVY_VERSION}",
103
+ _trivy_asset, False,
104
+ ),
105
+ }
106
+
107
+
108
+ def _download(url: str) -> bytes | None:
109
+ try:
110
+ with urllib.request.urlopen(url, timeout=DOWNLOAD_TIMEOUT_SECONDS) as resp:
111
+ return resp.read()
112
+ except (urllib.error.URLError, OSError, TimeoutError):
113
+ return None
114
+
115
+
116
+ def _extract_binary(archive_bytes: bytes, asset_name: str, member_name: str, dest_path: Path) -> bool:
117
+ try:
118
+ if asset_name.endswith(".zip"):
119
+ with zipfile.ZipFile(io.BytesIO(archive_bytes)) as zf:
120
+ with zf.open(member_name) as src, open(dest_path, "wb") as dst:
121
+ shutil.copyfileobj(src, dst)
122
+ elif asset_name.endswith(".tar.gz"):
123
+ with tarfile.open(fileobj=io.BytesIO(archive_bytes), mode="r:gz") as tf:
124
+ member = tf.getmember(member_name)
125
+ extracted = tf.extractfile(member)
126
+ if extracted is None:
127
+ return False
128
+ with extracted, open(dest_path, "wb") as dst:
129
+ shutil.copyfileobj(extracted, dst)
130
+ else:
131
+ # osv-scanner: the downloaded asset already IS the binary.
132
+ dest_path.write_bytes(archive_bytes)
133
+ except (zipfile.BadZipFile, tarfile.TarError, KeyError, OSError):
134
+ return False
135
+ return True
136
+
137
+
138
+ def ensure_binary(name: str) -> str | None:
139
+ """Returns a usable path to `name` — an existing PATH install if
140
+ found, otherwise auto-downloads the pinned version into
141
+ ~/.codeintely/bin/ (reused on every later call/run). Returns None
142
+ only when neither a PATH install nor a download succeeds
143
+ (unsupported platform/architecture, no network, GitHub unreachable)
144
+ — callers treat that the same as "not installed."
145
+ """
146
+ existing = shutil.which(name)
147
+ if existing:
148
+ return existing
149
+
150
+ exe_name = f"{name}.exe" if sys.platform == "win32" else name
151
+ cached = CACHE_DIR / exe_name
152
+ if cached.is_file():
153
+ return str(cached)
154
+
155
+ system, arch = _os_arch()
156
+ if system is None or arch is None:
157
+ return None
158
+
159
+ base_url, asset_fn, is_raw_binary = _TOOLS[name]
160
+ asset = asset_fn(system, arch)
161
+ if asset is None:
162
+ return None
163
+
164
+ print(f"codeintely: downloading {name} (one-time, cached under {CACHE_DIR})...", file=sys.stderr)
165
+ data = _download(f"{base_url}/{asset}")
166
+ if data is None:
167
+ logger.error("Could not download %s from %s/%s", name, base_url, asset)
168
+ return None
169
+
170
+ CACHE_DIR.mkdir(parents=True, exist_ok=True)
171
+ member_name = exe_name if not is_raw_binary else asset
172
+ if not _extract_binary(data, asset, member_name, cached):
173
+ logger.error("Downloaded %s but couldn't extract/save it", name)
174
+ return None
175
+
176
+ if sys.platform != "win32":
177
+ cached.chmod(cached.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
178
+ return str(cached)
@@ -0,0 +1,76 @@
1
+ """`codeintely` CLI entry point (P2d). See pyproject.toml's [project.scripts]."""
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from . import __version__, output, scanners
8
+
9
+ # Windows consoles commonly default stdout to a legacy codepage (cp1252)
10
+ # that can't encode the ✓ in a clean report or non-ASCII bytes a scanner
11
+ # might legitimately emit (a file path, a finding message) — confirmed
12
+ # live: a bare `print()` of this module's own "No findings" line crashed
13
+ # with UnicodeEncodeError before this reconfigure. errors="replace" over a
14
+ # stricter mode since a scan report should never crash on output — a
15
+ # mangled character is a much smaller problem than the tool being unusable
16
+ # on a stock Windows terminal.
17
+ if hasattr(sys.stdout, "reconfigure"):
18
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
19
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
20
+
21
+ SEVERITY_ORDER = output.SEVERITY_ORDER
22
+
23
+
24
+ def build_parser() -> argparse.ArgumentParser:
25
+ parser = argparse.ArgumentParser(
26
+ prog="codeintely",
27
+ description="CodeIntely local security scanner — the same custom rule pack the GitHub App uses, run locally.",
28
+ )
29
+ parser.add_argument("--version", action="version", version=f"codeintely-cli {__version__}")
30
+ subparsers = parser.add_subparsers(dest="command", required=True)
31
+
32
+ scan = subparsers.add_parser("scan", help="Scan a local directory (default: current directory).")
33
+ scan.add_argument("path", nargs="?", default=".", help="Directory to scan (default: .)")
34
+ scan.add_argument("--format", choices=["text", "json"], default="text", help="Output format (default: text)")
35
+ scan.add_argument(
36
+ "--severity-threshold", choices=SEVERITY_ORDER, default="HIGH",
37
+ help="Exit non-zero only when a finding at or above this severity exists (default: HIGH) — matches "
38
+ "the same bar the GitHub App's PR check run uses.",
39
+ )
40
+ scan.add_argument("--no-color", action="store_true", help="Disable ANSI color in text output.")
41
+ return parser
42
+
43
+
44
+ def _exceeds_threshold(findings: list[dict], threshold: str) -> bool:
45
+ threshold_index = SEVERITY_ORDER.index(threshold)
46
+ return any(
47
+ SEVERITY_ORDER.index(f["severity"]) <= threshold_index
48
+ for f in findings if f["severity"] in SEVERITY_ORDER
49
+ )
50
+
51
+
52
+ def run_scan(args) -> int:
53
+ target_dir = Path(args.path).resolve()
54
+ if not target_dir.is_dir():
55
+ print(f"error: {target_dir} is not a directory", file=sys.stderr)
56
+ return 2
57
+
58
+ findings, skipped = scanners.run_all(target_dir)
59
+
60
+ if args.format == "json":
61
+ print(output.render_json(findings, skipped, target_dir))
62
+ else:
63
+ print(output.render_text(findings, skipped, target_dir, use_color=not args.no_color))
64
+
65
+ return 1 if _exceeds_threshold(findings, args.severity_threshold) else 0
66
+
67
+
68
+ def main() -> None:
69
+ parser = build_parser()
70
+ args = parser.parse_args()
71
+ if args.command == "scan":
72
+ sys.exit(run_scan(args))
73
+
74
+
75
+ if __name__ == "__main__":
76
+ main()
@@ -0,0 +1,63 @@
1
+ """Text/JSON reporting for the CLI. Stdlib-only ANSI coloring — no `rich`/
2
+ `click` dependency, keeping `pip install codeintely-cli` lean.
3
+ """
4
+
5
+ import json
6
+ import sys
7
+
8
+ SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW"]
9
+ _SEVERITY_COLOR = {"CRITICAL": "\033[1;31m", "HIGH": "\033[31m", "MEDIUM": "\033[33m", "LOW": "\033[90m"}
10
+ _RESET = "\033[0m"
11
+ _BOLD = "\033[1m"
12
+
13
+
14
+ def _supports_color() -> bool:
15
+ # Modern Windows terminals (10+) handle ANSI codes fine when attached
16
+ # to a real console; the only case to avoid coloring is output being
17
+ # redirected/piped (a file, `| less`, CI log capture), where isatty()
18
+ # is False on every platform.
19
+ return sys.stdout.isatty()
20
+
21
+
22
+ def render_text(findings: list[dict], skipped: list[str], target_dir, use_color: bool) -> str:
23
+ lines = []
24
+ color = use_color and _supports_color()
25
+
26
+ def c(code, text):
27
+ return f"{code}{text}{_RESET}" if color else text
28
+
29
+ lines.append(c(_BOLD, f"codeintely scan — {target_dir}"))
30
+ lines.append("")
31
+
32
+ if skipped:
33
+ lines.append(f"Skipped (not installed): {', '.join(skipped)} — install for fuller coverage.")
34
+ lines.append("")
35
+
36
+ if not findings:
37
+ lines.append(c("\033[32m", "No findings. ✓"))
38
+ return "\n".join(lines)
39
+
40
+ findings_sorted = sorted(
41
+ findings, key=lambda f: SEVERITY_ORDER.index(f["severity"]) if f["severity"] in SEVERITY_ORDER else 99
42
+ )
43
+ for f in findings_sorted:
44
+ sev = f["severity"]
45
+ sev_label = c(_SEVERITY_COLOR.get(sev, ""), f"[{sev}]")
46
+ location = f"{f['file_path']}:{f['line_number']}" if f.get("line_number") else f["file_path"]
47
+ lines.append(f"{sev_label} {c(_BOLD, f['rule_id'])} ({f['scanner']}) — {location}")
48
+ lines.append(f" {f['message']}")
49
+ lines.append("")
50
+
51
+ counts = {sev: sum(1 for f in findings if f["severity"] == sev) for sev in SEVERITY_ORDER}
52
+ summary = ", ".join(f"{counts[s]} {s}" for s in SEVERITY_ORDER if counts[s])
53
+ lines.append(c(_BOLD, f"{len(findings)} finding(s): {summary}"))
54
+ return "\n".join(lines)
55
+
56
+
57
+ def render_json(findings: list[dict], skipped: list[str], target_dir) -> str:
58
+ return json.dumps({
59
+ "target": str(target_dir),
60
+ "skipped_scanners": skipped,
61
+ "finding_count": len(findings),
62
+ "findings": findings,
63
+ }, indent=2)