Skip to main content

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

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

$ 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

$ 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

$ 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

$ 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

$ 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

$ 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

$ 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:

[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:

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

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

Metadata

Release files for cleargate 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cleargate 0.1.1
File Size Uploaded Provenance Actions
cleargate-0.1.1.tar.gz 119.7 kB Without provenance Details for cleargate-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cleargate 0.1.1
File Interpreter ABI Platform Actions
cleargate-0.1.1-py3-none-any.whl Python 3 none any Details for cleargate-0.1.1-py3-none-any.whl

Total release size: 246.9 kB

Release files / cleargate-0.1.1.tar.gz

Download URL cleargate-0.1.1.tar.gz
Size 119.7 kB
Tags Source
SHA-256 checksum
How to use checksums
56fd8b49694eb4227617d44471cb29eaa8e920d7bb4cfef2a3ce130205c4e14d
BLAKE2b-256 checksum
How to use checksums
0b111014ae08ad7bf56c0359f50eee41d3ecde0b53b02b99c5153bdd842ac258
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.5

Release files / cleargate-0.1.1-py3-none-any.whl

Download URL cleargate-0.1.1-py3-none-any.whl
Size 127.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4783c26e17326969c3fecdaf9bcc67227c11fff09990998295965be5c7da20bf
BLAKE2b-256 checksum
How to use checksums
3f003018f6352e337544ab27c7570ba8074af031c2125d3b4415c2ac7208e601
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.5

Security for cleargate 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page