Skip to content

Commit

Permalink
Use ruff as linter and code formatter (#502)
Browse files Browse the repository at this point in the history
  • Loading branch information
tkrabel authored Jan 19, 2024
1 parent cb213e0 commit fc2851a
Show file tree
Hide file tree
Showing 66 changed files with 241 additions and 213 deletions.
14 changes: 6 additions & 8 deletions .github/workflows/static.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,12 @@ jobs:
# If we don't install pycodestyle, pylint will throw an unused-argument error in pylsp/plugins/pycodestyle_lint.py:72
# This error cannot be resolved by adding a pylint: disable=unused-argument comment ...
- run: |
pip install -e .[pylint,pycodestyle,pyflakes]
pip install black
- name: Pylint checks
run: pylint pylsp test
- name: Code style checks with black
run: black --check pylsp test
- name: Pyflakes checks
run: pyflakes pylsp test
pip install -e .[pylint,pycodestyle]
pip install ruff
- name: ruff linter and code style checks
run: ruff check pylsp test
- name: ruff code formatter check
run: ruff format --check pylsp test
- name: Validate JSON schema
run: echo {} | jsonschema pylsp/config/schema.json
- name: Ensure JSON schema and Markdown docs are in sync
Expand Down
2 changes: 1 addition & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,4 @@ reports = no

generated-members =
pylsp_*
cache_clear
cache_clear
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ include README.md
include versioneer.py
include pylsp/_version.py
include LICENSE
include ruff.toml
include .pylintrc
recursive-include test *.py
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,13 @@ To run the test suite:
pytest
```

Running ruff as a linter and code formatter on the repo:
```sh
ruff check . # linter
ruff check --fix . # fix all auto-fixable lint issues
ruff format . # format the document
```

After adding configuration options to `schema.json`, refresh the `CONFIGURATION.md` file with

```
Expand Down
2 changes: 2 additions & 0 deletions pylsp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
# Copyright 2021- Python Language Server Contributors.

import os

import pluggy

from . import _version
from ._version import __version__

Expand Down
4 changes: 2 additions & 2 deletions pylsp/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@

try:
import ujson as json
except Exception: # pylint: disable=broad-except
except Exception:
import json

from ._version import __version__
from .python_lsp import (
PythonLSPServer,
start_io_lang_server,
start_tcp_lang_server,
start_ws_lang_server,
)
from ._version import __version__

LOG_FORMAT = "%(asctime)s {0} - %(levelname)s - %(name)s - %(message)s".format(
time.localtime().tm_zone
Expand Down
2 changes: 1 addition & 1 deletion pylsp/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def throttle(seconds=1):

def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs): # pylint: disable=inconsistent-return-statements
def wrapper(*args, **kwargs):
if not hasattr(wrapper, "last_call"):
wrapper.last_call = 0
if time.time() - wrapper.last_call >= seconds:
Expand Down
7 changes: 3 additions & 4 deletions pylsp/config/config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# Copyright 2017-2020 Palantir Technologies, Inc.
# Copyright 2021- Python Language Server Contributors.
# pylint: disable=import-outside-toplevel

import logging
import sys
Expand All @@ -10,7 +9,7 @@
import pluggy
from pluggy._hooks import HookImpl

from pylsp import _utils, hookspecs, uris, PYLSP
from pylsp import PYLSP, _utils, hookspecs, uris

# See compatibility note on `group` keyword:
# https://docs.python.org/3/library/importlib.metadata.html#entry-points
Expand Down Expand Up @@ -38,7 +37,7 @@ def _hookexec(
# enable_tracing will set its own wrapping function at self._inner_hookexec
try:
return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
except Exception as e: # pylint: disable=broad-except
except Exception as e:
log.warning(f"Failed to load hook {hook_name}: {e}", exc_info=True)
return []

Expand Down Expand Up @@ -79,7 +78,7 @@ def __init__(self, root_uri, init_opts, process_id, capabilities):
for entry_point in entry_points(group=PYLSP):
try:
entry_point.load()
except Exception as e: # pylint: disable=broad-except
except Exception as e:
log.info(
"Failed to load %s entry point '%s': %s", PYLSP, entry_point.name, e
)
Expand Down
2 changes: 2 additions & 0 deletions pylsp/config/flake8_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

import logging
import os

from pylsp._utils import find_parents

from .source import ConfigSource

log = logging.getLogger(__name__)
Expand Down
3 changes: 2 additions & 1 deletion pylsp/config/pycodestyle_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
# Copyright 2021- Python Language Server Contributors.

import pycodestyle

from pylsp._utils import find_parents
from .source import ConfigSource

from .source import ConfigSource

CONFIG_KEY = "pycodestyle"
USER_CONFIGS = [pycodestyle.USER_CONFIG] if pycodestyle.USER_CONFIG else []
Expand Down
1 change: 0 additions & 1 deletion pylsp/hookspecs.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Copyright 2017-2020 Palantir Technologies, Inc.
# Copyright 2021- Python Language Server Contributors.

# pylint: disable=redefined-builtin, unused-argument
from pylsp import hookspec


Expand Down
5 changes: 2 additions & 3 deletions pylsp/plugins/_resolvers.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
# Copyright 2017-2020 Palantir Technologies, Inc.
# Copyright 2021- Python Language Server Contributors.

from collections import defaultdict
import logging
from collections import defaultdict
from time import time

from jedi.api.classes import Completion

from pylsp import lsp


log = logging.getLogger(__name__)


Expand Down Expand Up @@ -77,7 +76,7 @@ def resolve(self, completion):
try:
sig = completion.get_signatures()
return self.callback(completion, sig)
except Exception as e: # pylint: disable=broad-except
except Exception as e:
log.warning(
f"Something went wrong when resolving label for {completion}: {e}"
)
Expand Down
3 changes: 1 addition & 2 deletions pylsp/plugins/_rope_task_handle.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
from __future__ import annotations

import logging

from typing import Callable, ContextManager, List, Optional, Sequence

from rope.base.taskhandle import BaseJobSet, BaseTaskHandle

from pylsp.workspace import Workspace
from pylsp._utils import throttle
from pylsp.workspace import Workspace

log = logging.getLogger(__name__)
Report = Callable[[str, int], None]
Expand Down
11 changes: 4 additions & 7 deletions pylsp/plugins/autopep8_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import logging

import pycodestyle
from autopep8 import fix_code, continued_indentation as autopep8_c_i
from autopep8 import continued_indentation as autopep8_c_i
from autopep8 import fix_code

from pylsp import hookimpl
from pylsp._utils import get_eol_chars
Expand All @@ -13,18 +14,14 @@


@hookimpl(tryfirst=True) # Prefer autopep8 over YAPF
def pylsp_format_document(
config, workspace, document, options
): # pylint: disable=unused-argument
def pylsp_format_document(config, workspace, document, options):
with workspace.report_progress("format: autopep8"):
log.info("Formatting document %s with autopep8", document)
return _format(config, document)


@hookimpl(tryfirst=True) # Prefer autopep8 over YAPF
def pylsp_format_range(
config, workspace, document, range, options
): # pylint: disable=redefined-builtin,unused-argument
def pylsp_format_range(config, workspace, document, range, options):
log.info("Formatting document %s in range %s with autopep8", document, range)

# First we 'round' the range up/down to full lines only
Expand Down
6 changes: 4 additions & 2 deletions pylsp/plugins/definition.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
# Copyright 2017-2020 Palantir Technologies, Inc.
# Copyright 2021- Python Language Server Contributors.
from __future__ import annotations

import logging
from typing import Any, Dict, List, TYPE_CHECKING
from typing import TYPE_CHECKING, Any, Dict, List

import jedi

from pylsp import hookimpl, uris, _utils
from pylsp import _utils, hookimpl, uris

if TYPE_CHECKING:
from jedi.api import Script
from jedi.api.classes import Name

from pylsp.config.config import Config
from pylsp.workspace import Document

Expand Down
4 changes: 1 addition & 3 deletions pylsp/plugins/flake8_lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,7 @@ def run_flake8(flake8_executable, args, document, source):
)
cmd = [sys.executable, "-m", "flake8"]
cmd.extend(args)
p = Popen( # pylint: disable=consider-using-with
cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, **popen_kwargs
)
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, **popen_kwargs)
(stdout, stderr) = p.communicate(source.encode())
if stderr:
log.error("Error while running flake8 '%s'", stderr.decode())
Expand Down
3 changes: 2 additions & 1 deletion pylsp/plugins/highlight.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
# Copyright 2021- Python Language Server Contributors.

