Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
200 changes: 200 additions & 0 deletions .github/scripts/check_markdown_snippets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
"""Type-check the Python snippets of the Markdown files with pyrefly.

Every ```python block in a Markdown file tracked by git, apart from the
changelogs, is checked against the installed workspace packages, so the READMEs
and MIGRATION.md cannot show code that does not match the API.

A block is the body of an async function, so it can use `await` and
`async with`. It imports what it uses, as the code a user copies has to. The
names a file's snippets share, such as the client its README creates once, are
declared in PRELUDES with their types. Their types are imported under private
aliases, so a snippet that uses a class without importing it still fails. A block fenced as ```python skip is not checked, for
example v2 code shown as "before" or a fragment that only shows a shape.

Run it from the repository root in an environment with every package and extra
installed:

uv sync --all-packages --all-extras
uv run python .github/scripts/check_markdown_snippets.py
"""

import json
import os
import re
import subprocess
import sys
import tempfile
from dataclasses import dataclass
from pathlib import Path

LANGUAGES = {"python", "py", "python3"}
FENCE = re.compile(r"^(?P<indent>\s*)(?P<fence>`{3,}|~{3,})(?P<info>.*)$")

PRELUDES = {
"MIGRATION.md": {
"client": "supabase.Client",
"url": "str",
"key": "str",
"my_storage": "supabase_auth.SyncSupportedStorage",
"account_id": "str",
},
"src/supabase/README.md": {"supabase": "supabase.Client"},
"src/auth/README.md": {"client": "supabase_auth.SyncSupabaseAuthClient"},
"src/postgrest/README.md": {"client": "postgrest.AsyncPostgrestClient"},
"src/realtime/README.md": {"client": "realtime.RealtimeClient"},
"src/storage/README.md": {"storage_client": "storage3.AsyncStorageClient"},
}

PYREFLY_CONFIG = """\
python-version = "3.12"

[errors]
deprecated = "error"
"""


@dataclass(frozen=True)
class Snippet:
markdown: str
first_line: int
lines: list[str]


def markdown_files() -> list[str]:
output = subprocess.run(
["git", "ls-files", "*.md"],
check=True,
capture_output=True,
text=True,
).stdout
return sorted(
path
for path in output.splitlines()
if Path(path).name != "CHANGELOG.md" and not Path(path).is_symlink()
)


def python_snippets(markdown: str) -> list[Snippet]:
snippets: list[Snippet] = []
lines = Path(markdown).read_text(encoding="utf-8").splitlines()
index = 0
while index < len(lines):
opening = FENCE.match(lines[index])
index += 1
if opening is None:
continue
fence = opening["fence"]
indent = len(opening["indent"])
words = opening["info"].split()
first_line = index + 1
body: list[str] = []
while index < len(lines):
closing = FENCE.match(lines[index])
index += 1
if (
closing is not None
and closing["fence"].startswith(fence)
and not closing["info"].strip()
):
break
line = lines[index - 1]
body.append(line[min(indent, len(line) - len(line.lstrip())) :])
if words and words[0] in LANGUAGES and "skip" not in words[1:]:
snippets.append(Snippet(markdown, first_line, body))
return snippets


def prelude(markdown: str) -> list[str]:
imports: list[str] = []
declarations: list[str] = []
for number, (name, type_path) in enumerate(PRELUDES.get(markdown, {}).items()):
module, _, type_name = type_path.rpartition(".")
if module:
alias = f"_Prelude{number}"
imports.append(f"from {module} import {type_name} as {alias}")
type_name = alias
declarations.append(f"{name}: {type_name}")
return [*imports, *declarations]


def module_source(snippet: Snippet) -> tuple[str, int]:
"""Return the module that wraps the snippet and the number of lines before
the snippet's first line."""
header = [
*prelude(snippet.markdown),
"",
"",
"async def _snippet() -> None:",
]
body = [f" {line}" if line.strip() else "" for line in snippet.lines]
if not any(line.strip() for line in body):
body = [" pass"]
return "\n".join([*header, *body, ""]), len(header)


def main() -> int:
snippets = [
snippet
for markdown in markdown_files()
for snippet in python_snippets(markdown)
]
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "pyrefly.toml").write_text(PYREFLY_CONFIG, encoding="utf-8")
modules: dict[str, tuple[Snippet, int]] = {}
for number, snippet in enumerate(snippets):
source, header_lines = module_source(snippet)
module = root / f"snippet_{number}.py"
module.write_text(source, encoding="utf-8")
modules[module.name] = (snippet, header_lines)

result = subprocess.run(
[
sys.executable,
"-m",
"pyrefly",
"check",
"--config",
str(root / "pyrefly.toml"),
"--output-format",
"json",
*(str(root / name) for name in modules),
],
check=False,
capture_output=True,
text=True,
)
try:
errors = json.loads(result.stdout)["errors"]
except (json.JSONDecodeError, KeyError):
sys.stderr.write(result.stdout + result.stderr)
return result.returncode or 1

located: list[tuple[str, int, str]] = []
for error in errors:
located_module = modules.get(Path(error["path"]).name)
if located_module is None:
located.append((error["path"], error["line"], error["description"]))
continue
snippet, header_lines = located_module
line = snippet.first_line + error["line"] - header_lines - 1
located.append(
(snippet.markdown, line, f"{error['description']} [{error['name']}]")
)

