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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ on:
- '.github/workflows/codacy.yml'
- '.github/workflows/release.yml'
- '.github/workflows/lint-workflows.yml'
- '.github/workflows/types.yml'
- '.github/zizmor.yml'
- '.github/dependabot.yml'

Expand Down
47 changes: 47 additions & 0 deletions .github/workflows/types.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: Types

# pyright on the Python code: the tests, the scripts and the stubs, in strict mode with the rules of .vscode/settings.json, as Pylance shows
# in VS Code. An error or a warning fails the run. ./bin/check_types.sh runs the same, with the same versions.
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
workflow_dispatch:

# A new push to a pull request cancels the previous run. Other events get their own
# group so they are never cancelled or replaced.
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions:
contents: read

jobs:
pyright:
name: pyright
runs-on: ubuntu-24.04
timeout-minutes: 10

steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

- name: Setup Python
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: '3.12'
cache: pip
cache-dependency-path: |
tests/requirements.txt
docs/mkdocs/requirements.in

# pyright is the one of the requirements of the docs, with griffe, which a script of the docs imports
- name: Install the packages that the code imports
run: pip install -r tests/requirements.txt -r docs/mkdocs/requirements.in

- name: Check the types
run: python bin/check_types.py
9 changes: 8 additions & 1 deletion .vscode/extensions/status-bar-buttons/lint.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ const LINTS = [
description: 'actionlint and zizmor on .github',
sources: ['actionlint', 'zizmor'],
},
{
task: 'lint: types',
name: 'Types',
icon: 'symbol-class',
description: 'pyright on the tests, the scripts and the stubs',
sources: ['check_types'],
},
{
task: 'lint: examples',
name: 'Examples',
Expand Down Expand Up @@ -150,7 +157,7 @@ function createLintButton(context) {
const busy = LINTS.find(lint => running.isRunning(lint.task));
show({
text: busy ? `$(sync~spin) Lint ${busy.name}` : '$(checklist) Lint',
tooltip: busy ? busy.description : 'check the links, the spelling, the workflows or the examples',
tooltip: busy ? busy.description : 'check the links, the spelling, the workflows, the types or the examples',
// while one runs, as the other buttons: VS Code asks whether to stop it
command: busy ? { title: 'Lint', command: 'workbench.action.tasks.runTask', arguments: [busy.task] } : COMMAND,
waitsFor: busy ? undefined : running.blocker(LINTS.map(lint => lint.task)),
Expand Down
19 changes: 19 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,25 @@
"pattern": { "regexp": "^(.+):(\\d+): (.+)$", "file": 1, "line": 2, "message": 3 }
}
},
{
// pyright on the whole code, as .github/workflows/types.yml does: Pylance checks the same while it is edited
"label": "lint: types",
"type": "shell",
"command": "./bin/check_types.sh",
"problemMatcher": {
"owner": "check_types",
"source": "check_types",
"fileLocation": ["relative", "${workspaceFolder}"],
"pattern": {
"regexp": "^(.+\\.pyi?):(\\d+):(\\d+): (error|warning): (.+)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
},
{
// the code of the docs and of README.md against the stubs, the first step of "docs: build"
"label": "lint: examples",
Expand Down
91 changes: 91 additions & 0 deletions bin/check_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""Checks the types of the Python code of the repository with pyright, as Pylance does in VS Code: the tests, the scripts and the
stubs, with the rules of .vscode/settings.json, which are declared only there. An error or a warning fails it. The module is not
needed, the stubs of src/monero say what it has.

./bin/check_types.sh # installs what it needs and runs this
python3 bin/check_types.py # with tests/requirements.txt and docs/mkdocs/requirements.in installed, as CI does

CI runs it in .github/workflows/types.yml, with the pyright of docs/mkdocs/requirements.in.
"""

from __future__ import annotations

import json
import os
import re
import subprocess

Check notice on line 17 in bin/check_types.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

bin/check_types.py#L17

Consider possible security implications associated with the subprocess module.
import sys
import tempfile
from pathlib import Path
from typing import Any

ROOT: Path = Path(__file__).resolve().parent.parent
SETTINGS: Path = ROOT / ".vscode" / "settings.json"
PREFIX: str = "python.analysis."


def read_settings() -> dict[str, Any]:
"""The settings of VS Code, whose JSON has comments on their own lines and can have trailing commas."""
text: str = re.sub(r"^\s*//.*$", "", SETTINGS.read_text(encoding="utf-8"), flags=re.MULTILINE)
return json.loads(re.sub(r",(\s*[\]}])", r"\1", text))


def get_config(folder: str) -> dict[str, Any]:
"""The configuration of pyright that matches the settings of Pylance, for a file in the given folder: it is written in a
temporary one, as one in the repository would replace the settings in VS Code."""
settings: dict[str, Any] = read_settings()

def path(value: str) -> str:
return str(ROOT / value.replace("${workspaceFolder}/", ""))

# pyright ignores the absolute paths of "include" and "exclude"
def relative(value: str) -> str:
return os.path.relpath(path(value), os.path.realpath(folder))

config: dict[str, Any] = {
"include": [relative(".")],
"exclude": [relative(p) for p in settings[PREFIX + "exclude"]] + ["**/__pycache__", "**/node_modules"],
# and the root of the repository, which Pylance searches too: conftest.py imports tests.utils
"extraPaths": [path(p) for p in settings[PREFIX + "extraPaths"]] + [str(ROOT)],
"stubPath": path(settings[PREFIX + "stubPath"]),
"typeCheckingMode": settings[PREFIX + "typeCheckingMode"],
# the module is compiled, and it is not built to check the types
"reportMissingModuleSource": "none",
}
config.update(settings[PREFIX + "diagnosticSeverityOverrides"])
return config


def main() -> int:
with tempfile.TemporaryDirectory() as folder:
(Path(folder) / "pyrightconfig.json").write_text(json.dumps(get_config(folder)), encoding="utf-8")
command: list[str] = [sys.executable, "-m", "pyright", "--pythonpath", sys.executable, "--outputjson"]
run = subprocess.run(command, cwd=folder, capture_output=True, text=True)

Check failure on line 64 in bin/check_types.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

bin/check_types.py#L64

Detected subprocess function 'run' without a static string.

Check warning on line 64 in bin/check_types.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

bin/check_types.py#L64

subprocess call - check for execution of untrusted input.
try:
report: dict[str, Any] = json.loads(run.stdout[run.stdout.index("{"):])
except ValueError:
print(run.stdout + run.stderr, file=sys.stderr)
return 2

found: int = 0
for diagnostic in report.get("generalDiagnostics", []):
if diagnostic["severity"] == "information":
continue
start: dict[str, int] = diagnostic["range"]["start"]
file: Path = Path(diagnostic["file"])
name: Path = file.relative_to(ROOT) if file.is_relative_to(ROOT) else file
message: str = " ".join(line.strip() for line in diagnostic["message"].splitlines())
rule: str = f" ({diagnostic['rule']})" if "rule" in diagnostic else ""
print(f"{name}:{start['line'] + 1}:{start['character'] + 1}: {diagnostic['severity']}: {message}{rule}")
found += 1
files: int = report.get("summary", {}).get("filesAnalyzed", 0)
print(f"{files} files checked, {found} errors and warnings")
# pyright did not check anything: a wrong configuration, which would pass otherwise
if files == 0:
return 2
return 1 if found else 0


if __name__ == "__main__":
sys.exit(main())
20 changes: 20 additions & 0 deletions bin/check_types.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Checks the types of the Python code as .github/workflows/types.yml does, with bin/check_types.py. The versions of
# tests/requirements.txt and of docs/mkdocs/requirements.in, which has pyright, are installed in .cache, again when they change.
#
# ./bin/check_types.sh
set -euo pipefail

root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
tests="$root/tests/requirements.txt"
docs="$root/docs/mkdocs/requirements.in"

# in a folder of its own, not in a virtual environment: Debian and Ubuntu need python3-venv for one
packages="$root/.cache/types-$(cat "$tests" "$docs" | sha256sum | cut -c1-12)"
if [ ! -f "$packages/.installed" ]; then
rm -rf "$packages"
python3 -m pip install --quiet --disable-pip-version-check --target "$packages" -r "$tests" -r "$docs"
touch "$packages/.installed"
fi

PYTHONPATH="$packages" exec python3 "$root/bin/check_types.py"
Loading
Loading