Metadata-Version: 2.4
Name: cleargate
Version: 0.1.1
Summary: Find, explain, fix and plan SonarCloud-style issues locally, read PR findings, and keep a quality gate when the cloud scan is refused.
Project-URL: Homepage, https://github.com/Pandiyarajk/cleargate
Project-URL: Repository, https://github.com/Pandiyarajk/cleargate
Project-URL: Issues, https://github.com/Pandiyarajk/cleargate/issues
Project-URL: Changelog, https://github.com/Pandiyarajk/cleargate/blob/main/CHANGELOG.md
Author: Pandiyaraj Karuppasamy
License-Expression: MIT
License-File: LICENSE
Keywords: autofix,code-quality,github-actions,lint,linter,quality-gate,sarif,sonarcloud,sonarqube,static-analysis
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Testing
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: cognitive-complexity>=1.3
Provides-Extra: ai
Requires-Dist: anthropic>=0.40; extra == 'ai'
Provides-Extra: dev
Requires-Dist: black>=24.0; extra == 'dev'
Requires-Dist: build>=1.0; extra == 'dev'
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pylint>=3.0; extra == 'dev'
Requires-Dist: pytest-timeout>=2.3; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: twine>=4.0; extra == 'dev'
Description-Content-Type: text/markdown

<!-- cleargate README. Author: Pandiyaraj Karuppasamy | Date: Nov-23-2026 | Modified: Nov-23-2026 -->
# cleargate

Find, explain and fix SonarCloud-style issues on your own machine, before you
push. cleargate also reads a pull request's real SonarCloud findings, writes a
prioritised fix plan, estimates your lines of code against a plan limit, and
keeps a quality gate running when SonarCloud refuses to scan a pull request
(for example when an organisation is over its lines-of-code limit).

- **scan**: SonarCloud-style rules for Python, shell, Dockerfiles, CSS and
  JavaScript, with file, line, column and the offending code.
- **explain**: why a rule matters and how to fix it, offline, or with Claude
  (`--ai`).
- **fix**: safe automatic fixes, shown as a diff or applied.
- **plan**: a Markdown fix plan, most important rules first.
- **pr**: a pull request's SonarCloud findings, mapped to rules and explained.
- **loc**: a lines-of-code estimate and the configuration changes that free
  lines.
- **gate**: a fallback quality gate on new code, published as a GitHub check.

cleargate is not affiliated with, endorsed by or connected to SonarSource.
SonarCloud and SonarQube are trademarks of SonarSource SA. Rule keys such as
`python:S1244` are used only to point at the matching public rule.

## Install

```bash
pip install cleargate          # core
pip install "cleargate[ai]"    # adds optional Claude explanations and plans
```

Requires Python 3.11 or newer. `pr` and `gate --publish` use the GitHub CLI
(`gh`), logged in or with `GH_TOKEN` set. `--ai` needs `ANTHROPIC_API_KEY`;
without it cleargate prints one warning and uses the offline text.

## Quickstart

### scan

```console
$ cleargate scan .
app/main.py:6:10: CG-S1313 Hard-coded IP address 192.0.2.10; read it from configuration.
    SERVER = "192.0.2.10"
app/main.py:11:5: CG-S5145 Log call writes request-derived data (name); log a length, count or flag instead.
    log.info("reading %s", name)
tests/test_ratio.py:2:12: CG-S1244 Equality test on a float literal; compare with a tolerance (pytest.approx or math.isclose). [fixable]
    assert 1 / 4 == 0.25

3 issues found.
```

`--format text|json|sarif|md` picks the output; SARIF 2.1.0 carries rule
metadata and fingerprints for code-scanning tools. `--fail-on` sets the lowest
severity that makes the exit code 1. Silence one line with
`# cleargate: ignore[CG-S1313]`.

### explain

```console
$ cleargate explain S1244
CG-S1244: Floating point numbers should not be tested for equality
Severity: major   Category: reliability

Why it matters:
Floating point arithmetic rounds, so 0.1 + 0.2 is not exactly 0.3 and an exact
comparison can fail on one machine and pass on another. ...

Noncompliant:
    assert score == 0.2

Compliant:
    assert score == pytest.approx(0.2)
```

The rule can be given as `CG-S1244`, `S1244` or `python:S1244`. Add `--ai` for
an explanation from Claude; only the rule text and a short snippet are sent.

### fix

```console
$ cleargate fix .
--- a/tests/test_ratio.py
+++ b/tests/test_ratio.py
@@ -1,2 +1,3 @@
+import pytest
 def test_ratio():
-    assert 1 / 4 == 0.25
+    assert 1 / 4 == pytest.approx(0.25)
1 finding(s) in 1 file(s) can be fixed.

$ cleargate fix . --apply
```

`--diff` is the default and changes nothing. `--apply` writes a file only when
every fix for it succeeded and, for Python, the result still parses.
`--rule ID` limits the fixers. Fixers that can change behaviour (JavaScript
`var`, the Dockerfile pip flag) run only with `--unsafe`.

### plan

```console
$ cleargate plan . -o plan.md
$ head plan.md
# cleargate fix plan

3 finding(s) across 3 rule(s); 1 can be fixed automatically.

## Security

### 1. CG-S1313: Using hardcoded IP addresses is security-sensitive (minor, 1 finding)

Why: An IP address in code ties the program to one network, leaks internal topology ...
Fix: Read real hosts from configuration.
```

Security comes first, then reliability, then maintainability; within each,
the most severe rules, and among those the rules with the most findings. Each
rule lists its files and lines, and the `cleargate fix --rule` command when it
can be fixed automatically. `--from-pr owner/repo#123` merges that pull
request's SonarCloud findings into the plan; `--ai` appends Claude's suggested
approach. `-o -` prints to stdout.