annotate = os.environ.get("GITHUB_ACTIONS") == "true"
for markdown, line, message in sorted(located):
if annotate:
print(f"::error file={markdown},line={line}::{message}")
else:
print(f"{markdown}:{line}: {message}")

if errors:
print(f"{len(errors)} errors in {len(snippets)} Python snippets.")
return 1
print(f"All {len(snippets)} Python snippets type-check.")
return 0


if __name__ == "__main__":
sys.exit(main())
24 changes: 22 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,24 @@ jobs:
done
check supabase --extra aiohttp

markdown-snippets:
name: Markdown snippets
runs-on: ubuntu-latest
steps:
- name: Clone Repository
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0

- name: Install uv
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.12"

- name: Install dependencies
run: uv sync --frozen --all-packages --all-extras

- name: Type-check the Python snippets of the Markdown files
run: uv run --frozen --no-sync python .github/scripts/check_markdown_snippets.py

test:
name: py${{ matrix.python-version }} | ${{ matrix.package }}${{ matrix.resolution == 'lowest-direct' && ' | lowest' || '' }}
needs: changes
Expand Down Expand Up @@ -192,7 +210,7 @@ jobs:

ci-passed:
name: CI passed
needs: [changes, lint, import-without-httpx, test]
needs: [changes, lint, import-without-httpx, markdown-snippets, test]
if: ${{ always() }}
runs-on: ubuntu-latest
steps:
Expand All @@ -201,10 +219,12 @@ jobs:
CHANGES: ${{ needs.changes.result }}
LINT: ${{ needs.lint.result }}
IMPORTS: ${{ needs.import-without-httpx.result }}
SNIPPETS: ${{ needs.markdown-snippets.result }}
TEST: ${{ needs.test.result }}
run: |
echo "changes=$CHANGES lint=$LINT imports=$IMPORTS test=$TEST"
echo "changes=$CHANGES lint=$LINT imports=$IMPORTS snippets=$SNIPPETS test=$TEST"
[ "$CHANGES" = success ] && [ "$LINT" = success ] && [ "$IMPORTS" = success ] \
&& [ "$SNIPPETS" = success ] \
&& { [ "$TEST" = success ] || [ "$TEST" = skipped ]; }

release-please:
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Setup and commands: [README.md § Local Development](README.md#local-development
- `make <pkg>.tests` runs pyrefly and pytest. For `auth`, `postgrest`, `storage` and `realtime`, pytest first starts Docker / Supabase CLI infra; `make stop-infra` when done.
- Fast loop for tests that need no infra: from `src/<pkg>`, `uv run --frozen --package <import name> pytest tests/<file>.py`.
- Code must run on Python 3.12, CI tests 3.12 to 3.15 ([ci.yml](.github/workflows/ci.yml)).
- `make snippets` type-checks every `python` code block of the Markdown files, apart from the changelogs, against the workspace. A block is the body of an async function and imports what it uses. Names a file's blocks share, like the client its README creates, are declared in `PRELUDES` of [check_markdown_snippets.py](.github/scripts/check_markdown_snippets.py). Fence v2 code shown as "before" as `python skip`.

## Public API

Expand Down
3 changes: 3 additions & 0 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ Names that mirror a wire format keep their wire spelling, for example the JWT cl
`ClientOptions`, `AsyncClientOptions`, their v2 names `SyncClientOptions` and `AClientOptions`, and the `supabase.lib.client_options` module are removed. `create_client`, `create_async_client`, `Client`, `AsyncClient` and their `create` methods take the settings as keyword-only arguments. Settings that apply to every service are arguments of their own. The settings of one service are grouped in an options class, passed in the argument named after the service.

```python
from supabase import AuthClientOptions, PostgrestClientOptions, StorageClientOptions
from supabase.httpx import create_client

client = create_client(
url,
key,
Expand Down
7 changes: 6 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ help::
@echo "Available commands"
@echo " help -- (default) print this message"

ci: ruff $(call FORALL_PKGS,tests)
ci: ruff snippets $(call FORALL_PKGS,tests)
help::
@echo " ci -- Run tests for all packages, the same way as CI does"

Expand All @@ -30,6 +30,11 @@ help::
@echo " stop-infra -- Stop all infra used by tests."
@echo " NOTE: run this command to ensure all containers are stopped after tests"

snippets:
uv run --all-packages --all-extras python .github/scripts/check_markdown_snippets.py
help::
@echo " snippets -- Type-check the Python snippets of the Markdown files"

pyrefly: $(call FORALL_PKGS,pyrefly)
help::
@echo " pyrefly -- Run pyrefly on all packages"
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ Python monorepo for all [Supabase](https://supabase.com) libraries.
> See [CONTRIBUTING.md](CONTRIBUTING.md) for details.

- [supabase](src/supabase/README.md)
- [realtime-py](src/realtime/README.md)
- [realtime](src/realtime/README.md)
- [supabase_functions](src/functions/README.md)
- [storage3](src/storage/README.md)
- [postgrest](src/postgrest/README.md)
- [supabase_auth](src/auth/README.md)
- [supabase_utils](src/utils/README.md)

Relevant links:

Expand Down
Loading
Loading