Skip to content

Commit

Permalink
Use ruff as linter and code formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
tkrabel committed Dec 24, 2023
1 parent de87a80 commit 69cba72
Show file tree
Hide file tree
Showing 30 changed files with 49 additions and 122 deletions.
16 changes: 6 additions & 10 deletions .github/workflows/static.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,13 @@ jobs:
python-version: '3.8'
architecture: 'x64'
- run: python -m pip install --upgrade pip setuptools jsonschema
# 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 .
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
31 changes: 0 additions & 31 deletions .pylintrc

This file was deleted.

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

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

from .python_lsp import (
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
6 changes: 3 additions & 3 deletions pylsp/config/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Copyright 2017-2020 Palantir Technologies, Inc.
# Copyright 2021- Python Language Server Contributors.
# Copyright 2021- Python Language Server Contributors
# pylint: disable=import-outside-toplevel

import logging
Expand Down Expand Up @@ -38,7 +38,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 +79,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
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
2 changes: 1 addition & 1 deletion pylsp/plugins/_resolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,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
4 changes: 2 additions & 2 deletions pylsp/plugins/autopep8_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
@hookimpl(tryfirst=True) # Prefer autopep8 over YAPF
def pylsp_format_document(
config, workspace, document, options
): # pylint: disable=unused-argument
):
with workspace.report_progress("format: autopep8"):
log.info("Formatting document %s with autopep8", document)
return _format(config, document)
Expand All @@ -24,7 +24,7 @@ def pylsp_format_document(
@hookimpl(tryfirst=True) # Prefer autopep8 over YAPF
def pylsp_format_range(
config, workspace, document, range, options
): # pylint: disable=redefined-builtin,unused-argument
):
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
2 changes: 1 addition & 1 deletion pylsp/plugins/flake8_lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +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
p = Popen(
cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, **popen_kwargs
)
(stdout, stderr) = p.communicate(source.encode())
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
3 changes: 1 addition & 2 deletions pylsp/plugins/jedi_rename.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
@hookimpl
def pylsp_rename(
config, workspace, document, position, new_name
): # pylint: disable=unused-argument
):
log.debug(
"Executing rename of %s to %s", document.word_at_position(position), new_name
)
Expand All @@ -20,7 +20,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: 1 addition & 1 deletion pylsp/plugins/preload_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,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
1 change: 0 additions & 1 deletion pylsp/plugins/pydocstyle_lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,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
6 changes: 3 additions & 3 deletions pylsp/plugins/pylint_lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

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

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -50,7 +50,7 @@ class PylintLinter:
@classmethod
def lint(
cls, document, is_saved, flags=""
): # pylint: disable=too-many-locals,too-many-branches
):
"""Plugin interface to pylsp linter.
Args:
Expand Down Expand Up @@ -289,7 +289,7 @@ def _run_pylint_stdio(pylint_executable, document, flags):
cmd = [sys.executable, "-m", "pylint"]
cmd.extend(flags)
cmd.extend(["--from-stdin", document.path])
p = Popen( # pylint: disable=consider-using-with
p = Popen(
cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE
)
(stdout, stderr) = p.communicate(document.source.encode())
Expand Down
15 changes: 5 additions & 10 deletions pylsp/plugins/rope_autoimport.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ def pylsp_settings() -> Dict[str, Dict[str, Dict[str, Any]]]:
}


# pylint: disable=too-many-return-statements
def _should_insert(expr: tree.BaseNode, word_node: tree.Leaf) -> bool:
"""
Check if we should insert the word_node on the given expr.
Expand Down Expand Up @@ -214,7 +213,7 @@ def _process_statements(
"kind": "quickfix",
"edit": {"changes": {doc_uri: [edit]}},
# data is a supported field for codeAction responses
# See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_codeAction # pylint: disable=line-too-long
# See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_codeAction
"data": {"sortText": _sort_import(score)},
}
else:
Expand All @@ -225,7 +224,7 @@ def get_names(script: Script) -> Set[str]:
"""Get all names to ignore from the current file."""
raw_names = script.get_names(definitions=True)
log.debug(raw_names)
return set(name.name for name in raw_names)
return {name.name for name in raw_names}