### pr

```console
$ cleargate pr owner/repo 123
1a2b3c4  issues  Quality Gate failed
app/main.py:11:5: CG-S5145 (Logging should not be vulnerable to injection attacks)
    Change this code to not log user-controlled data.
    > log.info("reading %s", name)

1 finding(s), 1 also found by a local scan
```

Each annotation from the SonarCloud check run is mapped to a catalogue rule
(by rule key, phrase or wording); findings that match nothing are reported as
`CG-UNKNOWN`. When the same rule fires locally on the same line, the finding
gets the local column and fixable flag. `--sha` reads another commit and
`--root` points at the checkout used for snippets.

When SonarCloud cancelled the analysis or reported "analysis failed" with no
annotations, `pr` prints `sonar-rejected`, the likely cause (such as the
organisation's line limit) and the fixes, and exits 3.

### loc

```console
$ cleargate loc . --limit 100000
Estimated ncloc (sonar.sources minus sonar.tests and exclusions):
  python    92,400
  TOTAL     92,400
  limit    100,000  (92.4% used, headroom 7,600)

Suggestions:
  undeclared-tests: app/tests saves 9,260 lines (41 files)
    sonar.tests += app/tests; sonar.exclusions += app/tests/**
```

The estimate follows `sonar-project.properties` (`sonar.sources`,
`sonar.tests`, `sonar.exclusions`). It finds test folders that sit under
`sonar.sources` but are not declared as tests, and generated or vendored code.
`--ref` counts a git ref instead of the working tree; `--write` applies the
suggested properties change.

### gate

```console
$ cleargate gate --base origin/main
a.py:4:12: CG-S1244 Equality test on a float literal; compare with a tolerance (pytest.approx or math.isclose).
    assert 1 / 4 == 0.25
a.py:5:10: CG-S1313 Hard-coded IP address 192.0.2.1; read it from configuration.
    SERVER = "192.0.2.1"

2 issues found.

Gate failed: Security B, Reliability C, Maintainability A (fails at B)
```

The fallback gate scans only the lines your branch changes, rates them the way
SonarCloud rates new code (one major bug gives Reliability C, one minor
vulnerability gives Security B) and fails at `--fail-on` (default B).
`--publish` posts the result as a GitHub check run named "cleargate gate" with
one annotation per finding; `--sarif` writes a SARIF file. `--auto` runs only
when the SonarCloud check on the pull request was rejected.

### rules and init-config

`cleargate rules` lists the catalogue (`--category`, `--language`,
`--search`). `cleargate init-config --ruff` prints a ruff `extend-select` that
catches several of these rules in the editor, and `--sonar` prints a
`sonar-project.properties` with a separate `sonar.tests` scope.

## Rules

`cleargate rules` lists 54 rules. The ones marked "local" have a detector:

| Area | Detected locally |
|---|---|
| Security | log injection (S5145), clear-text HTTP (S5332), hard-coded IPs (S1313), hidden Unicode tag characters, `pip install` running setup scripts (S6505) |
| Reliability | float equality (S1244) |
| Maintainability | cognitive complexity (S3776), duplicated literals (S1192), regex backtracking (S5852, S6019), undocumented FastAPI status codes (S6352), composite asserts, malformed suppression comments |
| Shell, Docker | `[` instead of `[[` in bash, consecutive `RUN` steps |
| CSS, JavaScript | duplicated selectors, `word-break: break-word`, `var`, global `parseInt`/`isNaN` |

The other rules are catalogue entries: `explain`, `plan` and `pr` use them to
explain findings that SonarCloud reports but cleargate does not detect itself.

## Configuration

Settings live in `pyproject.toml`:

```toml
[tool.cleargate]
select = []                        # only these rule ids (empty: all)
ignore = ["CG-S3776"]              # never report these
exclude = ["migrations/**"]        # paths to skip
fail_on = "major"                  # scan: lowest failing severity
duplicate_literal_min = 3          # S1192: uses before a literal is reported
duplicate_literal_in_tests = false # S1192: also check test files
complexity_max = 15                # S3776 threshold
allowed_hosts = ["localhost"]      # S5332: hosts allowed over http
allowed_ips = []                   # S1313: added to 127.0.0.1, ::1, 0.0.0.0, ::
loc_limit = 100000                 # default --limit for loc
sonar_check_name = "SonarCloud Code Analysis"
ai_model = "claude-sonnet-5-5"
ai_max_tokens = 800
```

## Exit codes

| Code | Meaning |
|---|---|
| 0 | clean, the gate passed, or nothing to fix |
| 1 | findings at or above the fail level, a failed gate, or fixes available (`fix --diff`) |
| 2 | a usage or environment problem (bad option, `gh` missing, unknown rule) |
| 3 | SonarCloud rejected the pull request's scan |

## GitHub Actions

Run the fallback gate next to the SonarCloud check. With `--auto` it does
nothing while SonarCloud is scanning normally, and takes over when the scan is
rejected:

```yaml
name: cleargate
on:
  pull_request:

permissions:
  checks: write
  contents: read

jobs:
  gate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install cleargate
      - name: Fallback quality gate
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: >
          cleargate gate --auto --publish
          --repo ${{ github.repository }}
          --pr ${{ github.event.pull_request.number }}
          --base origin/${{ github.base_ref }}
```

`--auto` reads the SonarCloud check on the pull request head, so run this job
after that check has finished (for example in a later job, or on a
`check_run: completed` trigger) if the two race.

## Development

```bash
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev,ai]"
pytest
```

`scripts/release_gate.ps1` runs the dash check, ruff, black, pylint, mypy, the
tests, the build and `twine check`.

## License

MIT
