Skip to content

Commit

Permalink
Add ruff linter
Browse files Browse the repository at this point in the history
  • Loading branch information
gi0baro committed Oct 9, 2024
1 parent 6c58b96 commit c16034d
Show file tree
Hide file tree
Showing 107 changed files with 6,258 additions and 6,979 deletions.
30 changes: 30 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: lint

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

env:
PYTHON_VERSION: 3.12

jobs:
lint:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ env.PYTHON_VERSION }}
uses: actions/setup-python@v5
with:
python-version: ${{ env.PYTHON_VERSION }}
- name: Install uv
uses: astral-sh/setup-uv@v3
- name: Install dependencies
run: |
uv sync --dev
- name: Lint
run: |
source .venv/bin/activate
make lint
3 changes: 3 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ on:
tags-ignore:
- "**"
pull_request:
types: [opened, synchronize]
branches:
- master

jobs:
Linux:
Expand Down
19 changes: 19 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
.DEFAULT_GOAL := all
pysources = emmett tests

.PHONY: format
format:
ruff check --fix $(pysources)
ruff format $(pysources)

.PHONY: lint
lint:
ruff check $(pysources)
ruff format --check $(pysources)

.PHONY: test
test:
pytest -v tests

.PHONY: all
all: format lint test
2 changes: 1 addition & 1 deletion emmett/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@
from .http import redirect
from .locals import T, now, request, response, session, websocket
from .orm import Field
from .pipeline import Pipe, Injector
from .pipeline import Injector, Pipe
from .routing.urls import url
11 changes: 6 additions & 5 deletions emmett/__main__.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
# -*- coding: utf-8 -*-
"""
emmett.__main__
----------------
emmett.__main__
----------------
Alias for Emmett CLI.
Alias for Emmett CLI.
:copyright: 2014 Giovanni Barillari
:license: BSD-3-Clause
:copyright: 2014 Giovanni Barillari
:license: BSD-3-Clause
"""

from emmett.cli import main


main(as_module=True)
25 changes: 10 additions & 15 deletions emmett/_internal.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
# -*- coding: utf-8 -*-
"""
emmett._internal
----------------
emmett._internal
----------------
Provides internally used helpers and objects.
Provides internally used helpers and objects.
:copyright: 2014 Giovanni Barillari
:copyright: 2014 Giovanni Barillari
Several parts of this code comes from Flask and Werkzeug.
:copyright: (c) 2014 by Armin Ronacher.
Several parts of this code comes from Flask and Werkzeug.
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD-3-Clause
:license: BSD-3-Clause
"""

from __future__ import annotations
Expand All @@ -23,18 +23,13 @@
#: monkey patches
def _pendulum_to_datetime(obj):
return datetime.datetime(
obj.year, obj.month, obj.day,
obj.hour, obj.minute, obj.second, obj.microsecond,
tzinfo=obj.tzinfo
obj.year, obj.month, obj.day, obj.hour, obj.minute, obj.second, obj.microsecond, tzinfo=obj.tzinfo
)


def _pendulum_to_naive_datetime(obj):
obj = obj.in_timezone('UTC')
return datetime.datetime(
obj.year, obj.month, obj.day,
obj.hour, obj.minute, obj.second, obj.microsecond
)
obj = obj.in_timezone("UTC")
return datetime.datetime(obj.year, obj.month, obj.day, obj.hour, obj.minute, obj.second, obj.microsecond)


def _pendulum_json(obj):
Expand Down
58 changes: 25 additions & 33 deletions emmett/_reloader.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
# -*- coding: utf-8 -*-
"""
emmett._reloader
----------------
emmett._reloader
----------------
Provides auto-reloading utilities.
Provides auto-reloading utilities.
:copyright: 2014 Giovanni Barillari
:copyright: 2014 Giovanni Barillari
Adapted from werkzeug code (http://werkzeug.pocoo.org)
:copyright: (c) 2015 by Armin Ronacher.
Adapted from werkzeug code (http://werkzeug.pocoo.org)
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD-3-Clause
:license: BSD-3-Clause
"""

import multiprocessing
Expand All @@ -19,12 +19,10 @@
import subprocess
import sys
import time

from itertools import chain
from typing import Optional

import click

from emmett_core._internal import locate_app
from emmett_core.server import run as _server_run