@hookimpl
Expand Down Expand Up @@ -257,14 +256,12 @@ def pylsp_completions(
)
autoimport = workspace._rope_autoimport(rope_config)
suggestions = list(autoimport.search_full(word, ignored_names=ignored_names))
results = list(
sorted(
results = sorted(
_process_statements(
suggestions, document.uri, word, autoimport, document, "completions"
),
key=lambda statement: statement["sortText"],
)
)
if len(results) > MAX_RESULTS_COMPLETIONS:
results = results[:MAX_RESULTS_COMPLETIONS]
return results
Expand Down Expand Up @@ -306,7 +303,7 @@ def pylsp_code_actions(
config: Config,
workspace: Workspace,
document: Document,
range: Dict, # pylint: disable=redefined-builtin
range: Dict,
context: Dict,
) -> List[Dict]:
"""
Expand Down Expand Up @@ -348,8 +345,7 @@ def pylsp_code_actions(
autoimport = workspace._rope_autoimport(rope_config)
suggestions = list(autoimport.search_full(word))
log.debug("autoimport: suggestions: %s", suggestions)
results = list(
sorted(
results = sorted(
_process_statements(
suggestions,
document.uri,
Expand All @@ -360,7 +356,6 @@ def pylsp_code_actions(
),
key=lambda statement: statement["data"]["sortText"],
)
)

if len(results) > MAX_RESULTS_CODE_ACTIONS:
results = results[:MAX_RESULTS_CODE_ACTIONS]
Expand Down
5 changes: 1 addition & 4 deletions pylsp/plugins/rope_completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ def pylsp_settings():


def _resolve_completion(completion, data, markup_kind):
# pylint: disable=broad-except
try:
doc = _utils.format_docstring(data.get_doc(), markup_kind=markup_kind)
except Exception as e:
Expand All @@ -30,8 +29,6 @@ def _resolve_completion(completion, data, markup_kind):

@hookimpl
def pylsp_completions(config, workspace, document, position):
# pylint: disable=too-many-locals

settings = config.plugin_settings("rope_completion", document_path=document.path)
resolve_eagerly = settings.get("eager", False)

Expand Down Expand Up @@ -63,7 +60,7 @@ def pylsp_completions(config, workspace, document, position):
definitions = code_assist(
rope_project, document.source, offset, document_rope, maxfixes=3
)
except Exception as e: # pylint: disable=broad-except
except Exception as e:
log.debug("Failed to run Rope code assist: %s", e)
return []

Expand Down
8 changes: 1 addition & 7 deletions pylsp/plugins/symbols.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,6 @@

@hookimpl
def pylsp_document_symbols(config, document):
# pylint: disable=broad-except
# pylint: disable=too-many-nested-blocks
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements

symbols_settings = config.plugin_settings("jedi_symbols")
all_scopes = symbols_settings.get("all_scopes", True)
add_import_symbols = symbols_settings.get("include_import_symbols", True)
Expand Down Expand Up @@ -150,7 +144,7 @@ def _container(definition):
# as children of the module.
if parent.parent():
return parent.name
except: # pylint: disable=bare-except
except:
return None

return None
Expand Down
2 changes: 1 addition & 1 deletion pylsp/plugins/yapf_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def pylsp_format_document(workspace, document, options):


@hookimpl
def pylsp_format_range(document, range, options): # pylint: disable=redefined-builtin
def pylsp_format_range(document, range, options):
log.info("Formatting document %s in range %s with yapf", document, range)
# First we 'round' the range up/down to full lines only
range["start"]["character"] = 0
Expand Down
Loading

0 comments on commit 69cba72

Please sign in to comment.