import logging
from pylsp import hookimpl, lsp, _utils

from pylsp import _utils, hookimpl, lsp

log = logging.getLogger(__name__)

Expand Down
2 changes: 1 addition & 1 deletion pylsp/plugins/hover.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import logging

from pylsp import hookimpl, _utils
from pylsp import _utils, hookimpl

log = logging.getLogger(__name__)

Expand Down
2 changes: 0 additions & 2 deletions pylsp/plugins/jedi_completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
@hookimpl
def pylsp_completions(config, document, position):
"""Get formatted completions for current code position"""
# pylint: disable=too-many-locals
settings = config.plugin_settings("jedi_completion", document_path=document.path)
resolve_eagerly = settings.get("eager", False)
code_position = _utils.position_to_jedi_linecolumn(document, position)
Expand Down Expand Up @@ -209,7 +208,6 @@ def use_snippets(document, position):


def _resolve_completion(completion, d, markup_kind: str):
# pylint: disable=broad-except
completion["detail"] = _detail(d)
try:
docs = _utils.format_docstring(
Expand Down
7 changes: 2 additions & 5 deletions pylsp/plugins/jedi_rename.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@

import logging

from pylsp import hookimpl, uris, _utils
from pylsp import _utils, hookimpl, uris

log = logging.getLogger(__name__)


@hookimpl
def pylsp_rename(
config, workspace, document, position, new_name
): # pylint: disable=unused-argument
def pylsp_rename(config, workspace, document, position, new_name):
log.debug(
"Executing rename of %s to %s", document.word_at_position(position), new_name
)
Expand All @@ -20,7 +18,6 @@ def pylsp_rename(
try:
refactoring = document.jedi_script().rename(**kwargs)
except NotImplementedError as exc:
# pylint: disable=broad-exception-raised
raise Exception(
"No support for renaming in Python 2/3.5 with Jedi. "
"Consider using the rope_rename plugin instead"
Expand Down
2 changes: 2 additions & 0 deletions pylsp/plugins/mccabe_lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

import ast
import logging

import mccabe

from pylsp import hookimpl, lsp

log = logging.getLogger(__name__)
Expand Down
3 changes: 2 additions & 1 deletion pylsp/plugins/preload_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Copyright 2021- Python Language Server Contributors.

import logging

from pylsp import hookimpl

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -71,7 +72,7 @@ def pylsp_initialize(config):
try:
__import__(mod_name)
log.debug("Preloaded module %s", mod_name)
except Exception: # pylint: disable=broad-except
except Exception:
# Catch any exception since not only ImportError can be raised here
# For example, old versions of NumPy can cause a ValueError.
# See spyder-ide/spyder#13985
Expand Down
2 changes: 1 addition & 1 deletion pylsp/plugins/pydocstyle_lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import sys

import pydocstyle

from pylsp import hookimpl, lsp

log = logging.getLogger(__name__)
Expand All @@ -28,7 +29,6 @@ def pylsp_settings():

@hookimpl
def pylsp_lint(config, workspace, document):
# pylint: disable=too-many-locals
with workspace.report_progress("lint: pydocstyle"):
settings = config.plugin_settings("pydocstyle", document_path=document.path)
log.debug("Got pydocstyle settings: %s", settings)
Expand Down
4 changes: 3 additions & 1 deletion pylsp/plugins/pyflakes_lint.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
# Copyright 2017-2020 Palantir Technologies, Inc.
# Copyright 2021- Python Language Server Contributors.

from pyflakes import api as pyflakes_api, messages
from pyflakes import api as pyflakes_api
from pyflakes import messages

from pylsp import hookimpl, lsp

# Pyflakes messages that should be reported as Errors instead of Warns
Expand Down
Loading

0 comments on commit fc2851a

Please sign in to comment.