Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Align codestyle #124

Merged
merged 8 commits into from
Sep 25, 2023
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
32 changes: 32 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: lint

on:
pull_request:
types: [opened, synchronize]
branches:
- master

env:
MATURIN_VERSION: 1.2.3
PYTHON_VERSION: 3.11

jobs:
lint:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ env.PYTHON_VERSION }}
uses: actions/setup-python@v4
with:
python-version: ${{ env.PYTHON_VERSION }}
- name: Install
run: |
python -m venv .venv
source .venv/bin/activate
pip install maturin==${{ env.MATURIN_VERSION }}
maturin develop --extras=lint
- name: Lint
run: |
source .venv/bin/activate
make lint
26 changes: 26 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
fail_fast: true

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.0.1
hooks:
- id: check-yaml
- id: check-toml
- id: end-of-file-fixer
- id: trailing-whitespace
- id: check-added-large-files

- repo: local
hooks:
- id: lint-python
name: Lint Python
entry: make lint-python
types: [python]
language: system
pass_filenames: false
- id: lint-rust
name: Lint Rust
entry: make lint-rust
types: [rust]
language: system
pass_filenames: false
1 change: 1 addition & 0 deletions .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
max_width = 120
67 changes: 67 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
.DEFAULT_GOAL := all
black = black granian tests
ruff = ruff granian tests

