Skip to content

ci: flag Flask imports with ast-grep - #730

Merged
uniqueg merged 4 commits into
devfrom
ci/flask-import-rule
Nov 7, 2026
Merged

uniqueg merged 4 commits into
devfrom
ci/flask-import-rule

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Closes #636

Summary

  • App rule flask-import (.ast-grep/rules/flask-import.yml, severity warning)
    • It flags imports of:
      • flask (including flask.globals.request_ctx) and Flask extensions (flask_*, e.g., flask_cors, flask_pymongo);
      • werkzeug;
      • Connexion's Flask modules (connexion.apis.flask_*, connexion.apps.flask_app, connexion.security.flask_*, also when imported by name from their package) and connexion.FlaskApp/FlaskApi (imported or as attributes), and wildcard imports from connexion;
      • connexion.request and connexion.context, as imports and as attributes.
    • Its note names the replacements:
      • foca.context.current_request();
      • current_token_info() and current_claims() of foca.security.auth;
      • foca.errors;
      • foca.testing;
      • foca.get_config();
      • tuples as responses.
    • It also says what's not covered: connexion.App, and attributes of an aliased connexion module.
    • In FOCA it covers examples/**. Apps set files: to their package and their tests.
  • FOCA baseline no-new-flask-internals (severity error, foca/**)
    • It has the same rule body.
    • It excludes the 19 modules that still import Flask in 0.22, as found by a scan of dev. A reviewer confirmed that none of these exclusions is stale.
    • Remove a module's exclusion once it is decoupled.
  • Rule tests: in .ast-grep/rule-tests/, one file per rule, with the same cases. The cases include parenthesized, aliased, relative and wildcard imports.
  • Docs
    • The contributing guide lists the rules and their severity per version.
    • The migration guide to 0.22 has a new section, "Finding Flask imports", on adopting the rule. It links the rule file in the repository, since the rule is not part of the Python package, and notes that apps switch their copy to error with the ASGI release.
    • The "Preparing for the ASGI release" page follows in docs: add "Preparing for the ASGI release" #637.

Deviation from the issue: the issue asked for a second rule with the same pattern for tests/**. Instead, apps list <pkg>/** and tests/** in the files: of the single flask-import rule. A separate rule would have been dead in FOCA, which has no example tests, and would have added a fourth copy of the rule body.

Verification

  • ast-grep test --skip-snapshot-tests: 9 passed.
  • ast-grep scan: exit 0, with 2 flask-import warnings, in examples/petstore/controllers.py and examples/petstore-access-control/controllers.py.
  • Probes:
    • A temporary foca/_probe.py with from werkzeug.exceptions import NotFound makes the scan fail (exit 1).
    • A temporary examples/_probe.py only warns (exit 0).
  • Every replacement named in the notes was checked by import.
  • pre-commit run --all-files: passed.
  • mkdocs build --strict: passed.
  • No package code changed, so the FOCA test suite and the proTES and cloud-registry suites are unaffected and were not rerun.
  • CI: all checks passed (CI passed, CodeQL, codecov, Read the Docs).
  • Sourcery: 3 findings (FlaskApp as an attribute, wildcard imports, the rule missing from the package), all fixed in a00609c; threads resolved.

Declined review findings

  • Flag from connexion import App: declined. FOCA 0.22 has no replacement for it yet. The ASGI release changes the app type, and docs: add "Preparing for the ASGI release" #637 documents that. The note says it isn't covered.
  • Flag attributes of an aliased connexion module (import connexion as cx; cx.request): declined. It's rare, and the note says it isn't covered.
  • Deduplicate the rule body with utils:, or add a sync check: declined. Apps would have to copy two files. The rule files and test files carry "keep in sync" comments instead.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 3 commits November 7, 2026 07:30
Add the app rules flask-import and flask-import-tests (severity warning
until the ASGI release; in FOCA scoped to the examples) and the FOCA
baseline rule no-new-flask-internals (error in foca/, excluding the
modules that still need Flask in 0.22). Each rule has rule tests.
Document the rules in the contributing guide and the migration guide
to 0.22.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cover Flask extensions and Connexion's Flask modules, merge the tests
rule into flask-import (apps list their package and tests in files:),
add rule tests for parenthesized, aliased and relative imports, and
correct the docs: the note names the replacements, and apps update
their copies to error with the ASGI release.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Also flag `from connexion.apps import flask_app` and the like, and
FlaskApp and FlaskApi from connexion. Mark the rule test files as
twins, and rewrap the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.22.0 milestone Nov 7, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Configuration

Review the two matching ast-grep rules together: they define which Flask, Werkzeug, and Connexion imports are reported in examples and prevented in FOCA, including the baseline exclusions.

  • .ast-grep/rules/flask-import.yml L1-58
  • .ast-grep/rules/no-new-flask-internals.yml L1-65

Documentation

Review the contributing and migration guidance together for rule scope, severity, adoption, and replacement recommendations.

  • docs/contributing/index.md L412-423
  • docs/migration-0.22.md L212-229

Tests

Check that the paired rule-test files cover the same accepted and rejected import forms, including aliases, parenthesized imports, relative imports, and wildcard imports.

  • .ast-grep/rule-tests/flask-import-test.yml L1-62
  • .ast-grep/rule-tests/no-new-flask-internals-test.yml L1-62

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (0b886fc) to head (a00609c).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #730   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           74        74           
  Lines         9325      9325           
=========================================
  Hits          9325      9325           
Flag Coverage Δ
test_unit 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 7, 2026 06:52

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path=".ast-grep/rules/flask-import.yml" line_range="48" />
<code_context>
+            kind: dotted_name
+            regex: ^(context|request|[Ff]lask\w*)$
+            stopBy: end
+    - pattern: connexion.request
+    - pattern: connexion.context
</code_context>
<issue_to_address>
**Flask class accesses pass scan**

When code uses `connexion.FlaskApp` or `connexion.FlaskApi` through an unaliased `import connexion`, the `connexion.request` and `connexion.context` patterns do not match those class accesses, so the migration scan produces no finding and the Flask API use remains until the ASGI migration.

Extend the attribute patterns to flag `connexion.FlaskApp` and `connexion.FlaskApi`.

Also at `.ast-grep/rules/no-new-flask-internals.yml:55-56`, `.ast-grep/rules/flask-import.yml:49`.
</issue_to_address>

### Comment 2
<location path=".ast-grep/rules/flask-import.yml" line_range="46" />
<code_context>
+            regex: ^connexion(\.[\w.]+)?$
+        - has:
+            kind: dotted_name
+            regex: ^(context|request|[Ff]lask\w*)$
+            stopBy: end
+    - pattern: connexion.request
</code_context>
<issue_to_address>
**Wildcard imports pass migration scan**

When an app uses a Connexion 2 wildcard import that exports Flask internals, the Connexion import checks have no named symbol to match, so the scan produces no warning and Flask-specific exports can remain in the app until Connexion 3 removes them.

Add a rule that flags wildcard imports from Connexion.

Also at `.ast-grep/rules/no-new-flask-internals.yml:52-54`.
</issue_to_address>

### Comment 3
<location path="docs/migration-0.22.md" line_range="223" />
<code_context>
+accessors above, `foca.errors`, `foca.testing`, `foca.get_config()`, and
+tuples as responses. Werkzeug stays installed, but don't import it.
+
+To adopt it, copy the file into your app's `.ast-grep/rules/`, set its
+`files:` to your package and tests (e.g., `my_app/**` and `tests/**`), and run
+`ast-grep scan` (e.g., via pre-commit). The rule has the severity `warning`
</code_context>
<issue_to_address>
**Installed package lacks rule**

When a user follows the migration guide using an installed FOCA distribution, the source distribution excludes `.ast-grep`, and the package configuration does not include it, so users cannot obtain the rule from the installed package and cannot adopt it as instructed.

Include the rule in FOCA distributions or direct users to a repository copy they can download.
</issue_to_address>

Linked issues

#636 ci: flag Flask imports with ast-grep · 5 of 6 met

# Requirement Status Notes
1 Flag the specified Flask, Werkzeug and Connexion imports in the app rule, with package and test coverage and the requested severities. ✅ Met The rule covers the requested import forms in FOCA’s examples. Apps can set its files: to both <pkg>/** and tests/**; that provides the requested coverage with one rule. The rule is warning-level, and the docs say apps should switch their copies to error for the ASGI release.
2 Name the FOCA 0.22 replacements in the app rule’s note. ✅ Met The note names request accessors, token and claim accessors, errors, testing utilities, configuration, and response tuples; the referenced FOCA accessors and utilities are present.
3 Add the FOCA baseline rule at error severity, excluding modules that still need Flask and removing exclusions as they are decoupled. ✅ Met The rule covers foca/**, lists the exclusions, and documents removing them when no longer needed.
4 Test both rules and have scans warn on imports in examples and fail on new imports in non-excluded FOCA modules. ✅ Met There is a test file for each rule with matching cases, and the rule scopes and severities implement the requested scan behavior. The PR also reports successful scans and probes.
5 Add the rule to the contributing docs and the preparation page, and document its severity per FOCA version. 🟡 Partly met The contributing guide and migration guide document the rule and severities, but the preparation page is not updated. The PR says, “The 'Preparing for the ASGI release' page follows in #637.”
6 Keep Werkzeug installed; this is a rule against importing it, not a dependency-removal change. ✅ Met The change adds the import rule and does not remove Werkzeug as a dependency.

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: .ast-grep/rules/flask-import.yml:48, .ast-grep/rules/flask-import.yml:46, docs/migration-0.22.md:223


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread .ast-grep/rules/flask-import.yml Resolved
Comment thread .ast-grep/rules/flask-import.yml Resolved
Comment thread docs/migration-0.22.md Resolved
Flag connexion.FlaskApp and connexion.FlaskApi as attributes and
wildcard imports from connexion, and link the rule file in the
migration guide, since it isn't part of the Python package.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Linked issues

#636 ci: flag Flask imports with ast-grep · 6 of 7 met

# Requirement Status Notes
1 Flag the requested Flask, Werkzeug and Connexion imports, with an app rule covering package and test files at the required severities. ✅ Met The flask-import rule covers the requested import forms, including Flask extensions, Connexion Flask modules, and Connexion request/context imports. Apps are instructed to set files: to both their package and tests; the rule is a warning in FOCA 0.22 and the ASGI release is documented as error.
2 Name the replacements for request data, exceptions, tests, configuration and responses in the rule note. ✅ Met The rule note names the FOCA accessors and modules, foca.get_config(), and tuple responses.
3 Add a no-new-flask-internals error rule for foca/**, excluding modules that still need Flask and removing exclusions as modules are decoupled. ✅ Met The baseline rule scopes to foca/**, lists the current exclusions, and instructs maintainers to remove exclusions once modules no longer need Flask.
4 Add ast-grep tests for both rules. ✅ Met There is a rule-test file for each rule, with matching cases.
5 Add the rule to the contributing documentation and the preparation page, and document its severity per FOCA version. 🟡 Partly met The contributing guide documents the rules and severities, and the migration guide explains adoption; the preparation page is deferred to #637 and is not updated here.
6 Ensure every replacement named in the rule notes exists in FOCA 0.22. ✅ Met The named accessors and get_config() are present, and the foca.errors and foca.testing APIs are provided.
7 Keep Werkzeug installed; make this a rule against importing it, not a dependency removal. ✅ Met The change adds import checks and does not remove a dependency.

Comment thread docs/contributing/index.md Resolved

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery assessment

Approved.

@uniqueg
uniqueg merged commit 2faa7de into dev Nov 7, 2026
65 of 83 checks passed
@uniqueg
uniqueg deleted the ci/flask-import-rule branch November 7, 2026 07:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ci: flag Flask imports with ast-grep

1 participant