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
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root=true

[*]
indent_style=space
indent_size=4
end_of_line=lf
charset=utf-8
trim_trailing_whitespace=true
insert_final_newline=true

[{*.yml,*.yaml,*.json}]
indent_size=2
4 changes: 0 additions & 4 deletions .isort.cfg

This file was deleted.

65 changes: 0 additions & 65 deletions pre-commit.githook

This file was deleted.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ requires-python = '~=3.12'
ursh = 'ursh.cli.core:cli'

[project.optional-dependencies]
dev = ['pytest', 'isort']
dev = ['pytest', 'ruff']

[project.urls]
Issues = 'https://github.com/indico/ursh/issues'
Expand Down
150 changes: 150 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
target-version = 'py312'
line-length = 120

[lint]
preview = true

select = [
'E', # pycodestyle (errors)
'W', # pycodestyle (warnings)
'F', # pyflakes
'N', # pep8-naming
'Q', # flake8-quotes
'RUF', # ruff
'UP', # pyupgrade
'D', # pydocstyle
'S', # flake8-bandit
'C4', # flake8-comprehensions
'INT', # flake8-gettext
'LOG', # flake8-logging
'G', # flake8-logging-format
'B', # flake8-bugbear
'A001', # flake8-builtins
'COM', # flake8-commas
'T10', # flake8-debugger
'EXE', # flake8-executable
'ISC', # flake8-implicit-str-concat
'PIE', # flake8-pie
'PT', # flake8-pytest-style
'RSE', # flake8-raise
'RET504', # flake8-return
'SIM', # flake8-simplify
'TID', # flake8-tidy-imports
'PGH', # pygrep-hooks
'PL', # pylint
'TRY', # tryceratops
'PERF', # perflint
'FURB', # refurb
'I', # isort
]
ignore = [
'E226', # allow omitting whitespace around arithmetic operators
'E731', # allow assigning lambdas (it's useful for single-line functions defined inside other functions)
'N818', # not all our exceptions are errors
'RUF012', # ultra-noisy and dicts in classvars are very common
'RUF015', # not always more readable, and we don't do it for huge lists
'RUF022', # autofix messes up our formatting instead of just sorting
'UP038', # it looks kind of weird and it slower than a tuple
'D205', # too many docstrings which have no summary line
'D301', # https://github.com/astral-sh/ruff/issues/8696
'D1', # we have way too many missing docstrings :(
'D400', # weird with openapi docstrings
'D412', # we do not use section, and in click docstrings those blank lines are useful
'S101', # we use asserts outside tests, and do not run python with `-O` (also see B011)
'S113', # enforcing timeouts would likely require config in some places - maybe later
'S311', # false positives, it does not care about the context
'S324', # all our md5/sha1 usages are for non-security purposes
'S404', # useless, triggers on *all* subprocess imports
'S403', # there's already a warning on using pickle, no need to have one for the import
'S405', # we don't use lxml in unsafe ways
'S603', # useless, triggers on *all* subprocess calls: https://github.com/astral-sh/ruff/issues/4045
'S607', # we trust the PATH to be sane
'B011', # we don't run python with `-O` (also see S101)
'B904', # possibly useful but too noisy
'PIE807', # `lambda: []` is much clearer for `load_default` in schemas
'PT011', # very noisy
'PT015', # nice for tests but not so nice elsewhere
'PT018', # ^ likewise
'SIM102', # sometimes nested ifs are more readable
'SIM103', # sometimes this is more readable (especially when checking multiple conditions)
'SIM105', # try-except-pass is faster and people are used to it
'SIM108', # noisy ternary
'SIM114', # sometimes separate ifs are more readable (especially if they just return a bool)
'SIM117', # nested context managers may be more readable
'PLC0415', # local imports are there for a reason
'PLC2701', # some private imports are needed
'PLR09', # too-many-<whatever> is just noisy
'PLR0913', # very noisy
'PLR2004', # extremely noisy and generally annoying
'PLR6201', # sets are faster (by a factor of 10!) but it's noisy and we're in nanoseconds territory
'PLR6301', # extremely noisy and generally annoying
'PLW0108', # a lambda often makes it more clear what you actually want
'PLW1510', # we often do not care about the status code of commands
'PLW1514', # we expect UTF8 environments everywhere
'PLW1641', # false positives with SA comparator classes
'PLW2901', # noisy and reassigning to the loop var is usually intentional
'TRY002', # super noisy, and those exceptions are pretty exceptional anyway
'TRY003', # super noisy and also useless w/ werkzeugs http exceptions
'TRY300', # kind of strange in many cases
'TRY301', # sometimes doing that is actually useful
'TRY400', # not all exceptions need exception logging
'PERF203', # noisy, false positives, and not applicable for 3.11+
'FURB113', # less readable
'FURB140', # less readable and actually slower in 3.12+
'PLW0603', # globals are fine here
'COM812', # formatter conflict
'ISC001', # formatter conflict
]

extend-safe-fixes = [
'RUF005', # we typically don't deal with objects overriding `__add__` or `__radd__`
'C4', # they seem pretty safe
'UP008', # ^ likewise
'D200', # ^ likewise
'D400', # ^ likewise
'PT014', # duplicate test case parametrizations are never intentional
'RSE102', # we do not use `raise func()` (with `func` returning the exception instance)
'RET504', # looks pretty safe
'SIM110', # ^ likewise
'PERF102', # ^ likewise
]

[format]
quote-style = 'single'

[lint.flake8-builtins]
builtins-ignorelist = ['id', 'format', 'input', 'type', 'credits']

[lint.flake8-pytest-style]
fixture-parentheses = false
mark-parentheses = false
parametrize-names-type = 'tuple'
parametrize-values-type = 'tuple'
parametrize-values-row-type = 'tuple'