Expand All @@ -37,7 +35,7 @@ def _iter_module_files():
for module in list(sys.modules.values()):
if module is None:
continue
filename = getattr(module, '__file__', None)
filename = getattr(module, "__file__", None)
if filename:
old = None
while not os.path.isfile(filename):
Expand All @@ -58,15 +56,9 @@ def _get_args_for_reloading():
"""
rv = [sys.executable]
py_script = sys.argv[0]
if (
os.name == 'nt' and not os.path.exists(py_script) and
os.path.exists(py_script + '.exe')
):
py_script += '.exe'
if (
os.path.splitext(rv[0])[1] == '.exe' and
os.path.splitext(py_script)[1] == '.exe'
):
if os.name == "nt" and not os.path.exists(py_script) and os.path.exists(py_script + ".exe"):
py_script += ".exe"
if os.path.splitext(rv[0])[1] == ".exe" and os.path.splitext(py_script)[1] == ".exe":
rv.pop(0)
rv.append(py_script)
rv.extend(sys.argv[1:])
Expand All @@ -82,8 +74,7 @@ class ReloaderLoop(object):
_sleep = staticmethod(time.sleep)

def __init__(self, extra_files=None, interval=1):
self.extra_files = set(
os.path.abspath(x) for x in extra_files or ())
self.extra_files = {os.path.abspath(x) for x in extra_files or ()}
self.interval = interval

def run(self):
Expand All @@ -94,10 +85,10 @@ def restart_with_reloader(self):
but running the reloader thread.
"""
while 1:
click.secho('> Restarting (%s mode)' % self.name, fg='yellow')
click.secho("> Restarting (%s mode)" % self.name, fg="yellow")
args = _get_args_for_reloading()
new_environ = os.environ.copy()
new_environ['EMMETT_RUN_MAIN'] = 'true'
new_environ["EMMETT_RUN_MAIN"] = "true"

# a weird bug on windows. sometimes unicode strings end up in the
# environment and subprocess.call does not like this, encode them
Expand All @@ -107,20 +98,20 @@ def restart_with_reloader(self):
# if isinstance(value, unicode):
# new_environ[key] = value.encode('iso-8859-1')

exit_code = subprocess.call(args, env=new_environ)
exit_code = subprocess.call(args, env=new_environ) # noqa: S603
if exit_code != 3:
return exit_code

def trigger_reload(self, process, filename):
filename = os.path.abspath(filename)
click.secho('> Detected change in %r, reloading' % filename, fg='cyan')
click.secho("> Detected change in %r, reloading" % filename, fg="cyan")
os.kill(process.pid, signal.SIGTERM)
process.join()
sys.exit(3)


class StatReloaderLoop(ReloaderLoop):
name = 'stat'
name = "stat"

def run(self, process):
mtimes = {}
Expand All @@ -141,18 +132,18 @@ def run(self, process):


reloader_loops = {
'stat': StatReloaderLoop,
"stat": StatReloaderLoop,
}

reloader_loops['auto'] = reloader_loops['stat']
reloader_loops["auto"] = reloader_loops["stat"]


def run_with_reloader(
interface,
app_target,
host='127.0.0.1',
host="127.0.0.1",
port=8000,
loop='auto',
loop="auto",
log_level=None,
log_access=False,
threads=1,
Expand All @@ -161,14 +152,15 @@ def run_with_reloader(
ssl_keyfile: Optional[str] = None,
extra_files=None,
interval=1,
reloader_type='auto'
reloader_type="auto",
):
reloader = reloader_loops[reloader_type](extra_files, interval)
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))

try:
if os.environ.get('EMMETT_RUN_MAIN') == 'true':
if os.environ.get("EMMETT_RUN_MAIN") == "true":
from .app import App

# FIXME: find a better way to have app files in stat checker
locate_app(App, *app_target)

Expand All @@ -185,7 +177,7 @@ def run_with_reloader(
"threading_mode": threading_mode,
"ssl_certfile": ssl_certfile,
"ssl_keyfile": ssl_keyfile,
}
},
)
process.start()
reloader.run(process)
Expand Down
22 changes: 11 additions & 11 deletions emmett/_shortcuts.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
# -*- coding: utf-8 -*-
"""
emmett._shortcuts
-----------------
emmett._shortcuts
-----------------
Some shortcuts
Some shortcuts
:copyright: 2014 Giovanni Barillari
:license: BSD-3-Clause
:copyright: 2014 Giovanni Barillari
:license: BSD-3-Clause
"""

import hashlib

from uuid import uuid4

hashlib_md5 = lambda s: hashlib.md5(bytes(s, 'utf8'))
hashlib_sha1 = lambda s: hashlib.sha1(bytes(s, 'utf8'))

hashlib_md5 = lambda s: hashlib.md5(bytes(s, "utf8"))
hashlib_sha1 = lambda s: hashlib.sha1(bytes(s, "utf8"))
uuid = lambda: str(uuid4())


def to_bytes(obj, charset='utf8', errors='strict'):
def to_bytes(obj, charset="utf8", errors="strict"):
if obj is None:
return None
if isinstance(obj, (bytes, bytearray, memoryview)):
return bytes(obj)
if isinstance(obj, str):
return obj.encode(charset, errors)
raise TypeError('Expected bytes')
raise TypeError("Expected bytes")


def to_unicode(obj, charset='utf8', errors='strict'):
def to_unicode(obj, charset="utf8", errors="strict"):
if obj is None:
return None
if not isinstance(obj, bytes):
Expand Down
Loading

0 comments on commit c16034d

Please sign in to comment.