pax_global_header00006660000000000000000000000064143607473220014522gustar00rootroot0000000000000052 comment=deb5f47ffeb9907dbef641247cdb4604a09a1c9f python-lsp-isort-0.1/000077500000000000000000000000001436074732200146355ustar00rootroot00000000000000python-lsp-isort-0.1/.gitignore000066400000000000000000000023021436074732200166220ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # dotenv .env # virtualenv .venv venv/ ENV/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ # IDE settings .vscode/ .idea/ # ctags tags python-lsp-isort-0.1/LICENSE000066400000000000000000000020631436074732200156430ustar00rootroot00000000000000MIT License Copyright (c) 2023, Hiroki Teranishi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-lsp-isort-0.1/README.md000066400000000000000000000015451436074732200161210ustar00rootroot00000000000000# python-lsp-isort [isort](https://github.com/PyCQA/isort) plugin for the [Python LSP Server](https://github.com/python-lsp/python-lsp-server). ## Install In the same `virtualenv` as `python-lsp-server`: ```shell pip install python-lsp-isort ``` ## Configuration The plugin follows [python-lsp-server's configuration](https://github.com/python-lsp/python-lsp-server/#configuration). These are the valid configuration keys: - `pylsp.plugins.isort.enabled`: boolean to enable/disable the plugin. `true` by default. - `pylsp.plugins.isort.*`: any other key-value pair under `pylsp.plugins.isort` is passed to `isort.settings.Config`. See the [reference](https://pycqa.github.io/isort/reference/isort/settings.html#config) for details. Note that any configurations passed to isort via `pylsp` are ignored when isort detects a config file, such as `pyproject.toml`. python-lsp-isort-0.1/pylsp_isort/000077500000000000000000000000001436074732200172245ustar00rootroot00000000000000python-lsp-isort-0.1/pylsp_isort/__init__.py000066400000000000000000000000001436074732200213230ustar00rootroot00000000000000python-lsp-isort-0.1/pylsp_isort/plugin.py000066400000000000000000000071431436074732200211010ustar00rootroot00000000000000import logging import os from pathlib import Path from typing import Any, Dict, Generator, Optional, TypedDict, Union import isort from pylsp import hookimpl from pylsp.config.config import Config from pylsp.workspace import Document logger = logging.getLogger(__name__) class Position(TypedDict): line: int character: int class Range(TypedDict): start: Position end: Position @hookimpl def pylsp_settings() -> Dict[str, Any]: return { "plugins": { "isort": { "enabled": True, }, }, } @hookimpl(hookwrapper=True) def pylsp_format_document(config: Config, document: Document) -> Generator: outcome = yield _format(outcome, config, document) @hookimpl(hookwrapper=True) def pylsp_format_range(config: Config, document: Document, range: Range) -> Generator: outcome = yield _format(outcome, config, document, range) def _format( outcome, config: Config, document: Document, range: Optional[Range] = None ) -> None: result = outcome.get_result() if result: text = result[0]["newText"] range = result[0]["range"] elif range: text = "".join(document.lines[range["start"]["line"] : range["end"]["line"]]) else: text = document.source range = Range( start={"line": 0, "character": 0}, end={"line": len(document.lines), "character": 0}, ) IGNORE_KEYS = {"enabled"} settings = config.plugin_settings("isort", document_path=document.path) settings = {k: v for k, v in settings.items() if k not in IGNORE_KEYS} new_text = run_isort(text, settings, file_path=document.path) if new_text != text: result = [{"range": range, "newText": new_text}] outcome.force_result(result) def run_isort( text: str, settings: Optional[Dict[str, Any]] = None, file_path: Optional[Union[str, bytes, os.PathLike]] = None, ) -> str: config = isort_config(settings or {}, file_path) file_path = Path(os.fsdecode(file_path)) if file_path else None return isort.code(text, config=config, file_path=file_path) def isort_config( settings: Dict[str, Any], target_path: Optional[Union[str, bytes, os.PathLike]] = None, ) -> isort.Config: config_kwargs = {} unsupported_kwargs = {} defined_args = set(getattr(isort.Config, "__dataclass_fields__", {}).keys()) for key, value in settings.items(): if key in defined_args: config_kwargs[key] = value else: unsupported_kwargs[key] = value if "settings_path" in settings: if os.path.isfile(settings["settings_path"]): config_kwargs["settings_file"] = os.path.abspath(settings["settings_path"]) config_kwargs["settings_path"] = os.path.dirname( config_kwargs["settings_file"] ) else: config_kwargs["settings_path"] = os.path.abspath(settings["settings_path"]) elif target_path: settings_path = os.path.abspath(target_path) if not os.path.isdir(settings_path): settings_path = os.path.dirname(settings_path) _, found_settings = isort.settings._find_config(settings_path) if found_settings: logger.info( "Found a config file: `%s`, skipping given settings.", found_settings["source"], ) config_kwargs = {} config_kwargs["settings_path"] = settings_path logger.debug("config_kwargs=%r", config_kwargs) if unsupported_kwargs: logger.info("unsupported_kwargs=%r", unsupported_kwargs) return isort.Config(**config_kwargs) python-lsp-isort-0.1/pyproject.toml000066400000000000000000000014261436074732200175540ustar00rootroot00000000000000[build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [project] name = "python-lsp-isort" version = "0.1" authors = [ {name = "Hiroki Teranishi", email = "teranishi.hiroki@gmail.com"} ] description = "isort plugin for the Python LSP Server" readme = "README.md" license = {text = "MIT"} requires-python = ">=3.7" dependencies = [ "python-lsp-server", "isort>=5.0", ] [project.urls] Homepage = "https://github.com/chantera/python-lsp-isort" "Bug Tracker" = "https://github.com/chantera/python-lsp-isort/issues" [project.optional-dependencies] dev = ["pytest"] [project.entry-points.pylsp] isort = "pylsp_isort.plugin" [tool.flake8] max-line-length = 88 extend-ignore = "E203" [tool.mypy] ignore_missing_imports = true [tool.isort] profile = "black" python-lsp-isort-0.1/tests/000077500000000000000000000000001436074732200157775ustar00rootroot00000000000000python-lsp-isort-0.1/tests/__init__.py000066400000000000000000000000001436074732200200760ustar00rootroot00000000000000python-lsp-isort-0.1/tests/conftest.py000066400000000000000000000020031436074732200201710ustar00rootroot00000000000000import shutil from pathlib import Path from unittest.mock import Mock import pytest from pylsp import uris from pylsp.config.config import Config from pylsp.workspace import Document, Workspace here = Path(__file__).parent fixtures_dir = here / "fixtures" @pytest.fixture def config(workspace): return Config(workspace.root_uri, {}, 0, {}) @pytest.fixture def workspace(tmpdir): """Return a workspace.""" ws = Workspace(uris.from_fs_path(str(tmpdir)), Mock()) ws._config = Config(ws.root_uri, {}, 0, {}) return ws @pytest.fixture def unformatted_document(workspace): return create_document(workspace, "unformatted.py") @pytest.fixture def formatted_document(workspace): return create_document(workspace, "formatted.py") def create_document(workspace, name): template_path = fixtures_dir / name dest_path = Path(workspace.root_path) / name shutil.copy(template_path, dest_path) document_uri = uris.from_fs_path(str(dest_path)) return Document(document_uri, workspace) python-lsp-isort-0.1/tests/fixtures/000077500000000000000000000000001436074732200176505ustar00rootroot00000000000000python-lsp-isort-0.1/tests/fixtures/formatted.py000066400000000000000000000004241436074732200222070ustar00rootroot00000000000000from __future__ import absolute_import import os import sys from third_party import (lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9, lib10, lib11, lib12, lib13, lib14, lib15) from pylsp_isort.plugin import Range, isort_config, pylsp_settings python-lsp-isort-0.1/tests/fixtures/formatted_black.py000066400000000000000000000004721436074732200233460ustar00rootroot00000000000000from __future__ import absolute_import import os import sys from third_party import ( lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9, lib10, lib11, lib12, lib13, lib14, lib15, ) from pylsp_isort.plugin import Range, isort_config, pylsp_settings python-lsp-isort-0.1/tests/fixtures/unformatted.py000066400000000000000000000005421436074732200225530ustar00rootroot00000000000000from pylsp_isort.plugin import isort_config import os from pylsp_isort.plugin import Range from pylsp_isort.plugin import pylsp_settings import sys from third_party import lib15, lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9, lib10, lib11, lib12, lib13, lib14 import sys from __future__ import absolute_import from third_party import lib3 python-lsp-isort-0.1/tests/test_plugin.py000066400000000000000000000073031436074732200207110ustar00rootroot00000000000000import os from dataclasses import asdict import isort import pytest from pylsp_isort import plugin def _read_content(filename): path = os.path.join(os.path.dirname(__file__), "fixtures", filename) with open(path) as f: return f.read() @pytest.mark.parametrize( ("text", "settings", "expected"), [ ( _read_content("unformatted.py"), {}, _read_content("formatted.py"), ), ( _read_content("unformatted.py"), {"profile": "black"}, _read_content("formatted_black.py"), ), ], ) def test_run_isort(text, settings, expected): actual = plugin.run_isort(text, settings) assert actual == expected @pytest.mark.parametrize( ("settings", "target_path", "expected", "check_sources"), [ ( {}, None, isort.Config(), True, ), ( {"profile": "black"}, None, isort.Config(profile="black"), True, ), ( {"profile": "black", "line_length": 120}, None, isort.Config(profile="black", line_length=120), True, ), ( {}, __file__, isort.Config(settings_path=os.path.dirname(__file__)), True, ), ( {}, __file__, isort.Config(profile="black"), False, ), ( {"profile": "django"}, __file__, isort.Config(profile="black"), False, ), ], ) def test_isort_config(settings, target_path, expected, check_sources): actual = plugin.isort_config(settings, target_path) actual_dict = asdict(actual) expected_dict = asdict(expected) if not check_sources: del actual_dict["sources"] del expected_dict["sources"] assert actual_dict == expected_dict def test_pylsp_settings(config): plugins = dict(config.plugin_manager.list_name_plugin()) assert "isort" in plugins assert plugins["isort"] not in config.disabled_plugins config.update({"plugins": {"isort": {"enabled": False}}}) assert plugins["isort"] in config.disabled_plugins config.update(plugin.pylsp_settings()) assert plugins["isort"] not in config.disabled_plugins def test_pylsp_format_document(config, unformatted_document, formatted_document): actual = _receive(plugin.pylsp_format_document, config, unformatted_document) text = _read_content(formatted_document.path) range = plugin.Range( start={"line": 0, "character": 0}, end={"line": len(unformatted_document.lines), "character": 0}, ) expected = [{"range": range, "newText": text}] assert actual == expected def test_pylsp_format_range(config, unformatted_document): range = plugin.Range( start={"line": 2, "character": 0}, end={"line": 9, "character": 0}, ) actual = _receive(plugin.pylsp_format_range, config, unformatted_document, range) text = "\n".join( [ "import os", "import sys", "", "from pylsp_isort.plugin import Range, pylsp_settings", ] ) text += "\n" expected = [{"range": range, "newText": text}] assert actual == expected def _receive(func, *args): gen = func(*args) next(gen) outcome = MockResult([]) try: gen.send(outcome) except StopIteration: pass return outcome.get_result() class MockResult: def __init__(self, result): self.result = result def get_result(self): return self.result def force_result(self, result): self.result = result