.PHONY: build-dev
build-dev:
@rm -f granian/*.so
maturin develop --extras test

.PHONY: format
format:
$(black)
$(ruff) --fix --exit-zero
cargo fmt

.PHONY: lint-python
lint-python:
$(ruff)
$(black) --check --diff

.PHONY: lint-rust
lint-rust:
cargo fmt --version
cargo fmt --all -- --check
cargo clippy --version
cargo clippy --tests -- \
-D warnings \
-W clippy::pedantic \
-W clippy::dbg_macro \
-W clippy::print_stdout \
-A clippy::cast-possible-truncation \
-A clippy::cast-possible-wrap \
-A clippy::cast-precision-loss \
-A clippy::cast-sign-loss \
-A clippy::declare-interior-mutable-const \
-A clippy::float-cmp \
-A clippy::fn-params-excessive-bools \
-A clippy::if-not-else \
-A clippy::inline-always \
-A clippy::manual-let-else \
-A clippy::match-bool \
-A clippy::match-same-arms \
-A clippy::missing-errors-doc \
-A clippy::missing-panics-doc \
-A clippy::module-name-repetitions \
-A clippy::must-use-candidate \
-A clippy::needless-pass-by-value \
-A clippy::similar-names \
-A clippy::single-match-else \
-A clippy::struct-excessive-bools \
-A clippy::too-many-arguments \
-A clippy::too-many-lines \
-A clippy::type-complexity \
-A clippy::unnecessary-wraps \
-A clippy::unused-self \
-A clippy::used-underscore-binding \
-A clippy::wrong-self-convention

.PHONY: lint
lint: lint-python lint-rust

.PHONY: test
test:
pytest -v test

.PHONY: all
all: format build-dev lint test
2 changes: 1 addition & 1 deletion granian/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from .server import Granian
from .server import Granian # noqa
1 change: 1 addition & 0 deletions granian/__main__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from granian.cli import cli


cli()
2 changes: 1 addition & 1 deletion granian/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.6.0"
__version__ = '0.6.0'
19 changes: 3 additions & 16 deletions granian/_granian.pyi
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
from typing import Any, Dict, List, Tuple, Optional
from typing import Any, Dict, List, Optional, Tuple

from ._types import WebsocketMessage


class ASGIScope:
def as_dict(self, root_path: str) -> Dict[str, Any]: ...


class RSGIHeaders:
def __contains__(self, key: str) -> bool: ...
def keys(self) -> List[str]: ...
def values(self) -> List[str]: ...
def items(self) -> List[Tuple[str]]: ...
def get(self, key: str, default: Any = None) -> Any: ...


class RSGIScope:
proto: str
http_version: str
Expand All @@ -29,12 +26,10 @@ class RSGIScope:
@property
def headers(self) -> RSGIHeaders: ...


class RSGIHTTPStreamTransport:
async def send_bytes(self, data: bytes): ...
async def send_str(self, data: str): ...


class RSGIHTTPProtocol:
async def __call__(self) -> bytes: ...
def response_empty(self, status: int, headers: List[Tuple[str, str]]): ...
Expand All @@ -43,25 +38,17 @@ class RSGIHTTPProtocol:
def response_file(self, status: int, headers: List[Tuple[str, str]], file: str): ...
def response_stream(self, status: int, headers: List[Tuple[str, str]]) -> RSGIHTTPStreamTransport: ...


class RSGIWebsocketTransport:
async def receive(self) -> WebsocketMessage: ...
async def send_bytes(self, data: bytes): ...
async def send_str(self, data: str): ...


class RSGIWebsocketProtocol:
async def accept(self) -> RSGIWebsocketTransport: ...
def close(self, status: Optional[int]) -> Tuple[int, bool]: ...


class RSGIProtocolError(RuntimeError):
...


class RSGIProtocolClosed(RuntimeError):
...

class RSGIProtocolError(RuntimeError): ...
class RSGIProtocolClosed(RuntimeError): ...

class WSGIScope:
def to_environ(self, environ: Dict[str, Any]) -> Dict[str, Any]: ...
23 changes: 9 additions & 14 deletions granian/_internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,21 @@
import re
import sys
import traceback

from types import ModuleType
from typing import Callable, List, Optional


def get_import_components(path: str) -> List[Optional[str]]:
return (re.split(r":(?![\\/])", path, 1) + [None])[:2]
return (re.split(r':(?![\\/])', path, 1) + [None])[:2]


def prepare_import(path: str) -> str:
path = os.path.realpath(path)

fname, ext = os.path.splitext(path)
if ext == ".py":
if ext == '.py':
path = fname
if os.path.basename(path) == "__init__":
if os.path.basename(path) == '__init__':
path = os.path.dirname(path)

module_name = []
Expand All @@ -27,26 +26,22 @@ def prepare_import(path: str) -> str:
path, name = os.path.split(path)
module_name.append(name)

if not os.path.exists(os.path.join(path, "__init__.py")):
if not os.path.exists(os.path.join(path, '__init__.py')):
break

if sys.path[0] != path:
sys.path.insert(0, path)

return ".".join(module_name[::-1])
return '.'.join(module_name[::-1])


def load_module(
module_name: str,
raise_on_failure: bool = True
) -> Optional[ModuleType]:
def load_module(module_name: str, raise_on_failure: bool = True) -> Optional[ModuleType]:
try:
__import__(module_name)
except ImportError:
if sys.exc_info()[-1].tb_next:
raise RuntimeError(
f"While importing '{module_name}', an ImportError was raised:"
f"\n\n{traceback.format_exc()}"
f"While importing '{module_name}', an ImportError was raised:" f"\n\n{traceback.format_exc()}"
)
elif raise_on_failure:
raise RuntimeError(f"Could not import '{module_name}'.")
Expand All @@ -58,9 +53,9 @@ def load_module(
def load_target(target: str) -> Callable[..., None]:
path, name = get_import_components(target)
path = prepare_import(path) if path else None
name = name or "app"
name = name or 'app'
module = load_module(path)
rv = module
for element in name.split("."):
for element in name.split('.'):
rv = getattr(rv, element)
return rv
12 changes: 4 additions & 8 deletions granian/_loops.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@
import os
import signal
import sys

from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple


class Registry:
__slots__ = ["_data"]
__slots__ = ['_data']

def __init__(self):
self._data: Dict[str, Callable[..., Any]] = {}
Expand All @@ -22,6 +21,7 @@ def register(self, key: str) -> Callable[[], Callable[..., Any]]:
def wrap(builder: Callable[..., Any]) -> Callable[..., Any]:
self._data[key] = builder
return builder

return wrap

def get(self, key: str) -> Callable[..., Any]:
Expand All @@ -31,18 +31,13 @@ def get(self, key: str) -> Callable[..., Any]:
raise RuntimeError(f"'{key}' implementation not available.")



class BuilderRegistry(Registry):
__slots__ = []

def __init__(self):
self._data: Dict[str, Tuple[Callable[..., Any], List[str]]] = {}

def register(
self,
key: str,
packages: Optional[List[str]] = None
) -> Callable[[], Callable[..., Any]]:
def register(self, key: str, packages: Optional[List[str]] = None) -> Callable[[], Callable[..., Any]]:
packages = packages or []

def wrap(builder: Callable[..., Any]) -> Callable[..., Any]:
Expand All @@ -56,6 +51,7 @@ def wrap(builder: Callable[..., Any]) -> Callable[..., Any]:
if implemented:
self._data[key] = (builder, loaded_packages)
return builder

return wrap

def get(self, key: str) -> Callable[..., Any]:
Expand Down
Loading
Loading