[lint.flake8-tidy-imports]
ban-relative-imports = 'all'

[lint.flake8-quotes]
inline-quotes = 'single'
multiline-quotes = 'double'
docstring-quotes = 'double'
avoid-escape = true

[lint.pep8-naming]
classmethod-decorators = [
'classmethod',
'declared_attr',
'expression',
'comparator',
]

[lint.pydocstyle]
convention = 'pep257'

[lint.ruff]
parenthesize-tuple-in-subscript = true

[lint.per-file-ignores]
# signals use wildcard imports to expose everything in `indico.core.signals`
'ursh/cli/*.py' = ['D401']
2 changes: 0 additions & 2 deletions setup.cfg

This file was deleted.

8 changes: 2 additions & 6 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,5 @@ passenv = URSH_TEST_DATABASE_URI

[testenv:style]
skip_install = true
deps =
flake8
isort
commands =
isort --diff --check-only ursh
flake8 ursh/
deps = ruff
commands = ruff check --output-format github .
1 change: 0 additions & 1 deletion ursh/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from ursh.core.db import db


__version__ = '0.0.dev0'
__all__ = ('db',)
9 changes: 4 additions & 5 deletions ursh/blueprints/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from .api.blueprint import bp as api
from .misc import bp as misc
from .redirection import bp as redirection
from ursh.blueprints.api.blueprint import bp as api
from ursh.blueprints.misc import bp as misc
from ursh.blueprints.redirection import bp as redirection


__all__ = [redirection, api, misc]
__all__ = ['redirection', 'api', 'misc']
16 changes: 11 additions & 5 deletions ursh/blueprints/api/blueprint.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
from datetime import datetime, timezone
from datetime import UTC, datetime

from flask import Blueprint, g, request
from sqlalchemy.exc import DataError, SQLAlchemyError
from werkzeug.exceptions import BadRequest, Conflict, MethodNotAllowed, NotFound

from ursh import db
from ursh.blueprints.api.handlers import (create_error_json, handle_bad_requests, handle_conflict, handle_db_errors,
handle_internal_exceptions, handle_method_not_allowed, handle_not_found)
from ursh.blueprints.api.handlers import (
create_error_json,
handle_bad_requests,
handle_conflict,
handle_db_errors,
handle_internal_exceptions,
handle_method_not_allowed,
handle_not_found,
)
from ursh.blueprints.api.resources import TokenResource, URLResource
from ursh.models import Token


bp = Blueprint('urls', __name__, url_prefix='/api')

tokens_view = TokenResource.as_view('tokens')
Expand All @@ -35,7 +41,7 @@ def authorize_request():
if token is None or token.is_blocked:
return error_json
token.token_uses = Token.token_uses + 1
token.last_access = datetime.now(timezone.utc)
token.last_access = datetime.now(UTC)
db.session.commit()

g.token = token
Expand Down
6 changes: 3 additions & 3 deletions ursh/blueprints/api/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def handle_conflict(error):


def handle_internal_exceptions(error):
current_app.logger.exception('Unexpected error')
current_app.logger.exception('Unexpected error') # noqa: LOG004
return create_error_json(500, 'internal-error', 'Sorry, something went wrong')


Expand All @@ -31,8 +31,8 @@ def create_error_json(status_code, error_code, message, **kwargs):
'status': status_code,
'error': {
'code': error_code,
'description': message
}
'description': message,
},
}
message_dict['error'].update(kwargs)
return jsonify(message_dict), status_code
9 changes: 7 additions & 2 deletions ursh/blueprints/api/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from flask import Response, current_app, g
from flask_apispec import MethodResource, marshal_with, use_kwargs
from marshmallow import fields
from sqlalchemy.exc import IntegrityError
from werkzeug.exceptions import BadRequest, Conflict, MethodNotAllowed, NotFound

Expand Down Expand Up @@ -31,6 +32,7 @@ class TokenResource(MethodResource):
401:
description: not authorized
"""

@admin_only
@marshal_with(TokenSchema, code=201)
@use_kwargs(TokenSchema)
Expand Down Expand Up @@ -270,8 +272,7 @@ def get(self, api_key=None, **kwargs):
if not api_key:
filter_params = ['name', 'is_admin', 'is_blocked', 'callback_url']
filter_dict = {key: value for key, value in kwargs.items() if key in filter_params}
tokens = Token.query.filter_by(**filter_dict)
return tokens
return Token.query.filter_by(**filter_dict).all()
try:
UUID(api_key)
except ValueError:
Expand Down Expand Up @@ -302,6 +303,7 @@ class URLResource(MethodResource):
401:
description: not authorized
"""

@marshal_with(URLSchema, code=201)
@use_kwargs(URLSchema)
@use_kwargs(ShortcutSchemaRestricted, location='view_args')
Expand Down Expand Up @@ -566,6 +568,9 @@ def delete(self, shortcut=None, **kwargs):

@marshal_many_or_one(URLSchema, 'shortcut', code=200)
@use_kwargs(URLSchema, location='query')
@use_kwargs({
'all': fields.Boolean(load_default=False),
}, location='query')
@authorize_request_for_url
def get(self, shortcut=None, **kwargs):
"""Obtain one or more URL objects.
Expand Down
1 change: 0 additions & 1 deletion ursh/blueprints/misc.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from flask import Blueprint, Response, current_app, redirect


bp = Blueprint('misc', __name__)


Expand Down
1 change: 0 additions & 1 deletion ursh/blueprints/redirection.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from ursh.models import URL


bp = Blueprint('redirection', __name__)


Expand Down
Loading
Loading