Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
home:bnavigator:pyqt:dependers
spyder
spyder-pr15657-python-lsp-server.patch
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File spyder-pr15657-python-lsp-server.patch of Package spyder
Index: spyder-5.0.5/.github/scripts/install.sh =================================================================== --- spyder-5.0.5.orig/.github/scripts/install.sh +++ spyder-5.0.5/.github/scripts/install.sh @@ -26,10 +26,7 @@ if [ "$USE_CONDA" = "true" ]; then # Remove packages we have subrepos for conda remove spyder-kernels --force -q -y - conda remove python-language-server --force -q -y - - # Provisional change to prevent error from jupyter_client 6.1.13 - conda install jupyter_client=6.1.12 + conda remove python-lsp-server --force -q -y else # Update pip and setuptools pip install -U pip setuptools @@ -51,16 +48,14 @@ else # Remove packages we have subrepos for pip uninstall spyder-kernels -q -y - pip uninstall python-language-server -q -y + pip uninstall python-lsp-server -q -y - # Provisional change to prevent error from jupyter_client 6.1.13 - pip install jupyter_client==6.1.12 fi # This is necessary only for Windows (don't know why). if [ "$OS" = "win" ]; then - # Install python-language-server from our subrepo - pushd external-deps/python-language-server + # Install python-lsp-server from our subrepo + pushd external-deps/python-lsp-server pip install --no-deps -q -e . popd fi Index: spyder-5.0.5/.github/workflows/installer-macos.yml =================================================================== --- spyder-5.0.5.orig/.github/workflows/installer-macos.yml +++ spyder-5.0.5/.github/workflows/installer-macos.yml @@ -40,7 +40,7 @@ jobs: run: | python3.9 -m pip install \ -e ${GITHUB_WORKSPACE}/external-deps/spyder-kernels \ - -e ${GITHUB_WORKSPACE}/external-deps/python-language-server \ + -e ${GITHUB_WORKSPACE}/external-deps/python-lsp-server \ -e ${GITHUB_WORKSPACE}/external-deps/qdarkstyle - name: Show Build Environment run: | Index: spyder-5.0.5/.github/workflows/test-files.yml =================================================================== --- spyder-5.0.5.orig/.github/workflows/test-files.yml +++ spyder-5.0.5/.github/workflows/test-files.yml @@ -98,7 +98,7 @@ jobs: - name: Use QtAwesome 1.0.1 if: env.RUN_BUILD == 'true' shell: bash -l {0} - run: conda install -q -y qtawesome=1.0.1 + run: pip install --no-deps qtawesome==1.0.1 - name: Install QDarkStyle from master if: env.RUN_BUILD == 'true' shell: bash -l {0} Index: spyder-5.0.5/.gitignore =================================================================== --- spyder-5.0.5.orig/.gitignore +++ spyder-5.0.5/.gitignore @@ -42,5 +42,5 @@ result.xml .pylint.d/ # Ignore setuptools development files in the PyLS subrepo -external-deps/python-language-server/python_language_server.egg-info/ -external-deps/python-language-server/.installation-dir/ +external-deps/python-lsp-server/python_lsp_server.egg-info/ +external-deps/python-lsp-server/.installation-dir/ Index: spyder-5.0.5/CONTRIBUTING.md =================================================================== --- spyder-5.0.5.orig/CONTRIBUTING.md +++ spyder-5.0.5/CONTRIBUTING.md @@ -206,36 +206,36 @@ As an example, let's assume that (i) you where `<branch>` needs to be `1.x` if your `fix_in_spyder` branch was done against Spyder's `4.x` branch; and `master`, if you did it against our `master` branch here. -## Making contributions that depend on pull requests in python-language-server +## Making contributions that depend on pull requests in python-lsp-server -As with spyder-kernels, Spyder is tightly integrated with the [python-language-server](https://github.com/palantir/python-language-server) to provide code completion, linting and folding on its editor. +As with spyder-kernels, Spyder is tightly integrated with the [python-lsp-server](https://github.com/python-lsp/python-lsp-server) to provide code completion, linting and folding on its editor. -Due to that, a clone of that project is placed in the `external-deps` directory, which is managed with the `git subrepo` project. If you want to make a pull request in python-language-server that affects functionality in Spyder, please read carefully the instructions in the previous section because they are very similar for this case. A summary of those instructions applied to this project is the following: +Due to that, a clone of that project is placed in the `external-deps` directory, which is managed with the `git subrepo` project. If you want to make a pull request in python-lsp-server that affects functionality in Spyder, please read carefully the instructions in the previous section because they are very similar for this case. A summary of those instructions applied to this project is the following: -* First you need to create a pull request in python-language-server with the changes you want to make there. Let's assume the branch from which that pull request is created is called `fix_in_pyls`. +* First you need to create a pull request in python-lsp-server with the changes you want to make there. Let's assume the branch from which that pull request is created is called `fix_in_pyls`. -* Then you need to create a branch in Spyder (let's call it `fix_in_spyder`) with the fixes that require that pull request and update the python-language-server subrepo. For that you need to execute the following commands: +* Then you need to create a branch in Spyder (let's call it `fix_in_spyder`) with the fixes that require that pull request and update the python-lsp-server subrepo. For that you need to execute the following commands: ``` $ git checkout -b fix_in_spyder - $ git subrepo clone https://github.com/myuser/python-language-server.git external-deps/python-language-server -b fix_in_pyls -f + $ git subrepo clone https://github.com/myuser/python-lsp-server.git external-deps/python-lsp-server -b fix_in_pylsp -f ``` and then commit the changes you need to make in Spyder. -* If you need to add more commits to `fix_in_pyls`, you need to update `fix_in_spyder` with these commands: +* If you need to add more commits to `fix_in_pylsp`, you need to update `fix_in_spyder` with these commands: ``` $ git checkout fix_in_spyder - $ git subrepo pull external-deps/python-language-server + $ git subrepo pull external-deps/python-lsp-server $ git push origin fix_in_spyder ``` -* After `fix_in_pyls` is merged, you need to update the python-language-server subrepo in your `fix_in_spyder` branch with +* After `fix_in_pylsp` is merged, you need to update the python-lsp-server subrepo in your `fix_in_spyder` branch with ``` $ git checkout fix_in_spyder - $ git subrepo clone https://github.com/palantir/python-language-server.git external-deps/python-language-server -b develop -f + $ git subrepo clone https://github.com/palantir/python-lsp-server.git external-deps/python-lsp-server -b develop -f ``` Index: spyder-5.0.5/MAINTENANCE.md =================================================================== --- spyder-5.0.5.orig/MAINTENANCE.md +++ spyder-5.0.5/MAINTENANCE.md @@ -27,9 +27,9 @@ These are some instructions meant for ma - git commit with the files left and the same message format as above. - git subrepo pull external-deps/spyder-kernels -* If a PR in spyder-kernels solves an issue in Spyder but was not part of a PR that updated its subrepo, you need to open one that does precisely that, i.e. update its subrepo, in order to fix that issue. +* If a PR in spyder-kernels solves an issue in Spyder but was not part of a PR that updated its subrepo, you need to open one that does precisely that, i.e. update its subrepo, in order to fix that issue. - The same goes for the python-language-server subrepo. + The same goes for the python-lsp-server subrepo. * There's a bot that constantly monitors all issues in order to close duplicates or already solved issues and inform users what they can do about them (basically wait to be fixed or update). Index: spyder-5.0.5/RELEASE.md =================================================================== --- spyder-5.0.5.orig/RELEASE.md +++ spyder-5.0.5/RELEASE.md @@ -87,7 +87,7 @@ To release a new version of Spyder you n * Release a new version of `spyder-kernels`, if required. -* Release a new version of `python-language-server`, if required. +* Release a new version of `python-lsp-server`, if required. * Create a new branch in your fork with the name `update-core-deps` @@ -113,7 +113,7 @@ To release a new version of Spyder you n * Update our subrepos with the following commands, but only if new versions are available! git subrepo pull external-deps/spyder-kernels - git subrepo pull external-deps/python-language-server + git subrepo pull external-deps/python-lsp-server * Merge this PR following the procedure mentioned on `MAINTENANCE.md` @@ -178,7 +178,7 @@ To release a new version of Spyder you n * Publish release announcements to our list. -* Merge PRs on Conda-forge that update the `spyder-kernels` and `python-language-server` feedstocks. +* Merge PRs on Conda-forge that update the `spyder-kernels` and `python-lsp-server` feedstocks. **Notes**: Index: spyder-5.0.5/binder/environment.yml =================================================================== --- spyder-5.0.5.orig/binder/environment.yml +++ spyder-5.0.5/binder/environment.yml @@ -25,13 +25,14 @@ dependencies: - pickleshare >=0.4 - psutil >=5.3 - pygments >=2.0 -- pylint >=1.0 -- pyls-black >=0.4.6 -- pyls-spyder >=0.3.2,<0.4.0 +- pylint >=2.5.0 +- python-lsp-server >=1.0.0 +- python-lsp-black >=1.0.0 +- pyls-spyder >=0.4.0 - pyqt <5.13 -# NOTE: There's no need to set constraints for python-language-server +# NOTE: There's no need to set constraints for python-lsp-server # here because Spyder uses the subrepo for it when started in Binder. -- python-language-server +- python-lsp-server - pyxdg >=0.26 - pyzmq >=17 - qdarkstyle =3.0.2 Index: spyder-5.0.5/bootstrap.py =================================================================== --- spyder-5.0.5.orig/bootstrap.py +++ spyder-5.0.5/bootstrap.py @@ -145,10 +145,10 @@ for path in os.listdir(DEPS_PATH): i += 1 # Create an egg-info folder to declare the PyLS subrepo entry points. -pyls_submodule = osp.join(DEPS_PATH, 'python-language-server') +pyls_submodule = osp.join(DEPS_PATH, 'python-lsp-server') pyls_installation_dir = osp.join(pyls_submodule, '.installation-dir') pyls_installation_egg = osp.join( - pyls_submodule, 'python_language_server.egg-info') + pyls_submodule, 'python_lsp_server.egg-info') def remove_pyls_installation(): @@ -158,11 +158,11 @@ def remove_pyls_installation(): if osp.exists(pyls_installation_dir) or osp.exists(pyls_installation_egg): # Remove any leftover installation from previous execution - print("*. Removing previous PyLS local installation.") + print("*. Removing previous PyLSP local installation.") remove_pyls_installation() # Install PyLS locally -print("*. Installing PyLS locally") +print("*. Installing PyLSP locally") subprocess.check_output( [sys.executable, '-W', Index: spyder-5.0.5/conftest.py =================================================================== --- spyder-5.0.5.orig/conftest.py +++ spyder-5.0.5/conftest.py @@ -36,10 +36,10 @@ for path in os.listdir(DEPS_PATH): # Install PyLS locally. This fails on Windows and our CIs if os.name != 'nt' or os.name == 'nt' and not bool(os.environ.get('CI')): # Create an egg-info folder to declare the PyLS subrepo entry points. - pyls_submodule = osp.join(DEPS_PATH, 'python-language-server') + pyls_submodule = osp.join(DEPS_PATH, 'python-lsp-server') pyls_installation_dir = osp.join(pyls_submodule, '.installation-dir') pyls_installation_egg = osp.join( - pyls_submodule, 'python_language_server.egg-info') + pyls_submodule, 'python_lsp_server.egg-info') # Remove previous local PyLS installation. if osp.exists(pyls_installation_dir) or osp.exists(pyls_installation_egg): Index: spyder-5.0.5/external-deps/python-language-server/.circleci/config.yml =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/.circleci/config.yml +++ /dev/null @@ -1,60 +0,0 @@ -version: 2 - -jobs: - python2-test: - docker: - - image: "python:2.7-stretch" - steps: - - checkout - - run: pip install -e .[all] .[test] - - run: py.test -v test/ - - run: pylint pyls test - - run: pycodestyle pyls test - - run: pyflakes pyls test - - python3-test: - docker: - - image: "python:3.6-stretch" - steps: - - checkout - # To test Jedi environments - - run: python3 -m venv /tmp/pyenv - - run: /tmp/pyenv/bin/python -m pip install loghub - - run: pip install -e .[all] .[test] - - run: py.test -v test/ - - lint: - docker: - - image: "python:2.7-stretch" - steps: - - checkout - - run: pip install -e .[all] .[test] - - run: pylint pyls test - - run: pycodestyle pyls test - - run: pyflakes pyls test - - publish: - docker: - - image: "python:3.6-stretch" - steps: - - checkout - - run: ./scripts/circle/pypi.sh - - -workflows: - version: 2 - build: - jobs: - - python2-test: - filters: { tags: { only: /.*/ } } - - python3-test: - filters: { tags: { only: /.*/ } } - - publish: - filters: - tags: - only: /[0-9]+(\.[0-9]+)+((-(beta|rc)[0-9]{1,2})(\.[0-9])?)?/ - branches: - ignore: /.*/ - requires: - - python2-test - - python3-test Index: spyder-5.0.5/external-deps/python-language-server/.coveragerc =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/.coveragerc +++ /dev/null @@ -1,2 +0,0 @@ -[run] -omit = pyls/_version.py Index: spyder-5.0.5/external-deps/python-language-server/.gitattributes =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -pyls/_version.py export-subst Index: spyder-5.0.5/external-deps/python-language-server/README.rst =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/README.rst +++ /dev/null @@ -1,168 +0,0 @@ -Python Language Server -====================== - -.. image:: https://github.com/palantir/python-language-server/workflows/Linux%20tests/badge.svg - :target: https://github.com/palantir/python-language-server/actions?query=workflow%3A%22Linux+tests%22 - -.. image:: https://github.com/palantir/python-language-server/workflows/Mac%20tests/badge.svg - :target: https://github.com/palantir/python-language-server/actions?query=workflow%3A%22Mac+tests%22 - -.. image:: https://github.com/palantir/python-language-server/workflows/Windows%20tests/badge.svg - :target: https://github.com/palantir/python-language-server/actions?query=workflow%3A%22Windows+tests%22 - -.. image:: https://img.shields.io/github/license/palantir/python-language-server.svg - :target: https://github.com/palantir/python-language-server/blob/master/LICENSE - -A Python 2.7 and 3.5+ implementation of the `Language Server Protocol`_. - -Installation ------------- - -The base language server requires Jedi_ to provide Completions, Definitions, Hover, References, Signature Help, and -Symbols: - -``pip install python-language-server`` - -If the respective dependencies are found, the following optional providers will be enabled: - -* Rope_ for Completions and renaming -* Pyflakes_ linter to detect various errors -* McCabe_ linter for complexity checking -* pycodestyle_ linter for style checking -* pydocstyle_ linter for docstring style checking (disabled by default) -* autopep8_ for code formatting -* YAPF_ for code formatting (preferred over autopep8) - -Optional providers can be installed using the `extras` syntax. To install YAPF_ formatting for example: - -``pip install 'python-language-server[yapf]'`` - -All optional providers can be installed using: - -``pip install 'python-language-server[all]'`` - -If you get an error similar to ``'install_requires' must be a string or list of strings`` then please upgrade setuptools before trying again. - -``pip install -U setuptools`` - -3rd Party Plugins -~~~~~~~~~~~~~~~~~ -Installing these plugins will add extra functionality to the language server: - -* pyls-mypy_ Mypy type checking for Python 3 -* pyls-isort_ Isort import sort code formatting -* pyls-black_ for code formatting using Black_ - -Please see the above repositories for examples on how to write plugins for the Python Language Server. Please file an -issue if you require assistance writing a plugin. - -Configuration -------------- - -Configuration is loaded from zero or more configuration sources. Currently implemented are: - -* pycodestyle: discovered in ~/.config/pycodestyle, setup.cfg, tox.ini and pycodestyle.cfg. -* flake8: discovered in ~/.config/flake8, setup.cfg, tox.ini and flake8.cfg - -The default configuration source is pycodestyle. Change the `pyls.configurationSources` setting to `['flake8']` in -order to respect flake8 configuration instead. - -Overall configuration is computed first from user configuration (in home directory), overridden by configuration -passed in by the language client, and then overriden by configuration discovered in the workspace. - -To enable pydocstyle for linting docstrings add the following setting in your LSP configuration: -``` -"pyls.plugins.pydocstyle.enabled": true -``` - -See `vscode-client/package.json`_ for the full set of supported configuration options. - -.. _vscode-client/package.json: vscode-client/package.json - -Language Server Features ------------------------- - -Auto Completion: - -.. image:: https://raw.githubusercontent.com/palantir/python-language-server/develop/resources/auto-complete.gif - -Code Linting with pycodestyle and pyflakes: - -.. image:: https://raw.githubusercontent.com/palantir/python-language-server/develop/resources/linting.gif - -Signature Help: - -.. image:: https://raw.githubusercontent.com/palantir/python-language-server/develop/resources/signature-help.gif - -Go to definition: - -.. image:: https://raw.githubusercontent.com/palantir/python-language-server/develop/resources/goto-definition.gif - -Hover: - -.. image:: https://raw.githubusercontent.com/palantir/python-language-server/develop/resources/hover.gif - -Find References: - -.. image:: https://raw.githubusercontent.com/palantir/python-language-server/develop/resources/references.gif - -Document Symbols: - -.. image:: https://raw.githubusercontent.com/palantir/python-language-server/develop/resources/document-symbols.gif - -Document Formatting: - -.. image:: https://raw.githubusercontent.com/palantir/python-language-server/develop/resources/document-format.gif - -Development ------------ - -To run the test suite: - -``pip install .[test] && pytest`` - -Develop against VS Code -======================= - -The Python language server can be developed against a local instance of Visual Studio Code. - -Install `VSCode <https://code.visualstudio.com/download>`_ - -.. code-block:: bash - - # Setup a virtual env - virtualenv env - . env/bin/activate - - # Install pyls - pip install . - - # Install the vscode-client extension - cd vscode-client - yarn install - - # Run VSCode which is configured to use pyls - # See the bottom of vscode-client/src/extension.ts for info - yarn run vscode -- $PWD/../ - -Then to debug, click View -> Output and in the dropdown will be pyls. -To refresh VSCode, press `Cmd + r` - -License -------- - -This project is made available under the MIT License. - -.. _Language Server Protocol: https://github.com/Microsoft/language-server-protocol -.. _Jedi: https://github.com/davidhalter/jedi -.. _Rope: https://github.com/python-rope/rope -.. _Pyflakes: https://github.com/PyCQA/pyflakes -.. _McCabe: https://github.com/PyCQA/mccabe -.. _pycodestyle: https://github.com/PyCQA/pycodestyle -.. _pydocstyle: https://github.com/PyCQA/pydocstyle -.. _YAPF: https://github.com/google/yapf -.. _autopep8: https://github.com/hhatto/autopep8 -.. _pyls-mypy: https://github.com/tomv564/pyls-mypy -.. _pyls-isort: https://github.com/paradoxxxzero/pyls-isort -.. _pyls-black: https://github.com/rupert/pyls-black -.. _Black: https://github.com/ambv/black Index: spyder-5.0.5/external-deps/python-language-server/RELEASE.md =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/RELEASE.md +++ /dev/null @@ -1,11 +0,0 @@ -To release a new version of the PyLS you need to follow these steps: - -* Close the current milestone on Github - -* git pull or git fetch/merge - -* git tag -a X.X.X -m 'Release X.X.X' - -* git push upstream --tags - -* Publish release in our Github Releases page Index: spyder-5.0.5/external-deps/python-language-server/pyls/__init__.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import os -import sys -import pluggy -from ._version import get_versions - -if sys.version_info[0] < 3: - from future.standard_library import install_aliases - install_aliases() - -__version__ = get_versions()['version'] -del get_versions - -PYLS = 'pyls' - -hookspec = pluggy.HookspecMarker(PYLS) -hookimpl = pluggy.HookimplMarker(PYLS) - -IS_WIN = os.name == 'nt' Index: spyder-5.0.5/external-deps/python-language-server/pyls/config/__init__.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/config/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. Index: spyder-5.0.5/external-deps/python-language-server/pyls/hookspecs.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/hookspecs.py +++ /dev/null @@ -1,122 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -# pylint: disable=redefined-builtin, unused-argument -from pyls import hookspec - - -@hookspec -def pyls_code_actions(config, workspace, document, range, context): - pass - - -@hookspec -def pyls_code_lens(config, workspace, document): - pass - - -@hookspec -def pyls_commands(config, workspace): - """The list of command strings supported by the server. - - Returns: - List[str]: The supported commands. - """ - - -@hookspec -def pyls_completions(config, workspace, document, position): - pass - - -@hookspec -def pyls_definitions(config, workspace, document, position): - pass - - -@hookspec -def pyls_dispatchers(config, workspace): - pass - - -@hookspec -def pyls_document_did_open(config, workspace, document): - pass - - -@hookspec -def pyls_document_did_save(config, workspace, document): - pass - - -@hookspec -def pyls_document_highlight(config, workspace, document, position): - pass - - -@hookspec -def pyls_document_symbols(config, workspace, document): - pass - - -@hookspec(firstresult=True) -def pyls_execute_command(config, workspace, command, arguments): - pass - - -@hookspec -def pyls_experimental_capabilities(config, workspace): - pass - - -@hookspec -def pyls_folding_range(config, workspace, document): - pass - - -@hookspec(firstresult=True) -def pyls_format_document(config, workspace, document): - pass - - -@hookspec(firstresult=True) -def pyls_format_range(config, workspace, document, range): - pass - - -@hookspec(firstresult=True) -def pyls_hover(config, workspace, document, position): - pass - - -@hookspec -def pyls_initialize(config, workspace): - pass - - -@hookspec -def pyls_initialized(): - pass - - -@hookspec -def pyls_lint(config, workspace, document, is_saved): - pass - - -@hookspec -def pyls_references(config, workspace, document, position, exclude_declaration): - pass - - -@hookspec(firstresult=True) -def pyls_rename(config, workspace, document, position, new_name): - pass - - -@hookspec -def pyls_settings(config): - pass - - -@hookspec(firstresult=True) -def pyls_signature_help(config, workspace, document, position): - pass Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/__init__.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. Index: spyder-5.0.5/external-deps/python-language-server/setup.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/setup.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python -import sys -from setuptools import find_packages, setup -import versioneer -import sys - -README = open('README.rst', 'r').read() - -install_requires = [ - 'configparser; python_version<"3.0"', - 'future>=0.14.0; python_version<"3"', - 'backports.functools_lru_cache; python_version<"3.2"', - 'jedi>=0.17.2,<0.18.0', - 'python-jsonrpc-server>=0.4.0', - 'pluggy', - 'ujson<=2.0.3 ; platform_system!="Windows" and python_version<"3.0"', - 'ujson>=3.0.0 ; python_version>"3"'] - -setup( - name='python-language-server', - - # Versions should comply with PEP440. For a discussion on single-sourcing - # the version across setup.py and the project code, see - # https://packaging.python.org/en/latest/single_source_version.html - version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), - - description='Python Language Server for the Language Server Protocol', - - long_description=README, - - # The project's main homepage. - url='https://github.com/palantir/python-language-server', - - author='Palantir Technologies, Inc.', - - # You can just specify the packages manually here if your project is - # simple. Or you can use find_packages(). - packages=find_packages(exclude=['contrib', 'docs', 'test', 'test.*']), - - # List run-time dependencies here. These will be installed by pip when - # your project is installed. For an analysis of "install_requires" vs pip's - # requirements files see: - # https://packaging.python.org/en/latest/requirements.html - install_requires=install_requires, - - # List additional groups of dependencies here (e.g. development - # dependencies). You can install these using the following syntax, - # for example: - # $ pip install -e .[test] - extras_require={ - 'all': [ - 'autopep8', - 'flake8>=3.8.0', - 'mccabe>=0.6.0,<0.7.0', - 'pycodestyle>=2.6.0,<2.7.0', - 'pydocstyle>=2.0.0', - 'pyflakes>=2.2.0,<2.3.0', - # pylint >= 2.5.0 is required for working through stdin and only - # available with python3 - 'pylint>=2.5.0' if sys.version_info.major >= 3 else 'pylint', - 'rope>=0.10.5', - 'yapf', - ], - 'autopep8': ['autopep8'], - 'flake8': ['flake8>=3.8.0'], - 'mccabe': ['mccabe>=0.6.0,<0.7.0'], - 'pycodestyle': ['pycodestyle>=2.6.0,<2.7.0'], - 'pydocstyle': ['pydocstyle>=2.0.0'], - 'pyflakes': ['pyflakes>=2.2.0,<2.3.0'], - 'pylint': [ - 'pylint>=2.5.0' if sys.version_info.major >= 3 else 'pylint'], - 'rope': ['rope>0.10.5'], - 'yapf': ['yapf'], - 'test': ['versioneer', - 'pylint>=2.5.0' if sys.version_info.major >= 3 else 'pylint', - 'pytest', 'mock', 'pytest-cov', 'coverage', 'numpy', 'pandas', - 'matplotlib', 'pyqt5;python_version>="3"', 'flaky'], - }, - - # To provide executable scripts, use entry points in preference to the - # "scripts" keyword. Entry points provide cross-platform support and allow - # pip to create the appropriate form of executable for the target platform. - entry_points={ - 'console_scripts': [ - 'pyls = pyls.__main__:main', - ], - 'pyls': [ - 'autopep8 = pyls.plugins.autopep8_format', - 'folding = pyls.plugins.folding', - 'flake8 = pyls.plugins.flake8_lint', - 'jedi_completion = pyls.plugins.jedi_completion', - 'jedi_definition = pyls.plugins.definition', - 'jedi_hover = pyls.plugins.hover', - 'jedi_highlight = pyls.plugins.highlight', - 'jedi_references = pyls.plugins.references', - 'jedi_rename = pyls.plugins.jedi_rename', - 'jedi_signature_help = pyls.plugins.signature', - 'jedi_symbols = pyls.plugins.symbols', - 'mccabe = pyls.plugins.mccabe_lint', - 'preload = pyls.plugins.preload_imports', - 'pycodestyle = pyls.plugins.pycodestyle_lint', - 'pydocstyle = pyls.plugins.pydocstyle_lint', - 'pyflakes = pyls.plugins.pyflakes_lint', - 'pylint = pyls.plugins.pylint_lint', - 'rope_completion = pyls.plugins.rope_completion', - 'rope_rename = pyls.plugins.rope_rename', - 'yapf = pyls.plugins.yapf_format' - ] - }, -) Index: spyder-5.0.5/external-deps/python-language-server/versioneer.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/versioneer.py +++ /dev/null @@ -1,1822 +0,0 @@ - -# Version: 0.18 - -"""The Versioneer - like a rocketeer, but for versions. - -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/warner/python-versioneer -* Brian Warner -* License: Public Domain -* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy -* [![Latest Version] -(https://pypip.in/version/versioneer/badge.svg?style=flat) -](https://pypi.python.org/pypi/versioneer/) -* [![Build Status] -(https://travis-ci.org/warner/python-versioneer.png?branch=master) -](https://travis-ci.org/warner/python-versioneer) - -This is a tool for managing a recorded version number in distutils-based -python projects. The goal is to remove the tedious and error-prone "update -the embedded version string" step from your release process. Making a new -release should be as easy as recording a new tag in your version-control -system, and maybe making new tarballs. - - -## Quick Install - -* `pip install versioneer` to somewhere to your $PATH -* add a `[versioneer]` section to your setup.cfg (see below) -* run `versioneer install` in your source tree, commit the results - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like github's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -for example `git describe --tags --dirty --always` reports things like -"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the -0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes. - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -See [INSTALL.md](./INSTALL.md) for detailed installation instructions. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the - commit date in ISO 8601 format. This will be None if the date is not - available. - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See [details.md](details.md) in the Versioneer -source tree for descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Known Limitations - -Some situations are known to cause problems for Versioneer. This details the -most significant ones. More can be found on Github -[issues page](https://github.com/warner/python-versioneer/issues). - -### Subprojects - -Versioneer has limited support for source trees in which `setup.py` is not in -the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are -two common reasons why `setup.py` might not be in the root: - -* Source trees which contain multiple subprojects, such as - [Buildbot](https://github.com/buildbot/buildbot), which contains both - "master" and "slave" subprojects, each with their own `setup.py`, - `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI - distributions (and upload multiple independently-installable tarballs). -* Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other langauges) in subdirectories. - -Versioneer will look for `.git` in parent directories, and most operations -should get the right version string. However `pip` and `setuptools` have bugs -and implementation details which frequently cause `pip install .` from a -subproject directory to fail to find a correct version string (so it usually -defaults to `0+unknown`). - -`pip install --editable .` should work correctly. `setup.py install` might -work too. - -Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in -some later version. - -[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking -this issue. The discussion in -[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the -issue from the Versioneer side in more detail. -[pip PR#3176](https://github.com/pypa/pip/pull/3176) and -[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve -pip to let Versioneer work correctly. - -Versioneer-0.16 and earlier only looked for a `.git` directory next to the -`setup.cfg`, so subprojects were completely unsupported with those releases. - -### Editable installs with setuptools <= 18.5 - -`setup.py develop` and `pip install --editable .` allow you to install a -project into a virtualenv once, then continue editing the source code (and -test) without re-installing after every change. - -"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a -convenient way to specify executable scripts that should be installed along -with the python package. - -These both work as expected when using modern setuptools. When using -setuptools-18.5 or earlier, however, certain operations will cause -`pkg_resources.DistributionNotFound` errors when running the entrypoint -script, which must be resolved by re-installing the package. This happens -when the install happens with one version, then the egg_info data is -regenerated while a different version is checked out. Many setup.py commands -cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into -a different virtualenv), so this can be surprising. - -[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes -this one, but upgrading to a newer version of setuptools should probably -resolve it. - -### Unicode version strings - -While Versioneer works (and is continually tested) with both Python 2 and -Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. -Newer releases probably generate unicode version strings on py2. It's not -clear that this is wrong, but it may be surprising for applications when then -write these strings to a network connection or include them in bytes-oriented -APIs like cryptographic checksums. - -[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates -this question. - - -## Updating Versioneer - -To upgrade your project to a new release of Versioneer, do the following: - -* install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg`, if necessary, to include any new configuration settings - indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -direction and include code from all supported VCS systems, reducing the -number of intermediate scripts. - - -## License - -To make Versioneer easier to embed, all its code is dedicated to the public -domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the Creative Commons "Public Domain -Dedication" license (CC0-1.0), as described in -https://creativecommons.org/publicdomain/zero/1.0/ . - -""" - -from __future__ import print_function -try: - import configparser -except ImportError: - import ConfigParser as configparser -import errno -import json -import os -import re -import subprocess -import sys - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_root(): - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - me = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(me)[0]) - vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir: - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(me), versioneer_py)) - except NameError: - pass - return root - - -def get_config_from_root(root): - """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise EnvironmentError (if setup.cfg is missing), or - # configparser.NoSectionError (if it lacks a [versioneer] section), or - # configparser.NoOptionError (if it lacks "VCS="). See the docstring at - # the top of versioneer.py for instructions on writing your setup.cfg . - setup_cfg = os.path.join(root, "setup.cfg") - parser = configparser.SafeConfigParser() - with open(setup_cfg, "r") as f: - parser.readfp(f) - VCS = parser.get("versioneer", "VCS") # mandatory - - def get(parser, name): - if parser.has_option("versioneer", name): - return parser.get("versioneer", name) - return None - cfg = VersioneerConfig() - cfg.VCS = VCS - cfg.style = get(parser, "style") or "" - cfg.versionfile_source = get(parser, "versionfile_source") - cfg.versionfile_build = get(parser, "versionfile_build") - cfg.tag_prefix = get(parser, "tag_prefix") - if cfg.tag_prefix in ("''", '""'): - cfg.tag_prefix = "" - cfg.parentdir_prefix = get(parser, "parentdir_prefix") - cfg.verbose = get(parser, "verbose") - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode - - -LONG_VERSION_PY['git'] = ''' -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. Generated by -# versioneer-0.18 (https://github.com/warner/python-versioneer) - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %%s (error)" %% dispcmd) - print("stdout was %%s" %% stdout) - return None, p.returncode - return stdout, p.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %%s but none started with prefix %%s" %% - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - date = keywords.get("date") - if date is not None: - # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %%d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs - tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %%s" %% r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%%s*" %% tag_prefix], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], - cwd=root)[0].strip() - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%%d" %% pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Eexceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - date = keywords.get("date") - if date is not None: - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], - cwd=root)[0].strip() - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def do_vcs_install(manifest_in, versionfile_source, ipy): - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-subst keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [manifest_in, versionfile_source] - if ipy: - files.append(ipy) - try: - me = __file__ - if me.endswith(".pyc") or me.endswith(".pyo"): - me = os.path.splitext(me)[0] + ".py" - versioneer_file = os.path.relpath(me) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) - present = False - try: - f = open(".gitattributes", "r") - for line in f.readlines(): - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - f.close() - except EnvironmentError: - pass - if not present: - f = open(".gitattributes", "a+") - f.write("%s export-subst\n" % versionfile_source) - f.close() - files.append(".gitattributes") - run_command(GITS, ["add", "--"] + files) - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.18) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename): - """Try to determine the version from _version.py if present.""" - try: - with open(filename) as f: - contents = f.read() - except EnvironmentError: - raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename, versions): - """Write the given version number to the given _version.py file.""" - os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Eexceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -class VersioneerBadRootError(Exception): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose=False): - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or github's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version", - "date": None} - - -def get_version(): - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(): - """Get the custom setuptools/distutils subclasses used by Versioneer.""" - if "versioneer" in sys.modules: - del sys.modules["versioneer"] - # this fixes the "python setup.py develop" case (also 'install' and - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to it's pre-build state, so the - # parent is protected against the child's "import versioneer". By - # removing ourselves from sys.modules here, before the child build - # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/warner/python-versioneer/issues/52 - - cmds = {} - - # we add "version" to both distutils and setuptools - from distutils.core import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - print(" date: %s" % vers.get("date")) - if vers["error"]: - print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - - # we override "build_py" in both distutils and setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # we override different "build_py" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.build_py import build_py as _build_py - else: - from distutils.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe - # nczeczulin reports that py2exe won't like the pep440-style string - # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. - # setup(console=[{ - # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION - # "product_version": versioneer.get_version(), - # ... - - class cmd_build_exe(_build_exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - if 'py2exe' in sys.modules: # py2exe enabled? - try: - from py2exe.distutils_buildexe import py2exe as _py2exe # py3 - except ImportError: - from py2exe.build_exe import py2exe as _py2exe # py2 - - class cmd_py2exe(_py2exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _py2exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["py2exe"] = cmd_py2exe - - # we override different "sdist" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist - else: - from distutils.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -INIT_PY_SNIPPET = """ -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions -""" - - -def do_setup(): - """Main VCS-independent setup function for installing Versioneer.""" - root = get_root() - try: - cfg = get_config_from_root(root) - except (EnvironmentError, configparser.NoSectionError, - configparser.NoOptionError) as e: - if isinstance(e, (EnvironmentError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except EnvironmentError: - old = "" - if INIT_PY_SNIPPET not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(INIT_PY_SNIPPET) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make sure both the top-level "versioneer.py" and versionfile_source - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so - # they'll be copied into source distributions. Pip won't be able to - # install the package without this. - manifest_in = os.path.join(root, "MANIFEST.in") - simple_includes = set() - try: - with open(manifest_in, "r") as f: - for line in f: - if line.startswith("include "): - for include in line.split()[1:]: - simple_includes.add(include) - except EnvironmentError: - pass - # That doesn't cover everything MANIFEST.in can do - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so - # it might give some false negatives. Appending redundant 'include' - # lines is safe, though. - if "versioneer.py" not in simple_includes: - print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: - f.write("include versioneer.py\n") - else: - print(" 'versioneer.py' already in MANIFEST.in") - if cfg.versionfile_source not in simple_includes: - print(" appending versionfile_source ('%s') to MANIFEST.in" % - cfg.versionfile_source) - with open(manifest_in, "a") as f: - f.write("include %s\n" % cfg.versionfile_source) - else: - print(" versionfile_source already in MANIFEST.in") - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-subst keyword - # substitution. - do_vcs_install(manifest_in, cfg.versionfile_source, ipy) - return 0 - - -def scan_setup_py(): - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1) Index: spyder-5.0.5/external-deps/python-language-server/vscode-client/.gitignore =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/vscode-client/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -out -server -node_modules -.vscode-dev \ No newline at end of file Index: spyder-5.0.5/external-deps/python-language-server/vscode-client/.vscodeignore =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/vscode-client/.vscodeignore +++ /dev/null @@ -1,9 +0,0 @@ -.vscode/** -typings/** -out/test/** -test/** -src/** -**/*.map -.gitignore -tsconfig.json -vsc-extension-quickstart.md Index: spyder-5.0.5/external-deps/python-language-server/vscode-client/License.txt =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/vscode-client/License.txt +++ /dev/null @@ -1,11 +0,0 @@ -Copyright (c) Microsoft Corporation - -All rights reserved. - -MIT License - -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. Index: spyder-5.0.5/external-deps/python-language-server/vscode-client/README.md =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/vscode-client/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# vscode-client - -The vscode-client extension for Visual Studio Code helps you develop -and debug language servers. It lets you run multiple language servers -at once with minimal extra configuration per language. - -## Using this extension - - -1. Follow the [Develop against VS Code instructions](/../../#develop-against-vs-code) -1. Open a `.py` file and hover over text to start using the Python language server. - -To view a language server's stderr output in VSCode, select View → Output. -To debug further, see the "Hacking on this extension" section below. - -After updating the binary for a language server (during development or after an upgrade), just kill the process (e.g., `killall pyls`). -VSCode will automatically restart and reconnect to the language server process. - -> **Note for those who use VSCode as their primary editor:** Because this extension's functionality conflicts with other VSCode extensions -(e.g., showing Python hover information), the `yarn run vscode` script launches a separate instance of VSCode and stores its config in `../.vscode-dev`. -It will still show your existing extensions in the panel (which seems to be a VSCode bug), but they won't be activated. - -## Adding a language server - -Register your language server at the bottom of [`extension.ts`](src/extension.ts). - -## Hacking on this extension - -1. Run `yarn install` in this directory (`vscode-client`). -1. Open this directory by itself in Visual Studio Code. -1. Hit F5 to open a new VSCode instance in a debugger running this extension. (This is equivalent to going to the Debug pane on the left and running the "Launch Extension" task.) - -See the [Node.js example language server tutorial](https://code.visualstudio.com/docs/extensions/example-language-server) under "To test the language server" for more information. Index: spyder-5.0.5/external-deps/python-language-server/vscode-client/ThirdPartyNotices.txt =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/vscode-client/ThirdPartyNotices.txt +++ /dev/null @@ -1,31 +0,0 @@ -THIRD-PARTY SOFTWARE NOTICES AND INFORMATION -For Microsoft vscode-languageserver-node-example - -This project incorporates material from the project(s) listed below (collectively, “Third Party Code”). -Microsoft is not the original author of the Third Party Code. The original copyright notice and license -under which Microsoft received such Third Party Code are set out below. This Third Party Code is licensed -to you under their original license terms set forth below. Microsoft reserves all other rights not expressly -granted, whether by implication, estoppel or otherwise. - -1. DefinitelyTyped version 0.0.1 (https://github.com/borisyankov/DefinitelyTyped) - -This project is licensed under the MIT license. -Copyrights are respective of each contributor listed at the beginning of each definition file. - -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. \ No newline at end of file Index: spyder-5.0.5/external-deps/python-language-server/vscode-client/package.json =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/vscode-client/package.json +++ /dev/null @@ -1,316 +0,0 @@ -{ - "name": "pyls", - "description": "Python language server", - "author": "Sourcegraph", - "repository": "https://github.com/Microsoft/vscode-languageserver-node", - "license": "MIT", - "version": "0.0.1", - "publisher": "sqs", - "engines": { - "vscode": "^1.15.0" - }, - "categories": [ - "Other" - ], - "activationEvents": [ - "*" - ], - "contributes": { - "configuration": { - "title": "Python Language Server Configuration", - "type": "object", - "properties": { - "pyls.executable": { - "type": "string", - "default": "pyls", - "description": "Language server executable" - }, - "pyls.configurationSources": { - "type": "array", - "default": ["pycodestyle"], - "description": "List of configuration sources to use.", - "items": { - "type": "string", - "enum": ["pycodestyle", "pyflakes"] - }, - "uniqueItems": true - }, - "pyls.plugins.jedi.extra_paths": { - "type": "array", - "default": [], - "description": "Define extra paths for jedi.Script." - }, - "pyls.plugins.jedi.env_vars": { - "type": "dictionary", - "default": null, - "description": "Define environment variables for jedi.Script and Jedi.names." - }, - "pyls.plugins.jedi.environment": { - "type": "string", - "default": null, - "description": "Define environment for jedi.Script and Jedi.names." - }, - "pyls.plugins.jedi_completion.enabled": { - "type": "boolean", - "default": true, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.jedi_completion.include_params": { - "type": "boolean", - "default": true, - "description": "Auto-completes methods and classes with tabstops for each parameter." - }, - "pyls.plugins.jedi_completion.include_class_objects": { - "type": "boolean", - "default": true, - "description": "Adds class objects as a separate completion item." - }, - "pyls.plugins.jedi_completion.fuzzy": { - "type": "boolean", - "default": false, - "description": "Enable fuzzy when requesting autocomplete." - }, - "pyls.plugins.jedi_definition.enabled": { - "type": "boolean", - "default": true, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.jedi_definition.follow_imports": { - "type": "boolean", - "default": true, - "description": "The goto call will follow imports." - }, - "pyls.plugins.jedi_definition.follow_builtin_imports": { - "type": "boolean", - "default": true, - "description": "If follow_imports is True will decide if it follow builtin imports." - }, - "pyls.plugins.jedi_hover.enabled": { - "type": "boolean", - "default": true, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.jedi_references.enabled": { - "type": "boolean", - "default": true, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.jedi_signature_help.enabled": { - "type": "boolean", - "default": true, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.jedi_symbols.enabled": { - "type": "boolean", - "default": true, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.jedi_symbols.all_scopes": { - "type": "boolean", - "default": true, - "description": "If True lists the names of all scopes instead of only the module namespace." - }, - "pyls.plugins.mccabe.enabled": { - "type": "boolean", - "default": true, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.mccabe.threshold": { - "type": "number", - "default": 15, - "description": "The minimum threshold that triggers warnings about cyclomatic complexity." - }, - "pyls.plugins.preload.enabled": { - "type": "boolean", - "default": true, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.preload.modules": { - "type": "array", - "default": null, - "items": { - "type": "string" - }, - "uniqueItems": true, - "description": "List of modules to import on startup" - }, - "pyls.plugins.pycodestyle.enabled": { - "type": "boolean", - "default": true, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.pycodestyle.exclude": { - "type": "array", - "default": null, - "items": { - "type": "string" - }, - "uniqueItems": true, - "description": "Exclude files or directories which match these patterns." - }, - "pyls.plugins.pycodestyle.filename": { - "type": "array", - "default": null, - "items": { - "type": "string" - }, - "uniqueItems": true, - "description": "When parsing directories, only check filenames matching these patterns." - }, - "pyls.plugins.pycodestyle.select": { - "type": "array", - "default": null, - "items": { - "type": "string" - }, - "uniqueItems": true, - "description": "Select errors and warnings" - }, - "pyls.plugins.pycodestyle.ignore": { - "type": "array", - "default": null, - "items": { - "type": "string" - }, - "uniqueItems": true, - "description": "Ignore errors and warnings" - }, - "pyls.plugins.pycodestyle.hangClosing": { - "type": "boolean", - "default": null, - "description": "Hang closing bracket instead of matching indentation of opening bracket's line." - }, - "pyls.plugins.pycodestyle.maxLineLength": { - "type": "number", - "default": null, - "description": "Set maximum allowed line length." - }, - "pyls.plugins.pydocstyle.enabled": { - "type": "boolean", - "default": false, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.pydocstyle.convention": { - "type": "string", - "default": null, - "enum": [ - "pep257", - "numpy" - ], - "description": "Choose the basic list of checked errors by specifying an existing convention." - }, - "pyls.plugins.pydocstyle.addIgnore": { - "type": "array", - "default": null, - "items": { - "type": "string" - }, - "uniqueItems": true, - "description": "Ignore errors and warnings in addition to the specified convention." - }, - "pyls.plugins.pydocstyle.addSelect": { - "type": "array", - "default": null, - "items": { - "type": "string" - }, - "uniqueItems": true, - "description": "Select errors and warnings in addition to the specified convention." - }, - "pyls.plugins.pydocstyle.ignore": { - "type": "array", - "default": null, - "items": { - "type": "string" - }, - "uniqueItems": true, - "description": "Ignore errors and warnings" - }, - "pyls.plugins.pydocstyle.select": { - "type": "array", - "default": null, - "items": { - "type": "string" - }, - "uniqueItems": true, - "description": "Select errors and warnings" - }, - "pyls.plugins.pydocstyle.match": { - "type": "string", - "default": "(?!test_).*\\.py", - "description": "Check only files that exactly match the given regular expression; default is to match files that don't start with 'test_' but end with '.py'." - }, - "pyls.plugins.pydocstyle.matchDir": { - "type": "string", - "default": "[^\\.].*", - "description": "Search only dirs that exactly match the given regular expression; default is to match dirs which do not begin with a dot." - }, - "pyls.plugins.pyflakes.enabled": { - "type": "boolean", - "default": true, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.pylint.enabled": { - "type": "boolean", - "default": false, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.pylint.args": { - "type": "array", - "default": null, - "items": { - "type": "string" - }, - "uniqueItems": false, - "description": "Arguments to pass to pylint." - }, - "pyls.plugins.pylint.executable": { - "type": "string", - "default": null, - "description": "Executable to run pylint with. Enabling this will run pylint on unsaved files via stdin. Can slow down workflow. Only works with python3." - }, - "pyls.plugins.rope_completion.enabled": { - "type": "boolean", - "default": true, - "description": "Enable or disable the plugin." - }, - "pyls.plugins.yapf.enabled": { - "type": "boolean", - "default": true, - "description": "Enable or disable the plugin." - }, - "pyls.rope.extensionModules": { - "type": "string", - "default": null, - "description": "Builtin and c-extension modules that are allowed to be imported and inspected by rope." - }, - "pyls.rope.ropeFolder": { - "type": "array", - "default": null, - "items": { - "type": "string" - }, - "uniqueItems": true, - "description": "The name of the folder in which rope stores project configurations and data. Pass `null` for not using such a folder at all." - } - } - } - }, - "main": "./out/extension", - "scripts": { - "vscode:prepublish": "tsc -p ./", - "compile": "tsc -watch -p ./", - "postinstall": "node ./node_modules/vscode/bin/install", - "vscode": "npm run vscode:prepublish && VSCODE=$(which code-insiders || which code || echo echo ERROR: neither the code nor code-insiders vscode executable is installed); USER=dummy-dont-share-vscode-instance $VSCODE --user-data-dir=$PWD/.vscode-dev/user-data --extensionHomePath=$PWD/.vscode-dev/extensions --extensionDevelopmentPath=$PWD $*" - }, - "devDependencies": { - "typescript": "^2.3.4", - "vscode": "^1.1.4", - "mocha": "^2.3.3", - "@types/node": "^6.0.40", - "@types/mocha": "^2.2.32" - }, - "dependencies": { - "vscode-languageclient": "^3.4.5" - } -} Index: spyder-5.0.5/external-deps/python-language-server/vscode-client/src/extension.ts =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/vscode-client/src/extension.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -'use strict'; - -import * as net from 'net'; - -import { workspace, Disposable, ExtensionContext } from 'vscode'; -import { LanguageClient, LanguageClientOptions, SettingMonitor, ServerOptions, ErrorAction, ErrorHandler, CloseAction, TransportKind } from 'vscode-languageclient'; - -function startLangServer(command: string, args: string[], documentSelector: string[]): Disposable { - const serverOptions: ServerOptions = { - command, - args, - }; - const clientOptions: LanguageClientOptions = { - documentSelector: documentSelector, - synchronize: { - configurationSection: "pyls" - } - } - return new LanguageClient(command, serverOptions, clientOptions).start(); -} - -function startLangServerTCP(addr: number, documentSelector: string[]): Disposable { - const serverOptions: ServerOptions = function() { - return new Promise((resolve, reject) => { - var client = new net.Socket(); - client.connect(addr, "127.0.0.1", function() { - resolve({ - reader: client, - writer: client - }); - }); - }); - } - - const clientOptions: LanguageClientOptions = { - documentSelector: documentSelector, - } - return new LanguageClient(`tcp lang server (port ${addr})`, serverOptions, clientOptions).start(); -} - -export function activate(context: ExtensionContext) { - const executable = workspace.getConfiguration("pyls").get<string>("executable"); - context.subscriptions.push(startLangServer(executable, ["-vv"], ["python"])); - // For TCP server needs to be started seperately - // context.subscriptions.push(startLangServerTCP(2087, ["python"])); -} - Index: spyder-5.0.5/external-deps/python-language-server/vscode-client/tsconfig.json =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/vscode-client/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "outDir": "out", - "lib": [ "es6" ], - "sourceMap": true - }, - "exclude": [ - "node_modules", - "server" - ] -} Index: spyder-5.0.5/external-deps/python-language-server/vscode-client/yarn.lock =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/vscode-client/yarn.lock +++ /dev/null @@ -1,1867 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -"@types/mocha@^2.2.32": - version "2.2.46" - resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-2.2.46.tgz#b04713f7759d1cf752effdaae7b3969e285ebc16" - -"@types/node@^6.0.40": - version "6.0.96" - resolved "https://registry.yarnpkg.com/@types/node/-/node-6.0.96.tgz#7bf0bf40d6ce51e93762cc47d010c8cc5ebb2179" - -ajv@^5.1.0: - version "5.5.2" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-5.5.2.tgz#73b5eeca3fab653e3d3f9422b341ad42205dc965" - dependencies: - co "^4.6.0" - fast-deep-equal "^1.0.0" - fast-json-stable-stringify "^2.0.0" - json-schema-traverse "^0.3.0" - -ansi-cyan@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/ansi-cyan/-/ansi-cyan-0.1.1.tgz#538ae528af8982f28ae30d86f2f17456d2609873" - dependencies: - ansi-wrap "0.1.0" - -ansi-gray@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/ansi-gray/-/ansi-gray-0.1.1.tgz#2962cf54ec9792c48510a3deb524436861ef7251" - dependencies: - ansi-wrap "0.1.0" - -ansi-red@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/ansi-red/-/ansi-red-0.1.1.tgz#8c638f9d1080800a353c9c28c8a81ca4705d946c" - dependencies: - ansi-wrap "0.1.0" - -ansi-regex@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" - -ansi-styles@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" - -ansi-wrap@0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/ansi-wrap/-/ansi-wrap-0.1.0.tgz#a82250ddb0015e9a27ca82e82ea603bbfa45efaf" - -arr-diff@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-1.1.0.tgz#687c32758163588fef7de7b36fabe495eb1a399a" - dependencies: - arr-flatten "^1.0.1" - array-slice "^0.2.3" - -arr-diff@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-2.0.0.tgz#8f3b827f955a8bd669697e4a4256ac3ceae356cf" - dependencies: - arr-flatten "^1.0.1" - -arr-flatten@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1" - -arr-union@^2.0.1: - version "2.1.0" - resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-2.1.0.tgz#20f9eab5ec70f5c7d215b1077b1c39161d292c7d" - -array-differ@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/array-differ/-/array-differ-1.0.0.tgz#eff52e3758249d33be402b8bb8e564bb2b5d4031" - -array-slice@^0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/array-slice/-/array-slice-0.2.3.tgz#dd3cfb80ed7973a75117cdac69b0b99ec86186f5" - -array-union@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39" - dependencies: - array-uniq "^1.0.1" - -array-uniq@^1.0.1, array-uniq@^1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/array-uniq/-/array-uniq-1.0.3.tgz#af6ac877a25cc7f74e058894753858dfdb24fdb6" - -array-unique@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.2.1.tgz#a1d97ccafcbc2625cc70fadceb36a50c58b01a53" - -arrify@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" - -asn1@~0.2.3: - version "0.2.4" - resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.2.4.tgz#8d2475dfab553bb33e77b54e59e880bb8ce23136" - dependencies: - safer-buffer "~2.1.0" - -assert-plus@1.0.0, assert-plus@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525" - -assert-plus@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-0.2.0.tgz#d74e1b87e7affc0db8aadb7021f3fe48101ab234" - -asynckit@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" - -aws-sign2@~0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.6.0.tgz#14342dd38dbcc94d0e5b87d763cd63612c0e794f" - -aws-sign2@~0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8" - -aws4@^1.2.1, aws4@^1.6.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.6.0.tgz#83ef5ca860b2b32e4a0deedee8c771b9db57471e" - -balanced-match@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" - -bcrypt-pbkdf@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz#a4301d389b6a43f9b67ff3ca11a3f6637e360e9e" - dependencies: - tweetnacl "^0.14.3" - -beeper@^1.0.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/beeper/-/beeper-1.1.1.tgz#e6d5ea8c5dad001304a70b22638447f69cb2f809" - -block-stream@*: - version "0.0.9" - resolved "https://registry.yarnpkg.com/block-stream/-/block-stream-0.0.9.tgz#13ebfe778a03205cfe03751481ebb4b3300c126a" - dependencies: - inherits "~2.0.0" - -boom@2.x.x: - version "2.10.1" - resolved "https://registry.yarnpkg.com/boom/-/boom-2.10.1.tgz#39c8918ceff5799f83f9492a848f625add0c766f" - dependencies: - hoek "2.x.x" - -boom@4.x.x: - version "4.3.1" - resolved "https://registry.yarnpkg.com/boom/-/boom-4.3.1.tgz#4f8a3005cb4a7e3889f749030fd25b96e01d2e31" - dependencies: - hoek "4.x.x" - -boom@5.x.x: - version "5.2.0" - resolved "https://registry.yarnpkg.com/boom/-/boom-5.2.0.tgz#5dd9da6ee3a5f302077436290cb717d3f4a54e02" - dependencies: - hoek "4.x.x" - -brace-expansion@^1.1.7: - version "1.1.11" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - -braces@^1.8.2: - version "1.8.5" - resolved "https://registry.yarnpkg.com/braces/-/braces-1.8.5.tgz#ba77962e12dff969d6b76711e914b737857bf6a7" - dependencies: - expand-range "^1.8.1" - preserve "^0.2.0" - repeat-element "^1.1.2" - -browser-stdout@1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/browser-stdout/-/browser-stdout-1.3.0.tgz#f351d32969d32fa5d7a5567154263d928ae3bd1f" - -buffer-crc32@~0.2.3: - version "0.2.13" - resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242" - -caseless@~0.11.0: - version "0.11.0" - resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.11.0.tgz#715b96ea9841593cc33067923f5ec60ebda4f7d7" - -caseless@~0.12.0: - version "0.12.0" - resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc" - -chalk@^1.0.0, chalk@^1.1.1: - version "1.1.3" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" - dependencies: - ansi-styles "^2.2.1" - escape-string-regexp "^1.0.2" - has-ansi "^2.0.0" - strip-ansi "^3.0.0" - supports-color "^2.0.0" - -clone-buffer@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/clone-buffer/-/clone-buffer-1.0.0.tgz#e3e25b207ac4e701af721e2cb5a16792cac3dc58" - -clone-stats@^0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/clone-stats/-/clone-stats-0.0.1.tgz#b88f94a82cf38b8791d58046ea4029ad88ca99d1" - -clone-stats@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/clone-stats/-/clone-stats-1.0.0.tgz#b3782dff8bb5474e18b9b6bf0fdfe782f8777680" - -clone@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/clone/-/clone-0.2.0.tgz#c6126a90ad4f72dbf5acdb243cc37724fe93fc1f" - -clone@^1.0.0: - version "1.0.3" - resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.3.tgz#298d7e2231660f40c003c2ed3140decf3f53085f" - -clone@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/clone/-/clone-2.1.1.tgz#d217d1e961118e3ac9a4b8bba3285553bf647cdb" - -cloneable-readable@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/cloneable-readable/-/cloneable-readable-1.0.0.tgz#a6290d413f217a61232f95e458ff38418cfb0117" - dependencies: - inherits "^2.0.1" - process-nextick-args "^1.0.6" - through2 "^2.0.1" - -co@^4.6.0: - version "4.6.0" - resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" - -color-support@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz#93834379a1cc9a0c61f82f52f0d04322251bd5a2" - -combined-stream@^1.0.5, combined-stream@~1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.5.tgz#938370a57b4a51dea2c77c15d5c5fdf895164009" - dependencies: - delayed-stream "~1.0.0" - -commander@0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/commander/-/commander-0.6.1.tgz#fa68a14f6a945d54dbbe50d8cdb3320e9e3b1a06" - -commander@2.11.0: - version "2.11.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.11.0.tgz#157152fd1e7a6c8d98a5b715cf376df928004563" - -commander@2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.3.0.tgz#fd430e889832ec353b9acd1de217c11cb3eef873" - -commander@^2.9.0: - version "2.13.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.13.0.tgz#6964bca67685df7c1f1430c584f07d7597885b9c" - -concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - -convert-source-map@^1.1.1: - version "1.5.1" - resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.5.1.tgz#b8278097b9bc229365de5c62cf5fcaed8b5599e5" - -core-util-is@1.0.2, core-util-is@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" - -cryptiles@2.x.x: - version "2.0.5" - resolved "https://registry.yarnpkg.com/cryptiles/-/cryptiles-2.0.5.tgz#3bdfecdc608147c1c67202fa291e7dca59eaa3b8" - dependencies: - boom "2.x.x" - -cryptiles@3.x.x: - version "3.1.2" - resolved "https://registry.yarnpkg.com/cryptiles/-/cryptiles-3.1.2.tgz#a89fbb220f5ce25ec56e8c4aa8a4fd7b5b0d29fe" - dependencies: - boom "5.x.x" - -dashdash@^1.12.0: - version "1.14.1" - resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0" - dependencies: - assert-plus "^1.0.0" - -dateformat@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-2.2.0.tgz#4065e2013cf9fb916ddfd82efb506ad4c6769062" - -debug@2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/debug/-/debug-2.2.0.tgz#f87057e995b1a1f6ae6a4960664137bc56f039da" - dependencies: - ms "0.7.1" - -debug@3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261" - dependencies: - ms "2.0.0" - -deep-assign@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/deep-assign/-/deep-assign-1.0.0.tgz#b092743be8427dc621ea0067cdec7e70dd19f37b" - dependencies: - is-obj "^1.0.0" - -delayed-stream@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" - -diff@1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/diff/-/diff-1.4.0.tgz#7f28d2eb9ee7b15a97efd89ce63dcfdaa3ccbabf" - -diff@3.3.1: - version "3.3.1" - resolved "https://registry.yarnpkg.com/diff/-/diff-3.3.1.tgz#aa8567a6eed03c531fc89d3f711cd0e5259dec75" - -duplexer2@0.0.2: - version "0.0.2" - resolved "https://registry.yarnpkg.com/duplexer2/-/duplexer2-0.0.2.tgz#c614dcf67e2fb14995a91711e5a617e8a60a31db" - dependencies: - readable-stream "~1.1.9" - -duplexer@~0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1" - -duplexify@^3.2.0: - version "3.5.3" - resolved "https://registry.yarnpkg.com/duplexify/-/duplexify-3.5.3.tgz#8b5818800df92fd0125b27ab896491912858243e" - dependencies: - end-of-stream "^1.0.0" - inherits "^2.0.1" - readable-stream "^2.0.0" - stream-shift "^1.0.0" - -ecc-jsbn@~0.1.1: - version "0.1.2" - resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz#3a83a904e54353287874c564b7549386849a98c9" - dependencies: - jsbn "~0.1.0" - safer-buffer "^2.1.0" - -end-of-stream@^1.0.0: - version "1.4.1" - resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.1.tgz#ed29634d19baba463b6ce6b80a37213eab71ec43" - dependencies: - once "^1.4.0" - -escape-string-regexp@1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.2.tgz#4dbc2fe674e71949caf3fb2695ce7f2dc1d9a8d1" - -escape-string-regexp@1.0.5, escape-string-regexp@^1.0.2: - version "1.0.5" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" - -event-stream@^3.3.1, event-stream@~3.3.4: - version "3.3.4" - resolved "https://registry.yarnpkg.com/event-stream/-/event-stream-3.3.4.tgz#4ab4c9a0f5a54db9338b4c34d86bfce8f4b35571" - dependencies: - duplexer "~0.1.1" - from "~0" - map-stream "~0.1.0" - pause-stream "0.0.11" - split "0.3" - stream-combiner "~0.0.4" - through "~2.3.1" - -expand-brackets@^0.1.4: - version "0.1.5" - resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-0.1.5.tgz#df07284e342a807cd733ac5af72411e581d1177b" - dependencies: - is-posix-bracket "^0.1.0" - -expand-range@^1.8.1: - version "1.8.2" - resolved "https://registry.yarnpkg.com/expand-range/-/expand-range-1.8.2.tgz#a299effd335fe2721ebae8e257ec79644fc85337" - dependencies: - fill-range "^2.1.0" - -extend-shallow@^1.1.2: - version "1.1.4" - resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-1.1.4.tgz#19d6bf94dfc09d76ba711f39b872d21ff4dd9071" - dependencies: - kind-of "^1.1.0" - -extend-shallow@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f" - dependencies: - is-extendable "^0.1.0" - -extend@^3.0.0, extend@~3.0.0, extend@~3.0.1: - version "3.0.2" - resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" - -extglob@^0.3.1: - version "0.3.2" - resolved "https://registry.yarnpkg.com/extglob/-/extglob-0.3.2.tgz#2e18ff3d2f49ab2765cec9023f011daa8d8349a1" - dependencies: - is-extglob "^1.0.0" - -extsprintf@1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05" - -extsprintf@^1.2.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f" - -fancy-log@^1.1.0: - version "1.3.2" - resolved "https://registry.yarnpkg.com/fancy-log/-/fancy-log-1.3.2.tgz#f41125e3d84f2e7d89a43d06d958c8f78be16be1" - dependencies: - ansi-gray "^0.1.1" - color-support "^1.1.3" - time-stamp "^1.0.0" - -fast-deep-equal@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-1.0.0.tgz#96256a3bc975595eb36d82e9929d060d893439ff" - -fast-json-stable-stringify@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2" - -fd-slicer@~1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.0.1.tgz#8b5bcbd9ec327c5041bf9ab023fd6750f1177e65" - dependencies: - pend "~1.2.0" - -filename-regex@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/filename-regex/-/filename-regex-2.0.1.tgz#c1c4b9bee3e09725ddb106b75c1e301fe2f18b26" - -fill-range@^2.1.0: - version "2.2.3" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-2.2.3.tgz#50b77dfd7e469bc7492470963699fe7a8485a723" - dependencies: - is-number "^2.1.0" - isobject "^2.0.0" - randomatic "^1.1.3" - repeat-element "^1.1.2" - repeat-string "^1.5.2" - -first-chunk-stream@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/first-chunk-stream/-/first-chunk-stream-1.0.0.tgz#59bfb50cd905f60d7c394cd3d9acaab4e6ad934e" - -for-in@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80" - -for-own@^0.1.4: - version "0.1.5" - resolved "https://registry.yarnpkg.com/for-own/-/for-own-0.1.5.tgz#5265c681a4f294dabbf17c9509b6763aa84510ce" - dependencies: - for-in "^1.0.1" - -forever-agent@~0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91" - -form-data@~2.1.1: - version "2.1.4" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.1.4.tgz#33c183acf193276ecaa98143a69e94bfee1750d1" - dependencies: - asynckit "^0.4.0" - combined-stream "^1.0.5" - mime-types "^2.1.12" - -form-data@~2.3.1: - version "2.3.1" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.1.tgz#6fb94fbd71885306d73d15cc497fe4cc4ecd44bf" - dependencies: - asynckit "^0.4.0" - combined-stream "^1.0.5" - mime-types "^2.1.12" - -from@~0: - version "0.1.7" - resolved "https://registry.yarnpkg.com/from/-/from-0.1.7.tgz#83c60afc58b9c56997007ed1a768b3ab303a44fe" - -fs.realpath@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" - -fstream@^1.0.2: - version "1.0.12" - resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.12.tgz#4e8ba8ee2d48be4f7d0de505455548eae5932045" - dependencies: - graceful-fs "^4.1.2" - inherits "~2.0.0" - mkdirp ">=0.5 0" - rimraf "2" - -function-bind@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" - -generate-function@^2.0.0: - version "2.3.1" - resolved "https://registry.yarnpkg.com/generate-function/-/generate-function-2.3.1.tgz#f069617690c10c868e73b8465746764f97c3479f" - dependencies: - is-property "^1.0.2" - -generate-object-property@^1.1.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/generate-object-property/-/generate-object-property-1.2.0.tgz#9c0e1c40308ce804f4783618b937fa88f99d50d0" - dependencies: - is-property "^1.0.0" - -getpass@^0.1.1: - version "0.1.7" - resolved "https://registry.yarnpkg.com/getpass/-/getpass-0.1.7.tgz#5eff8e3e684d569ae4cb2b1282604e8ba62149fa" - dependencies: - assert-plus "^1.0.0" - -glob-base@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/glob-base/-/glob-base-0.3.0.tgz#dbb164f6221b1c0b1ccf82aea328b497df0ea3c4" - dependencies: - glob-parent "^2.0.0" - is-glob "^2.0.0" - -glob-parent@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-2.0.0.tgz#81383d72db054fcccf5336daa902f182f6edbb28" - dependencies: - is-glob "^2.0.0" - -glob-parent@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-3.1.0.tgz#9e6af6299d8d3bd2bd40430832bd113df906c5ae" - dependencies: - is-glob "^3.1.0" - path-dirname "^1.0.0" - -glob-stream@^5.3.2: - version "5.3.5" - resolved "https://registry.yarnpkg.com/glob-stream/-/glob-stream-5.3.5.tgz#a55665a9a8ccdc41915a87c701e32d4e016fad22" - dependencies: - extend "^3.0.0" - glob "^5.0.3" - glob-parent "^3.0.0" - micromatch "^2.3.7" - ordered-read-streams "^0.3.0" - through2 "^0.6.0" - to-absolute-glob "^0.1.1" - unique-stream "^2.0.2" - -glob@3.2.11: - version "3.2.11" - resolved "https://registry.yarnpkg.com/glob/-/glob-3.2.11.tgz#4a973f635b9190f715d10987d5c00fd2815ebe3d" - dependencies: - inherits "2" - minimatch "0.3" - -glob@7.1.2, glob@^7.1.2: - version "7.1.2" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15" - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.4" - once "^1.3.0" - path-is-absolute "^1.0.0" - -glob@^5.0.3: - version "5.0.15" - resolved "https://registry.yarnpkg.com/glob/-/glob-5.0.15.tgz#1bc936b9e02f4a603fcc222ecf7633d30b8b93b1" - dependencies: - inflight "^1.0.4" - inherits "2" - minimatch "2 || 3" - once "^1.3.0" - path-is-absolute "^1.0.0" - -glob@^7.1.3: - version "7.1.6" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.4" - once "^1.3.0" - path-is-absolute "^1.0.0" - -glogg@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/glogg/-/glogg-1.0.0.tgz#7fe0f199f57ac906cf512feead8f90ee4a284fc5" - dependencies: - sparkles "^1.0.0" - -graceful-fs@^4.0.0, graceful-fs@^4.1.2: - version "4.2.3" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.3.tgz#4a12ff1b60376ef09862c2093edd908328be8423" - -growl@1.10.3: - version "1.10.3" - resolved "https://registry.yarnpkg.com/growl/-/growl-1.10.3.tgz#1926ba90cf3edfe2adb4927f5880bc22c66c790f" - -growl@1.9.2: - version "1.9.2" - resolved "https://registry.yarnpkg.com/growl/-/growl-1.9.2.tgz#0ea7743715db8d8de2c5ede1775e1b45ac85c02f" - -gulp-chmod@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/gulp-chmod/-/gulp-chmod-2.0.0.tgz#00c390b928a0799b251accf631aa09e01cc6299c" - dependencies: - deep-assign "^1.0.0" - stat-mode "^0.2.0" - through2 "^2.0.0" - -gulp-filter@^5.0.1: - version "5.1.0" - resolved "https://registry.yarnpkg.com/gulp-filter/-/gulp-filter-5.1.0.tgz#a05e11affb07cf7dcf41a7de1cb7b63ac3783e73" - dependencies: - multimatch "^2.0.0" - plugin-error "^0.1.2" - streamfilter "^1.0.5" - -gulp-gunzip@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/gulp-gunzip/-/gulp-gunzip-1.0.0.tgz#15b741145e83a9c6f50886241b57cc5871f151a9" - dependencies: - through2 "~0.6.5" - vinyl "~0.4.6" - -gulp-remote-src@^0.4.3: - version "0.4.3" - resolved "https://registry.yarnpkg.com/gulp-remote-src/-/gulp-remote-src-0.4.3.tgz#5728cfd643433dd4845ddef0969f0f971a2ab4a1" - dependencies: - event-stream "~3.3.4" - node.extend "~1.1.2" - request "~2.79.0" - through2 "~2.0.3" - vinyl "~2.0.1" - -gulp-sourcemaps@1.6.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/gulp-sourcemaps/-/gulp-sourcemaps-1.6.0.tgz#b86ff349d801ceb56e1d9e7dc7bbcb4b7dee600c" - dependencies: - convert-source-map "^1.1.1" - graceful-fs "^4.1.2" - strip-bom "^2.0.0" - through2 "^2.0.0" - vinyl "^1.0.0" - -gulp-symdest@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/gulp-symdest/-/gulp-symdest-1.1.0.tgz#c165320732d192ce56fd94271ffa123234bf2ae0" - dependencies: - event-stream "^3.3.1" - mkdirp "^0.5.1" - queue "^3.1.0" - vinyl-fs "^2.4.3" - -gulp-untar@^0.0.6: - version "0.0.6" - resolved "https://registry.yarnpkg.com/gulp-untar/-/gulp-untar-0.0.6.tgz#d6bdefde7e9a8e054c9f162385a0782c4be74000" - dependencies: - event-stream "~3.3.4" - gulp-util "~3.0.8" - streamifier "~0.1.1" - tar "^2.2.1" - through2 "~2.0.3" - -gulp-util@~3.0.8: - version "3.0.8" - resolved "https://registry.yarnpkg.com/gulp-util/-/gulp-util-3.0.8.tgz#0054e1e744502e27c04c187c3ecc505dd54bbb4f" - dependencies: - array-differ "^1.0.0" - array-uniq "^1.0.2" - beeper "^1.0.0" - chalk "^1.0.0" - dateformat "^2.0.0" - fancy-log "^1.1.0" - gulplog "^1.0.0" - has-gulplog "^0.1.0" - lodash._reescape "^3.0.0" - lodash._reevaluate "^3.0.0" - lodash._reinterpolate "^3.0.0" - lodash.template "^3.0.0" - minimist "^1.1.0" - multipipe "^0.1.2" - object-assign "^3.0.0" - replace-ext "0.0.1" - through2 "^2.0.0" - vinyl "^0.5.0" - -gulp-vinyl-zip@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/gulp-vinyl-zip/-/gulp-vinyl-zip-2.1.0.tgz#24e40685dc05b7149995245099e0590263be8dad" - dependencies: - event-stream "^3.3.1" - queue "^4.2.1" - through2 "^2.0.3" - vinyl "^2.0.2" - vinyl-fs "^2.0.0" - yauzl "^2.2.1" - yazl "^2.2.1" - -gulplog@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/gulplog/-/gulplog-1.0.0.tgz#e28c4d45d05ecbbed818363ce8f9c5926229ffe5" - dependencies: - glogg "^1.0.0" - -har-schema@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92" - -har-validator@~2.0.6: - version "2.0.6" - resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-2.0.6.tgz#cdcbc08188265ad119b6a5a7c8ab70eecfb5d27d" - dependencies: - chalk "^1.1.1" - commander "^2.9.0" - is-my-json-valid "^2.12.4" - pinkie-promise "^2.0.0" - -har-validator@~5.0.3: - version "5.0.3" - resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.0.3.tgz#ba402c266194f15956ef15e0fcf242993f6a7dfd" - dependencies: - ajv "^5.1.0" - har-schema "^2.0.0" - -has-ansi@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" - dependencies: - ansi-regex "^2.0.0" - -has-flag@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-2.0.0.tgz#e8207af1cc7b30d446cc70b734b5e8be18f88d51" - -has-gulplog@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/has-gulplog/-/has-gulplog-0.1.0.tgz#6414c82913697da51590397dafb12f22967811ce" - dependencies: - sparkles "^1.0.0" - -has@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796" - dependencies: - function-bind "^1.1.1" - -hawk@~3.1.3: - version "3.1.3" - resolved "https://registry.yarnpkg.com/hawk/-/hawk-3.1.3.tgz#078444bd7c1640b0fe540d2c9b73d59678e8e1c4" - dependencies: - boom "2.x.x" - cryptiles "2.x.x" - hoek "2.x.x" - sntp "1.x.x" - -hawk@~6.0.2: - version "6.0.2" - resolved "https://registry.yarnpkg.com/hawk/-/hawk-6.0.2.tgz#af4d914eb065f9b5ce4d9d11c1cb2126eecc3038" - dependencies: - boom "4.x.x" - cryptiles "3.x.x" - hoek "4.x.x" - sntp "2.x.x" - -he@1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/he/-/he-1.1.1.tgz#93410fd21b009735151f8868c2f271f3427e23fd" - -hoek@2.x.x: - version "2.16.3" - resolved "https://registry.yarnpkg.com/hoek/-/hoek-2.16.3.tgz#20bb7403d3cea398e91dc4710a8ff1b8274a25ed" - -hoek@4.x.x: - version "4.2.0" - resolved "https://registry.yarnpkg.com/hoek/-/hoek-4.2.0.tgz#72d9d0754f7fe25ca2d01ad8f8f9a9449a89526d" - -http-signature@~1.1.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.1.1.tgz#df72e267066cd0ac67fb76adf8e134a8fbcf91bf" - dependencies: - assert-plus "^0.2.0" - jsprim "^1.2.2" - sshpk "^1.7.0" - -http-signature@~1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.2.0.tgz#9aecd925114772f3d95b65a60abb8f7c18fbace1" - dependencies: - assert-plus "^1.0.0" - jsprim "^1.2.2" - sshpk "^1.7.0" - -inflight@^1.0.4: - version "1.0.6" - resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" - dependencies: - once "^1.3.0" - wrappy "1" - -inherits@2, inherits@^2.0.1, inherits@~2.0.0, inherits@~2.0.1, inherits@~2.0.3: - version "2.0.4" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" - -is-buffer@^1.1.5: - version "1.1.6" - resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" - -is-dotfile@^1.0.0: - version "1.0.3" - resolved "https://registry.yarnpkg.com/is-dotfile/-/is-dotfile-1.0.3.tgz#a6a2f32ffd2dfb04f5ca25ecd0f6b83cf798a1e1" - -is-equal-shallow@^0.1.3: - version "0.1.3" - resolved "https://registry.yarnpkg.com/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz#2238098fc221de0bcfa5d9eac4c45d638aa1c534" - dependencies: - is-primitive "^2.0.0" - -is-extendable@^0.1.0, is-extendable@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89" - -is-extglob@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-1.0.0.tgz#ac468177c4943405a092fc8f29760c6ffc6206c0" - -is-extglob@^2.1.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" - -is-glob@^2.0.0, is-glob@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-2.0.1.tgz#d096f926a3ded5600f3fdfd91198cb0888c2d863" - dependencies: - is-extglob "^1.0.0" - -is-glob@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz#7ba5ae24217804ac70707b96922567486cc3e84a" - dependencies: - is-extglob "^2.1.0" - -is-my-ip-valid@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-my-ip-valid/-/is-my-ip-valid-1.0.0.tgz#7b351b8e8edd4d3995d4d066680e664d94696824" - -is-my-json-valid@^2.12.4: - version "2.20.0" - resolved "https://registry.yarnpkg.com/is-my-json-valid/-/is-my-json-valid-2.20.0.tgz#1345a6fca3e8daefc10d0fa77067f54cedafd59a" - dependencies: - generate-function "^2.0.0" - generate-object-property "^1.1.0" - is-my-ip-valid "^1.0.0" - jsonpointer "^4.0.0" - xtend "^4.0.0" - -is-number@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-2.1.0.tgz#01fcbbb393463a548f2f466cce16dece49db908f" - dependencies: - kind-of "^3.0.2" - -is-number@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195" - dependencies: - kind-of "^3.0.2" - -is-obj@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz#3e4729ac1f5fde025cd7d83a896dab9f4f67db0f" - -is-posix-bracket@^0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz#3334dc79774368e92f016e6fbc0a88f5cd6e6bc4" - -is-primitive@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/is-primitive/-/is-primitive-2.0.0.tgz#207bab91638499c07b2adf240a41a87210034575" - -is-property@^1.0.0, is-property@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-property/-/is-property-1.0.2.tgz#57fe1c4e48474edd65b09911f26b1cd4095dda84" - -is-stream@^1.0.1, is-stream@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-1.1.0.tgz#12d4a3dd4e68e0b79ceb8dbc84173ae80d91ca44" - -is-typedarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" - -is-utf8@^0.2.0: - version "0.2.1" - resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72" - -is-valid-glob@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/is-valid-glob/-/is-valid-glob-0.3.0.tgz#d4b55c69f51886f9b65c70d6c2622d37e29f48fe" - -is@^3.2.1: - version "3.3.0" - resolved "https://registry.yarnpkg.com/is/-/is-3.3.0.tgz#61cff6dd3c4193db94a3d62582072b44e5645d79" - -isarray@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf" - -isarray@1.0.0, isarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" - -isobject@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89" - dependencies: - isarray "1.0.0" - -isstream@~0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" - -jade@0.26.3: - version "0.26.3" - resolved "https://registry.yarnpkg.com/jade/-/jade-0.26.3.tgz#8f10d7977d8d79f2f6ff862a81b0513ccb25686c" - dependencies: - commander "0.6.1" - mkdirp "0.3.0" - -jsbn@~0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" - -json-schema-traverse@^0.3.0: - version "0.3.1" - resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz#349a6d44c53a51de89b40805c5d5e59b417d3340" - -json-schema@0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13" - -json-stable-stringify@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz#9a759d39c5f2ff503fd5300646ed445f88c4f9af" - dependencies: - jsonify "~0.0.0" - -json-stringify-safe@~5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" - -jsonify@~0.0.0: - version "0.0.0" - resolved "https://registry.yarnpkg.com/jsonify/-/jsonify-0.0.0.tgz#2c74b6ee41d93ca51b7b5aaee8f503631d252a73" - -jsonpointer@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/jsonpointer/-/jsonpointer-4.0.1.tgz#4fd92cb34e0e9db3c89c8622ecf51f9b978c6cb9" - -jsprim@^1.2.2: - version "1.4.1" - resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2" - dependencies: - assert-plus "1.0.0" - extsprintf "1.3.0" - json-schema "0.2.3" - verror "1.10.0" - -kind-of@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-1.1.0.tgz#140a3d2d41a36d2efcfa9377b62c24f8495a5c44" - -kind-of@^3.0.2: - version "3.2.2" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" - dependencies: - is-buffer "^1.1.5" - -kind-of@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57" - dependencies: - is-buffer "^1.1.5" - -lazystream@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/lazystream/-/lazystream-1.0.0.tgz#f6995fe0f820392f61396be89462407bb77168e4" - dependencies: - readable-stream "^2.0.5" - -lodash._basecopy@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz#8da0e6a876cf344c0ad8a54882111dd3c5c7ca36" - -lodash._basetostring@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/lodash._basetostring/-/lodash._basetostring-3.0.1.tgz#d1861d877f824a52f669832dcaf3ee15566a07d5" - -lodash._basevalues@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/lodash._basevalues/-/lodash._basevalues-3.0.0.tgz#5b775762802bde3d3297503e26300820fdf661b7" - -lodash._getnative@^3.0.0: - version "3.9.1" - resolved "https://registry.yarnpkg.com/lodash._getnative/-/lodash._getnative-3.9.1.tgz#570bc7dede46d61cdcde687d65d3eecbaa3aaff5" - -lodash._isiterateecall@^3.0.0: - version "3.0.9" - resolved "https://registry.yarnpkg.com/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz#5203ad7ba425fae842460e696db9cf3e6aac057c" - -lodash._reescape@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/lodash._reescape/-/lodash._reescape-3.0.0.tgz#2b1d6f5dfe07c8a355753e5f27fac7f1cde1616a" - -lodash._reevaluate@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/lodash._reevaluate/-/lodash._reevaluate-3.0.0.tgz#58bc74c40664953ae0b124d806996daca431e2ed" - -lodash._reinterpolate@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz#0ccf2d89166af03b3663c796538b75ac6e114d9d" - -lodash._root@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/lodash._root/-/lodash._root-3.0.1.tgz#fba1c4524c19ee9a5f8136b4609f017cf4ded692" - -lodash.escape@^3.0.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/lodash.escape/-/lodash.escape-3.2.0.tgz#995ee0dc18c1b48cc92effae71a10aab5b487698" - dependencies: - lodash._root "^3.0.0" - -lodash.isarguments@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz#2f573d85c6a24289ff00663b491c1d338ff3458a" - -lodash.isarray@^3.0.0: - version "3.0.4" - resolved "https://registry.yarnpkg.com/lodash.isarray/-/lodash.isarray-3.0.4.tgz#79e4eb88c36a8122af86f844aa9bcd851b5fbb55" - -lodash.isequal@^4.0.0: - version "4.5.0" - resolved "https://registry.yarnpkg.com/lodash.isequal/-/lodash.isequal-4.5.0.tgz#415c4478f2bcc30120c22ce10ed3226f7d3e18e0" - -lodash.keys@^3.0.0: - version "3.1.2" - resolved "https://registry.yarnpkg.com/lodash.keys/-/lodash.keys-3.1.2.tgz#4dbc0472b156be50a0b286855d1bd0b0c656098a" - dependencies: - lodash._getnative "^3.0.0" - lodash.isarguments "^3.0.0" - lodash.isarray "^3.0.0" - -lodash.restparam@^3.0.0: - version "3.6.1" - resolved "https://registry.yarnpkg.com/lodash.restparam/-/lodash.restparam-3.6.1.tgz#936a4e309ef330a7645ed4145986c85ae5b20805" - -lodash.template@^3.0.0: - version "3.6.2" - resolved "https://registry.yarnpkg.com/lodash.template/-/lodash.template-3.6.2.tgz#f8cdecc6169a255be9098ae8b0c53d378931d14f" - dependencies: - lodash._basecopy "^3.0.0" - lodash._basetostring "^3.0.0" - lodash._basevalues "^3.0.0" - lodash._isiterateecall "^3.0.0" - lodash._reinterpolate "^3.0.0" - lodash.escape "^3.0.0" - lodash.keys "^3.0.0" - lodash.restparam "^3.0.0" - lodash.templatesettings "^3.0.0" - -lodash.templatesettings@^3.0.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/lodash.templatesettings/-/lodash.templatesettings-3.1.1.tgz#fb307844753b66b9f1afa54e262c745307dba8e5" - dependencies: - lodash._reinterpolate "^3.0.0" - lodash.escape "^3.0.0" - -lru-cache@2: - version "2.7.3" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-2.7.3.tgz#6d4524e8b955f95d4f5b58851ce21dd72fb4e952" - -map-stream@~0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/map-stream/-/map-stream-0.1.0.tgz#e56aa94c4c8055a16404a0674b78f215f7c8e194" - -merge-stream@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-1.0.1.tgz#4041202d508a342ba00174008df0c251b8c135e1" - dependencies: - readable-stream "^2.0.1" - -micromatch@^2.3.7: - version "2.3.11" - resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-2.3.11.tgz#86677c97d1720b363431d04d0d15293bd38c1565" - dependencies: - arr-diff "^2.0.0" - array-unique "^0.2.1" - braces "^1.8.2" - expand-brackets "^0.1.4" - extglob "^0.3.1" - filename-regex "^2.0.0" - is-extglob "^1.0.0" - is-glob "^2.0.1" - kind-of "^3.0.2" - normalize-path "^2.0.1" - object.omit "^2.0.0" - parse-glob "^3.0.4" - regex-cache "^0.4.2" - -mime-db@~1.30.0: - version "1.30.0" - resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.30.0.tgz#74c643da2dd9d6a45399963465b26d5ca7d71f01" - -mime-types@^2.1.12, mime-types@~2.1.17, mime-types@~2.1.7: - version "2.1.17" - resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.17.tgz#09d7a393f03e995a79f8af857b70a9e0ab16557a" - dependencies: - mime-db "~1.30.0" - -minimatch@0.3: - version "0.3.0" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-0.3.0.tgz#275d8edaac4f1bb3326472089e7949c8394699dd" - dependencies: - lru-cache "2" - sigmund "~1.0.0" - -"minimatch@2 || 3", minimatch@^3.0.0, minimatch@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" - dependencies: - brace-expansion "^1.1.7" - -minimist@0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" - -minimist@^1.1.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" - -minimist@^1.2.5: - version "1.2.5" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602" - -mkdirp@0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.3.0.tgz#1bbf5ab1ba827af23575143490426455f481fe1e" - -mkdirp@0.5.1: - version "0.5.1" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" - dependencies: - minimist "0.0.8" - -"mkdirp@>=0.5 0", mkdirp@^0.5.0, mkdirp@^0.5.1: - version "0.5.5" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def" - dependencies: - minimist "^1.2.5" - -mocha@^2.3.3: - version "2.5.3" - resolved "https://registry.yarnpkg.com/mocha/-/mocha-2.5.3.tgz#161be5bdeb496771eb9b35745050b622b5aefc58" - dependencies: - commander "2.3.0" - debug "2.2.0" - diff "1.4.0" - escape-string-regexp "1.0.2" - glob "3.2.11" - growl "1.9.2" - jade "0.26.3" - mkdirp "0.5.1" - supports-color "1.2.0" - to-iso-string "0.0.2" - -mocha@^4.0.1: - version "4.1.0" - resolved "https://registry.yarnpkg.com/mocha/-/mocha-4.1.0.tgz#7d86cfbcf35cb829e2754c32e17355ec05338794" - dependencies: - browser-stdout "1.3.0" - commander "2.11.0" - debug "3.1.0" - diff "3.3.1" - escape-string-regexp "1.0.5" - glob "7.1.2" - growl "1.10.3" - he "1.1.1" - mkdirp "0.5.1" - supports-color "4.4.0" - -ms@0.7.1: - version "0.7.1" - resolved "https://registry.yarnpkg.com/ms/-/ms-0.7.1.tgz#9cd13c03adbff25b65effde7ce864ee952017098" - -ms@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" - -multimatch@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/multimatch/-/multimatch-2.1.0.tgz#9c7906a22fb4c02919e2f5f75161b4cdbd4b2a2b" - dependencies: - array-differ "^1.0.0" - array-union "^1.0.1" - arrify "^1.0.0" - minimatch "^3.0.0" - -multipipe@^0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/multipipe/-/multipipe-0.1.2.tgz#2a8f2ddf70eed564dff2d57f1e1a137d9f05078b" - dependencies: - duplexer2 "0.0.2" - -node.extend@~1.1.2: - version "1.1.8" - resolved "https://registry.yarnpkg.com/node.extend/-/node.extend-1.1.8.tgz#0aab3e63789f4e6d68b42bc00073ad1881243cf0" - dependencies: - has "^1.0.3" - is "^3.2.1" - -normalize-path@^2.0.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9" - dependencies: - remove-trailing-separator "^1.0.1" - -oauth-sign@~0.8.1, oauth-sign@~0.8.2: - version "0.8.2" - resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.8.2.tgz#46a6ab7f0aead8deae9ec0565780b7d4efeb9d43" - -object-assign@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-3.0.0.tgz#9bedd5ca0897949bca47e7ff408062d549f587f2" - -object-assign@^4.0.0: - version "4.1.1" - resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" - -object.omit@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/object.omit/-/object.omit-2.0.1.tgz#1a9c744829f39dbb858c76ca3579ae2a54ebd1fa" - dependencies: - for-own "^0.1.4" - is-extendable "^0.1.1" - -once@^1.3.0, once@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" - dependencies: - wrappy "1" - -ordered-read-streams@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/ordered-read-streams/-/ordered-read-streams-0.3.0.tgz#7137e69b3298bb342247a1bbee3881c80e2fd78b" - dependencies: - is-stream "^1.0.1" - readable-stream "^2.0.1" - -parse-glob@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/parse-glob/-/parse-glob-3.0.4.tgz#b2c376cfb11f35513badd173ef0bb6e3a388391c" - dependencies: - glob-base "^0.3.0" - is-dotfile "^1.0.0" - is-extglob "^1.0.0" - is-glob "^2.0.0" - -path-dirname@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/path-dirname/-/path-dirname-1.0.2.tgz#cc33d24d525e099a5388c0336c6e32b9160609e0" - -path-is-absolute@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" - -pause-stream@0.0.11: - version "0.0.11" - resolved "https://registry.yarnpkg.com/pause-stream/-/pause-stream-0.0.11.tgz#fe5a34b0cbce12b5aa6a2b403ee2e73b602f1445" - dependencies: - through "~2.3" - -pend@~1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50" - -performance-now@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" - -pinkie-promise@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa" - dependencies: - pinkie "^2.0.0" - -pinkie@^2.0.0: - version "2.0.4" - resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" - -plugin-error@^0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/plugin-error/-/plugin-error-0.1.2.tgz#3b9bb3335ccf00f425e07437e19276967da47ace" - dependencies: - ansi-cyan "^0.1.1" - ansi-red "^0.1.1" - arr-diff "^1.0.1" - arr-union "^2.0.1" - extend-shallow "^1.1.2" - -preserve@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" - -process-nextick-args@^1.0.6, process-nextick-args@~1.0.6: - version "1.0.7" - resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-1.0.7.tgz#150e20b756590ad3f91093f25a4f2ad8bff30ba3" - -punycode@^1.4.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e" - -qs@~6.3.0: - version "6.3.2" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.3.2.tgz#e75bd5f6e268122a2a0e0bda630b2550c166502c" - -qs@~6.5.1: - version "6.5.1" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.1.tgz#349cdf6eef89ec45c12d7d5eb3fc0c870343a6d8" - -querystringify@^2.1.1: - version "2.2.0" - resolved "https://registry.yarnpkg.com/querystringify/-/querystringify-2.2.0.tgz#3345941b4153cb9d082d8eee4cda2016a9aef7f6" - -queue@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/queue/-/queue-3.1.0.tgz#6c49d01f009e2256788789f2bffac6b8b9990585" - dependencies: - inherits "~2.0.0" - -queue@^4.2.1: - version "4.4.2" - resolved "https://registry.yarnpkg.com/queue/-/queue-4.4.2.tgz#5a9733d9a8b8bd1b36e934bc9c55ab89b28e29c7" - dependencies: - inherits "~2.0.0" - -randomatic@^1.1.3: - version "1.1.7" - resolved "https://registry.yarnpkg.com/randomatic/-/randomatic-1.1.7.tgz#c7abe9cc8b87c0baa876b19fde83fd464797e38c" - dependencies: - is-number "^3.0.0" - kind-of "^4.0.0" - -"readable-stream@>=1.0.33-1 <1.1.0-0": - version "1.0.34" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.0.34.tgz#125820e34bc842d2f2aaafafe4c2916ee32c157c" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.1" - isarray "0.0.1" - string_decoder "~0.10.x" - -readable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.2, readable-stream@^2.0.4, readable-stream@^2.0.5, readable-stream@^2.1.5: - version "2.3.3" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.3.tgz#368f2512d79f9d46fdfc71349ae7878bbc1eb95c" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.3" - isarray "~1.0.0" - process-nextick-args "~1.0.6" - safe-buffer "~5.1.1" - string_decoder "~1.0.3" - util-deprecate "~1.0.1" - -readable-stream@~1.1.9: - version "1.1.14" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.14.tgz#7cf4c54ef648e3813084c636dd2079e166c081d9" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.1" - isarray "0.0.1" - string_decoder "~0.10.x" - -regex-cache@^0.4.2: - version "0.4.4" - resolved "https://registry.yarnpkg.com/regex-cache/-/regex-cache-0.4.4.tgz#75bdc58a2a1496cec48a12835bc54c8d562336dd" - dependencies: - is-equal-shallow "^0.1.3" - -remove-trailing-separator@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef" - -repeat-element@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.2.tgz#ef089a178d1483baae4d93eb98b4f9e4e11d990a" - -repeat-string@^1.5.2: - version "1.6.1" - resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" - -replace-ext@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/replace-ext/-/replace-ext-0.0.1.tgz#29bbd92078a739f0bcce2b4ee41e837953522924" - -replace-ext@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/replace-ext/-/replace-ext-1.0.0.tgz#de63128373fcbf7c3ccfa4de5a480c45a67958eb" - -request@^2.83.0: - version "2.83.0" - resolved "https://registry.yarnpkg.com/request/-/request-2.83.0.tgz#ca0b65da02ed62935887808e6f510381034e3356" - dependencies: - aws-sign2 "~0.7.0" - aws4 "^1.6.0" - caseless "~0.12.0" - combined-stream "~1.0.5" - extend "~3.0.1" - forever-agent "~0.6.1" - form-data "~2.3.1" - har-validator "~5.0.3" - hawk "~6.0.2" - http-signature "~1.2.0" - is-typedarray "~1.0.0" - isstream "~0.1.2" - json-stringify-safe "~5.0.1" - mime-types "~2.1.17" - oauth-sign "~0.8.2" - performance-now "^2.1.0" - qs "~6.5.1" - safe-buffer "^5.1.1" - stringstream "~0.0.5" - tough-cookie "~2.3.3" - tunnel-agent "^0.6.0" - uuid "^3.1.0" - -request@~2.79.0: - version "2.79.0" - resolved "https://registry.yarnpkg.com/request/-/request-2.79.0.tgz#4dfe5bf6be8b8cdc37fcf93e04b65577722710de" - dependencies: - aws-sign2 "~0.6.0" - aws4 "^1.2.1" - caseless "~0.11.0" - combined-stream "~1.0.5" - extend "~3.0.0" - forever-agent "~0.6.1" - form-data "~2.1.1" - har-validator "~2.0.6" - hawk "~3.1.3" - http-signature "~1.1.0" - is-typedarray "~1.0.0" - isstream "~0.1.2" - json-stringify-safe "~5.0.1" - mime-types "~2.1.7" - oauth-sign "~0.8.1" - qs "~6.3.0" - stringstream "~0.0.4" - tough-cookie "~2.3.0" - tunnel-agent "~0.4.1" - uuid "^3.0.0" - -requires-port@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/requires-port/-/requires-port-1.0.0.tgz#925d2601d39ac485e091cf0da5c6e694dc3dcaff" - -rimraf@2: - version "2.7.1" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" - dependencies: - glob "^7.1.3" - -safe-buffer@^5.0.1, safe-buffer@^5.1.1, safe-buffer@~5.1.0, safe-buffer@~5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.1.tgz#893312af69b2123def71f57889001671eeb2c853" - -safer-buffer@^2.0.2, safer-buffer@^2.1.0, safer-buffer@~2.1.0: - version "2.1.2" - resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" - -semver@^5.4.1: - version "5.5.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.5.0.tgz#dc4bbc7a6ca9d916dee5d43516f0092b58f7b8ab" - -sigmund@~1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/sigmund/-/sigmund-1.0.1.tgz#3ff21f198cad2175f9f3b781853fd94d0d19b590" - -sntp@1.x.x: - version "1.0.9" - resolved "https://registry.yarnpkg.com/sntp/-/sntp-1.0.9.tgz#6541184cc90aeea6c6e7b35e2659082443c66198" - dependencies: - hoek "2.x.x" - -sntp@2.x.x: - version "2.1.0" - resolved "https://registry.yarnpkg.com/sntp/-/sntp-2.1.0.tgz#2c6cec14fedc2222739caf9b5c3d85d1cc5a2cc8" - dependencies: - hoek "4.x.x" - -source-map-support@^0.5.0: - version "0.5.2" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.2.tgz#1a6297fd5b2e762b39688c7fc91233b60984f0a5" - dependencies: - source-map "^0.6.0" - -source-map@^0.6.0: - version "0.6.1" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" - -sparkles@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/sparkles/-/sparkles-1.0.0.tgz#1acbbfb592436d10bbe8f785b7cc6f82815012c3" - -split@0.3: - version "0.3.3" - resolved "https://registry.yarnpkg.com/split/-/split-0.3.3.tgz#cd0eea5e63a211dfff7eb0f091c4133e2d0dd28f" - dependencies: - through "2" - -sshpk@^1.7.0: - version "1.16.1" - resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.16.1.tgz#fb661c0bef29b39db40769ee39fa70093d6f6877" - dependencies: - asn1 "~0.2.3" - assert-plus "^1.0.0" - bcrypt-pbkdf "^1.0.0" - dashdash "^1.12.0" - ecc-jsbn "~0.1.1" - getpass "^0.1.1" - jsbn "~0.1.0" - safer-buffer "^2.0.2" - tweetnacl "~0.14.0" - -stat-mode@^0.2.0: - version "0.2.2" - resolved "https://registry.yarnpkg.com/stat-mode/-/stat-mode-0.2.2.tgz#e6c80b623123d7d80cf132ce538f346289072502" - -stream-combiner@~0.0.4: - version "0.0.4" - resolved "https://registry.yarnpkg.com/stream-combiner/-/stream-combiner-0.0.4.tgz#4d5e433c185261dde623ca3f44c586bcf5c4ad14" - dependencies: - duplexer "~0.1.1" - -stream-shift@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/stream-shift/-/stream-shift-1.0.0.tgz#d5c752825e5367e786f78e18e445ea223a155952" - -streamfilter@^1.0.5: - version "1.0.7" - resolved "https://registry.yarnpkg.com/streamfilter/-/streamfilter-1.0.7.tgz#ae3e64522aa5a35c061fd17f67620c7653c643c9" - dependencies: - readable-stream "^2.0.2" - -streamifier@~0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/streamifier/-/streamifier-0.1.1.tgz#97e98d8fa4d105d62a2691d1dc07e820db8dfc4f" - -string_decoder@~0.10.x: - version "0.10.31" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.10.31.tgz#62e203bc41766c6c28c9fc84301dab1c5310fa94" - -string_decoder@~1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.0.3.tgz#0fc67d7c141825de94282dd536bec6b9bce860ab" - dependencies: - safe-buffer "~5.1.0" - -stringstream@~0.0.4, stringstream@~0.0.5: - version "0.0.6" - resolved "https://registry.yarnpkg.com/stringstream/-/stringstream-0.0.6.tgz#7880225b0d4ad10e30927d167a1d6f2fd3b33a72" - -strip-ansi@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" - dependencies: - ansi-regex "^2.0.0" - -strip-bom-stream@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/strip-bom-stream/-/strip-bom-stream-1.0.0.tgz#e7144398577d51a6bed0fa1994fa05f43fd988ee" - dependencies: - first-chunk-stream "^1.0.0" - strip-bom "^2.0.0" - -strip-bom@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e" - dependencies: - is-utf8 "^0.2.0" - -supports-color@1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-1.2.0.tgz#ff1ed1e61169d06b3cf2d588e188b18d8847e17e" - -supports-color@4.4.0: - version "4.4.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-4.4.0.tgz#883f7ddabc165142b2a61427f3352ded195d1a3e" - dependencies: - has-flag "^2.0.0" - -supports-color@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" - -tar@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/tar/-/tar-2.2.1.tgz#8e4d2a256c0e2185c6b18ad694aec968b83cb1d1" - dependencies: - block-stream "*" - fstream "^1.0.2" - inherits "2" - -through2-filter@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/through2-filter/-/through2-filter-2.0.0.tgz#60bc55a0dacb76085db1f9dae99ab43f83d622ec" - dependencies: - through2 "~2.0.0" - xtend "~4.0.0" - -through2@^0.6.0, through2@~0.6.5: - version "0.6.5" - resolved "https://registry.yarnpkg.com/through2/-/through2-0.6.5.tgz#41ab9c67b29d57209071410e1d7a7a968cd3ad48" - dependencies: - readable-stream ">=1.0.33-1 <1.1.0-0" - xtend ">=4.0.0 <4.1.0-0" - -through2@^2.0.0, through2@^2.0.1, through2@^2.0.3, through2@~2.0.0, through2@~2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.3.tgz#0004569b37c7c74ba39c43f3ced78d1ad94140be" - dependencies: - readable-stream "^2.1.5" - xtend "~4.0.1" - -through@2, through@~2.3, through@~2.3.1: - version "2.3.8" - resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" - -time-stamp@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/time-stamp/-/time-stamp-1.1.0.tgz#764a5a11af50561921b133f3b44e618687e0f5c3" - -to-absolute-glob@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/to-absolute-glob/-/to-absolute-glob-0.1.1.tgz#1cdfa472a9ef50c239ee66999b662ca0eb39937f" - dependencies: - extend-shallow "^2.0.1" - -to-iso-string@0.0.2: - version "0.0.2" - resolved "https://registry.yarnpkg.com/to-iso-string/-/to-iso-string-0.0.2.tgz#4dc19e664dfccbe25bd8db508b00c6da158255d1" - -tough-cookie@~2.3.0, tough-cookie@~2.3.3: - version "2.3.3" - resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.3.3.tgz#0b618a5565b6dea90bf3425d04d55edc475a7561" - dependencies: - punycode "^1.4.1" - -tunnel-agent@^0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd" - dependencies: - safe-buffer "^5.0.1" - -tunnel-agent@~0.4.1: - version "0.4.3" - resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.4.3.tgz#6373db76909fe570e08d73583365ed828a74eeeb" - -tweetnacl@^0.14.3, tweetnacl@~0.14.0: - version "0.14.5" - resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64" - -typescript@^2.3.4: - version "2.6.2" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.6.2.tgz#3c5b6fd7f6de0914269027f03c0946758f7673a4" - -unique-stream@^2.0.2: - version "2.2.1" - resolved "https://registry.yarnpkg.com/unique-stream/-/unique-stream-2.2.1.tgz#5aa003cfbe94c5ff866c4e7d668bb1c4dbadb369" - dependencies: - json-stable-stringify "^1.0.0" - through2-filter "^2.0.0" - -url-parse@^1.1.9: - version "1.4.7" - resolved "https://registry.yarnpkg.com/url-parse/-/url-parse-1.4.7.tgz#a8a83535e8c00a316e403a5db4ac1b9b853ae278" - dependencies: - querystringify "^2.1.1" - requires-port "^1.0.0" - -util-deprecate@~1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" - -uuid@^3.0.0, uuid@^3.1.0: - version "3.2.1" - resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.2.1.tgz#12c528bb9d58d0b9265d9a2f6f0fe8be17ff1f14" - -vali-date@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/vali-date/-/vali-date-1.0.0.tgz#1b904a59609fb328ef078138420934f6b86709a6" - -verror@1.10.0: - version "1.10.0" - resolved "https://registry.yarnpkg.com/verror/-/verror-1.10.0.tgz#3a105ca17053af55d6e270c1f8288682e18da400" - dependencies: - assert-plus "^1.0.0" - core-util-is "1.0.2" - extsprintf "^1.2.0" - -vinyl-fs@^2.0.0, vinyl-fs@^2.4.3: - version "2.4.4" - resolved "https://registry.yarnpkg.com/vinyl-fs/-/vinyl-fs-2.4.4.tgz#be6ff3270cb55dfd7d3063640de81f25d7532239" - dependencies: - duplexify "^3.2.0" - glob-stream "^5.3.2" - graceful-fs "^4.0.0" - gulp-sourcemaps "1.6.0" - is-valid-glob "^0.3.0" - lazystream "^1.0.0" - lodash.isequal "^4.0.0" - merge-stream "^1.0.0" - mkdirp "^0.5.0" - object-assign "^4.0.0" - readable-stream "^2.0.4" - strip-bom "^2.0.0" - strip-bom-stream "^1.0.0" - through2 "^2.0.0" - through2-filter "^2.0.0" - vali-date "^1.0.0" - vinyl "^1.0.0" - -vinyl-source-stream@^1.1.0: - version "1.1.2" - resolved "https://registry.yarnpkg.com/vinyl-source-stream/-/vinyl-source-stream-1.1.2.tgz#62b53a135610a896e98ca96bee3a87f008a8e780" - dependencies: - through2 "^2.0.3" - vinyl "^0.4.3" - -vinyl@^0.4.3, vinyl@~0.4.6: - version "0.4.6" - resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-0.4.6.tgz#2f356c87a550a255461f36bbeb2a5ba8bf784847" - dependencies: - clone "^0.2.0" - clone-stats "^0.0.1" - -vinyl@^0.5.0: - version "0.5.3" - resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-0.5.3.tgz#b0455b38fc5e0cf30d4325132e461970c2091cde" - dependencies: - clone "^1.0.0" - clone-stats "^0.0.1" - replace-ext "0.0.1" - -vinyl@^1.0.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-1.2.0.tgz#5c88036cf565e5df05558bfc911f8656df218884" - dependencies: - clone "^1.0.0" - clone-stats "^0.0.1" - replace-ext "0.0.1" - -vinyl@^2.0.2: - version "2.1.0" - resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-2.1.0.tgz#021f9c2cf951d6b939943c89eb5ee5add4fd924c" - dependencies: - clone "^2.1.1" - clone-buffer "^1.0.0" - clone-stats "^1.0.0" - cloneable-readable "^1.0.0" - remove-trailing-separator "^1.0.1" - replace-ext "^1.0.0" - -vinyl@~2.0.1: - version "2.0.2" - resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-2.0.2.tgz#0a3713d8d4e9221c58f10ca16c0116c9e25eda7c" - dependencies: - clone "^1.0.0" - clone-buffer "^1.0.0" - clone-stats "^1.0.0" - cloneable-readable "^1.0.0" - is-stream "^1.1.0" - remove-trailing-separator "^1.0.1" - replace-ext "^1.0.0" - -vscode-jsonrpc@^3.5.0: - version "3.5.0" - resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-3.5.0.tgz#87239d9e166b2d7352245b8a813597804c1d63aa" - -vscode-languageclient@^3.4.5: - version "3.5.0" - resolved "https://registry.yarnpkg.com/vscode-languageclient/-/vscode-languageclient-3.5.0.tgz#36d02cc186a8365a4467719a290fb200a9ae490a" - dependencies: - vscode-languageserver-protocol "^3.5.0" - -vscode-languageserver-protocol@^3.5.0: - version "3.5.0" - resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.5.0.tgz#067c5cbe27709795398d119692c97ebba1452209" - dependencies: - vscode-jsonrpc "^3.5.0" - vscode-languageserver-types "^3.5.0" - -vscode-languageserver-types@^3.5.0: - version "3.5.0" - resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.5.0.tgz#e48d79962f0b8e02de955e3f524908e2b19c0374" - -vscode@^1.1.4: - version "1.1.10" - resolved "https://registry.yarnpkg.com/vscode/-/vscode-1.1.10.tgz#d1cba378ab24f1d3ddf9cd470d242ee1472dd35b" - dependencies: - glob "^7.1.2" - gulp-chmod "^2.0.0" - gulp-filter "^5.0.1" - gulp-gunzip "1.0.0" - gulp-remote-src "^0.4.3" - gulp-symdest "^1.1.0" - gulp-untar "^0.0.6" - gulp-vinyl-zip "^2.1.0" - mocha "^4.0.1" - request "^2.83.0" - semver "^5.4.1" - source-map-support "^0.5.0" - url-parse "^1.1.9" - vinyl-source-stream "^1.1.0" - -wrappy@1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" - -"xtend@>=4.0.0 <4.1.0-0", xtend@^4.0.0, xtend@~4.0.0, xtend@~4.0.1: - version "4.0.2" - resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" - -yauzl@^2.2.1: - version "2.9.1" - resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.9.1.tgz#a81981ea70a57946133883f029c5821a89359a7f" - dependencies: - buffer-crc32 "~0.2.3" - fd-slicer "~1.0.1" - -yazl@^2.2.1: - version "2.4.3" - resolved "https://registry.yarnpkg.com/yazl/-/yazl-2.4.3.tgz#ec26e5cc87d5601b9df8432dbdd3cd2e5173a071" - dependencies: - buffer-crc32 "~0.2.3" Index: spyder-5.0.5/external-deps/python-lsp-server/.coveragerc =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/.coveragerc @@ -0,0 +1,2 @@ +[run] +omit = pylsp/_version.py Index: spyder-5.0.5/external-deps/python-lsp-server/.gitattributes =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/.gitattributes @@ -0,0 +1 @@ +pylsp/_version.py export-subst Index: spyder-5.0.5/external-deps/python-lsp-server/.github/workflows/static.yml =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/.github/workflows/static.yml @@ -0,0 +1,40 @@ +name: Static code analysis + +on: + push: + branches: + - develop + + pull_request: + branches: + - '*' + +jobs: + build: + name: Static code analysis + runs-on: ubuntu-latest + env: + CI: 'true' + OS: 'linux' + timeout-minutes: 2 + steps: + - uses: actions/cache@v1 + with: + path: ~/.cache/pip + key: static-pip-${{ hashFiles('setup.py') }} + restore-keys: static-pip- + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + with: + # TODO: check with Python 3, but need to fix the + # errors first + python-version: '3.6' + architecture: 'x64' + - run: python -m pip install --upgrade pip setuptools + - run: pip install -e .[pylint,pycodestyle,pyflakes] + - name: Pylint checks + run: pylint pylsp test + - name: Code style checks + run: pycodestyle pylsp test + - name: Pyflakes checks + run: pyflakes pylsp test Index: spyder-5.0.5/external-deps/python-language-server/.github/workflows/test-linux.yml =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/.github/workflows/test-linux.yml +++ /dev/null @@ -1,52 +0,0 @@ -name: Linux tests - -on: - push: - branches: - - develop - - pull_request: - branches: - - '*' - -jobs: - build: - name: Linux Py${{ matrix.PYTHON_VERSION }} - runs-on: ubuntu-latest - env: - CI: 'true' - OS: 'linux' - PYTHON_VERSION: ${{ matrix.PYTHON_VERSION }} - strategy: - fail-fast: false - matrix: - PYTHON_VERSION: ['3.8', '3.7', '3.6', '2.7'] - timeout-minutes: 10 - steps: - - uses: actions/cache@v1 - with: - path: ~/.cache/pip - key: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip-${{ hashFiles('setup.py') }} - restore-keys: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip- - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 - with: - python-version: ${{ matrix.PYTHON_VERSION }} - architecture: 'x64' - - name: Create Jedi environment for testing - if: matrix.PYTHON_VERSION != '2.7' - run: | - python3 -m venv /tmp/pyenv - /tmp/pyenv/bin/python -m pip install loghub - - run: python -m pip install --upgrade pip setuptools - - run: pip install -e .[all,test] - - run: py.test -v test/ - - name: Pylint checks - if: matrix.PYTHON_VERSION == '2.7' - run: pylint pyls test - - name: Code style checks - if: matrix.PYTHON_VERSION == '2.7' - run: pycodestyle pyls test - - name: Pyflakes checks - if: matrix.PYTHON_VERSION == '2.7' - run: pyflakes pyls test Index: spyder-5.0.5/external-deps/python-lsp-server/.github/workflows/test-linux.yml =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/.github/workflows/test-linux.yml @@ -0,0 +1,47 @@ +name: Linux tests + +on: + push: + branches: + - develop + + pull_request: + branches: + - '*' + +jobs: + build: + name: Linux Py${{ matrix.PYTHON_VERSION }} + runs-on: ubuntu-latest + env: + CI: 'true' + OS: 'linux' + PYTHON_VERSION: ${{ matrix.PYTHON_VERSION }} + strategy: + fail-fast: false + matrix: + PYTHON_VERSION: ['3.9', '3.8', '3.7', '3.6'] + timeout-minutes: 10 + steps: + - uses: actions/cache@v1 + with: + path: ~/.cache/pip + key: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip-${{ hashFiles('setup.py') }} + restore-keys: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip- + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.PYTHON_VERSION }} + architecture: 'x64' + - name: Create Jedi environment for testing + if: matrix.PYTHON_VERSION != '2.7' + run: | + python3 -m venv /tmp/pyenv + /tmp/pyenv/bin/python -m pip install loghub + - run: python -m pip install --upgrade pip setuptools + - run: pip install -e .[all,test] + - run: pytest -v test/ + # Enable this if SSH debugging is required + # - name: Setup tmate session + # uses: mxschmitt/action-tmate@v3 + # if: ${{ failure() }} Index: spyder-5.0.5/external-deps/python-language-server/.github/workflows/test-mac.yml =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/.github/workflows/test-mac.yml +++ /dev/null @@ -1,43 +0,0 @@ -name: Mac tests - -on: - push: - branches: - - develop - - pull_request: - branches: - - '*' - -jobs: - build: - name: Mac Py${{ matrix.PYTHON_VERSION }} - runs-on: macos-latest - env: - CI: 'true' - OS: 'macos' - PYTHON_VERSION: ${{ matrix.PYTHON_VERSION }} - strategy: - fail-fast: false - matrix: - PYTHON_VERSION: ['3.8', '3.7', '3.6', '2.7'] - timeout-minutes: 10 - steps: - - uses: actions/cache@v1 - with: - path: ~/Library/Caches/pip - key: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip-${{ hashFiles('setup.py') }} - restore-keys: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip- - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 - with: - python-version: ${{ matrix.PYTHON_VERSION }} - architecture: 'x64' - - name: Create Jedi environment for testing - if: matrix.PYTHON_VERSION != '2.7' - run: | - python3 -m venv /tmp/pyenv - /tmp/pyenv/bin/python -m pip install loghub - - run: python -m pip install --upgrade pip setuptools - - run: pip install -e .[all,test] - - run: py.test -v test/ Index: spyder-5.0.5/external-deps/python-lsp-server/.github/workflows/test-mac.yml =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/.github/workflows/test-mac.yml @@ -0,0 +1,47 @@ +name: Mac tests + +on: + push: + branches: + - develop + + pull_request: + branches: + - '*' + +jobs: + build: + name: Mac Py${{ matrix.PYTHON_VERSION }} + runs-on: macos-latest + env: + CI: 'true' + OS: 'macos' + PYTHON_VERSION: ${{ matrix.PYTHON_VERSION }} + strategy: + fail-fast: false + matrix: + PYTHON_VERSION: ['3.9', '3.8', '3.7', '3.6'] + timeout-minutes: 10 + steps: + - uses: actions/cache@v1 + with: + path: ~/Library/Caches/pip + key: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip-${{ hashFiles('setup.py') }} + restore-keys: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip- + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.PYTHON_VERSION }} + architecture: 'x64' + - name: Create Jedi environment for testing + if: matrix.PYTHON_VERSION != '2.7' + run: | + python3 -m venv /tmp/pyenv + /tmp/pyenv/bin/python -m pip install loghub + - run: python -m pip install --upgrade pip setuptools + - run: pip install -e .[all,test] + - run: pytest -v test/ + # Enable this if SSH debugging is required + # - name: Setup tmate session + # uses: mxschmitt/action-tmate@v3 + # if: ${{ failure() }} Index: spyder-5.0.5/external-deps/python-language-server/.github/workflows/test-win.yml =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/.github/workflows/test-win.yml +++ /dev/null @@ -1,38 +0,0 @@ -name: Windows tests - -on: - push: - branches: - - develop - - pull_request: - branches: - - '*' - -jobs: - build: - name: Win Py${{ matrix.PYTHON_VERSION }} - runs-on: windows-latest - env: - CI: 'true' - OS: 'win' - PYTHON_VERSION: ${{ matrix.PYTHON_VERSION }} - strategy: - fail-fast: false - matrix: - PYTHON_VERSION: ['3.8', '3.7', '3.6', '2.7'] - timeout-minutes: 10 - steps: - - uses: actions/cache@v1 - with: - path: ~\AppData\Local\pip\Cache - key: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip-${{ hashFiles('setup.py') }} - restore-keys: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip- - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 - with: - python-version: ${{ matrix.PYTHON_VERSION }} - architecture: 'x64' - - run: python -m pip install --upgrade pip setuptools - - run: pip install -e .[all,test] - - run: py.test -v test/ Index: spyder-5.0.5/external-deps/python-lsp-server/.github/workflows/test-win.yml =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/.github/workflows/test-win.yml @@ -0,0 +1,38 @@ +name: Windows tests + +on: + push: + branches: + - develop + + pull_request: + branches: + - '*' + +jobs: + build: + name: Win Py${{ matrix.PYTHON_VERSION }} + runs-on: windows-latest + env: + CI: 'true' + OS: 'win' + PYTHON_VERSION: ${{ matrix.PYTHON_VERSION }} + strategy: + fail-fast: false + matrix: + PYTHON_VERSION: ['3.9', '3.8', '3.7', '3.6'] + timeout-minutes: 10 + steps: + - uses: actions/cache@v1 + with: + path: ~\AppData\Local\pip\Cache + key: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip-${{ hashFiles('setup.py') }} + restore-keys: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip- + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.PYTHON_VERSION }} + architecture: 'x64' + - run: python -m pip install --upgrade pip setuptools + - run: pip install -e .[all,test] + - run: pytest -v test/ Index: spyder-5.0.5/external-deps/python-language-server/.gitrepo =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/.gitrepo +++ /dev/null @@ -1,12 +0,0 @@ -; DO NOT EDIT (unless you know what you are doing) -; -; This subdirectory is a git "subrepo", and this file is maintained by the -; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme -; -[subrepo] - remote = https://github.com/palantir/python-language-server.git - branch = develop - commit = 7d7f6a47b9487b29bd8a07776dcf5425e0877d6f - parent = 1d5d76f462b8006977be5946b985de6ed47c8b94 - method = merge - cmdver = 0.4.1 Index: spyder-5.0.5/external-deps/python-lsp-server/.gitrepo =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/.gitrepo @@ -0,0 +1,12 @@ +; DO NOT EDIT (unless you know what you are doing) +; +; This subdirectory is a git "subrepo", and this file is maintained by the +; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme +; +[subrepo] + remote = https://github.com/python-lsp/python-lsp-server.git + branch = develop + commit = 22a746e5e1dc1c075360242cfd27813687f1b142 + parent = 04e393bcea8ee2968bab4ff9a861300c3f802b20 + method = merge + cmdver = 0.4.3 Index: spyder-5.0.5/external-deps/python-language-server/.pylintrc =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/.pylintrc +++ /dev/null @@ -1,29 +0,0 @@ -[FORMAT] - -max-line-length = 120 - -[MESSAGES CONTROL] - -enable = - useless-suppression - -disable = - duplicate-code, - invalid-name, - fixme, - missing-docstring, - protected-access, - too-few-public-methods, - too-many-arguments, - too-many-instance-attributes, - import-error - -[REPORTS] - -reports = no - -[TYPECHECK] - -generated-members = - pyls_* - cache_clear Index: spyder-5.0.5/external-deps/python-lsp-server/.pylintrc =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/.pylintrc @@ -0,0 +1,29 @@ +[FORMAT] + +max-line-length = 120 + +[MESSAGES CONTROL] + +enable = + useless-suppression + +disable = + duplicate-code, + invalid-name, + fixme, + missing-docstring, + protected-access, + too-few-public-methods, + too-many-arguments, + too-many-instance-attributes, + import-error + +[REPORTS] + +reports = no + +[TYPECHECK] + +generated-members = + pylsp_* + cache_clear Index: spyder-5.0.5/external-deps/python-lsp-server/CHANGELOG.md =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/CHANGELOG.md @@ -0,0 +1,38 @@ +## Version 1.0.1 (2021-04-22) + +### Issues Closed + +* [Issue 16](https://github.com/python-lsp/python-lsp-server/issues/16) - Release v1.0.1 + +In this release 1 issue was closed. + +### Pull Requests Merged + +* [PR 15](https://github.com/python-lsp/python-lsp-server/pull/15) - PR: Update pyflakes and pycodestyle dependency versions, by [@andfoy](https://github.com/andfoy) +* [PR 14](https://github.com/python-lsp/python-lsp-server/pull/14) - PR: Small fix in Readme, by [@yaegassy](https://github.com/yaegassy) + +In this release 2 pull requests were closed. + + +## Version 1.0.0 (2021/04/14) + +### Issues Closed + +* [Issue 13](https://github.com/python-lsp/python-lsp-server/issues/13) - Release v1.0.0 +* [Issue 4](https://github.com/python-lsp/python-lsp-server/issues/4) - Transition plan + +In this release 2 issues were closed. + +### Pull Requests Merged + +* [PR 12](https://github.com/python-lsp/python-lsp-server/pull/12) - PR: Use python-lsp-jsonrpc instead of python-jsonrpc-server, by [@andfoy](https://github.com/andfoy) +* [PR 11](https://github.com/python-lsp/python-lsp-server/pull/11) - PR: Remove references to VSCode in Readme, by [@ccordoba12](https://github.com/ccordoba12) +* [PR 10](https://github.com/python-lsp/python-lsp-server/pull/10) - PR: Rename namespace to pylsp and package to python-lsp-server, by [@andfoy](https://github.com/andfoy) +* [PR 9](https://github.com/python-lsp/python-lsp-server/pull/9) - TST: accept folding of decorator parameters in Python 3.9, by [@bnavigator](https://github.com/bnavigator) ([8](https://github.com/python-lsp/python-lsp-server/issues/8)) +* [PR 7](https://github.com/python-lsp/python-lsp-server/pull/7) - Unpin numpy, by [@bnavigator](https://github.com/bnavigator) +* [PR 6](https://github.com/python-lsp/python-lsp-server/pull/6) - Rewrite README from rst to md, by [@xiaoxiae](https://github.com/xiaoxiae) +* [PR 5](https://github.com/python-lsp/python-lsp-server/pull/5) - Update README.rst, by [@marimeireles](https://github.com/marimeireles) +* [PR 3](https://github.com/python-lsp/python-lsp-server/pull/3) - Fix CI tests by temporarily pinning numpy; update repo paths, by [@krassowski](https://github.com/krassowski) +* [PR 2](https://github.com/python-lsp/python-lsp-server/pull/2) - bump jedi compatibility: compare to Path-like object, by [@bnavigator](https://github.com/bnavigator) + +In this release 9 pull requests were closed. Index: spyder-5.0.5/external-deps/python-language-server/LICENSE =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright 2017 Palantir Technologies, Inc. - -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. Index: spyder-5.0.5/external-deps/python-lsp-server/LICENSE =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright 2017-2020 Palantir Technologies, Inc. +Copyright 2021 Python Language Server Contributors. + +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. Index: spyder-5.0.5/external-deps/python-language-server/MANIFEST.in =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/MANIFEST.in +++ /dev/null @@ -1,6 +0,0 @@ -include README.rst -include versioneer.py -include pyls/_version.py -include LICENSE -include .pylintrc -recursive-include test *.py Index: spyder-5.0.5/external-deps/python-lsp-server/MANIFEST.in =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/MANIFEST.in @@ -0,0 +1,6 @@ +include README.md +include versioneer.py +include pylsp/_version.py +include LICENSE +include .pylintrc +recursive-include test *.py Index: spyder-5.0.5/external-deps/python-lsp-server/README.md =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/README.md @@ -0,0 +1,90 @@ +# Python LSP Server + +[![image](https://github.com/python-ls/python-ls/workflows/Linux%20tests/badge.svg)](https://github.com/python-ls/python-ls/actions?query=workflow%3A%22Linux+tests%22) [![image](https://github.com/python-ls/python-ls/workflows/Mac%20tests/badge.svg)](https://github.com/python-ls/python-ls/actions?query=workflow%3A%22Mac+tests%22) [![image](https://github.com/python-ls/python-ls/workflows/Windows%20tests/badge.svg)](https://github.com/python-ls/python-ls/actions?query=workflow%3A%22Windows+tests%22) [![image](https://img.shields.io/github/license/python-ls/python-ls.svg)](https://github.com/python-ls/python-ls/blob/master/LICENSE) + +A Python 3.6+ implementation of the [Language Server Protocol](https://github.com/Microsoft/language-server-protocol). + +## Installation + +The base language server requires [Jedi](https://github.com/davidhalter/jedi) to provide Completions, Definitions, Hover, References, Signature Help, and Symbols: + +``` +pip install python-lsp-server +``` + +If the respective dependencies are found, the following optional providers will be enabled: +- [Rope](https://github.com/python-rope/rope) for Completions and renaming +- [Pyflakes](https://github.com/PyCQA/pyflakes) linter to detect various errors +- [McCabe](https://github.com/PyCQA/mccabe) linter for complexity checking +- [pycodestyle](https://github.com/PyCQA/pycodestyle) linter for style checking +- [pydocstyle](https://github.com/PyCQA/pydocstyle) linter for docstring style checking (disabled by default) +- [autopep8](https://github.com/hhatto/autopep8) for code formatting +- [YAPF](https://github.com/google/yapf) for code formatting (preferred over autopep8) + +Optional providers can be installed using the `extras` syntax. To install [YAPF](https://github.com/google/yapf) formatting for example: + +``` +pip install 'python-lsp-server[yapf]' +``` + +All optional providers can be installed using: + +``` +pip install 'python-lsp-server[all]' +``` + +If you get an error similar to `'install_requires' must be a string or list of strings` then please upgrade setuptools before trying again. + +``` +pip install -U setuptools +``` + +### 3rd Party Plugins + +Installing these plugins will add extra functionality to the language server: + +- [pyls-mypy](https://github.com/tomv564/pyls-mypy) Mypy type checking for Python 3 +- [pyls-isort](https://github.com/paradoxxxzero/pyls-isort) Isort import sort code formatting +- [pyls-black](https://github.com/rupert/pyls-black) for code formatting using [Black](https://github.com/ambv/black) +- [pyls-memestra](https://github.com/QuantStack/pyls-memestra) for detecting the use of deprecated APIs + +Please see the above repositories for examples on how to write plugins for the Python Language Server. Please file an issue if you require assistance writing a plugin. + +## Configuration + +Configuration is loaded from zero or more configuration sources. Currently implemented are: + +- pycodestyle: discovered in `~/.config/pycodestyle`, `setup.cfg`, `tox.ini` and `pycodestyle.cfg`. +- flake8: discovered in `~/.config/flake8`, `setup.cfg`, `tox.ini` and `flake8.cfg` + +The default configuration source is pycodestyle. Change the `pylsp.configurationSources` setting to `['flake8']` in order to respect flake8 configuration instead. + +Overall configuration is computed first from user configuration (in home directory), overridden by configuration passed in by the language client, and then overriden by configuration discovered in the workspace. + +To enable pydocstyle for linting docstrings add the following setting in your LSP configuration: +`"pylsp.plugins.pydocstyle.enabled": true` + +## Language Server Features + +* Auto Completion +* Code Linting +* Signature Help +* Go to definition +* Hover +* Find References +* Document Symbols +* Document Formatting +* Code folding +* Multiple workspaces + +## Development + +To run the test suite: + +``` +pip install .[test] && pytest +``` + +## License + +This project is made available under the MIT License. Index: spyder-5.0.5/external-deps/python-lsp-server/RELEASE.md =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/RELEASE.md @@ -0,0 +1,17 @@ +To release a new version of python-lsp-server: +1. git fetch upstream && git checkout upstream/master +2. Close milestone on GitHub +3. git clean -xfdi +4. Update CHANGELOG.md with loghub +5. git add -A && git commit -m "Update Changelog" +6. Update release version in ``_version.py`` (set release version, remove 'dev0') +7. git add -A && git commit -m "Release vX.X.X" +8. python setup.py sdist +9. python setup.py bdist_wheel +10. twine check +11. twine upload +12. git tag -a vX.X.X -m "Release vX.X.X" +13. Update development version in ``_version.py`` (add 'dev0' and increment minor) +14. git add -A && git commit -m "Back to work" +15. git push upstream master +16. git push upstream --tags Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/__init__.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import os +import pluggy +from ._version import __version__ + +PYLSP = 'pylsp' +IS_WIN = os.name == 'nt' + +hookspec = pluggy.HookspecMarker(PYLSP) +hookimpl = pluggy.HookimplMarker(PYLSP) + +__all__ = [__version__] Index: spyder-5.0.5/external-deps/python-language-server/pyls/__main__.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/__main__.py +++ /dev/null @@ -1,127 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import argparse -import logging -import logging.config -import sys - -try: - import ujson as json -except Exception: # pylint: disable=broad-except - import json - -from .python_ls import (PythonLanguageServer, start_io_lang_server, - start_tcp_lang_server) - -LOG_FORMAT = "%(asctime)s UTC - %(levelname)s - %(name)s - %(message)s" - - -def add_arguments(parser): - parser.description = "Python Language Server" - - parser.add_argument( - "--tcp", action="store_true", - help="Use TCP server instead of stdio" - ) - parser.add_argument( - "--host", default="127.0.0.1", - help="Bind to this address" - ) - parser.add_argument( - "--port", type=int, default=2087, - help="Bind to this port" - ) - parser.add_argument( - '--check-parent-process', action="store_true", - help="Check whether parent process is still alive using os.kill(ppid, 0) " - "and auto shut down language server process when parent process is not alive." - "Note that this may not work on a Windows machine." - ) - - log_group = parser.add_mutually_exclusive_group() - log_group.add_argument( - "--log-config", - help="Path to a JSON file containing Python logging config." - ) - log_group.add_argument( - "--log-file", - help="Redirect logs to the given file instead of writing to stderr." - "Has no effect if used with --log-config." - ) - - parser.add_argument( - '-v', '--verbose', action='count', default=0, - help="Increase verbosity of log output, overrides log config file" - ) - - -def main(): - parser = argparse.ArgumentParser() - add_arguments(parser) - args = parser.parse_args() - _configure_logger(args.verbose, args.log_config, args.log_file) - - if args.tcp: - start_tcp_lang_server(args.host, args.port, args.check_parent_process, - PythonLanguageServer) - else: - stdin, stdout = _binary_stdio() - start_io_lang_server(stdin, stdout, args.check_parent_process, - PythonLanguageServer) - - -def _binary_stdio(): - """Construct binary stdio streams (not text mode). - - This seems to be different for Window/Unix Python2/3, so going by: - https://stackoverflow.com/questions/2850893/reading-binary-data-from-stdin - """ - PY3K = sys.version_info >= (3, 0) - - if PY3K: - # pylint: disable=no-member - stdin, stdout = sys.stdin.buffer, sys.stdout.buffer - else: - # Python 2 on Windows opens sys.stdin in text mode, and - # binary data that read from it becomes corrupted on \r\n - if sys.platform == "win32": - # set sys.stdin to binary mode - # pylint: disable=no-member,import-error - import os - import msvcrt - msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) - msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) - stdin, stdout = sys.stdin, sys.stdout - - return stdin, stdout - - -def _configure_logger(verbose=0, log_config=None, log_file=None): - root_logger = logging.root - - if log_config: - with open(log_config, 'r') as f: - logging.config.dictConfig(json.load(f)) - else: - formatter = logging.Formatter(LOG_FORMAT) - if log_file: - log_handler = logging.handlers.RotatingFileHandler( - log_file, mode='a', maxBytes=50*1024*1024, - backupCount=10, encoding=None, delay=0 - ) - else: - log_handler = logging.StreamHandler() - log_handler.setFormatter(formatter) - root_logger.addHandler(log_handler) - - if verbose == 0: - level = logging.WARNING - elif verbose == 1: - level = logging.INFO - elif verbose >= 2: - level = logging.DEBUG - - root_logger.setLevel(level) - - -if __name__ == '__main__': - main() Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/__main__.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/__main__.py @@ -0,0 +1,113 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import argparse +import logging +import logging.config +import sys + +try: + import ujson as json +except Exception: # pylint: disable=broad-except + import json + +from .python_lsp import (PythonLSPServer, start_io_lang_server, + start_tcp_lang_server) + +LOG_FORMAT = "%(asctime)s UTC - %(levelname)s - %(name)s - %(message)s" + + +def add_arguments(parser): + parser.description = "Python Language Server" + + parser.add_argument( + "--tcp", action="store_true", + help="Use TCP server instead of stdio" + ) + parser.add_argument( + "--host", default="127.0.0.1", + help="Bind to this address" + ) + parser.add_argument( + "--port", type=int, default=2087, + help="Bind to this port" + ) + parser.add_argument( + '--check-parent-process', action="store_true", + help="Check whether parent process is still alive using os.kill(ppid, 0) " + "and auto shut down language server process when parent process is not alive." + "Note that this may not work on a Windows machine." + ) + + log_group = parser.add_mutually_exclusive_group() + log_group.add_argument( + "--log-config", + help="Path to a JSON file containing Python logging config." + ) + log_group.add_argument( + "--log-file", + help="Redirect logs to the given file instead of writing to stderr." + "Has no effect if used with --log-config." + ) + + parser.add_argument( + '-v', '--verbose', action='count', default=0, + help="Increase verbosity of log output, overrides log config file" + ) + + +def main(): + parser = argparse.ArgumentParser() + add_arguments(parser) + args = parser.parse_args() + _configure_logger(args.verbose, args.log_config, args.log_file) + + if args.tcp: + start_tcp_lang_server(args.host, args.port, args.check_parent_process, + PythonLSPServer) + else: + stdin, stdout = _binary_stdio() + start_io_lang_server(stdin, stdout, args.check_parent_process, + PythonLSPServer) + + +def _binary_stdio(): + """Construct binary stdio streams (not text mode). + + This seems to be different for Window/Unix Python2/3, so going by: + https://stackoverflow.com/questions/2850893/reading-binary-data-from-stdin + """ + stdin, stdout = sys.stdin.buffer, sys.stdout.buffer + return stdin, stdout + + +def _configure_logger(verbose=0, log_config=None, log_file=None): + root_logger = logging.root + + if log_config: + with open(log_config, 'r') as f: + logging.config.dictConfig(json.load(f)) + else: + formatter = logging.Formatter(LOG_FORMAT) + if log_file: + log_handler = logging.handlers.RotatingFileHandler( + log_file, mode='a', maxBytes=50*1024*1024, + backupCount=10, encoding=None, delay=0 + ) + else: + log_handler = logging.StreamHandler() + log_handler.setFormatter(formatter) + root_logger.addHandler(log_handler) + + if verbose == 0: + level = logging.WARNING + elif verbose == 1: + level = logging.INFO + elif verbose >= 2: + level = logging.DEBUG + + root_logger.setLevel(level) + + +if __name__ == '__main__': + main() Index: spyder-5.0.5/external-deps/python-language-server/pyls/_utils.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/_utils.py +++ /dev/null @@ -1,227 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import functools -import inspect -import logging -import os -import sys -import threading - -import jedi - -PY2 = sys.version_info.major == 2 -JEDI_VERSION = jedi.__version__ - -if PY2: - import pathlib2 as pathlib -else: - import pathlib - -log = logging.getLogger(__name__) - - -def debounce(interval_s, keyed_by=None): - """Debounce calls to this function until interval_s seconds have passed.""" - def wrapper(func): - timers = {} - lock = threading.Lock() - - @functools.wraps(func) - def debounced(*args, **kwargs): - call_args = inspect.getcallargs(func, *args, **kwargs) - key = call_args[keyed_by] if keyed_by else None - - def run(): - with lock: - del timers[key] - return func(*args, **kwargs) - - with lock: - old_timer = timers.get(key) - if old_timer: - old_timer.cancel() - - timer = threading.Timer(interval_s, run) - timers[key] = timer - timer.start() - return debounced - return wrapper - - -def find_parents(root, path, names): - """Find files matching the given names relative to the given path. - - Args: - path (str): The file path to start searching up from. - names (List[str]): The file/directory names to look for. - root (str): The directory at which to stop recursing upwards. - - Note: - The path MUST be within the root. - """ - if not root: - return [] - - if not os.path.commonprefix((root, path)): - log.warning("Path %s not in %s", path, root) - return [] - - # Split the relative by directory, generate all the parent directories, then check each of them. - # This avoids running a loop that has different base-cases for unix/windows - # e.g. /a/b and /a/b/c/d/e.py -> ['/a/b', 'c', 'd'] - dirs = [root] + os.path.relpath(os.path.dirname(path), root).split(os.path.sep) - - # Search each of /a/b/c, /a/b, /a - while dirs: - search_dir = os.path.join(*dirs) - existing = list(filter(os.path.exists, [os.path.join(search_dir, n) for n in names])) - if existing: - return existing - dirs.pop() - - # Otherwise nothing - return [] - - -def path_to_dot_name(path): - """Given a path to a module, derive its dot-separated full name.""" - directory = os.path.dirname(path) - module_name, _ = os.path.splitext(os.path.basename(path)) - full_name = [module_name] - while os.path.exists(os.path.join(directory, '__init__.py')): - this_directory = os.path.basename(directory) - directory = os.path.dirname(directory) - full_name = [this_directory] + full_name - return '.'.join(full_name) - - -def match_uri_to_workspace(uri, workspaces): - if uri is None: - return None - max_len, chosen_workspace = -1, None - path = pathlib.Path(uri).parts - for workspace in workspaces: - try: - workspace_parts = pathlib.Path(workspace).parts - except TypeError: - # This can happen in Python2 if 'value' is a subclass of string - workspace_parts = pathlib.Path(unicode(workspace)).parts - if len(workspace_parts) > len(path): - continue - match_len = 0 - for workspace_part, path_part in zip(workspace_parts, path): - if workspace_part == path_part: - match_len += 1 - if match_len > 0: - if match_len > max_len: - max_len = match_len - chosen_workspace = workspace - return chosen_workspace - - -def list_to_string(value): - return ",".join(value) if isinstance(value, list) else value - - -def merge_dicts(dict_a, dict_b): - """Recursively merge dictionary b into dictionary a. - - If override_nones is True, then - """ - def _merge_dicts_(a, b): - for key in set(a.keys()).union(b.keys()): - if key in a and key in b: - if isinstance(a[key], dict) and isinstance(b[key], dict): - yield (key, dict(_merge_dicts_(a[key], b[key]))) - elif b[key] is not None: - yield (key, b[key]) - else: - yield (key, a[key]) - elif key in a: - yield (key, a[key]) - elif b[key] is not None: - yield (key, b[key]) - return dict(_merge_dicts_(dict_a, dict_b)) - - -def format_docstring(contents): - """Python doc strings come in a number of formats, but LSP wants markdown. - - Until we can find a fast enough way of discovering and parsing each format, - we can do a little better by at least preserving indentation. - """ - contents = contents.replace('\t', u'\u00A0' * 4) - contents = contents.replace(' ', u'\u00A0' * 2) - return contents - - -def clip_column(column, lines, line_number): - """ - Normalise the position as per the LSP that accepts character positions > line length - - https://microsoft.github.io/language-server-protocol/specification#position - """ - max_column = len(lines[line_number].rstrip('\r\n')) if len(lines) > line_number else 0 - return min(column, max_column) - - -def position_to_jedi_linecolumn(document, position): - """ - Convert the LSP format 'line', 'character' to Jedi's 'line', 'column' - - https://microsoft.github.io/language-server-protocol/specification#position - """ - code_position = {} - if position: - code_position = {'line': position['line'] + 1, - 'column': clip_column(position['character'], - document.lines, - position['line'])} - return code_position - - -if os.name == 'nt': - import ctypes - - kernel32 = ctypes.windll.kernel32 - PROCESS_QUERY_INFROMATION = 0x1000 - - def is_process_alive(pid): - """Check whether the process with the given pid is still alive. - - Running `os.kill()` on Windows always exits the process, so it can't be used to check for an alive process. - see: https://docs.python.org/3/library/os.html?highlight=os%20kill#os.kill - - Hence ctypes is used to check for the process directly via windows API avoiding any other 3rd-party dependency. - - Args: - pid (int): process ID - - Returns: - bool: False if the process is not alive or don't have permission to check, True otherwise. - """ - process = kernel32.OpenProcess(PROCESS_QUERY_INFROMATION, 0, pid) - if process != 0: - kernel32.CloseHandle(process) - return True - return False - -else: - import errno - - def is_process_alive(pid): - """Check whether the process with the given pid is still alive. - - Args: - pid (int): process ID - - Returns: - bool: False if the process is not alive or don't have permission to check, True otherwise. - """ - if pid < 0: - return False - try: - os.kill(pid, 0) - except OSError as e: - return e.errno == errno.EPERM - else: - return True Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/_utils.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/_utils.py @@ -0,0 +1,220 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import functools +import inspect +import logging +import os +import pathlib +import threading + +import jedi + +JEDI_VERSION = jedi.__version__ + +log = logging.getLogger(__name__) + + +def debounce(interval_s, keyed_by=None): + """Debounce calls to this function until interval_s seconds have passed.""" + def wrapper(func): + timers = {} + lock = threading.Lock() + + @functools.wraps(func) + def debounced(*args, **kwargs): + sig = inspect.signature(func) + call_args = sig.bind(*args, **kwargs) + key = call_args.arguments[keyed_by] if keyed_by else None + + def run(): + with lock: + del timers[key] + return func(*args, **kwargs) + + with lock: + old_timer = timers.get(key) + if old_timer: + old_timer.cancel() + + timer = threading.Timer(interval_s, run) + timers[key] = timer + timer.start() + return debounced + return wrapper + + +def find_parents(root, path, names): + """Find files matching the given names relative to the given path. + + Args: + path (str): The file path to start searching up from. + names (List[str]): The file/directory names to look for. + root (str): The directory at which to stop recursing upwards. + + Note: + The path MUST be within the root. + """ + if not root: + return [] + + if not os.path.commonprefix((root, path)): + log.warning("Path %s not in %s", path, root) + return [] + + # Split the relative by directory, generate all the parent directories, then check each of them. + # This avoids running a loop that has different base-cases for unix/windows + # e.g. /a/b and /a/b/c/d/e.py -> ['/a/b', 'c', 'd'] + dirs = [root] + os.path.relpath(os.path.dirname(path), root).split(os.path.sep) + + # Search each of /a/b/c, /a/b, /a + while dirs: + search_dir = os.path.join(*dirs) + existing = list(filter(os.path.exists, [os.path.join(search_dir, n) for n in names])) + if existing: + return existing + dirs.pop() + + # Otherwise nothing + return [] + + +def path_to_dot_name(path): + """Given a path to a module, derive its dot-separated full name.""" + directory = os.path.dirname(path) + module_name, _ = os.path.splitext(os.path.basename(path)) + full_name = [module_name] + while os.path.exists(os.path.join(directory, '__init__.py')): + this_directory = os.path.basename(directory) + directory = os.path.dirname(directory) + full_name = [this_directory] + full_name + return '.'.join(full_name) + + +def match_uri_to_workspace(uri, workspaces): + if uri is None: + return None + max_len, chosen_workspace = -1, None + path = pathlib.Path(uri).parts + for workspace in workspaces: + workspace_parts = pathlib.Path(workspace).parts + if len(workspace_parts) > len(path): + continue + match_len = 0 + for workspace_part, path_part in zip(workspace_parts, path): + if workspace_part == path_part: + match_len += 1 + if match_len > 0: + if match_len > max_len: + max_len = match_len + chosen_workspace = workspace + return chosen_workspace + + +def list_to_string(value): + return ",".join(value) if isinstance(value, list) else value + + +def merge_dicts(dict_a, dict_b): + """Recursively merge dictionary b into dictionary a. + + If override_nones is True, then + """ + def _merge_dicts_(a, b): + for key in set(a.keys()).union(b.keys()): + if key in a and key in b: + if isinstance(a[key], dict) and isinstance(b[key], dict): + yield (key, dict(_merge_dicts_(a[key], b[key]))) + elif b[key] is not None: + yield (key, b[key]) + else: + yield (key, a[key]) + elif key in a: + yield (key, a[key]) + elif b[key] is not None: + yield (key, b[key]) + return dict(_merge_dicts_(dict_a, dict_b)) + + +def format_docstring(contents): + """Python doc strings come in a number of formats, but LSP wants markdown. + + Until we can find a fast enough way of discovering and parsing each format, + we can do a little better by at least preserving indentation. + """ + contents = contents.replace('\t', u'\u00A0' * 4) + contents = contents.replace(' ', u'\u00A0' * 2) + return contents + + +def clip_column(column, lines, line_number): + """ + Normalise the position as per the LSP that accepts character positions > line length + + https://microsoft.github.io/language-server-protocol/specification#position + """ + max_column = len(lines[line_number].rstrip('\r\n')) if len(lines) > line_number else 0 + return min(column, max_column) + + +def position_to_jedi_linecolumn(document, position): + """ + Convert the LSP format 'line', 'character' to Jedi's 'line', 'column' + + https://microsoft.github.io/language-server-protocol/specification#position + """ + code_position = {} + if position: + code_position = {'line': position['line'] + 1, + 'column': clip_column(position['character'], + document.lines, + position['line'])} + return code_position + + +if os.name == 'nt': + import ctypes + + kernel32 = ctypes.windll.kernel32 + PROCESS_QUERY_INFROMATION = 0x1000 + + def is_process_alive(pid): + """Check whether the process with the given pid is still alive. + + Running `os.kill()` on Windows always exits the process, so it can't be used to check for an alive process. + see: https://docs.python.org/3/library/os.html?highlight=os%20kill#os.kill + + Hence ctypes is used to check for the process directly via windows API avoiding any other 3rd-party dependency. + + Args: + pid (int): process ID + + Returns: + bool: False if the process is not alive or don't have permission to check, True otherwise. + """ + process = kernel32.OpenProcess(PROCESS_QUERY_INFROMATION, 0, pid) + if process != 0: + kernel32.CloseHandle(process) + return True + return False + +else: + import errno + + def is_process_alive(pid): + """Check whether the process with the given pid is still alive. + + Args: + pid (int): process ID + + Returns: + bool: False if the process is not alive or don't have permission to check, True otherwise. + """ + if pid < 0: + return False + try: + os.kill(pid, 0) + except OSError as e: + return e.errno == errno.EPERM + else: + return True Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/_version.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/_version.py @@ -0,0 +1,8 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +"""PyLSP versioning information.""" + + +VERSION_INFO = (1, 1, 0, 'dev0') +__version__ = '.'.join(map(str, VERSION_INFO)) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/config/__init__.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/config/__init__.py @@ -0,0 +1,2 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. Index: spyder-5.0.5/external-deps/python-language-server/pyls/config/config.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/config/config.py +++ /dev/null @@ -1,157 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging -import pkg_resources -try: - from functools import lru_cache -except ImportError: - from backports.functools_lru_cache import lru_cache - -import pluggy - -from pyls import _utils, hookspecs, uris, PYLS - -log = logging.getLogger(__name__) - -# Sources of config, first source overrides next source -DEFAULT_CONFIG_SOURCES = ['pycodestyle'] - - -class Config(object): - - def __init__(self, root_uri, init_opts, process_id, capabilities): - self._root_path = uris.to_fs_path(root_uri) - self._root_uri = root_uri - self._init_opts = init_opts - self._process_id = process_id - self._capabilities = capabilities - - self._settings = {} - self._plugin_settings = {} - - self._config_sources = {} - try: - from .flake8_conf import Flake8Config - self._config_sources['flake8'] = Flake8Config(self._root_path) - except ImportError: - pass - try: - from .pycodestyle_conf import PyCodeStyleConfig - self._config_sources['pycodestyle'] = PyCodeStyleConfig(self._root_path) - except ImportError: - pass - - self._pm = pluggy.PluginManager(PYLS) - self._pm.trace.root.setwriter(log.debug) - self._pm.enable_tracing() - self._pm.add_hookspecs(hookspecs) - - # Pluggy will skip loading a plugin if it throws a DistributionNotFound exception. - # However I don't want all plugins to have to catch ImportError and re-throw. So here we'll filter - # out any entry points that throw ImportError assuming one or more of their dependencies isn't present. - for entry_point in pkg_resources.iter_entry_points(PYLS): - try: - entry_point.load() - except ImportError as e: - log.warning("Failed to load %s entry point '%s': %s", PYLS, entry_point.name, e) - self._pm.set_blocked(entry_point.name) - - # Load the entry points into pluggy, having blocked any failing ones - self._pm.load_setuptools_entrypoints(PYLS) - - for name, plugin in self._pm.list_name_plugin(): - if plugin is not None: - log.info("Loaded pyls plugin %s from %s", name, plugin) - - for plugin_conf in self._pm.hook.pyls_settings(config=self): - self._plugin_settings = _utils.merge_dicts(self._plugin_settings, plugin_conf) - - self._update_disabled_plugins() - - @property - def disabled_plugins(self): - return self._disabled_plugins - - @property - def plugin_manager(self): - return self._pm - - @property - def init_opts(self): - return self._init_opts - - @property - def root_uri(self): - return self._root_uri - - @property - def process_id(self): - return self._process_id - - @property - def capabilities(self): - return self._capabilities - - @lru_cache(maxsize=32) - def settings(self, document_path=None): - """Settings are constructed from a few sources: - - 1. User settings, found in user's home directory - 2. Plugin settings, reported by PyLS plugins - 3. LSP settings, given to us from didChangeConfiguration - 4. Project settings, found in config files in the current project. - - Since this function is nondeterministic, it is important to call - settings.cache_clear() when the config is updated - """ - settings = {} - sources = self._settings.get('configurationSources', DEFAULT_CONFIG_SOURCES) - - # Plugin configuration - settings = _utils.merge_dicts(settings, self._plugin_settings) - - # LSP configuration - settings = _utils.merge_dicts(settings, self._settings) - - # User configuration - for source_name in reversed(sources): - source = self._config_sources.get(source_name) - if not source: - continue - source_conf = source.user_config() - log.debug("Got user config from %s: %s", source.__class__.__name__, source_conf) - settings = _utils.merge_dicts(settings, source_conf) - - # Project configuration - for source_name in reversed(sources): - source = self._config_sources.get(source_name) - if not source: - continue - source_conf = source.project_config(document_path or self._root_path) - log.debug("Got project config from %s: %s", source.__class__.__name__, source_conf) - settings = _utils.merge_dicts(settings, source_conf) - - log.debug("With configuration: %s", settings) - - return settings - - def find_parents(self, path, names): - root_path = uris.to_fs_path(self._root_uri) - return _utils.find_parents(root_path, path, names) - - def plugin_settings(self, plugin, document_path=None): - return self.settings(document_path=document_path).get('plugins', {}).get(plugin, {}) - - def update(self, settings): - """Recursively merge the given settings into the current settings.""" - self.settings.cache_clear() - self._settings = settings - log.info("Updated settings to %s", self._settings) - self._update_disabled_plugins() - - def _update_disabled_plugins(self): - # All plugins default to enabled - self._disabled_plugins = [ - plugin for name, plugin in self.plugin_manager.list_name_plugin() - if not self.settings().get('plugins', {}).get(name, {}).get('enabled', True) - ] - log.info("Disabled plugins: %s", self._disabled_plugins) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/config/config.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/config/config.py @@ -0,0 +1,156 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. +# pylint: disable=import-outside-toplevel + +import logging +from functools import lru_cache +import pkg_resources + +import pluggy + +from pylsp import _utils, hookspecs, uris, PYLSP + +log = logging.getLogger(__name__) + +# Sources of config, first source overrides next source +DEFAULT_CONFIG_SOURCES = ['pycodestyle'] + + +class Config: + def __init__(self, root_uri, init_opts, process_id, capabilities): + self._root_path = uris.to_fs_path(root_uri) + self._root_uri = root_uri + self._init_opts = init_opts + self._process_id = process_id + self._capabilities = capabilities + + self._settings = {} + self._plugin_settings = {} + + self._config_sources = {} + try: + from .flake8_conf import Flake8Config + self._config_sources['flake8'] = Flake8Config(self._root_path) + except ImportError: + pass + try: + from .pycodestyle_conf import PyCodeStyleConfig + self._config_sources['pycodestyle'] = PyCodeStyleConfig(self._root_path) + except ImportError: + pass + + self._pm = pluggy.PluginManager(PYLSP) + self._pm.trace.root.setwriter(log.debug) + self._pm.enable_tracing() + self._pm.add_hookspecs(hookspecs) + + # Pluggy will skip loading a plugin if it throws a DistributionNotFound exception. + # However I don't want all plugins to have to catch ImportError and re-throw. So here we'll filter + # out any entry points that throw ImportError assuming one or more of their dependencies isn't present. + for entry_point in pkg_resources.iter_entry_points(PYLSP): + try: + entry_point.load() + except ImportError as e: + log.warning("Failed to load %s entry point '%s': %s", PYLSP, entry_point.name, e) + self._pm.set_blocked(entry_point.name) + + # Load the entry points into pluggy, having blocked any failing ones + self._pm.load_setuptools_entrypoints(PYLSP) + + for name, plugin in self._pm.list_name_plugin(): + if plugin is not None: + log.info("Loaded pylsp plugin %s from %s", name, plugin) + + for plugin_conf in self._pm.hook.pylsp_settings(config=self): + self._plugin_settings = _utils.merge_dicts(self._plugin_settings, plugin_conf) + + self._update_disabled_plugins() + + @property + def disabled_plugins(self): + return self._disabled_plugins + + @property + def plugin_manager(self): + return self._pm + + @property + def init_opts(self): + return self._init_opts + + @property + def root_uri(self): + return self._root_uri + + @property + def process_id(self): + return self._process_id + + @property + def capabilities(self): + return self._capabilities + + @lru_cache(maxsize=32) + def settings(self, document_path=None): + """Settings are constructed from a few sources: + + 1. User settings, found in user's home directory + 2. Plugin settings, reported by PyLS plugins + 3. LSP settings, given to us from didChangeConfiguration + 4. Project settings, found in config files in the current project. + + Since this function is nondeterministic, it is important to call + settings.cache_clear() when the config is updated + """ + settings = {} + sources = self._settings.get('configurationSources', DEFAULT_CONFIG_SOURCES) + + # Plugin configuration + settings = _utils.merge_dicts(settings, self._plugin_settings) + + # LSP configuration + settings = _utils.merge_dicts(settings, self._settings) + + # User configuration + for source_name in reversed(sources): + source = self._config_sources.get(source_name) + if not source: + continue + source_conf = source.user_config() + log.debug("Got user config from %s: %s", source.__class__.__name__, source_conf) + settings = _utils.merge_dicts(settings, source_conf) + + # Project configuration + for source_name in reversed(sources): + source = self._config_sources.get(source_name) + if not source: + continue + source_conf = source.project_config(document_path or self._root_path) + log.debug("Got project config from %s: %s", source.__class__.__name__, source_conf) + settings = _utils.merge_dicts(settings, source_conf) + + log.debug("With configuration: %s", settings) + + return settings + + def find_parents(self, path, names): + root_path = uris.to_fs_path(self._root_uri) + return _utils.find_parents(root_path, path, names) + + def plugin_settings(self, plugin, document_path=None): + return self.settings(document_path=document_path).get('plugins', {}).get(plugin, {}) + + def update(self, settings): + """Recursively merge the given settings into the current settings.""" + self.settings.cache_clear() + self._settings = settings + log.info("Updated settings to %s", self._settings) + self._update_disabled_plugins() + + def _update_disabled_plugins(self): + # All plugins default to enabled + self._disabled_plugins = [ + plugin for name, plugin in self.plugin_manager.list_name_plugin() + if not self.settings().get('plugins', {}).get(name, {}).get('enabled', True) + ] + log.info("Disabled plugins: %s", self._disabled_plugins) Index: spyder-5.0.5/external-deps/python-language-server/pyls/config/flake8_conf.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/config/flake8_conf.py +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging -import os -from pyls._utils import find_parents -from .source import ConfigSource - -log = logging.getLogger(__name__) - -CONFIG_KEY = 'flake8' -PROJECT_CONFIGS = ['.flake8', 'setup.cfg', 'tox.ini'] - -OPTIONS = [ - # mccabe - ('max-complexity', 'plugins.mccabe.threshold', int), - # pycodestyle - ('exclude', 'plugins.pycodestyle.exclude', list), - ('filename', 'plugins.pycodestyle.filename', list), - ('hang-closing', 'plugins.pycodestyle.hangClosing', bool), - ('ignore', 'plugins.pycodestyle.ignore', list), - ('max-line-length', 'plugins.pycodestyle.maxLineLength', int), - ('select', 'plugins.pycodestyle.select', list), - # flake8 - ('exclude', 'plugins.flake8.exclude', list), - ('filename', 'plugins.flake8.filename', list), - ('hang-closing', 'plugins.flake8.hangClosing', bool), - ('ignore', 'plugins.flake8.ignore', list), - ('max-line-length', 'plugins.flake8.maxLineLength', int), - ('select', 'plugins.flake8.select', list), -] - - -class Flake8Config(ConfigSource): - """Parse flake8 configurations.""" - - def user_config(self): - config_file = self._user_config_file() - config = self.read_config_from_files([config_file]) - return self.parse_config(config, CONFIG_KEY, OPTIONS) - - def _user_config_file(self): - if self.is_windows: - return os.path.expanduser('~\\.flake8') - return os.path.join(self.xdg_home, 'flake8') - - def project_config(self, document_path): - files = find_parents(self.root_path, document_path, PROJECT_CONFIGS) - config = self.read_config_from_files(files) - return self.parse_config(config, CONFIG_KEY, OPTIONS) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/config/flake8_conf.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/config/flake8_conf.py @@ -0,0 +1,50 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging +import os +from pylsp._utils import find_parents +from .source import ConfigSource + +log = logging.getLogger(__name__) + +CONFIG_KEY = 'flake8' +PROJECT_CONFIGS = ['.flake8', 'setup.cfg', 'tox.ini'] + +OPTIONS = [ + # mccabe + ('max-complexity', 'plugins.mccabe.threshold', int), + # pycodestyle + ('exclude', 'plugins.pycodestyle.exclude', list), + ('filename', 'plugins.pycodestyle.filename', list), + ('hang-closing', 'plugins.pycodestyle.hangClosing', bool), + ('ignore', 'plugins.pycodestyle.ignore', list), + ('max-line-length', 'plugins.pycodestyle.maxLineLength', int), + ('select', 'plugins.pycodestyle.select', list), + # flake8 + ('exclude', 'plugins.flake8.exclude', list), + ('filename', 'plugins.flake8.filename', list), + ('hang-closing', 'plugins.flake8.hangClosing', bool), + ('ignore', 'plugins.flake8.ignore', list), + ('max-line-length', 'plugins.flake8.maxLineLength', int), + ('select', 'plugins.flake8.select', list), +] + + +class Flake8Config(ConfigSource): + """Parse flake8 configurations.""" + + def user_config(self): + config_file = self._user_config_file() + config = self.read_config_from_files([config_file]) + return self.parse_config(config, CONFIG_KEY, OPTIONS) + + def _user_config_file(self): + if self.is_windows: + return os.path.expanduser('~\\.flake8') + return os.path.join(self.xdg_home, 'flake8') + + def project_config(self, document_path): + files = find_parents(self.root_path, document_path, PROJECT_CONFIGS) + config = self.read_config_from_files(files) + return self.parse_config(config, CONFIG_KEY, OPTIONS) Index: spyder-5.0.5/external-deps/python-language-server/pyls/config/pycodestyle_conf.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/config/pycodestyle_conf.py +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import pycodestyle -from pyls._utils import find_parents -from .source import ConfigSource - - -CONFIG_KEY = 'pycodestyle' -USER_CONFIGS = [pycodestyle.USER_CONFIG] if pycodestyle.USER_CONFIG else [] -PROJECT_CONFIGS = ['pycodestyle.cfg', 'setup.cfg', 'tox.ini'] - -OPTIONS = [ - ('exclude', 'plugins.pycodestyle.exclude', list), - ('filename', 'plugins.pycodestyle.filename', list), - ('hang-closing', 'plugins.pycodestyle.hangClosing', bool), - ('ignore', 'plugins.pycodestyle.ignore', list), - ('max-line-length', 'plugins.pycodestyle.maxLineLength', int), - ('select', 'plugins.pycodestyle.select', list), - ('aggressive', 'plugins.pycodestyle.aggressive', int), -] - - -class PyCodeStyleConfig(ConfigSource): - - def user_config(self): - config = self.read_config_from_files(USER_CONFIGS) - return self.parse_config(config, CONFIG_KEY, OPTIONS) - - def project_config(self, document_path): - files = find_parents(self.root_path, document_path, PROJECT_CONFIGS) - config = self.read_config_from_files(files) - return self.parse_config(config, CONFIG_KEY, OPTIONS) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/config/pycodestyle_conf.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/config/pycodestyle_conf.py @@ -0,0 +1,33 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import pycodestyle +from pylsp._utils import find_parents +from .source import ConfigSource + + +CONFIG_KEY = 'pycodestyle' +USER_CONFIGS = [pycodestyle.USER_CONFIG] if pycodestyle.USER_CONFIG else [] +PROJECT_CONFIGS = ['pycodestyle.cfg', 'setup.cfg', 'tox.ini'] + +OPTIONS = [ + ('exclude', 'plugins.pycodestyle.exclude', list), + ('filename', 'plugins.pycodestyle.filename', list), + ('hang-closing', 'plugins.pycodestyle.hangClosing', bool), + ('ignore', 'plugins.pycodestyle.ignore', list), + ('max-line-length', 'plugins.pycodestyle.maxLineLength', int), + ('select', 'plugins.pycodestyle.select', list), + ('aggressive', 'plugins.pycodestyle.aggressive', int), +] + + +class PyCodeStyleConfig(ConfigSource): + + def user_config(self): + config = self.read_config_from_files(USER_CONFIGS) + return self.parse_config(config, CONFIG_KEY, OPTIONS) + + def project_config(self, document_path): + files = find_parents(self.root_path, document_path, PROJECT_CONFIGS) + config = self.read_config_from_files(files) + return self.parse_config(config, CONFIG_KEY, OPTIONS) Index: spyder-5.0.5/external-deps/python-language-server/pyls/config/source.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/config/source.py +++ /dev/null @@ -1,86 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import configparser -import logging -import os -import sys - -log = logging.getLogger(__name__) - - -class ConfigSource(object): - """Base class for implementing a config source.""" - - def __init__(self, root_path): - self.root_path = root_path - self.is_windows = sys.platform == 'win32' - self.xdg_home = os.environ.get( - 'XDG_CONFIG_HOME', os.path.expanduser('~/.config') - ) - - def user_config(self): - """Return user-level (i.e. home directory) configuration.""" - raise NotImplementedError() - - def project_config(self, document_path): - """Return project-level (i.e. workspace directory) configuration.""" - raise NotImplementedError() - - @staticmethod - def read_config_from_files(files): - config = configparser.RawConfigParser() - for filename in files: - if os.path.exists(filename) and not os.path.isdir(filename): - config.read(filename) - - return config - - @staticmethod - def parse_config(config, key, options): - """Parse the config with the given options.""" - conf = {} - for source, destination, opt_type in options: - opt_value = _get_opt(config, key, source, opt_type) - if opt_value is not None: - _set_opt(conf, destination, opt_value) - return conf - - -def _get_opt(config, key, option, opt_type): - """Get an option from a configparser with the given type.""" - for opt_key in [option, option.replace('-', '_')]: - if not config.has_option(key, opt_key): - continue - - if opt_type == bool: - return config.getboolean(key, opt_key) - - if opt_type == int: - return config.getint(key, opt_key) - - if opt_type == str: - return config.get(key, opt_key) - - if opt_type == list: - return _parse_list_opt(config.get(key, opt_key)) - - raise ValueError("Unknown option type: %s" % opt_type) - - -def _parse_list_opt(string): - return [s.strip() for s in string.split(",") if s.strip()] - - -def _set_opt(config_dict, path, value): - """Set the value in the dictionary at the given path if the value is not None.""" - if value is None: - return - - if '.' not in path: - config_dict[path] = value - return - - key, rest = path.split(".", 1) - if key not in config_dict: - config_dict[key] = {} - - _set_opt(config_dict[key], rest, value) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/config/source.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/config/source.py @@ -0,0 +1,88 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import configparser +import logging +import os +import sys + +log = logging.getLogger(__name__) + + +class ConfigSource: + """Base class for implementing a config source.""" + + def __init__(self, root_path): + self.root_path = root_path + self.is_windows = sys.platform == 'win32' + self.xdg_home = os.environ.get( + 'XDG_CONFIG_HOME', os.path.expanduser('~/.config') + ) + + def user_config(self): + """Return user-level (i.e. home directory) configuration.""" + raise NotImplementedError() + + def project_config(self, document_path): + """Return project-level (i.e. workspace directory) configuration.""" + raise NotImplementedError() + + @staticmethod + def read_config_from_files(files): + config = configparser.RawConfigParser() + for filename in files: + if os.path.exists(filename) and not os.path.isdir(filename): + config.read(filename) + + return config + + @staticmethod + def parse_config(config, key, options): + """Parse the config with the given options.""" + conf = {} + for source, destination, opt_type in options: + opt_value = _get_opt(config, key, source, opt_type) + if opt_value is not None: + _set_opt(conf, destination, opt_value) + return conf + + +def _get_opt(config, key, option, opt_type): + """Get an option from a configparser with the given type.""" + for opt_key in [option, option.replace('-', '_')]: + if not config.has_option(key, opt_key): + continue + + if opt_type == bool: + return config.getboolean(key, opt_key) + + if opt_type == int: + return config.getint(key, opt_key) + + if opt_type == str: + return config.get(key, opt_key) + + if opt_type == list: + return _parse_list_opt(config.get(key, opt_key)) + + raise ValueError("Unknown option type: %s" % opt_type) + + +def _parse_list_opt(string): + return [s.strip() for s in string.split(",") if s.strip()] + + +def _set_opt(config_dict, path, value): + """Set the value in the dictionary at the given path if the value is not None.""" + if value is None: + return + + if '.' not in path: + config_dict[path] = value + return + + key, rest = path.split(".", 1) + if key not in config_dict: + config_dict[key] = {} + + _set_opt(config_dict[key], rest, value) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/hookspecs.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/hookspecs.py @@ -0,0 +1,124 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +# pylint: disable=redefined-builtin, unused-argument +from pylsp import hookspec + + +@hookspec +def pylsp_code_actions(config, workspace, document, range, context): + pass + + +@hookspec +def pylsp_code_lens(config, workspace, document): + pass + + +@hookspec +def pylsp_commands(config, workspace): + """The list of command strings supported by the server. + + Returns: + List[str]: The supported commands. + """ + + +@hookspec +def pylsp_completions(config, workspace, document, position): + pass + + +@hookspec +def pylsp_definitions(config, workspace, document, position): + pass + + +@hookspec +def pylsp_dispatchers(config, workspace): + pass + + +@hookspec +def pylsp_document_did_open(config, workspace, document): + pass + + +@hookspec +def pylsp_document_did_save(config, workspace, document): + pass + + +@hookspec +def pylsp_document_highlight(config, workspace, document, position): + pass + + +@hookspec +def pylsp_document_symbols(config, workspace, document): + pass + + +@hookspec(firstresult=True) +def pylsp_execute_command(config, workspace, command, arguments): + pass + + +@hookspec +def pylsp_experimental_capabilities(config, workspace): + pass + + +@hookspec +def pylsp_folding_range(config, workspace, document): + pass + + +@hookspec(firstresult=True) +def pylsp_format_document(config, workspace, document): + pass + + +@hookspec(firstresult=True) +def pylsp_format_range(config, workspace, document, range): + pass + + +@hookspec(firstresult=True) +def pylsp_hover(config, workspace, document, position): + pass + + +@hookspec +def pylsp_initialize(config, workspace): + pass + + +@hookspec +def pylsp_initialized(): + pass + + +@hookspec +def pylsp_lint(config, workspace, document, is_saved): + pass + + +@hookspec +def pylsp_references(config, workspace, document, position, exclude_declaration): + pass + + +@hookspec(firstresult=True) +def pylsp_rename(config, workspace, document, position, new_name): + pass + + +@hookspec +def pylsp_settings(config): + pass + + +@hookspec(firstresult=True) +def pylsp_signature_help(config, workspace, document, position): + pass Index: spyder-5.0.5/external-deps/python-language-server/pyls/lsp.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/lsp.py +++ /dev/null @@ -1,85 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -"""Some Language Server Protocol constants - -https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md -""" - - -class CompletionItemKind(object): - Text = 1 - Method = 2 - Function = 3 - Constructor = 4 - Field = 5 - Variable = 6 - Class = 7 - Interface = 8 - Module = 9 - Property = 10 - Unit = 11 - Value = 12 - Enum = 13 - Keyword = 14 - Snippet = 15 - Color = 16 - File = 17 - Reference = 18 - Folder = 19 - EnumMember = 20 - Constant = 21 - Struct = 22 - Event = 23 - Operator = 24 - TypeParameter = 25 - - -class DocumentHighlightKind(object): - Text = 1 - Read = 2 - Write = 3 - - -class DiagnosticSeverity(object): - Error = 1 - Warning = 2 - Information = 3 - Hint = 4 - - -class InsertTextFormat(object): - PlainText = 1 - Snippet = 2 - - -class MessageType(object): - Error = 1 - Warning = 2 - Info = 3 - Log = 4 - - -class SymbolKind(object): - File = 1 - Module = 2 - Namespace = 3 - Package = 4 - Class = 5 - Method = 6 - Property = 7 - Field = 8 - Constructor = 9 - Enum = 10 - Interface = 11 - Function = 12 - Variable = 13 - Constant = 14 - String = 15 - Number = 16 - Boolean = 17 - Array = 18 - - -class TextDocumentSyncKind(object): - NONE = 0 - FULL = 1 - INCREMENTAL = 2 Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/lsp.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/lsp.py @@ -0,0 +1,87 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +"""Some Language Server Protocol constants + +https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md +""" + + +class CompletionItemKind: + Text = 1 + Method = 2 + Function = 3 + Constructor = 4 + Field = 5 + Variable = 6 + Class = 7 + Interface = 8 + Module = 9 + Property = 10 + Unit = 11 + Value = 12 + Enum = 13 + Keyword = 14 + Snippet = 15 + Color = 16 + File = 17 + Reference = 18 + Folder = 19 + EnumMember = 20 + Constant = 21 + Struct = 22 + Event = 23 + Operator = 24 + TypeParameter = 25 + + +class DocumentHighlightKind: + Text = 1 + Read = 2 + Write = 3 + + +class DiagnosticSeverity: + Error = 1 + Warning = 2 + Information = 3 + Hint = 4 + + +class InsertTextFormat: + PlainText = 1 + Snippet = 2 + + +class MessageType: + Error = 1 + Warning = 2 + Info = 3 + Log = 4 + + +class SymbolKind: + File = 1 + Module = 2 + Namespace = 3 + Package = 4 + Class = 5 + Method = 6 + Property = 7 + Field = 8 + Constructor = 9 + Enum = 10 + Interface = 11 + Function = 12 + Variable = 13 + Constant = 14 + String = 15 + Number = 16 + Boolean = 17 + Array = 18 + + +class TextDocumentSyncKind: + NONE = 0 + FULL = 1 + INCREMENTAL = 2 Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/__init__.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/__init__.py @@ -0,0 +1,2 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/autopep8_format.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/autopep8_format.py +++ /dev/null @@ -1,74 +0,0 @@ -# Copyright 2018 Palantir Technologies, Inc. -import logging -import pycodestyle -from autopep8 import fix_code, continued_indentation as autopep8_c_i -from pyls import hookimpl - -log = logging.getLogger(__name__) - - -@hookimpl(tryfirst=True) # Prefer autopep8 over YAPF -def pyls_format_document(config, document): - log.info("Formatting document %s with autopep8", document) - return _format(config, document) - - -@hookimpl(tryfirst=True) # Prefer autopep8 over YAPF -def pyls_format_range(config, document, range): # pylint: disable=redefined-builtin - log.info("Formatting document %s in range %s with autopep8", document, range) - - # First we 'round' the range up/down to full lines only - range['start']['character'] = 0 - range['end']['line'] += 1 - range['end']['character'] = 0 - - # Add 1 for 1-indexing vs LSP's 0-indexing - line_range = (range['start']['line'] + 1, range['end']['line'] + 1) - return _format(config, document, line_range=line_range) - - -def _format(config, document, line_range=None): - options = _autopep8_config(config, document) - if line_range: - options['line_range'] = list(line_range) - - # Temporarily re-monkey-patch the continued_indentation checker - #771 - del pycodestyle._checks['logical_line'][pycodestyle.continued_indentation] - pycodestyle.register_check(autopep8_c_i) - - new_source = fix_code(document.source, options=options) - - # Switch it back - del pycodestyle._checks['logical_line'][autopep8_c_i] - pycodestyle.register_check(pycodestyle.continued_indentation) - - if new_source == document.source: - return [] - - # I'm too lazy at the moment to parse diffs into TextEdit items - # So let's just return the entire file... - return [{ - 'range': { - 'start': {'line': 0, 'character': 0}, - # End char 0 of the line after our document - 'end': {'line': len(document.lines), 'character': 0} - }, - 'newText': new_source - }] - - -def _autopep8_config(config, document=None): - # We user pycodestyle settings to avoid redefining things - path = document.path if document is not None else None - settings = config.plugin_settings('pycodestyle', document_path=path) - options = { - 'exclude': settings.get('exclude'), - 'hang_closing': settings.get('hangClosing'), - 'ignore': settings.get('ignore'), - 'max_line_length': settings.get('maxLineLength'), - 'select': settings.get('select'), - 'aggressive': settings.get('aggressive'), - } - - # Filter out null options - return {k: v for k, v in options.items() if v} Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/autopep8_format.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/autopep8_format.py @@ -0,0 +1,76 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging +import pycodestyle +from autopep8 import fix_code, continued_indentation as autopep8_c_i +from pylsp import hookimpl + +log = logging.getLogger(__name__) + + +@hookimpl(tryfirst=True) # Prefer autopep8 over YAPF +def pylsp_format_document(config, document): + log.info("Formatting document %s with autopep8", document) + return _format(config, document) + + +@hookimpl(tryfirst=True) # Prefer autopep8 over YAPF +def pylsp_format_range(config, document, range): # pylint: disable=redefined-builtin + log.info("Formatting document %s in range %s with autopep8", document, range) + + # First we 'round' the range up/down to full lines only + range['start']['character'] = 0 + range['end']['line'] += 1 + range['end']['character'] = 0 + + # Add 1 for 1-indexing vs LSP's 0-indexing + line_range = (range['start']['line'] + 1, range['end']['line'] + 1) + return _format(config, document, line_range=line_range) + + +def _format(config, document, line_range=None): + options = _autopep8_config(config, document) + if line_range: + options['line_range'] = list(line_range) + + # Temporarily re-monkey-patch the continued_indentation checker - #771 + del pycodestyle._checks['logical_line'][pycodestyle.continued_indentation] + pycodestyle.register_check(autopep8_c_i) + + new_source = fix_code(document.source, options=options) + + # Switch it back + del pycodestyle._checks['logical_line'][autopep8_c_i] + pycodestyle.register_check(pycodestyle.continued_indentation) + + if new_source == document.source: + return [] + + # I'm too lazy at the moment to parse diffs into TextEdit items + # So let's just return the entire file... + return [{ + 'range': { + 'start': {'line': 0, 'character': 0}, + # End char 0 of the line after our document + 'end': {'line': len(document.lines), 'character': 0} + }, + 'newText': new_source + }] + + +def _autopep8_config(config, document=None): + # We user pycodestyle settings to avoid redefining things + path = document.path if document is not None else None + settings = config.plugin_settings('pycodestyle', document_path=path) + options = { + 'exclude': settings.get('exclude'), + 'hang_closing': settings.get('hangClosing'), + 'ignore': settings.get('ignore'), + 'max_line_length': settings.get('maxLineLength'), + 'select': settings.get('select'), + 'aggressive': settings.get('aggressive'), + } + + # Filter out null options + return {k: v for k, v in options.items() if v} Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/definition.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/definition.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging -from pyls import hookimpl, uris, _utils - -log = logging.getLogger(__name__) - - -@hookimpl -def pyls_definitions(config, document, position): - settings = config.plugin_settings('jedi_definition') - code_position = _utils.position_to_jedi_linecolumn(document, position) - definitions = document.jedi_script().goto( - follow_imports=settings.get('follow_imports', True), - follow_builtin_imports=settings.get('follow_builtin_imports', True), - **code_position) - - return [ - { - 'uri': uris.uri_with(document.uri, path=str(d.module_path)), - 'range': { - 'start': {'line': d.line - 1, 'character': d.column}, - 'end': {'line': d.line - 1, 'character': d.column + len(d.name)}, - } - } - for d in definitions if d.is_definition() and _not_internal_definition(d) - ] - - -def _not_internal_definition(definition): - return ( - definition.line is not None and - definition.column is not None and - definition.module_path is not None and - not definition.in_builtin_module() - ) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/definition.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/definition.py @@ -0,0 +1,37 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging +from pylsp import hookimpl, uris, _utils + +log = logging.getLogger(__name__) + + +@hookimpl +def pylsp_definitions(config, document, position): + settings = config.plugin_settings('jedi_definition') + code_position = _utils.position_to_jedi_linecolumn(document, position) + definitions = document.jedi_script().goto( + follow_imports=settings.get('follow_imports', True), + follow_builtin_imports=settings.get('follow_builtin_imports', True), + **code_position) + + return [ + { + 'uri': uris.uri_with(document.uri, path=str(d.module_path)), + 'range': { + 'start': {'line': d.line - 1, 'character': d.column}, + 'end': {'line': d.line - 1, 'character': d.column + len(d.name)}, + } + } + for d in definitions if d.is_definition() and _not_internal_definition(d) + ] + + +def _not_internal_definition(definition): + return ( + definition.line is not None and + definition.column is not None and + definition.module_path is not None and + not definition.in_builtin_module() + ) Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/flake8_lint.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/flake8_lint.py +++ /dev/null @@ -1,169 +0,0 @@ -# Copyright 2019 Palantir Technologies, Inc. -"""Linter pluging for flake8""" -import logging -import os.path -import re -from subprocess import Popen, PIPE -from pyls import hookimpl, lsp - -log = logging.getLogger(__name__) -FIX_IGNORES_RE = re.compile(r'([^a-zA-Z0-9_,]*;.*(\W+||$))') - - -@hookimpl -def pyls_settings(): - # Default flake8 to disabled - return {'plugins': {'flake8': {'enabled': False}}} - - -@hookimpl -def pyls_lint(workspace, document): - config = workspace._config - settings = config.plugin_settings('flake8', document_path=document.path) - log.debug("Got flake8 settings: %s", settings) - - opts = { - 'config': settings.get('config'), - 'exclude': settings.get('exclude'), - 'filename': settings.get('filename'), - 'hang-closing': settings.get('hangClosing'), - 'ignore': settings.get('ignore'), - 'max-line-length': settings.get('maxLineLength'), - 'select': settings.get('select'), - } - - # flake takes only absolute path to the config. So we should check and - # convert if necessary - if opts.get('config') and not os.path.isabs(opts.get('config')): - opts['config'] = os.path.abspath(os.path.expanduser(os.path.expandvars( - opts.get('config') - ))) - log.debug("using flake8 with config: %s", opts['config']) - - # Call the flake8 utility then parse diagnostics from stdout - flake8_executable = settings.get('executable', 'flake8') - - args = build_args(opts) - output = run_flake8(flake8_executable, args, document) - return parse_stdout(document, output) - - -def run_flake8(flake8_executable, args, document): - """Run flake8 with the provided arguments, logs errors - from stderr if any. - """ - # a quick temporary fix to deal with Atom - args = [(i if not i.startswith('--ignore=') else FIX_IGNORES_RE.sub('', i)) - for i in args if i is not None] - - # if executable looks like a path resolve it - if not os.path.isfile(flake8_executable) and os.sep in flake8_executable: - flake8_executable = os.path.abspath( - os.path.expanduser(os.path.expandvars(flake8_executable)) - ) - - log.debug("Calling %s with args: '%s'", flake8_executable, args) - try: - cmd = [flake8_executable] - cmd.extend(args) - p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) - except IOError: - log.debug("Can't execute %s. Trying with 'python -m flake8'", flake8_executable) - cmd = ['python', '-m', 'flake8'] - cmd.extend(args) - p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) - (stdout, stderr) = p.communicate(document.source.encode()) - if stderr: - log.error("Error while running flake8 '%s'", stderr.decode()) - return stdout.decode() - - -def build_args(options): - """Build arguments for calling flake8. - - Args: - options: dictionary of argument names and their values. - """ - args = ['-'] # use stdin - for arg_name, arg_val in options.items(): - if arg_val is None: - continue - arg = None - if isinstance(arg_val, list): - arg = '--{}={}'.format(arg_name, ','.join(arg_val)) - elif isinstance(arg_val, bool): - if arg_val: - arg = '--{}'.format(arg_name) - else: - arg = '--{}={}'.format(arg_name, arg_val) - args.append(arg) - return args - - -def parse_stdout(document, stdout): - """ - Build a diagnostics from flake8's output, it should extract every result and format - it into a dict that looks like this: - { - 'source': 'flake8', - 'code': code, # 'E501' - 'range': { - 'start': { - 'line': start_line, - 'character': start_column, - }, - 'end': { - 'line': end_line, - 'character': end_column, - }, - }, - 'message': msg, - 'severity': lsp.DiagnosticSeverity.*, - } - - Args: - document: The document to be linted. - stdout: output from flake8 - Returns: - A list of dictionaries. - """ - - diagnostics = [] - lines = stdout.splitlines() - for raw_line in lines: - parsed_line = re.match(r'(.*):(\d*):(\d*): (\w*) (.*)', raw_line) - if not parsed_line: - log.debug("Flake8 output parser can't parse line '%s'", raw_line) - continue - - parsed_line = parsed_line.groups() - if len(parsed_line) != 5: - log.debug("Flake8 output parser can't parse line '%s'", raw_line) - continue - - _, line, character, code, msg = parsed_line - line = int(line) - 1 - character = int(character) - 1 - # show also the code in message - msg = code + ' ' + msg - diagnostics.append( - { - 'source': 'flake8', - 'code': code, - 'range': { - 'start': { - 'line': line, - 'character': character - }, - 'end': { - 'line': line, - # no way to determine the column - 'character': len(document.lines[line]) - } - }, - 'message': msg, - 'severity': lsp.DiagnosticSeverity.Warning, - } - ) - - return diagnostics Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/flake8_lint.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/flake8_lint.py @@ -0,0 +1,171 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +"""Linter pluging for flake8""" +import logging +import os.path +import re +from subprocess import Popen, PIPE +from pylsp import hookimpl, lsp + +log = logging.getLogger(__name__) +FIX_IGNORES_RE = re.compile(r'([^a-zA-Z0-9_,]*;.*(\W+||$))') + + +@hookimpl +def pylsp_settings(): + # Default flake8 to disabled + return {'plugins': {'flake8': {'enabled': False}}} + + +@hookimpl +def pylsp_lint(workspace, document): + config = workspace._config + settings = config.plugin_settings('flake8', document_path=document.path) + log.debug("Got flake8 settings: %s", settings) + + opts = { + 'config': settings.get('config'), + 'exclude': settings.get('exclude'), + 'filename': settings.get('filename'), + 'hang-closing': settings.get('hangClosing'), + 'ignore': settings.get('ignore'), + 'max-line-length': settings.get('maxLineLength'), + 'select': settings.get('select'), + } + + # flake takes only absolute path to the config. So we should check and + # convert if necessary + if opts.get('config') and not os.path.isabs(opts.get('config')): + opts['config'] = os.path.abspath(os.path.expanduser(os.path.expandvars( + opts.get('config') + ))) + log.debug("using flake8 with config: %s", opts['config']) + + # Call the flake8 utility then parse diagnostics from stdout + flake8_executable = settings.get('executable', 'flake8') + + args = build_args(opts) + output = run_flake8(flake8_executable, args, document) + return parse_stdout(document, output) + + +def run_flake8(flake8_executable, args, document): + """Run flake8 with the provided arguments, logs errors + from stderr if any. + """ + # a quick temporary fix to deal with Atom + args = [(i if not i.startswith('--ignore=') else FIX_IGNORES_RE.sub('', i)) + for i in args if i is not None] + + # if executable looks like a path resolve it + if not os.path.isfile(flake8_executable) and os.sep in flake8_executable: + flake8_executable = os.path.abspath( + os.path.expanduser(os.path.expandvars(flake8_executable)) + ) + + log.debug("Calling %s with args: '%s'", flake8_executable, args) + try: + cmd = [flake8_executable] + cmd.extend(args) + p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) # pylint: disable=consider-using-with + except IOError: + log.debug("Can't execute %s. Trying with 'python -m flake8'", flake8_executable) + cmd = ['python', '-m', 'flake8'] + cmd.extend(args) + p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) # pylint: disable=consider-using-with + (stdout, stderr) = p.communicate(document.source.encode()) + if stderr: + log.error("Error while running flake8 '%s'", stderr.decode()) + return stdout.decode() + + +def build_args(options): + """Build arguments for calling flake8. + + Args: + options: dictionary of argument names and their values. + """ + args = ['-'] # use stdin + for arg_name, arg_val in options.items(): + if arg_val is None: + continue + arg = None + if isinstance(arg_val, list): + arg = '--{}={}'.format(arg_name, ','.join(arg_val)) + elif isinstance(arg_val, bool): + if arg_val: + arg = '--{}'.format(arg_name) + else: + arg = '--{}={}'.format(arg_name, arg_val) + args.append(arg) + return args + + +def parse_stdout(document, stdout): + """ + Build a diagnostics from flake8's output, it should extract every result and format + it into a dict that looks like this: + { + 'source': 'flake8', + 'code': code, # 'E501' + 'range': { + 'start': { + 'line': start_line, + 'character': start_column, + }, + 'end': { + 'line': end_line, + 'character': end_column, + }, + }, + 'message': msg, + 'severity': lsp.DiagnosticSeverity.*, + } + + Args: + document: The document to be linted. + stdout: output from flake8 + Returns: + A list of dictionaries. + """ + + diagnostics = [] + lines = stdout.splitlines() + for raw_line in lines: + parsed_line = re.match(r'(.*):(\d*):(\d*): (\w*) (.*)', raw_line) + if not parsed_line: + log.debug("Flake8 output parser can't parse line '%s'", raw_line) + continue + + parsed_line = parsed_line.groups() + if len(parsed_line) != 5: + log.debug("Flake8 output parser can't parse line '%s'", raw_line) + continue + + _, line, character, code, msg = parsed_line + line = int(line) - 1 + character = int(character) - 1 + # show also the code in message + msg = code + ' ' + msg + diagnostics.append( + { + 'source': 'flake8', + 'code': code, + 'range': { + 'start': { + 'line': line, + 'character': character + }, + 'end': { + 'line': line, + # no way to determine the column + 'character': len(document.lines[line]) + } + }, + 'message': msg, + 'severity': lsp.DiagnosticSeverity.Warning, + } + ) + + return diagnostics Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/folding.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/folding.py +++ /dev/null @@ -1,203 +0,0 @@ -# pylint: disable=len-as-condition -# Copyright 2019 Palantir Technologies, Inc. - -import re - -import parso -import parso.python.tree as tree_nodes - -from pyls import hookimpl - -SKIP_NODES = (tree_nodes.Module, tree_nodes.IfStmt, tree_nodes.TryStmt) -IDENTATION_REGEX = re.compile(r'(\s+).+') - - -@hookimpl -def pyls_folding_range(document): - program = document.source + '\n' - lines = program.splitlines() - tree = parso.parse(program) - ranges = __compute_folding_ranges(tree, lines) - - results = [] - for (start_line, end_line) in ranges: - start_line -= 1 - end_line -= 1 - # If start/end character is not defined, then it defaults to the - # corresponding line last character - results.append({ - 'startLine': start_line, - 'endLine': end_line, - }) - return results - - -def __merge_folding_ranges(left, right): - for start in list(left.keys()): - right_start = right.pop(start, None) - if right_start is not None: - left[start] = max(right_start, start) - left.update(right) - return left - - -def __empty_identation_stack(identation_stack, level_limits, - current_line, folding_ranges): - while identation_stack != []: - upper_level = identation_stack.pop(0) - level_start = level_limits.pop(upper_level) - folding_ranges.append((level_start, current_line)) - return folding_ranges - - -def __match_identation_stack(identation_stack, level, level_limits, - folding_ranges, current_line): - upper_level = identation_stack.pop(0) - while upper_level >= level: - level_start = level_limits.pop(upper_level) - folding_ranges.append((level_start, current_line)) - upper_level = identation_stack.pop(0) - identation_stack.insert(0, upper_level) - return identation_stack, folding_ranges - - -def __compute_folding_ranges_identation(text): - lines = text.splitlines() - folding_ranges = [] - identation_stack = [] - level_limits = {} - current_level = 0 - current_line = 0 - while lines[current_line] == '': - current_line += 1 - for i, line in enumerate(lines): - if i < current_line: - continue - i += 1 - identation_match = IDENTATION_REGEX.match(line) - if identation_match is not None: - whitespace = identation_match.group(1) - level = len(whitespace) - if level > current_level: - level_limits[current_level] = current_line - identation_stack.insert(0, current_level) - current_level = level - elif level < current_level: - identation_stack, folding_ranges = __match_identation_stack( - identation_stack, level, level_limits, folding_ranges, - current_line) - current_level = level - else: - folding_ranges = __empty_identation_stack( - identation_stack, level_limits, current_line, folding_ranges) - current_level = 0 - if line.strip() != '': - current_line = i - folding_ranges = __empty_identation_stack( - identation_stack, level_limits, current_line, folding_ranges) - return dict(folding_ranges) - - -def __check_if_node_is_valid(node): - valid = True - if isinstance(node, tree_nodes.PythonNode): - kind = node.type - valid = kind not in {'decorated', 'parameters', 'dictorsetmaker', - 'testlist_comp'} - if kind == 'suite': - if isinstance(node.parent, tree_nodes.Function): - valid = False - return valid - - -def __handle_skip(stack, skip): - body = stack[skip] - children = [body] - if hasattr(body, 'children'): - children = body.children - stack = stack[:skip] + children + stack[skip + 1:] - node = body - end_line, _ = body.end_pos - return node, end_line - - -def __handle_flow_nodes(node, end_line, stack): - from_keyword = False - if isinstance(node, tree_nodes.Keyword): - from_keyword = True - if node.value in {'if', 'elif', 'with', 'while'}: - node, end_line = __handle_skip(stack, 2) - elif node.value in {'except'}: - first_node = stack[0] - if isinstance(first_node, tree_nodes.Operator): - node, end_line = __handle_skip(stack, 1) - else: - node, end_line = __handle_skip(stack, 2) - elif node.value in {'for'}: - node, end_line = __handle_skip(stack, 4) - elif node.value in {'else'}: - node, end_line = __handle_skip(stack, 1) - return end_line, from_keyword, node, stack - - -def __compute_start_end_lines(node, stack): - start_line, _ = node.start_pos - end_line, _ = node.end_pos - modified = False - end_line, from_keyword, node, stack = __handle_flow_nodes( - node, end_line, stack) - - last_leaf = node.get_last_leaf() - last_newline = isinstance(last_leaf, tree_nodes.Newline) - last_operator = isinstance(last_leaf, tree_nodes.Operator) - node_is_operator = isinstance(node, tree_nodes.Operator) - last_operator = last_operator or not node_is_operator - - end_line -= 1 - - if isinstance(node.parent, tree_nodes.PythonNode) and not from_keyword: - kind = node.type - if kind in {'suite', 'atom', 'atom_expr', 'arglist'}: - if len(stack) > 0: - next_node = stack[0] - next_line, _ = next_node.start_pos - if next_line > end_line: - end_line += 1 - modified = True - if not last_newline and not modified and not last_operator: - end_line += 1 - return start_line, end_line, stack - - -def __compute_folding_ranges(tree, lines): - folding_ranges = {} - stack = [tree] - - while len(stack) > 0: - node = stack.pop(0) - if isinstance(node, tree_nodes.Newline): - # Skip newline nodes - continue - elif isinstance(node, tree_nodes.PythonErrorNode): - # Fallback to identation-based (best-effort) folding - start_line, _ = node.start_pos - start_line -= 1 - padding = [''] * start_line - text = '\n'.join(padding + lines[start_line:]) + '\n' - identation_ranges = __compute_folding_ranges_identation(text) - folding_ranges = __merge_folding_ranges( - folding_ranges, identation_ranges) - break - elif not isinstance(node, SKIP_NODES): - valid = __check_if_node_is_valid(node) - if valid: - start_line, end_line, stack = __compute_start_end_lines( - node, stack) - if end_line > start_line: - current_end = folding_ranges.get(start_line, -1) - folding_ranges[start_line] = max(current_end, end_line) - if hasattr(node, 'children'): - stack = node.children + stack - - folding_ranges = sorted(folding_ranges.items()) - return folding_ranges Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/folding.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/folding.py @@ -0,0 +1,203 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import re + +import parso +import parso.python.tree as tree_nodes + +from pylsp import hookimpl + +SKIP_NODES = (tree_nodes.Module, tree_nodes.IfStmt, tree_nodes.TryStmt) +IDENTATION_REGEX = re.compile(r'(\s+).+') + + +@hookimpl +def pylsp_folding_range(document): + program = document.source + '\n' + lines = program.splitlines() + tree = parso.parse(program) + ranges = __compute_folding_ranges(tree, lines) + + results = [] + for (start_line, end_line) in ranges: + start_line -= 1 + end_line -= 1 + # If start/end character is not defined, then it defaults to the + # corresponding line last character + results.append({ + 'startLine': start_line, + 'endLine': end_line, + }) + return results + + +def __merge_folding_ranges(left, right): + for start in list(left.keys()): + right_start = right.pop(start, None) + if right_start is not None: + left[start] = max(right_start, start) + left.update(right) + return left + + +def __empty_identation_stack(identation_stack, level_limits, + current_line, folding_ranges): + while identation_stack != []: + upper_level = identation_stack.pop(0) + level_start = level_limits.pop(upper_level) + folding_ranges.append((level_start, current_line)) + return folding_ranges + + +def __match_identation_stack(identation_stack, level, level_limits, + folding_ranges, current_line): + upper_level = identation_stack.pop(0) + while upper_level >= level: + level_start = level_limits.pop(upper_level) + folding_ranges.append((level_start, current_line)) + upper_level = identation_stack.pop(0) + identation_stack.insert(0, upper_level) + return identation_stack, folding_ranges + + +def __compute_folding_ranges_identation(text): + lines = text.splitlines() + folding_ranges = [] + identation_stack = [] + level_limits = {} + current_level = 0 + current_line = 0 + while lines[current_line] == '': + current_line += 1 + for i, line in enumerate(lines): + if i < current_line: + continue + i += 1 + identation_match = IDENTATION_REGEX.match(line) + if identation_match is not None: + whitespace = identation_match.group(1) + level = len(whitespace) + if level > current_level: + level_limits[current_level] = current_line + identation_stack.insert(0, current_level) + current_level = level + elif level < current_level: + identation_stack, folding_ranges = __match_identation_stack( + identation_stack, level, level_limits, folding_ranges, + current_line) + current_level = level + else: + folding_ranges = __empty_identation_stack( + identation_stack, level_limits, current_line, folding_ranges) + current_level = 0 + if line.strip() != '': + current_line = i + folding_ranges = __empty_identation_stack( + identation_stack, level_limits, current_line, folding_ranges) + return dict(folding_ranges) + + +def __check_if_node_is_valid(node): + valid = True + if isinstance(node, tree_nodes.PythonNode): + kind = node.type + valid = kind not in {'decorated', 'parameters', 'dictorsetmaker', + 'testlist_comp'} + if kind == 'suite': + if isinstance(node.parent, tree_nodes.Function): + valid = False + return valid + + +def __handle_skip(stack, skip): + body = stack[skip] + children = [body] + if hasattr(body, 'children'): + children = body.children + stack = stack[:skip] + children + stack[skip + 1:] + node = body + end_line, _ = body.end_pos + return node, end_line + + +def __handle_flow_nodes(node, end_line, stack): + from_keyword = False + if isinstance(node, tree_nodes.Keyword): + from_keyword = True + if node.value in {'if', 'elif', 'with', 'while'}: + node, end_line = __handle_skip(stack, 2) + elif node.value in {'except'}: + first_node = stack[0] + if isinstance(first_node, tree_nodes.Operator): + node, end_line = __handle_skip(stack, 1) + else: + node, end_line = __handle_skip(stack, 2) + elif node.value in {'for'}: + node, end_line = __handle_skip(stack, 4) + elif node.value in {'else'}: + node, end_line = __handle_skip(stack, 1) + return end_line, from_keyword, node, stack + + +def __compute_start_end_lines(node, stack): + start_line, _ = node.start_pos + end_line, _ = node.end_pos + modified = False + end_line, from_keyword, node, stack = __handle_flow_nodes( + node, end_line, stack) + + last_leaf = node.get_last_leaf() + last_newline = isinstance(last_leaf, tree_nodes.Newline) + last_operator = isinstance(last_leaf, tree_nodes.Operator) + node_is_operator = isinstance(node, tree_nodes.Operator) + last_operator = last_operator or not node_is_operator + + end_line -= 1 + + if isinstance(node.parent, tree_nodes.PythonNode) and not from_keyword: + kind = node.type + if kind in {'suite', 'atom', 'atom_expr', 'arglist'}: + if len(stack) > 0: + next_node = stack[0] + next_line, _ = next_node.start_pos + if next_line > end_line: + end_line += 1 + modified = True + if not last_newline and not modified and not last_operator: + end_line += 1 + return start_line, end_line, stack + + +def __compute_folding_ranges(tree, lines): + folding_ranges = {} + stack = [tree] + + while len(stack) > 0: + node = stack.pop(0) + if isinstance(node, tree_nodes.Newline): + # Skip newline nodes + continue + if isinstance(node, tree_nodes.PythonErrorNode): + # Fallback to indentation-based (best-effort) folding + start_line, _ = node.start_pos + start_line -= 1 + padding = [''] * start_line + text = '\n'.join(padding + lines[start_line:]) + '\n' + identation_ranges = __compute_folding_ranges_identation(text) + folding_ranges = __merge_folding_ranges( + folding_ranges, identation_ranges) + break + if not isinstance(node, SKIP_NODES): + valid = __check_if_node_is_valid(node) + if valid: + start_line, end_line, stack = __compute_start_end_lines( + node, stack) + if end_line > start_line: + current_end = folding_ranges.get(start_line, -1) + folding_ranges[start_line] = max(current_end, end_line) + if hasattr(node, 'children'): + stack = node.children + stack + + folding_ranges = sorted(folding_ranges.items()) + return folding_ranges Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/highlight.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/highlight.py +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging -from pyls import hookimpl, lsp, _utils - -log = logging.getLogger(__name__) - - -@hookimpl -def pyls_document_highlight(document, position): - code_position = _utils.position_to_jedi_linecolumn(document, position) - usages = document.jedi_script().get_references(**code_position) - - def is_valid(definition): - return definition.line is not None and definition.column is not None - - def local_to_document(definition): - return not definition.module_path or str(definition.module_path) == document.path - - return [{ - 'range': { - 'start': {'line': d.line - 1, 'character': d.column}, - 'end': {'line': d.line - 1, 'character': d.column + len(d.name)} - }, - 'kind': lsp.DocumentHighlightKind.Write if d.is_definition() else lsp.DocumentHighlightKind.Read - } for d in usages if is_valid(d) and local_to_document(d)] Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/highlight.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/highlight.py @@ -0,0 +1,27 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging +from pylsp import hookimpl, lsp, _utils + +log = logging.getLogger(__name__) + + +@hookimpl +def pylsp_document_highlight(document, position): + code_position = _utils.position_to_jedi_linecolumn(document, position) + usages = document.jedi_script().get_references(**code_position) + + def is_valid(definition): + return definition.line is not None and definition.column is not None + + def local_to_document(definition): + return not definition.module_path or str(definition.module_path) == document.path + + return [{ + 'range': { + 'start': {'line': d.line - 1, 'character': d.column}, + 'end': {'line': d.line - 1, 'character': d.column + len(d.name)} + }, + 'kind': lsp.DocumentHighlightKind.Write if d.is_definition() else lsp.DocumentHighlightKind.Read + } for d in usages if is_valid(d) and local_to_document(d)] Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/hover.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/hover.py +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. - -import logging - -from pyls import hookimpl, _utils - -log = logging.getLogger(__name__) - - -@hookimpl -def pyls_hover(document, position): - code_position = _utils.position_to_jedi_linecolumn(document, position) - definitions = document.jedi_script().infer(**code_position) - word = document.word_at_position(position) - - # Find first exact matching definition - definition = next((x for x in definitions if x.name == word), None) - - # Ensure a definition is used if only one is available - # even if the word doesn't match. An example of this case is 'np' - # where 'numpy' doesn't match with 'np'. Same for NumPy ufuncs - if len(definitions) == 1: - definition = definitions[0] - - if not definition: - return {'contents': ''} - - # raw docstring returns only doc, without signature - doc = _utils.format_docstring(definition.docstring(raw=True)) - - # Find first exact matching signature - signature = next((x.to_string() for x in definition.get_signatures() - if x.name == word), '') - - contents = [] - if signature: - contents.append({ - 'language': 'python', - 'value': signature, - }) - - if doc: - contents.append(doc) - - if not contents: - return {'contents': ''} - - return {'contents': contents} Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/hover.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/hover.py @@ -0,0 +1,49 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging + +from pylsp import hookimpl, _utils + +log = logging.getLogger(__name__) + + +@hookimpl +def pylsp_hover(document, position): + code_position = _utils.position_to_jedi_linecolumn(document, position) + definitions = document.jedi_script().infer(**code_position) + word = document.word_at_position(position) + + # Find first exact matching definition + definition = next((x for x in definitions if x.name == word), None) + + # Ensure a definition is used if only one is available + # even if the word doesn't match. An example of this case is 'np' + # where 'numpy' doesn't match with 'np'. Same for NumPy ufuncs + if len(definitions) == 1: + definition = definitions[0] + + if not definition: + return {'contents': ''} + + # raw docstring returns only doc, without signature + doc = _utils.format_docstring(definition.docstring(raw=True)) + + # Find first exact matching signature + signature = next((x.to_string() for x in definition.get_signatures() + if x.name == word), '') + + contents = [] + if signature: + contents.append({ + 'language': 'python', + 'value': signature, + }) + + if doc: + contents.append(doc) + + if not contents: + return {'contents': ''} + + return {'contents': contents} Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/jedi_completion.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/jedi_completion.py +++ /dev/null @@ -1,204 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging -import os.path as osp - -import parso - -from pyls import _utils, hookimpl, lsp - -log = logging.getLogger(__name__) - -# Map to the VSCode type -_TYPE_MAP = { - 'none': lsp.CompletionItemKind.Value, - 'type': lsp.CompletionItemKind.Class, - 'tuple': lsp.CompletionItemKind.Class, - 'dict': lsp.CompletionItemKind.Class, - 'dictionary': lsp.CompletionItemKind.Class, - 'function': lsp.CompletionItemKind.Function, - 'lambda': lsp.CompletionItemKind.Function, - 'generator': lsp.CompletionItemKind.Function, - 'class': lsp.CompletionItemKind.Class, - 'instance': lsp.CompletionItemKind.Reference, - 'method': lsp.CompletionItemKind.Method, - 'builtin': lsp.CompletionItemKind.Class, - 'builtinfunction': lsp.CompletionItemKind.Function, - 'module': lsp.CompletionItemKind.Module, - 'file': lsp.CompletionItemKind.File, - 'path': lsp.CompletionItemKind.Text, - 'xrange': lsp.CompletionItemKind.Class, - 'slice': lsp.CompletionItemKind.Class, - 'traceback': lsp.CompletionItemKind.Class, - 'frame': lsp.CompletionItemKind.Class, - 'buffer': lsp.CompletionItemKind.Class, - 'dictproxy': lsp.CompletionItemKind.Class, - 'funcdef': lsp.CompletionItemKind.Function, - 'property': lsp.CompletionItemKind.Property, - 'import': lsp.CompletionItemKind.Module, - 'keyword': lsp.CompletionItemKind.Keyword, - 'constant': lsp.CompletionItemKind.Variable, - 'variable': lsp.CompletionItemKind.Variable, - 'value': lsp.CompletionItemKind.Value, - 'param': lsp.CompletionItemKind.Variable, - 'statement': lsp.CompletionItemKind.Keyword, -} - -# Types of parso nodes for which snippet is not included in the completion -_IMPORTS = ('import_name', 'import_from') - -# Types of parso node for errors -_ERRORS = ('error_node', ) - - -@hookimpl -def pyls_completions(config, document, position): - """Get formatted completions for current code position""" - settings = config.plugin_settings('jedi_completion', document_path=document.path) - code_position = _utils.position_to_jedi_linecolumn(document, position) - - code_position["fuzzy"] = settings.get("fuzzy", False) - completions = document.jedi_script(use_document_path=True).complete(**code_position) - - if not completions: - return None - - completion_capabilities = config.capabilities.get('textDocument', {}).get('completion', {}) - snippet_support = completion_capabilities.get('completionItem', {}).get('snippetSupport') - - should_include_params = settings.get('include_params') - should_include_class_objects = settings.get('include_class_objects', True) - - include_params = snippet_support and should_include_params and use_snippets(document, position) - include_class_objects = snippet_support and should_include_class_objects and use_snippets(document, position) - - ready_completions = [ - _format_completion(c, include_params) - for c in completions - ] - - if include_class_objects: - for c in completions: - if c.type == 'class': - completion_dict = _format_completion(c, False) - completion_dict['kind'] = lsp.CompletionItemKind.TypeParameter - completion_dict['label'] += ' object' - ready_completions.append(completion_dict) - - return ready_completions or None - - -def is_exception_class(name): - """ - Determine if a class name is an instance of an Exception. - - This returns `False` if the name given corresponds with a instance of - the 'Exception' class, `True` otherwise - """ - try: - return name in [cls.__name__ for cls in Exception.__subclasses__()] - except AttributeError: - # Needed in case a class don't uses new-style - # class definition in Python 2 - return False - - -def use_snippets(document, position): - """ - Determine if it's necessary to return snippets in code completions. - - This returns `False` if a completion is being requested on an import - statement, `True` otherwise. - """ - line = position['line'] - lines = document.source.split('\n', line) - act_lines = [lines[line][:position['character']]] - line -= 1 - last_character = '' - while line > -1: - act_line = lines[line] - if (act_line.rstrip().endswith('\\') or - act_line.rstrip().endswith('(') or - act_line.rstrip().endswith(',')): - act_lines.insert(0, act_line) - line -= 1 - if act_line.rstrip().endswith('('): - # Needs to be added to the end of the code before parsing - # to make it valid, otherwise the node type could end - # being an 'error_node' for multi-line imports that use '(' - last_character = ')' - else: - break - if '(' in act_lines[-1].strip(): - last_character = ')' - code = '\n'.join(act_lines).split(';')[-1].strip() + last_character - tokens = parso.parse(code) - expr_type = tokens.children[0].type - return (expr_type not in _IMPORTS and - not (expr_type in _ERRORS and 'import' in code)) - - -def _format_completion(d, include_params=True): - completion = { - 'label': _label(d), - 'kind': _TYPE_MAP.get(d.type), - 'detail': _detail(d), - 'documentation': _utils.format_docstring(d.docstring()), - 'sortText': _sort_text(d), - 'insertText': d.name - } - - if d.type == 'path': - path = osp.normpath(d.name) - path = path.replace('\\', '\\\\') - path = path.replace('/', '\\/') - completion['insertText'] = path - - sig = d.get_signatures() - if (include_params and sig and not is_exception_class(d.name)): - positional_args = [param for param in sig[0].params - if '=' not in param.description and - param.name not in {'/', '*'}] - - if len(positional_args) > 1: - # For completions with params, we can generate a snippet instead - completion['insertTextFormat'] = lsp.InsertTextFormat.Snippet - snippet = d.name + '(' - for i, param in enumerate(positional_args): - snippet += '${%s:%s}' % (i + 1, param.name) - if i < len(positional_args) - 1: - snippet += ', ' - snippet += ')$0' - completion['insertText'] = snippet - elif len(positional_args) == 1: - completion['insertTextFormat'] = lsp.InsertTextFormat.Snippet - completion['insertText'] = d.name + '($0)' - else: - completion['insertText'] = d.name + '()' - - return completion - - -def _label(definition): - sig = definition.get_signatures() - if definition.type in ('function', 'method') and sig: - params = ', '.join(param.name for param in sig[0].params) - return '{}({})'.format(definition.name, params) - - return definition.name - - -def _detail(definition): - try: - return definition.parent().full_name or '' - except AttributeError: - return definition.full_name or '' - - -def _sort_text(definition): - """ Ensure builtins appear at the bottom. - Description is of format <type>: <module>.<item> - """ - - # If its 'hidden', put it next last - prefix = 'z{}' if definition.name.startswith('_') else 'a{}' - return prefix.format(definition.name) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/jedi_completion.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/jedi_completion.py @@ -0,0 +1,188 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging +import os.path as osp + +import parso + +from pylsp import _utils, hookimpl, lsp + +log = logging.getLogger(__name__) + +# Map to the LSP type +# > Valid values for type are ``module``, `` class ``, ``instance``, ``function``, +# > ``param``, ``path``, ``keyword``, ``property`` and ``statement``. +# see: https://jedi.readthedocs.io/en/latest/docs/api-classes.html#jedi.api.classes.BaseName.type +_TYPE_MAP = { + 'module': lsp.CompletionItemKind.Module, + 'namespace': lsp.CompletionItemKind.Module, # to be added in Jedi 0.18+ + 'class': lsp.CompletionItemKind.Class, + 'instance': lsp.CompletionItemKind.Reference, + 'function': lsp.CompletionItemKind.Function, + 'param': lsp.CompletionItemKind.Variable, + 'path': lsp.CompletionItemKind.File, + 'keyword': lsp.CompletionItemKind.Keyword, + 'property': lsp.CompletionItemKind.Property, # added in Jedi 0.18 + 'statement': lsp.CompletionItemKind.Variable +} + +# Types of parso nodes for which snippet is not included in the completion +_IMPORTS = ('import_name', 'import_from') + +# Types of parso node for errors +_ERRORS = ('error_node', ) + + +@hookimpl +def pylsp_completions(config, document, position): + """Get formatted completions for current code position""" + settings = config.plugin_settings('jedi_completion', document_path=document.path) + code_position = _utils.position_to_jedi_linecolumn(document, position) + + code_position["fuzzy"] = settings.get("fuzzy", False) + completions = document.jedi_script(use_document_path=True).complete(**code_position) + + if not completions: + return None + + completion_capabilities = config.capabilities.get('textDocument', {}).get('completion', {}) + snippet_support = completion_capabilities.get('completionItem', {}).get('snippetSupport') + + should_include_params = settings.get('include_params') + should_include_class_objects = settings.get('include_class_objects', True) + + include_params = snippet_support and should_include_params and use_snippets(document, position) + include_class_objects = snippet_support and should_include_class_objects and use_snippets(document, position) + + ready_completions = [ + _format_completion(c, include_params) + for c in completions + ] + + if include_class_objects: + for c in completions: + if c.type == 'class': + completion_dict = _format_completion(c, False) + completion_dict['kind'] = lsp.CompletionItemKind.TypeParameter + completion_dict['label'] += ' object' + ready_completions.append(completion_dict) + + return ready_completions or None + + +def is_exception_class(name): + """ + Determine if a class name is an instance of an Exception. + + This returns `False` if the name given corresponds with a instance of + the 'Exception' class, `True` otherwise + """ + try: + return name in [cls.__name__ for cls in Exception.__subclasses__()] + except AttributeError: + # Needed in case a class don't uses new-style + # class definition in Python 2 + return False + + +def use_snippets(document, position): + """ + Determine if it's necessary to return snippets in code completions. + + This returns `False` if a completion is being requested on an import + statement, `True` otherwise. + """ + line = position['line'] + lines = document.source.split('\n', line) + act_lines = [lines[line][:position['character']]] + line -= 1 + last_character = '' + while line > -1: + act_line = lines[line] + if (act_line.rstrip().endswith('\\') or + act_line.rstrip().endswith('(') or + act_line.rstrip().endswith(',')): + act_lines.insert(0, act_line) + line -= 1 + if act_line.rstrip().endswith('('): + # Needs to be added to the end of the code before parsing + # to make it valid, otherwise the node type could end + # being an 'error_node' for multi-line imports that use '(' + last_character = ')' + else: + break + if '(' in act_lines[-1].strip(): + last_character = ')' + code = '\n'.join(act_lines).split(';')[-1].strip() + last_character + tokens = parso.parse(code) + expr_type = tokens.children[0].type + return (expr_type not in _IMPORTS and + not (expr_type in _ERRORS and 'import' in code)) + + +def _format_completion(d, include_params=True): + completion = { + 'label': _label(d), + 'kind': _TYPE_MAP.get(d.type), + 'detail': _detail(d), + 'documentation': _utils.format_docstring(d.docstring()), + 'sortText': _sort_text(d), + 'insertText': d.name + } + + if d.type == 'path': + path = osp.normpath(d.name) + path = path.replace('\\', '\\\\') + path = path.replace('/', '\\/') + completion['insertText'] = path + + sig = d.get_signatures() + if (include_params and sig and not is_exception_class(d.name)): + positional_args = [param for param in sig[0].params + if '=' not in param.description and + param.name not in {'/', '*'}] + + if len(positional_args) > 1: + # For completions with params, we can generate a snippet instead + completion['insertTextFormat'] = lsp.InsertTextFormat.Snippet + snippet = d.name + '(' + for i, param in enumerate(positional_args): + snippet += '${%s:%s}' % (i + 1, param.name) + if i < len(positional_args) - 1: + snippet += ', ' + snippet += ')$0' + completion['insertText'] = snippet + elif len(positional_args) == 1: + completion['insertTextFormat'] = lsp.InsertTextFormat.Snippet + completion['insertText'] = d.name + '($0)' + else: + completion['insertText'] = d.name + '()' + + return completion + + +def _label(definition): + sig = definition.get_signatures() + if definition.type in ('function', 'method') and sig: + params = ', '.join(param.name for param in sig[0].params) + return '{}({})'.format(definition.name, params) + + return definition.name + + +def _detail(definition): + try: + return definition.parent().full_name or '' + except AttributeError: + return definition.full_name or '' + + +def _sort_text(definition): + """ Ensure builtins appear at the bottom. + Description is of format <type>: <module>.<item> + """ + + # If its 'hidden', put it next last + prefix = 'z{}' if definition.name.startswith('_') else 'a{}' + return prefix.format(definition.name) Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/jedi_rename.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/jedi_rename.py +++ /dev/null @@ -1,47 +0,0 @@ -# Copyright 2020 Palantir Technologies, Inc. -import logging - -from pyls import hookimpl, uris, _utils - -log = logging.getLogger(__name__) - - -@hookimpl -def pyls_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) - kwargs = _utils.position_to_jedi_linecolumn(document, position) - kwargs['new_name'] = new_name - try: - refactoring = document.jedi_script().rename(**kwargs) - except NotImplementedError: - raise Exception('No support for renaming in Python 2/3.5 with Jedi. ' - 'Consider using the rope_rename plugin instead') - log.debug('Finished rename: %s', refactoring.get_diff()) - changes = [] - for file_path, changed_file in refactoring.get_changed_files().items(): - uri = uris.from_fs_path(str(file_path)) - doc = workspace.get_maybe_document(uri) - changes.append({ - 'textDocument': { - 'uri': uri, - 'version': doc.version if doc else None - }, - 'edits': [ - { - 'range': { - 'start': {'line': 0, 'character': 0}, - 'end': { - 'line': _num_lines(changed_file.get_new_code()), - 'character': 0, - }, - }, - 'newText': changed_file.get_new_code(), - } - ], - }) - return {'documentChanges': changes} - - -def _num_lines(file_contents): - 'Count the number of lines in the given string.' - return len(file_contents.splitlines()) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/jedi_rename.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/jedi_rename.py @@ -0,0 +1,49 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging + +from pylsp import hookimpl, uris, _utils + +log = logging.getLogger(__name__) + + +@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) + kwargs = _utils.position_to_jedi_linecolumn(document, position) + kwargs['new_name'] = new_name + try: + refactoring = document.jedi_script().rename(**kwargs) + except NotImplementedError as exc: + raise Exception('No support for renaming in Python 2/3.5 with Jedi. ' + 'Consider using the rope_rename plugin instead') from exc + log.debug('Finished rename: %s', refactoring.get_diff()) + changes = [] + for file_path, changed_file in refactoring.get_changed_files().items(): + uri = uris.from_fs_path(str(file_path)) + doc = workspace.get_maybe_document(uri) + changes.append({ + 'textDocument': { + 'uri': uri, + 'version': doc.version if doc else None + }, + 'edits': [ + { + 'range': { + 'start': {'line': 0, 'character': 0}, + 'end': { + 'line': _num_lines(changed_file.get_new_code()), + 'character': 0, + }, + }, + 'newText': changed_file.get_new_code(), + } + ], + }) + return {'documentChanges': changes} + + +def _num_lines(file_contents): + 'Count the number of lines in the given string.' + return len(file_contents.splitlines()) Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/mccabe_lint.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/mccabe_lint.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import ast -import logging -import mccabe -from pyls import hookimpl, lsp - -log = logging.getLogger(__name__) - -THRESHOLD = 'threshold' -DEFAULT_THRESHOLD = 15 - - -@hookimpl -def pyls_lint(config, document): - threshold = config.plugin_settings('mccabe', document_path=document.path).get(THRESHOLD, DEFAULT_THRESHOLD) - log.debug("Running mccabe lint with threshold: %s", threshold) - - try: - tree = compile(document.source, document.path, "exec", ast.PyCF_ONLY_AST) - except SyntaxError: - # We'll let the other linters point this one out - return None - - visitor = mccabe.PathGraphingAstVisitor() - visitor.preorder(tree, visitor) - - diags = [] - for graph in visitor.graphs.values(): - if graph.complexity() >= threshold: - diags.append({ - 'source': 'mccabe', - 'range': { - 'start': {'line': graph.lineno - 1, 'character': graph.column}, - 'end': {'line': graph.lineno - 1, 'character': len(document.lines[graph.lineno])}, - }, - 'message': 'Cyclomatic complexity too high: %s (threshold %s)' % (graph.complexity(), threshold), - 'severity': lsp.DiagnosticSeverity.Warning - }) - - return diags Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/mccabe_lint.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/mccabe_lint.py @@ -0,0 +1,42 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import ast +import logging +import mccabe +from pylsp import hookimpl, lsp + +log = logging.getLogger(__name__) + +THRESHOLD = 'threshold' +DEFAULT_THRESHOLD = 15 + + +@hookimpl +def pylsp_lint(config, document): + threshold = config.plugin_settings('mccabe', document_path=document.path).get(THRESHOLD, DEFAULT_THRESHOLD) + log.debug("Running mccabe lint with threshold: %s", threshold) + + try: + tree = compile(document.source, document.path, "exec", ast.PyCF_ONLY_AST) + except SyntaxError: + # We'll let the other linters point this one out + return None + + visitor = mccabe.PathGraphingAstVisitor() + visitor.preorder(tree, visitor) + + diags = [] + for graph in visitor.graphs.values(): + if graph.complexity() >= threshold: + diags.append({ + 'source': 'mccabe', + 'range': { + 'start': {'line': graph.lineno - 1, 'character': graph.column}, + 'end': {'line': graph.lineno - 1, 'character': len(document.lines[graph.lineno])}, + }, + 'message': 'Cyclomatic complexity too high: %s (threshold %s)' % (graph.complexity(), threshold), + 'severity': lsp.DiagnosticSeverity.Warning + }) + + return diags Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/preload_imports.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/preload_imports.py +++ /dev/null @@ -1,37 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging -from pyls import hookimpl - -log = logging.getLogger(__name__) - -MODULES = [ - "OpenGL", "PIL", - "array", "audioop", "binascii", "cPickle", "cStringIO", "cmath", "collections", - "datetime", "errno", "exceptions", "gc", "imageop", "imp", "itertools", - "marshal", "math", "matplotlib", "mmap", "mpmath", "msvcrt", "networkx", "nose", "nt", - "numpy", "operator", "os", "os.path", "pandas", "parser", "rgbimg", "scipy", "signal", - "skimage", "sklearn", "statsmodels", "strop", "sympy", "sys", "thread", "time", - "wx", "xxsubtype", "zipimport", "zlib" -] - - -@hookimpl -def pyls_settings(): - # Setup default modules to preload, and rope extension modules - return { - 'plugins': {'preload': {'modules': MODULES}}, - 'rope': {'extensionModules': MODULES} - } - - -@hookimpl -def pyls_initialize(config): - for mod_name in config.plugin_settings('preload').get('modules', []): - try: - __import__(mod_name) - log.debug("Preloaded module %s", mod_name) - except Exception: # pylint: disable=broad-except - # 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 - pass Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/preload_imports.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/preload_imports.py @@ -0,0 +1,39 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging +from pylsp import hookimpl + +log = logging.getLogger(__name__) + +MODULES = [ + "OpenGL", "PIL", + "array", "audioop", "binascii", "cPickle", "cStringIO", "cmath", "collections", + "datetime", "errno", "exceptions", "gc", "imageop", "imp", "itertools", + "marshal", "math", "matplotlib", "mmap", "mpmath", "msvcrt", "networkx", "nose", "nt", + "numpy", "operator", "os", "os.path", "pandas", "parser", "rgbimg", "scipy", "signal", + "skimage", "sklearn", "statsmodels", "strop", "sympy", "sys", "thread", "time", + "wx", "xxsubtype", "zipimport", "zlib" +] + + +@hookimpl +def pylsp_settings(): + # Setup default modules to preload, and rope extension modules + return { + 'plugins': {'preload': {'modules': MODULES}}, + 'rope': {'extensionModules': MODULES} + } + + +@hookimpl +def pylsp_initialize(config): + for mod_name in config.plugin_settings('preload').get('modules', []): + try: + __import__(mod_name) + log.debug("Preloaded module %s", mod_name) + except Exception: # pylint: disable=broad-except + # 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 + pass Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/pycodestyle_lint.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/pycodestyle_lint.py +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging -import pycodestyle -from pyls import hookimpl, lsp - -try: - from autopep8 import continued_indentation as autopep8_c_i -except ImportError: - pass -else: - # Check if autopep8's continued_indentation implementation - # is overriding pycodestyle's and if so, re-register - # the check using pycodestyle's implementation as expected - if autopep8_c_i in pycodestyle._checks['logical_line']: - del pycodestyle._checks['logical_line'][autopep8_c_i] - pycodestyle.register_check(pycodestyle.continued_indentation) - -log = logging.getLogger(__name__) - - -@hookimpl -def pyls_lint(workspace, document): - config = workspace._config - settings = config.plugin_settings('pycodestyle', document_path=document.path) - log.debug("Got pycodestyle settings: %s", settings) - - opts = { - 'exclude': settings.get('exclude'), - 'filename': settings.get('filename'), - 'hang_closing': settings.get('hangClosing'), - 'ignore': settings.get('ignore'), - 'max_line_length': settings.get('maxLineLength'), - 'select': settings.get('select'), - } - kwargs = {k: v for k, v in opts.items() if v} - styleguide = pycodestyle.StyleGuide(kwargs) - - c = pycodestyle.Checker( - filename=document.uri, lines=document.lines, options=styleguide.options, - report=PyCodeStyleDiagnosticReport(styleguide.options) - ) - c.check_all() - diagnostics = c.report.diagnostics - - return diagnostics - - -class PyCodeStyleDiagnosticReport(pycodestyle.BaseReport): - - def __init__(self, options): - self.diagnostics = [] - super(PyCodeStyleDiagnosticReport, self).__init__(options=options) - - def error(self, line_number, offset, text, check): - code = text[:4] - if self._ignore_code(code): - return - - # Don't care about expected errors or warnings - if code in self.expected: - return - - # PyCodeStyle will sometimes give you an error the line after the end of the file - # e.g. no newline at end of file - # In that case, the end offset should just be some number ~100 - # (because why not? There's nothing to underline anyways) - err_range = { - 'start': {'line': line_number - 1, 'character': offset}, - 'end': { - # FIXME: It's a little naiive to mark until the end of the line, can we not easily do better? - 'line': line_number - 1, - 'character': 100 if line_number > len(self.lines) else len(self.lines[line_number - 1]) - }, - } - self.diagnostics.append({ - 'source': 'pycodestyle', - 'range': err_range, - 'message': text, - 'code': code, - # Are style errors really ever errors? - 'severity': _get_severity(code) - }) - - -def _get_severity(code): - # Are style errors ever really errors? - if code[0] == 'E' or code[0] == 'W': - return lsp.DiagnosticSeverity.Warning - # If no severity is specified, why wouldn't this be informational only? - return lsp.DiagnosticSeverity.Information Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/pycodestyle_lint.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/pycodestyle_lint.py @@ -0,0 +1,92 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging +import pycodestyle +from pylsp import hookimpl, lsp + +try: + from autopep8 import continued_indentation as autopep8_c_i +except ImportError: + pass +else: + # Check if autopep8's continued_indentation implementation + # is overriding pycodestyle's and if so, re-register + # the check using pycodestyle's implementation as expected + if autopep8_c_i in pycodestyle._checks['logical_line']: + del pycodestyle._checks['logical_line'][autopep8_c_i] + pycodestyle.register_check(pycodestyle.continued_indentation) + +log = logging.getLogger(__name__) + + +@hookimpl +def pylsp_lint(workspace, document): + config = workspace._config + settings = config.plugin_settings('pycodestyle', document_path=document.path) + log.debug("Got pycodestyle settings: %s", settings) + + opts = { + 'exclude': settings.get('exclude'), + 'filename': settings.get('filename'), + 'hang_closing': settings.get('hangClosing'), + 'ignore': settings.get('ignore'), + 'max_line_length': settings.get('maxLineLength'), + 'select': settings.get('select'), + } + kwargs = {k: v for k, v in opts.items() if v} + styleguide = pycodestyle.StyleGuide(kwargs) + + c = pycodestyle.Checker( + filename=document.uri, lines=document.lines, options=styleguide.options, + report=PyCodeStyleDiagnosticReport(styleguide.options) + ) + c.check_all() + diagnostics = c.report.diagnostics + + return diagnostics + + +class PyCodeStyleDiagnosticReport(pycodestyle.BaseReport): + + def __init__(self, options): + self.diagnostics = [] + super().__init__(options=options) + + def error(self, line_number, offset, text, check): + code = text[:4] + if self._ignore_code(code): + return + + # Don't care about expected errors or warnings + if code in self.expected: + return + + # PyCodeStyle will sometimes give you an error the line after the end of the file + # e.g. no newline at end of file + # In that case, the end offset should just be some number ~100 + # (because why not? There's nothing to underline anyways) + err_range = { + 'start': {'line': line_number - 1, 'character': offset}, + 'end': { + # FIXME: It's a little naiive to mark until the end of the line, can we not easily do better? + 'line': line_number - 1, + 'character': 100 if line_number > len(self.lines) else len(self.lines[line_number - 1]) + }, + } + self.diagnostics.append({ + 'source': 'pycodestyle', + 'range': err_range, + 'message': text, + 'code': code, + # Are style errors really ever errors? + 'severity': _get_severity(code) + }) + + +def _get_severity(code): + # Are style errors ever really errors? + if code[0] == 'E' or code[0] == 'W': + return lsp.DiagnosticSeverity.Warning + # If no severity is specified, why wouldn't this be informational only? + return lsp.DiagnosticSeverity.Information Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/pydocstyle_lint.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/pydocstyle_lint.py +++ /dev/null @@ -1,119 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import contextlib -import logging -import os -import re -import sys - -import pydocstyle -from pyls import hookimpl, lsp - -log = logging.getLogger(__name__) - -# PyDocstyle is a little verbose in debug message -pydocstyle_logger = logging.getLogger(pydocstyle.utils.__name__) -pydocstyle_logger.setLevel(logging.INFO) - -DEFAULT_MATCH_RE = pydocstyle.config.ConfigurationParser.DEFAULT_MATCH_RE -DEFAULT_MATCH_DIR_RE = pydocstyle.config.ConfigurationParser.DEFAULT_MATCH_DIR_RE - - -@hookimpl -def pyls_settings(): - # Default pydocstyle to disabled - return {'plugins': {'pydocstyle': {'enabled': False}}} - - -@hookimpl -def pyls_lint(config, document): - settings = config.plugin_settings('pydocstyle', document_path=document.path) - log.debug("Got pydocstyle settings: %s", settings) - - # Explicitly passing a path to pydocstyle means it doesn't respect the --match flag, so do it ourselves - filename_match_re = re.compile(settings.get('match', DEFAULT_MATCH_RE) + '$') - if not filename_match_re.match(os.path.basename(document.path)): - return [] - - # Likewise with --match-dir - dir_match_re = re.compile(settings.get('matchDir', DEFAULT_MATCH_DIR_RE) + '$') - if not dir_match_re.match(os.path.basename(os.path.dirname(document.path))): - return [] - - args = [document.path] - - if settings.get('convention'): - args.append('--convention=' + settings['convention']) - - if settings.get('addSelect'): - args.append('--add-select=' + ','.join(settings['addSelect'])) - if settings.get('addIgnore'): - args.append('--add-ignore=' + ','.join(settings['addIgnore'])) - - elif settings.get('select'): - args.append('--select=' + ','.join(settings['select'])) - elif settings.get('ignore'): - args.append('--ignore=' + ','.join(settings['ignore'])) - - log.info("Using pydocstyle args: %s", args) - - conf = pydocstyle.config.ConfigurationParser() - with _patch_sys_argv(args): - # TODO(gatesn): We can add more pydocstyle args here from our pyls config - conf.parse() - - # Will only yield a single filename, the document path - diags = [] - for filename, checked_codes, ignore_decorators in conf.get_files_to_check(): - errors = pydocstyle.checker.ConventionChecker().check_source( - document.source, filename, ignore_decorators=ignore_decorators - ) - - try: - for error in errors: - if error.code not in checked_codes: - continue - diags.append(_parse_diagnostic(document, error)) - except pydocstyle.parser.ParseError: - # In the case we cannot parse the Python file, just continue - pass - - log.debug("Got pydocstyle errors: %s", diags) - return diags - - -def _parse_diagnostic(document, error): - lineno = error.definition.start - 1 - line = document.lines[0] if document.lines else "" - - start_character = len(line) - len(line.lstrip()) - end_character = len(line) - - return { - 'source': 'pydocstyle', - 'code': error.code, - 'message': error.message, - 'severity': lsp.DiagnosticSeverity.Warning, - 'range': { - 'start': { - 'line': lineno, - 'character': start_character - }, - 'end': { - 'line': lineno, - 'character': end_character - } - } - } - - -@contextlib.contextmanager -def _patch_sys_argv(arguments): - old_args = sys.argv - - # Preserve argv[0] since it's the executable - sys.argv = old_args[0:1] + arguments - - try: - yield - finally: - sys.argv = old_args Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/pydocstyle_lint.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/pydocstyle_lint.py @@ -0,0 +1,121 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import contextlib +import logging +import os +import re +import sys + +import pydocstyle +from pylsp import hookimpl, lsp + +log = logging.getLogger(__name__) + +# PyDocstyle is a little verbose in debug message +pydocstyle_logger = logging.getLogger(pydocstyle.utils.__name__) +pydocstyle_logger.setLevel(logging.INFO) + +DEFAULT_MATCH_RE = pydocstyle.config.ConfigurationParser.DEFAULT_MATCH_RE +DEFAULT_MATCH_DIR_RE = pydocstyle.config.ConfigurationParser.DEFAULT_MATCH_DIR_RE + + +@hookimpl +def pylsp_settings(): + # Default pydocstyle to disabled + return {'plugins': {'pydocstyle': {'enabled': False}}} + + +@hookimpl +def pylsp_lint(config, document): + settings = config.plugin_settings('pydocstyle', document_path=document.path) + log.debug("Got pydocstyle settings: %s", settings) + + # Explicitly passing a path to pydocstyle means it doesn't respect the --match flag, so do it ourselves + filename_match_re = re.compile(settings.get('match', DEFAULT_MATCH_RE) + '$') + if not filename_match_re.match(os.path.basename(document.path)): + return [] + + # Likewise with --match-dir + dir_match_re = re.compile(settings.get('matchDir', DEFAULT_MATCH_DIR_RE) + '$') + if not dir_match_re.match(os.path.basename(os.path.dirname(document.path))): + return [] + + args = [document.path] + + if settings.get('convention'): + args.append('--convention=' + settings['convention']) + + if settings.get('addSelect'): + args.append('--add-select=' + ','.join(settings['addSelect'])) + if settings.get('addIgnore'): + args.append('--add-ignore=' + ','.join(settings['addIgnore'])) + + elif settings.get('select'): + args.append('--select=' + ','.join(settings['select'])) + elif settings.get('ignore'): + args.append('--ignore=' + ','.join(settings['ignore'])) + + log.info("Using pydocstyle args: %s", args) + + conf = pydocstyle.config.ConfigurationParser() + with _patch_sys_argv(args): + # TODO(gatesn): We can add more pydocstyle args here from our pylsp config + conf.parse() + + # Will only yield a single filename, the document path + diags = [] + for filename, checked_codes, ignore_decorators in conf.get_files_to_check(): + errors = pydocstyle.checker.ConventionChecker().check_source( + document.source, filename, ignore_decorators=ignore_decorators + ) + + try: + for error in errors: + if error.code not in checked_codes: + continue + diags.append(_parse_diagnostic(document, error)) + except pydocstyle.parser.ParseError: + # In the case we cannot parse the Python file, just continue + pass + + log.debug("Got pydocstyle errors: %s", diags) + return diags + + +def _parse_diagnostic(document, error): + lineno = error.definition.start - 1 + line = document.lines[0] if document.lines else "" + + start_character = len(line) - len(line.lstrip()) + end_character = len(line) + + return { + 'source': 'pydocstyle', + 'code': error.code, + 'message': error.message, + 'severity': lsp.DiagnosticSeverity.Warning, + 'range': { + 'start': { + 'line': lineno, + 'character': start_character + }, + 'end': { + 'line': lineno, + 'character': end_character + } + } + } + + +@contextlib.contextmanager +def _patch_sys_argv(arguments): + old_args = sys.argv + + # Preserve argv[0] since it's the executable + sys.argv = old_args[0:1] + arguments + + try: + yield + finally: + sys.argv = old_args Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/pyflakes_lint.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/pyflakes_lint.py +++ /dev/null @@ -1,80 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -from pyflakes import api as pyflakes_api, messages -from pyls import hookimpl, lsp - -# Pyflakes messages that should be reported as Errors instead of Warns -PYFLAKES_ERROR_MESSAGES = ( - messages.UndefinedName, - messages.UndefinedExport, - messages.UndefinedLocal, - messages.DuplicateArgument, - messages.FutureFeatureNotDefined, - messages.ReturnOutsideFunction, - messages.YieldOutsideFunction, - messages.ContinueOutsideLoop, - messages.BreakOutsideLoop, - messages.ContinueInFinally, - messages.TwoStarredExpressions, -) - - -@hookimpl -def pyls_lint(document): - reporter = PyflakesDiagnosticReport(document.lines) - pyflakes_api.check(document.source.encode('utf-8'), document.path, reporter=reporter) - return reporter.diagnostics - - -class PyflakesDiagnosticReport(object): - - def __init__(self, lines): - self.lines = lines - self.diagnostics = [] - - def unexpectedError(self, _filename, msg): # pragma: no cover - err_range = { - 'start': {'line': 0, 'character': 0}, - 'end': {'line': 0, 'character': 0}, - } - self.diagnostics.append({ - 'source': 'pyflakes', - 'range': err_range, - 'message': msg, - 'severity': lsp.DiagnosticSeverity.Error, - }) - - def syntaxError(self, _filename, msg, lineno, offset, text): - # We've seen that lineno and offset can sometimes be None - lineno = lineno or 1 - offset = offset or 0 - - err_range = { - 'start': {'line': lineno - 1, 'character': offset}, - 'end': {'line': lineno - 1, 'character': offset + len(text)}, - } - self.diagnostics.append({ - 'source': 'pyflakes', - 'range': err_range, - 'message': msg, - 'severity': lsp.DiagnosticSeverity.Error, - }) - - def flake(self, message): - """ Get message like <filename>:<lineno>: <msg> """ - err_range = { - 'start': {'line': message.lineno - 1, 'character': message.col}, - 'end': {'line': message.lineno - 1, 'character': len(self.lines[message.lineno - 1])}, - } - - severity = lsp.DiagnosticSeverity.Warning - for message_type in PYFLAKES_ERROR_MESSAGES: - if isinstance(message, message_type): - severity = lsp.DiagnosticSeverity.Error - break - - self.diagnostics.append({ - 'source': 'pyflakes', - 'range': err_range, - 'message': message.message % message.message_args, - 'severity': severity - }) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/pyflakes_lint.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/pyflakes_lint.py @@ -0,0 +1,82 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +from pyflakes import api as pyflakes_api, messages +from pylsp import hookimpl, lsp + +# Pyflakes messages that should be reported as Errors instead of Warns +PYFLAKES_ERROR_MESSAGES = ( + messages.UndefinedName, + messages.UndefinedExport, + messages.UndefinedLocal, + messages.DuplicateArgument, + messages.FutureFeatureNotDefined, + messages.ReturnOutsideFunction, + messages.YieldOutsideFunction, + messages.ContinueOutsideLoop, + messages.BreakOutsideLoop, + messages.ContinueInFinally, + messages.TwoStarredExpressions, +) + + +@hookimpl +def pylsp_lint(document): + reporter = PyflakesDiagnosticReport(document.lines) + pyflakes_api.check(document.source.encode('utf-8'), document.path, reporter=reporter) + return reporter.diagnostics + + +class PyflakesDiagnosticReport: + + def __init__(self, lines): + self.lines = lines + self.diagnostics = [] + + def unexpectedError(self, _filename, msg): # pragma: no cover + err_range = { + 'start': {'line': 0, 'character': 0}, + 'end': {'line': 0, 'character': 0}, + } + self.diagnostics.append({ + 'source': 'pyflakes', + 'range': err_range, + 'message': msg, + 'severity': lsp.DiagnosticSeverity.Error, + }) + + def syntaxError(self, _filename, msg, lineno, offset, text): + # We've seen that lineno and offset can sometimes be None + lineno = lineno or 1 + offset = offset or 0 + + err_range = { + 'start': {'line': lineno - 1, 'character': offset}, + 'end': {'line': lineno - 1, 'character': offset + len(text)}, + } + self.diagnostics.append({ + 'source': 'pyflakes', + 'range': err_range, + 'message': msg, + 'severity': lsp.DiagnosticSeverity.Error, + }) + + def flake(self, message): + """ Get message like <filename>:<lineno>: <msg> """ + err_range = { + 'start': {'line': message.lineno - 1, 'character': message.col}, + 'end': {'line': message.lineno - 1, 'character': len(self.lines[message.lineno - 1])}, + } + + severity = lsp.DiagnosticSeverity.Warning + for message_type in PYFLAKES_ERROR_MESSAGES: + if isinstance(message, message_type): + severity = lsp.DiagnosticSeverity.Error + break + + self.diagnostics.append({ + 'source': 'pyflakes', + 'range': err_range, + 'message': message.message % message.message_args, + 'severity': severity + }) Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/pylint_lint.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/pylint_lint.py +++ /dev/null @@ -1,304 +0,0 @@ -# Copyright 2018 Google LLC. -"""Linter plugin for pylint.""" -import collections -import logging -import sys -import re -from subprocess import Popen, PIPE - -from pylint.epylint import py_run -from pyls import hookimpl, lsp - -try: - import ujson as json -except Exception: # pylint: disable=broad-except - import json - -log = logging.getLogger(__name__) - - -class PylintLinter(object): - last_diags = collections.defaultdict(list) - - @classmethod - def lint(cls, document, is_saved, flags=''): - """Plugin interface to pyls linter. - - Args: - document: The document to be linted. - is_saved: Whether or not the file has been saved to disk. - flags: Additional flags to pass to pylint. Not exposed to - pyls_lint, but used for testing. - - Returns: - A list of dicts with the following format: - - { - 'source': 'pylint', - 'range': { - 'start': { - 'line': start_line, - 'character': start_column, - }, - 'end': { - 'line': end_line, - 'character': end_column, - }, - } - 'message': msg, - 'severity': lsp.DiagnosticSeverity.*, - } - """ - if not is_saved: - # Pylint can only be run on files that have been saved to disk. - # Rather than return nothing, return the previous list of - # diagnostics. If we return an empty list, any diagnostics we'd - # previously shown will be cleared until the next save. Instead, - # continue showing (possibly stale) diagnostics until the next - # save. - return cls.last_diags[document.path] - - # py_run will call shlex.split on its arguments, and shlex.split does - # not handle Windows paths (it will try to perform escaping). Turn - # backslashes into forward slashes first to avoid this issue. - path = document.path - if sys.platform.startswith('win'): - path = path.replace('\\', '/') - - pylint_call = '{} -f json {}'.format(path, flags) - log.debug("Calling pylint with '%s'", pylint_call) - json_out, err = py_run(pylint_call, return_std=True) - - # Get strings - json_out = json_out.getvalue() - err = err.getvalue() - - if err != '': - log.error("Error calling pylint: '%s'", err) - - # pylint prints nothing rather than [] when there are no diagnostics. - # json.loads will not parse an empty string, so just return. - if not json_out.strip(): - cls.last_diags[document.path] = [] - return [] - - # Pylint's JSON output is a list of objects with the following format. - # - # { - # "obj": "main", - # "path": "foo.py", - # "message": "Missing function docstring", - # "message-id": "C0111", - # "symbol": "missing-docstring", - # "column": 0, - # "type": "convention", - # "line": 5, - # "module": "foo" - # } - # - # The type can be any of: - # - # * convention - # * error - # * fatal - # * refactor - # * warning - diagnostics = [] - for diag in json.loads(json_out): - # pylint lines index from 1, pyls lines index from 0 - line = diag['line'] - 1 - - err_range = { - 'start': { - 'line': line, - # Index columns start from 0 - 'character': diag['column'], - }, - 'end': { - 'line': line, - # It's possible that we're linting an empty file. Even an empty - # file might fail linting if it isn't named properly. - 'character': len(document.lines[line]) if document.lines else 0, - }, - } - - if diag['type'] == 'convention': - severity = lsp.DiagnosticSeverity.Information - elif diag['type'] == 'error': - severity = lsp.DiagnosticSeverity.Error - elif diag['type'] == 'fatal': - severity = lsp.DiagnosticSeverity.Error - elif diag['type'] == 'refactor': - severity = lsp.DiagnosticSeverity.Hint - elif diag['type'] == 'warning': - severity = lsp.DiagnosticSeverity.Warning - - diagnostics.append({ - 'source': 'pylint', - 'range': err_range, - 'message': '[{}] {}'.format(diag['symbol'], diag['message']), - 'severity': severity, - 'code': diag['message-id'] - }) - cls.last_diags[document.path] = diagnostics - return diagnostics - - -def _build_pylint_flags(settings): - """Build arguments for calling pylint.""" - pylint_args = settings.get('args') - if pylint_args is None: - return '' - return ' '.join(pylint_args) - - -@hookimpl -def pyls_settings(): - # Default pylint to disabled because it requires a config - # file to be useful. - return {'plugins': {'pylint': { - 'enabled': False, - 'args': [], - # disabled by default as it can slow down the workflow - 'executable': None, - }}} - - -@hookimpl -def pyls_lint(config, document, is_saved): - """Run pylint linter.""" - settings = config.plugin_settings('pylint') - log.debug("Got pylint settings: %s", settings) - # pylint >= 2.5.0 is required for working through stdin and only - # available with python3 - if settings.get('executable') and sys.version_info[0] >= 3: - flags = build_args_stdio(settings) - pylint_executable = settings.get('executable', 'pylint') - return pylint_lint_stdin(pylint_executable, document, flags) - flags = _build_pylint_flags(settings) - return PylintLinter.lint(document, is_saved, flags=flags) - - -def build_args_stdio(settings): - """Build arguments for calling pylint. - - :param settings: client settings - :type settings: dict - - :return: arguments to path to pylint - :rtype: list - """ - pylint_args = settings.get('args') - if pylint_args is None: - return [] - return pylint_args - - -def pylint_lint_stdin(pylint_executable, document, flags): - """Run pylint linter from stdin. - - This runs pylint in a subprocess with popen. - This allows passing the file from stdin and as a result - run pylint on unsaved files. Can slowdown the workflow. - - :param pylint_executable: path to pylint executable - :type pylint_executable: string - :param document: document to run pylint on - :type document: pyls.workspace.Document - :param flags: arguments to path to pylint - :type flags: list - - :return: linting diagnostics - :rtype: list - """ - pylint_result = _run_pylint_stdio(pylint_executable, document, flags) - return _parse_pylint_stdio_result(document, pylint_result) - - -def _run_pylint_stdio(pylint_executable, document, flags): - """Run pylint in popen. - - :param pylint_executable: path to pylint executable - :type pylint_executable: string - :param document: document to run pylint on - :type document: pyls.workspace.Document - :param flags: arguments to path to pylint - :type flags: list - - :return: result of calling pylint - :rtype: string - """ - log.debug("Calling %s with args: '%s'", pylint_executable, flags) - try: - cmd = [pylint_executable] - cmd.extend(flags) - cmd.extend(['--from-stdin', document.path]) - p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) - except IOError: - log.debug("Can't execute %s. Trying with 'python -m pylint'", pylint_executable) - cmd = ['python', '-m', 'pylint'] - cmd.extend(flags) - cmd.extend(['--from-stdin', document.path]) - p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) - (stdout, stderr) = p.communicate(document.source.encode()) - if stderr: - log.error("Error while running pylint '%s'", stderr.decode()) - return stdout.decode() - - -def _parse_pylint_stdio_result(document, stdout): - """Parse pylint results. - - :param document: document to run pylint on - :type document: pyls.workspace.Document - :param stdout: pylint results to parse - :type stdout: string - - :return: linting diagnostics - :rtype: list - """ - diagnostics = [] - lines = stdout.splitlines() - for raw_line in lines: - parsed_line = re.match(r'(.*):(\d*):(\d*): (\w*): (.*)', raw_line) - if not parsed_line: - log.debug("Pylint output parser can't parse line '%s'", raw_line) - continue - - parsed_line = parsed_line.groups() - if len(parsed_line) != 5: - log.debug("Pylint output parser can't parse line '%s'", raw_line) - continue - - _, line, character, code, msg = parsed_line - line = int(line) - 1 - character = int(character) - severity_map = { - 'C': lsp.DiagnosticSeverity.Information, - 'E': lsp.DiagnosticSeverity.Error, - 'F': lsp.DiagnosticSeverity.Error, - 'R': lsp.DiagnosticSeverity.Hint, - 'W': lsp.DiagnosticSeverity.Warning, - } - severity = severity_map[code[0]] - diagnostics.append( - { - 'source': 'pylint', - 'code': code, - 'range': { - 'start': { - 'line': line, - 'character': character - }, - 'end': { - 'line': line, - # no way to determine the column - 'character': len(document.lines[line]) - 1 - } - }, - 'message': msg, - 'severity': severity, - } - ) - - return diagnostics Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/pylint_lint.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/pylint_lint.py @@ -0,0 +1,307 @@ +# Copyright 2018 Google LLC. +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +"""Linter plugin for pylint.""" +import collections +import logging +import sys +import re +from subprocess import Popen, PIPE + +from pylint.epylint import py_run +from pylsp import hookimpl, lsp + +try: + import ujson as json +except Exception: # pylint: disable=broad-except + import json + +log = logging.getLogger(__name__) + + +class PylintLinter: + last_diags = collections.defaultdict(list) + + @classmethod + def lint(cls, document, is_saved, flags=''): + """Plugin interface to pylsp linter. + + Args: + document: The document to be linted. + is_saved: Whether or not the file has been saved to disk. + flags: Additional flags to pass to pylint. Not exposed to + pylsp_lint, but used for testing. + + Returns: + A list of dicts with the following format: + + { + 'source': 'pylint', + 'range': { + 'start': { + 'line': start_line, + 'character': start_column, + }, + 'end': { + 'line': end_line, + 'character': end_column, + }, + } + 'message': msg, + 'severity': lsp.DiagnosticSeverity.*, + } + """ + if not is_saved: + # Pylint can only be run on files that have been saved to disk. + # Rather than return nothing, return the previous list of + # diagnostics. If we return an empty list, any diagnostics we'd + # previously shown will be cleared until the next save. Instead, + # continue showing (possibly stale) diagnostics until the next + # save. + return cls.last_diags[document.path] + + # py_run will call shlex.split on its arguments, and shlex.split does + # not handle Windows paths (it will try to perform escaping). Turn + # backslashes into forward slashes first to avoid this issue. + path = document.path + if sys.platform.startswith('win'): + path = path.replace('\\', '/') + + pylint_call = '{} -f json {}'.format(path, flags) + log.debug("Calling pylint with '%s'", pylint_call) + json_out, err = py_run(pylint_call, return_std=True) + + # Get strings + json_out = json_out.getvalue() + err = err.getvalue() + + if err != '': + log.error("Error calling pylint: '%s'", err) + + # pylint prints nothing rather than [] when there are no diagnostics. + # json.loads will not parse an empty string, so just return. + if not json_out.strip(): + cls.last_diags[document.path] = [] + return [] + + # Pylint's JSON output is a list of objects with the following format. + # + # { + # "obj": "main", + # "path": "foo.py", + # "message": "Missing function docstring", + # "message-id": "C0111", + # "symbol": "missing-docstring", + # "column": 0, + # "type": "convention", + # "line": 5, + # "module": "foo" + # } + # + # The type can be any of: + # + # * convention + # * error + # * fatal + # * refactor + # * warning + diagnostics = [] + for diag in json.loads(json_out): + # pylint lines index from 1, pylsp lines index from 0 + line = diag['line'] - 1 + + err_range = { + 'start': { + 'line': line, + # Index columns start from 0 + 'character': diag['column'], + }, + 'end': { + 'line': line, + # It's possible that we're linting an empty file. Even an empty + # file might fail linting if it isn't named properly. + 'character': len(document.lines[line]) if document.lines else 0, + }, + } + + if diag['type'] == 'convention': + severity = lsp.DiagnosticSeverity.Information + elif diag['type'] == 'error': + severity = lsp.DiagnosticSeverity.Error + elif diag['type'] == 'fatal': + severity = lsp.DiagnosticSeverity.Error + elif diag['type'] == 'refactor': + severity = lsp.DiagnosticSeverity.Hint + elif diag['type'] == 'warning': + severity = lsp.DiagnosticSeverity.Warning + + diagnostics.append({ + 'source': 'pylint', + 'range': err_range, + 'message': '[{}] {}'.format(diag['symbol'], diag['message']), + 'severity': severity, + 'code': diag['message-id'] + }) + cls.last_diags[document.path] = diagnostics + return diagnostics + + +def _build_pylint_flags(settings): + """Build arguments for calling pylint.""" + pylint_args = settings.get('args') + if pylint_args is None: + return '' + return ' '.join(pylint_args) + + +@hookimpl +def pylsp_settings(): + # Default pylint to disabled because it requires a config + # file to be useful. + return {'plugins': {'pylint': { + 'enabled': False, + 'args': [], + # disabled by default as it can slow down the workflow + 'executable': None, + }}} + + +@hookimpl +def pylsp_lint(config, document, is_saved): + """Run pylint linter.""" + settings = config.plugin_settings('pylint') + log.debug("Got pylint settings: %s", settings) + # pylint >= 2.5.0 is required for working through stdin and only + # available with python3 + if settings.get('executable') and sys.version_info[0] >= 3: + flags = build_args_stdio(settings) + pylint_executable = settings.get('executable', 'pylint') + return pylint_lint_stdin(pylint_executable, document, flags) + flags = _build_pylint_flags(settings) + return PylintLinter.lint(document, is_saved, flags=flags) + + +def build_args_stdio(settings): + """Build arguments for calling pylint. + + :param settings: client settings + :type settings: dict + + :return: arguments to path to pylint + :rtype: list + """ + pylint_args = settings.get('args') + if pylint_args is None: + return [] + return pylint_args + + +def pylint_lint_stdin(pylint_executable, document, flags): + """Run pylint linter from stdin. + + This runs pylint in a subprocess with popen. + This allows passing the file from stdin and as a result + run pylint on unsaved files. Can slowdown the workflow. + + :param pylint_executable: path to pylint executable + :type pylint_executable: string + :param document: document to run pylint on + :type document: pylsp.workspace.Document + :param flags: arguments to path to pylint + :type flags: list + + :return: linting diagnostics + :rtype: list + """ + pylint_result = _run_pylint_stdio(pylint_executable, document, flags) + return _parse_pylint_stdio_result(document, pylint_result) + + +def _run_pylint_stdio(pylint_executable, document, flags): + """Run pylint in popen. + + :param pylint_executable: path to pylint executable + :type pylint_executable: string + :param document: document to run pylint on + :type document: pylsp.workspace.Document + :param flags: arguments to path to pylint + :type flags: list + + :return: result of calling pylint + :rtype: string + """ + log.debug("Calling %s with args: '%s'", pylint_executable, flags) + try: + cmd = [pylint_executable] + cmd.extend(flags) + cmd.extend(['--from-stdin', document.path]) + p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) # pylint: disable=consider-using-with + except IOError: + log.debug("Can't execute %s. Trying with 'python -m pylint'", pylint_executable) + cmd = ['python', '-m', 'pylint'] + cmd.extend(flags) + cmd.extend(['--from-stdin', document.path]) + p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) # pylint: disable=consider-using-with + (stdout, stderr) = p.communicate(document.source.encode()) + if stderr: + log.error("Error while running pylint '%s'", stderr.decode()) + return stdout.decode() + + +def _parse_pylint_stdio_result(document, stdout): + """Parse pylint results. + + :param document: document to run pylint on + :type document: pylsp.workspace.Document + :param stdout: pylint results to parse + :type stdout: string + + :return: linting diagnostics + :rtype: list + """ + diagnostics = [] + lines = stdout.splitlines() + for raw_line in lines: + parsed_line = re.match(r'(.*):(\d*):(\d*): (\w*): (.*)', raw_line) + if not parsed_line: + log.debug("Pylint output parser can't parse line '%s'", raw_line) + continue + + parsed_line = parsed_line.groups() + if len(parsed_line) != 5: + log.debug("Pylint output parser can't parse line '%s'", raw_line) + continue + + _, line, character, code, msg = parsed_line + line = int(line) - 1 + character = int(character) + severity_map = { + 'C': lsp.DiagnosticSeverity.Information, + 'E': lsp.DiagnosticSeverity.Error, + 'F': lsp.DiagnosticSeverity.Error, + 'R': lsp.DiagnosticSeverity.Hint, + 'W': lsp.DiagnosticSeverity.Warning, + } + severity = severity_map[code[0]] + diagnostics.append( + { + 'source': 'pylint', + 'code': code, + 'range': { + 'start': { + 'line': line, + 'character': character + }, + 'end': { + 'line': line, + # no way to determine the column + 'character': len(document.lines[line]) - 1 + } + }, + 'message': msg, + 'severity': severity, + } + ) + + return diagnostics Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/references.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/references.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging -from pyls import hookimpl, uris, _utils - -log = logging.getLogger(__name__) - - -@hookimpl -def pyls_references(document, position, exclude_declaration=False): - code_position = _utils.position_to_jedi_linecolumn(document, position) - usages = document.jedi_script().get_references(**code_position) - - if exclude_declaration: - # Filter out if the usage is the actual declaration of the thing - usages = [d for d in usages if not d.is_definition()] - - # Filter out builtin modules - return [{ - 'uri': uris.uri_with(document.uri, path=str(d.module_path)) if d.module_path else document.uri, - 'range': { - 'start': {'line': d.line - 1, 'character': d.column}, - 'end': {'line': d.line - 1, 'character': d.column + len(d.name)} - } - } for d in usages if not d.in_builtin_module()] Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/references.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/references.py @@ -0,0 +1,26 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging +from pylsp import hookimpl, uris, _utils + +log = logging.getLogger(__name__) + + +@hookimpl +def pylsp_references(document, position, exclude_declaration=False): + code_position = _utils.position_to_jedi_linecolumn(document, position) + usages = document.jedi_script().get_references(**code_position) + + if exclude_declaration: + # Filter out if the usage is the actual declaration of the thing + usages = [d for d in usages if not d.is_definition()] + + # Filter out builtin modules + return [{ + 'uri': uris.uri_with(document.uri, path=str(d.module_path)) if d.module_path else document.uri, + 'range': { + 'start': {'line': d.line - 1, 'character': d.column}, + 'end': {'line': d.line - 1, 'character': d.column + len(d.name)} + } + } for d in usages if not d.in_builtin_module()] Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/rope_completion.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/rope_completion.py +++ /dev/null @@ -1,107 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging -from rope.contrib.codeassist import code_assist, sorted_proposals - -from pyls import hookimpl, lsp - - -log = logging.getLogger(__name__) - - -@hookimpl -def pyls_settings(): - # Default rope_completion to disabled - return {'plugins': {'rope_completion': {'enabled': False}}} - - -@hookimpl -def pyls_completions(config, workspace, document, position): - # Rope is a bit rubbish at completing module imports, so we'll return None - word = document.word_at_position({ - # The -1 should really be trying to look at the previous word, but that might be quite expensive - # So we only skip import completions when the cursor is one space after `import` - 'line': position['line'], 'character': max(position['character'] - 1, 0), - }) - if word == 'import': - return None - - offset = document.offset_at_position(position) - rope_config = config.settings(document_path=document.path).get('rope', {}) - rope_project = workspace._rope_project_builder(rope_config) - document_rope = document._rope_resource(rope_config) - - try: - definitions = code_assist(rope_project, document.source, offset, document_rope, maxfixes=3) - except Exception as e: # pylint: disable=broad-except - log.debug("Failed to run Rope code assist: %s", e) - return [] - - definitions = sorted_proposals(definitions) - new_definitions = [] - for d in definitions: - try: - doc = d.get_doc() - except AttributeError: - doc = None - new_definitions.append({ - 'label': d.name, - 'kind': _kind(d), - 'detail': '{0} {1}'.format(d.scope or "", d.name), - 'documentation': doc or "", - 'sortText': _sort_text(d) - }) - definitions = new_definitions - - return definitions or None - - -def _sort_text(definition): - """ Ensure builtins appear at the bottom. - Description is of format <type>: <module>.<item> - """ - if definition.name.startswith("_"): - # It's a 'hidden' func, put it next last - return 'z' + definition.name - elif definition.scope == 'builtin': - return 'y' + definition.name - - # Else put it at the front - return 'a' + definition.name - - -def _kind(d): - """ Return the VSCode type """ - MAP = { - 'none': lsp.CompletionItemKind.Value, - 'type': lsp.CompletionItemKind.Class, - 'tuple': lsp.CompletionItemKind.Class, - 'dict': lsp.CompletionItemKind.Class, - 'dictionary': lsp.CompletionItemKind.Class, - 'function': lsp.CompletionItemKind.Function, - 'lambda': lsp.CompletionItemKind.Function, - 'generator': lsp.CompletionItemKind.Function, - 'class': lsp.CompletionItemKind.Class, - 'instance': lsp.CompletionItemKind.Reference, - 'method': lsp.CompletionItemKind.Method, - 'builtin': lsp.CompletionItemKind.Class, - 'builtinfunction': lsp.CompletionItemKind.Function, - 'module': lsp.CompletionItemKind.Module, - 'file': lsp.CompletionItemKind.File, - 'xrange': lsp.CompletionItemKind.Class, - 'slice': lsp.CompletionItemKind.Class, - 'traceback': lsp.CompletionItemKind.Class, - 'frame': lsp.CompletionItemKind.Class, - 'buffer': lsp.CompletionItemKind.Class, - 'dictproxy': lsp.CompletionItemKind.Class, - 'funcdef': lsp.CompletionItemKind.Function, - 'property': lsp.CompletionItemKind.Property, - 'import': lsp.CompletionItemKind.Module, - 'keyword': lsp.CompletionItemKind.Keyword, - 'constant': lsp.CompletionItemKind.Variable, - 'variable': lsp.CompletionItemKind.Variable, - 'value': lsp.CompletionItemKind.Value, - 'param': lsp.CompletionItemKind.Variable, - 'statement': lsp.CompletionItemKind.Keyword, - } - - return MAP.get(d.type) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/rope_completion.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/rope_completion.py @@ -0,0 +1,109 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging +from rope.contrib.codeassist import code_assist, sorted_proposals + +from pylsp import hookimpl, lsp + + +log = logging.getLogger(__name__) + + +@hookimpl +def pylsp_settings(): + # Default rope_completion to disabled + return {'plugins': {'rope_completion': {'enabled': False}}} + + +@hookimpl +def pylsp_completions(config, workspace, document, position): + # Rope is a bit rubbish at completing module imports, so we'll return None + word = document.word_at_position({ + # The -1 should really be trying to look at the previous word, but that might be quite expensive + # So we only skip import completions when the cursor is one space after `import` + 'line': position['line'], 'character': max(position['character'] - 1, 0), + }) + if word == 'import': + return None + + offset = document.offset_at_position(position) + rope_config = config.settings(document_path=document.path).get('rope', {}) + rope_project = workspace._rope_project_builder(rope_config) + document_rope = document._rope_resource(rope_config) + + try: + definitions = code_assist(rope_project, document.source, offset, document_rope, maxfixes=3) + except Exception as e: # pylint: disable=broad-except + log.debug("Failed to run Rope code assist: %s", e) + return [] + + definitions = sorted_proposals(definitions) + new_definitions = [] + for d in definitions: + try: + doc = d.get_doc() + except AttributeError: + doc = None + new_definitions.append({ + 'label': d.name, + 'kind': _kind(d), + 'detail': '{0} {1}'.format(d.scope or "", d.name), + 'documentation': doc or "", + 'sortText': _sort_text(d) + }) + definitions = new_definitions + + return definitions or None + + +def _sort_text(definition): + """ Ensure builtins appear at the bottom. + Description is of format <type>: <module>.<item> + """ + if definition.name.startswith("_"): + # It's a 'hidden' func, put it next last + return 'z' + definition.name + if definition.scope == 'builtin': + return 'y' + definition.name + + # Else put it at the front + return 'a' + definition.name + + +def _kind(d): + """ Return the VSCode type """ + MAP = { + 'none': lsp.CompletionItemKind.Value, + 'type': lsp.CompletionItemKind.Class, + 'tuple': lsp.CompletionItemKind.Class, + 'dict': lsp.CompletionItemKind.Class, + 'dictionary': lsp.CompletionItemKind.Class, + 'function': lsp.CompletionItemKind.Function, + 'lambda': lsp.CompletionItemKind.Function, + 'generator': lsp.CompletionItemKind.Function, + 'class': lsp.CompletionItemKind.Class, + 'instance': lsp.CompletionItemKind.Reference, + 'method': lsp.CompletionItemKind.Method, + 'builtin': lsp.CompletionItemKind.Class, + 'builtinfunction': lsp.CompletionItemKind.Function, + 'module': lsp.CompletionItemKind.Module, + 'file': lsp.CompletionItemKind.File, + 'xrange': lsp.CompletionItemKind.Class, + 'slice': lsp.CompletionItemKind.Class, + 'traceback': lsp.CompletionItemKind.Class, + 'frame': lsp.CompletionItemKind.Class, + 'buffer': lsp.CompletionItemKind.Class, + 'dictproxy': lsp.CompletionItemKind.Class, + 'funcdef': lsp.CompletionItemKind.Function, + 'property': lsp.CompletionItemKind.Property, + 'import': lsp.CompletionItemKind.Module, + 'keyword': lsp.CompletionItemKind.Keyword, + 'constant': lsp.CompletionItemKind.Variable, + 'variable': lsp.CompletionItemKind.Variable, + 'value': lsp.CompletionItemKind.Value, + 'param': lsp.CompletionItemKind.Variable, + 'statement': lsp.CompletionItemKind.Keyword, + } + + return MAP.get(d.type) Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/rope_rename.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/rope_rename.py +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging - -from rope.base import libutils -from rope.refactor.rename import Rename - -from pyls import hookimpl, uris - -log = logging.getLogger(__name__) - - -@hookimpl -def pyls_settings(): - # Default rope_rename to disabled - return {'plugins': {'rope_rename': {'enabled': False}}} - - -@hookimpl -def pyls_rename(config, workspace, document, position, new_name): - rope_config = config.settings(document_path=document.path).get('rope', {}) - rope_project = workspace._rope_project_builder(rope_config) - - rename = Rename( - rope_project, - libutils.path_to_resource(rope_project, document.path), - document.offset_at_position(position) - ) - - log.debug("Executing rename of %s to %s", document.word_at_position(position), new_name) - changeset = rename.get_changes(new_name, in_hierarchy=True, docs=True) - log.debug("Finished rename: %s", changeset.changes) - changes = [] - for change in changeset.changes: - uri = uris.from_fs_path(change.resource.path) - doc = workspace.get_maybe_document(uri) - changes.append({ - 'textDocument': { - 'uri': uri, - 'version': doc.version if doc else None - }, - 'edits': [ - { - 'range': { - 'start': {'line': 0, 'character': 0}, - 'end': { - 'line': _num_lines(change.resource), - 'character': 0, - }, - }, - 'newText': change.new_contents, - } - ] - }) - return {'documentChanges': changes} - - -def _num_lines(resource): - "Count the number of lines in a `File` resource." - return len(resource.read().splitlines()) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/rope_rename.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/rope_rename.py @@ -0,0 +1,61 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging + +from rope.base import libutils +from rope.refactor.rename import Rename + +from pylsp import hookimpl, uris + +log = logging.getLogger(__name__) + + +@hookimpl +def pylsp_settings(): + # Default rope_rename to disabled + return {'plugins': {'rope_rename': {'enabled': False}}} + + +@hookimpl +def pylsp_rename(config, workspace, document, position, new_name): + rope_config = config.settings(document_path=document.path).get('rope', {}) + rope_project = workspace._rope_project_builder(rope_config) + + rename = Rename( + rope_project, + libutils.path_to_resource(rope_project, document.path), + document.offset_at_position(position) + ) + + log.debug("Executing rename of %s to %s", document.word_at_position(position), new_name) + changeset = rename.get_changes(new_name, in_hierarchy=True, docs=True) + log.debug("Finished rename: %s", changeset.changes) + changes = [] + for change in changeset.changes: + uri = uris.from_fs_path(change.resource.path) + doc = workspace.get_maybe_document(uri) + changes.append({ + 'textDocument': { + 'uri': uri, + 'version': doc.version if doc else None + }, + 'edits': [ + { + 'range': { + 'start': {'line': 0, 'character': 0}, + 'end': { + 'line': _num_lines(change.resource), + 'character': 0, + }, + }, + 'newText': change.new_contents, + } + ] + }) + return {'documentChanges': changes} + + +def _num_lines(resource): + "Count the number of lines in a `File` resource." + return len(resource.read().splitlines()) Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/signature.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/signature.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging -import re -from pyls import hookimpl, _utils - -log = logging.getLogger(__name__) - -SPHINX = re.compile(r"\s*:param\s+(?P<param>\w+):\s*(?P<doc>[^\n]+)") -EPYDOC = re.compile(r"\s*@param\s+(?P<param>\w+):\s*(?P<doc>[^\n]+)") -GOOGLE = re.compile(r"\s*(?P<param>\w+).*:\s*(?P<doc>[^\n]+)") - -DOC_REGEX = [SPHINX, EPYDOC, GOOGLE] - - -@hookimpl -def pyls_signature_help(document, position): - code_position = _utils.position_to_jedi_linecolumn(document, position) - signatures = document.jedi_script().get_signatures(**code_position) - - if not signatures: - return {'signatures': []} - - s = signatures[0] - - # Docstring contains one or more lines of signature, followed by empty line, followed by docstring - function_sig_lines = (s.docstring().split('\n\n') or [''])[0].splitlines() - function_sig = ' '.join([line.strip() for line in function_sig_lines]) - sig = { - 'label': function_sig, - 'documentation': _utils.format_docstring(s.docstring(raw=True)) - } - - # If there are params, add those - if s.params: - sig['parameters'] = [{ - 'label': p.name, - 'documentation': _param_docs(s.docstring(), p.name) - } for p in s.params] - - # We only return a single signature because Python doesn't allow overloading - sig_info = {'signatures': [sig], 'activeSignature': 0} - - if s.index is not None and s.params: - # Then we know which parameter we're looking at - sig_info['activeParameter'] = s.index - - return sig_info - - -def _param_docs(docstring, param_name): - for line in docstring.splitlines(): - for regex in DOC_REGEX: - m = regex.match(line) - if not m: - continue - if m.group('param') != param_name: - continue - return m.group('doc') or "" Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/signature.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/signature.py @@ -0,0 +1,60 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging +import re +from pylsp import hookimpl, _utils + +log = logging.getLogger(__name__) + +SPHINX = re.compile(r"\s*:param\s+(?P<param>\w+):\s*(?P<doc>[^\n]+)") +EPYDOC = re.compile(r"\s*@param\s+(?P<param>\w+):\s*(?P<doc>[^\n]+)") +GOOGLE = re.compile(r"\s*(?P<param>\w+).*:\s*(?P<doc>[^\n]+)") + +DOC_REGEX = [SPHINX, EPYDOC, GOOGLE] + + +@hookimpl +def pylsp_signature_help(document, position): + code_position = _utils.position_to_jedi_linecolumn(document, position) + signatures = document.jedi_script().get_signatures(**code_position) + + if not signatures: + return {'signatures': []} + + s = signatures[0] + + # Docstring contains one or more lines of signature, followed by empty line, followed by docstring + function_sig_lines = (s.docstring().split('\n\n') or [''])[0].splitlines() + function_sig = ' '.join([line.strip() for line in function_sig_lines]) + sig = { + 'label': function_sig, + 'documentation': _utils.format_docstring(s.docstring(raw=True)) + } + + # If there are params, add those + if s.params: + sig['parameters'] = [{ + 'label': p.name, + 'documentation': _param_docs(s.docstring(), p.name) + } for p in s.params] + + # We only return a single signature because Python doesn't allow overloading + sig_info = {'signatures': [sig], 'activeSignature': 0} + + if s.index is not None and s.params: + # Then we know which parameter we're looking at + sig_info['activeParameter'] = s.index + + return sig_info + + +def _param_docs(docstring, param_name): + for line in docstring.splitlines(): + for regex in DOC_REGEX: + m = regex.match(line) + if not m: + continue + if m.group('param') != param_name: + continue + return m.group('doc') or "" Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/symbols.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/symbols.py +++ /dev/null @@ -1,165 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging -import os - -from pyls import hookimpl -from pyls.lsp import SymbolKind - -log = logging.getLogger(__name__) - - -@hookimpl -def pyls_document_symbols(config, document): - # pylint: disable=broad-except - # pylint: disable=too-many-nested-blocks - # pylint: disable=too-many-locals - # pylint: disable=too-many-branches - 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) - - use_document_path = False - document_dir = os.path.normpath(os.path.dirname(document.path)) - if not os.path.isfile(os.path.join(document_dir, '__init__.py')): - use_document_path = True - - definitions = document.jedi_names(use_document_path, all_scopes=all_scopes) - module_name = document.dot_path - symbols = [] - exclude = set({}) - redefinitions = {} - while definitions != []: - d = definitions.pop(0) - if not add_import_symbols: - sym_full_name = d.full_name - if sym_full_name is not None: - if (not sym_full_name.startswith(module_name) and - not sym_full_name.startswith('__main__')): - continue - - if _include_def(d) and document.path == d.module_path: - tuple_range = _tuple_range(d) - if tuple_range in exclude: - continue - - kind = redefinitions.get(tuple_range, None) - if kind is not None: - exclude |= {tuple_range} - - if d.type == 'statement': - if d.description.startswith('self'): - kind = 'field' - - symbol = { - 'name': d.name, - 'containerName': _container(d), - 'location': { - 'uri': document.uri, - 'range': _range(d), - }, - 'kind': _kind(d) if kind is None else _SYMBOL_KIND_MAP[kind], - } - symbols.append(symbol) - - if d.type == 'class': - try: - defined_names = list(d.defined_names()) - for method in defined_names: - if method.type == 'function': - redefinitions[_tuple_range(method)] = 'method' - elif method.type == 'statement': - redefinitions[_tuple_range(method)] = 'field' - else: - redefinitions[_tuple_range(method)] = method.type - definitions = list(defined_names) + definitions - except Exception: - pass - return symbols - - -def _include_def(definition): - return ( - # Don't tend to include parameters as symbols - definition.type != 'param' and - # Unused vars should also be skipped - definition.name != '_' and - _kind(definition) is not None - ) - - -def _container(definition): - try: - # Jedi sometimes fails here. - parent = definition.parent() - # Here we check that a grand-parent exists to avoid declaring symbols - # as children of the module. - if parent.parent(): - return parent.name - except: # pylint: disable=bare-except - return None - - return None - - -def _range(definition): - # This gets us more accurate end position - definition = definition._name.tree_name.get_definition() - (start_line, start_column) = definition.start_pos - (end_line, end_column) = definition.end_pos - return { - 'start': {'line': start_line - 1, 'character': start_column}, - 'end': {'line': end_line - 1, 'character': end_column} - } - - -def _tuple_range(definition): - definition = definition._name.tree_name.get_definition() - return (definition.start_pos, definition.end_pos) - - -_SYMBOL_KIND_MAP = { - 'none': SymbolKind.Variable, - 'type': SymbolKind.Class, - 'tuple': SymbolKind.Class, - 'dict': SymbolKind.Class, - 'dictionary': SymbolKind.Class, - 'function': SymbolKind.Function, - 'lambda': SymbolKind.Function, - 'generator': SymbolKind.Function, - 'class': SymbolKind.Class, - 'instance': SymbolKind.Class, - 'method': SymbolKind.Method, - 'builtin': SymbolKind.Class, - 'builtinfunction': SymbolKind.Function, - 'module': SymbolKind.Module, - 'file': SymbolKind.File, - 'xrange': SymbolKind.Array, - 'slice': SymbolKind.Class, - 'traceback': SymbolKind.Class, - 'frame': SymbolKind.Class, - 'buffer': SymbolKind.Array, - 'dictproxy': SymbolKind.Class, - 'funcdef': SymbolKind.Function, - 'property': SymbolKind.Property, - 'import': SymbolKind.Module, - 'keyword': SymbolKind.Variable, - 'constant': SymbolKind.Constant, - 'variable': SymbolKind.Variable, - 'value': SymbolKind.Variable, - 'param': SymbolKind.Variable, - 'statement': SymbolKind.Variable, - 'boolean': SymbolKind.Boolean, - 'int': SymbolKind.Number, - 'longlean': SymbolKind.Number, - 'float': SymbolKind.Number, - 'complex': SymbolKind.Number, - 'string': SymbolKind.String, - 'unicode': SymbolKind.String, - 'list': SymbolKind.Array, - 'field': SymbolKind.Field -} - - -def _kind(d): - """ Return the VSCode Symbol Type """ - return _SYMBOL_KIND_MAP.get(d.type) Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/symbols.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/symbols.py @@ -0,0 +1,173 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging +import os + +from pylsp import hookimpl +from pylsp.lsp import SymbolKind + +log = logging.getLogger(__name__) + + +@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 + 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) + + use_document_path = False + document_dir = os.path.normpath(os.path.dirname(document.path)) + if not os.path.isfile(os.path.join(document_dir, '__init__.py')): + use_document_path = True + + definitions = document.jedi_names(use_document_path, all_scopes=all_scopes) + module_name = document.dot_path + symbols = [] + exclude = set({}) + redefinitions = {} + while definitions != []: + d = definitions.pop(0) + if not add_import_symbols: + sym_full_name = d.full_name + if sym_full_name is not None: + if (not sym_full_name.startswith(module_name) and + not sym_full_name.startswith('__main__')): + continue + try: + docismodule = os.path.samefile(document.path, d.module_path) + except TypeError: + # Python 2 on Windows has no .samefile, but then these are + # strings for sure + docismodule = document.path == d.module_path + + if _include_def(d) and docismodule: + tuple_range = _tuple_range(d) + if tuple_range in exclude: + continue + + kind = redefinitions.get(tuple_range, None) + if kind is not None: + exclude |= {tuple_range} + + if d.type == 'statement': + if d.description.startswith('self'): + kind = 'field' + + symbol = { + 'name': d.name, + 'containerName': _container(d), + 'location': { + 'uri': document.uri, + 'range': _range(d), + }, + 'kind': _kind(d) if kind is None else _SYMBOL_KIND_MAP[kind], + } + symbols.append(symbol) + + if d.type == 'class': + try: + defined_names = list(d.defined_names()) + for method in defined_names: + if method.type == 'function': + redefinitions[_tuple_range(method)] = 'method' + elif method.type == 'statement': + redefinitions[_tuple_range(method)] = 'field' + else: + redefinitions[_tuple_range(method)] = method.type + definitions = list(defined_names) + definitions + except Exception: + pass + return symbols + + +def _include_def(definition): + return ( + # Don't tend to include parameters as symbols + definition.type != 'param' and + # Unused vars should also be skipped + definition.name != '_' and + _kind(definition) is not None + ) + + +def _container(definition): + try: + # Jedi sometimes fails here. + parent = definition.parent() + # Here we check that a grand-parent exists to avoid declaring symbols + # as children of the module. + if parent.parent(): + return parent.name + except: # pylint: disable=bare-except + return None + + return None + + +def _range(definition): + # This gets us more accurate end position + definition = definition._name.tree_name.get_definition() + (start_line, start_column) = definition.start_pos + (end_line, end_column) = definition.end_pos + return { + 'start': {'line': start_line - 1, 'character': start_column}, + 'end': {'line': end_line - 1, 'character': end_column} + } + + +def _tuple_range(definition): + definition = definition._name.tree_name.get_definition() + return (definition.start_pos, definition.end_pos) + + +_SYMBOL_KIND_MAP = { + 'none': SymbolKind.Variable, + 'type': SymbolKind.Class, + 'tuple': SymbolKind.Class, + 'dict': SymbolKind.Class, + 'dictionary': SymbolKind.Class, + 'function': SymbolKind.Function, + 'lambda': SymbolKind.Function, + 'generator': SymbolKind.Function, + 'class': SymbolKind.Class, + 'instance': SymbolKind.Class, + 'method': SymbolKind.Method, + 'builtin': SymbolKind.Class, + 'builtinfunction': SymbolKind.Function, + 'module': SymbolKind.Module, + 'file': SymbolKind.File, + 'xrange': SymbolKind.Array, + 'slice': SymbolKind.Class, + 'traceback': SymbolKind.Class, + 'frame': SymbolKind.Class, + 'buffer': SymbolKind.Array, + 'dictproxy': SymbolKind.Class, + 'funcdef': SymbolKind.Function, + 'property': SymbolKind.Property, + 'import': SymbolKind.Module, + 'keyword': SymbolKind.Variable, + 'constant': SymbolKind.Constant, + 'variable': SymbolKind.Variable, + 'value': SymbolKind.Variable, + 'param': SymbolKind.Variable, + 'statement': SymbolKind.Variable, + 'boolean': SymbolKind.Boolean, + 'int': SymbolKind.Number, + 'longlean': SymbolKind.Number, + 'float': SymbolKind.Number, + 'complex': SymbolKind.Number, + 'string': SymbolKind.String, + 'unicode': SymbolKind.String, + 'list': SymbolKind.Array, + 'field': SymbolKind.Field +} + + +def _kind(d): + """ Return the VSCode Symbol Type """ + return _SYMBOL_KIND_MAP.get(d.type) Index: spyder-5.0.5/external-deps/python-language-server/pyls/plugins/yapf_format.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/plugins/yapf_format.py +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import logging -import os -from yapf.yapflib import file_resources -from yapf.yapflib.yapf_api import FormatCode -from pyls import hookimpl - -log = logging.getLogger(__name__) - - -@hookimpl -def pyls_format_document(document): - return _format(document) - - -@hookimpl -def pyls_format_range(document, range): # pylint: disable=redefined-builtin - # First we 'round' the range up/down to full lines only - range['start']['character'] = 0 - range['end']['line'] += 1 - range['end']['character'] = 0 - - # From Yapf docs: - # lines: (list of tuples of integers) A list of tuples of lines, [start, end], - # that we want to format. The lines are 1-based indexed. It can be used by - # third-party code (e.g., IDEs) when reformatting a snippet of code rather - # than a whole file. - - # Add 1 for 1-indexing vs LSP's 0-indexing - lines = [(range['start']['line'] + 1, range['end']['line'] + 1)] - return _format(document, lines=lines) - - -def _format(document, lines=None): - new_source, changed = FormatCode( - document.source, - lines=lines, - filename=document.filename, - style_config=file_resources.GetDefaultStyleForDir( - os.path.dirname(document.path) - ) - ) - - if not changed: - return [] - - # I'm too lazy at the moment to parse diffs into TextEdit items - # So let's just return the entire file... - return [{ - 'range': { - 'start': {'line': 0, 'character': 0}, - # End char 0 of the line after our document - 'end': {'line': len(document.lines), 'character': 0} - }, - 'newText': new_source - }] Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/yapf_format.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/plugins/yapf_format.py @@ -0,0 +1,58 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import logging +import os +from yapf.yapflib import file_resources +from yapf.yapflib.yapf_api import FormatCode +from pylsp import hookimpl + +log = logging.getLogger(__name__) + + +@hookimpl +def pylsp_format_document(document): + return _format(document) + + +@hookimpl +def pylsp_format_range(document, range): # pylint: disable=redefined-builtin + # First we 'round' the range up/down to full lines only + range['start']['character'] = 0 + range['end']['line'] += 1 + range['end']['character'] = 0 + + # From Yapf docs: + # lines: (list of tuples of integers) A list of tuples of lines, [start, end], + # that we want to format. The lines are 1-based indexed. It can be used by + # third-party code (e.g., IDEs) when reformatting a snippet of code rather + # than a whole file. + + # Add 1 for 1-indexing vs LSP's 0-indexing + lines = [(range['start']['line'] + 1, range['end']['line'] + 1)] + return _format(document, lines=lines) + + +def _format(document, lines=None): + new_source, changed = FormatCode( + document.source, + lines=lines, + filename=document.filename, + style_config=file_resources.GetDefaultStyleForDir( + os.path.dirname(document.path) + ) + ) + + if not changed: + return [] + + # I'm too lazy at the moment to parse diffs into TextEdit items + # So let's just return the entire file... + return [{ + 'range': { + 'start': {'line': 0, 'character': 0}, + # End char 0 of the line after our document + 'end': {'line': len(document.lines), 'character': 0} + }, + 'newText': new_source + }] Index: spyder-5.0.5/external-deps/python-language-server/pyls/python_ls.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/python_ls.py +++ /dev/null @@ -1,445 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -from functools import partial -import logging -import os -import socketserver -import threading - -from pyls_jsonrpc.dispatchers import MethodDispatcher -from pyls_jsonrpc.endpoint import Endpoint -from pyls_jsonrpc.streams import JsonRpcStreamReader, JsonRpcStreamWriter - -from . import lsp, _utils, uris -from .config import config -from .workspace import Workspace - -log = logging.getLogger(__name__) - - -LINT_DEBOUNCE_S = 0.5 # 500 ms -PARENT_PROCESS_WATCH_INTERVAL = 10 # 10 s -MAX_WORKERS = 64 -PYTHON_FILE_EXTENSIONS = ('.py', '.pyi') -CONFIG_FILEs = ('pycodestyle.cfg', 'setup.cfg', 'tox.ini', '.flake8') - - -class _StreamHandlerWrapper(socketserver.StreamRequestHandler, object): - """A wrapper class that is used to construct a custom handler class.""" - - delegate = None - - def setup(self): - super(_StreamHandlerWrapper, self).setup() - # pylint: disable=no-member - self.delegate = self.DELEGATE_CLASS(self.rfile, self.wfile) - - def handle(self): - try: - self.delegate.start() - except OSError as e: - if os.name == 'nt': - # Catch and pass on ConnectionResetError when parent process - # dies - # pylint: disable=no-member, undefined-variable - if isinstance(e, WindowsError) and e.winerror == 10054: - pass - - # pylint: disable=no-member - self.SHUTDOWN_CALL() - - -def start_tcp_lang_server(bind_addr, port, check_parent_process, handler_class): - if not issubclass(handler_class, PythonLanguageServer): - raise ValueError('Handler class must be an instance of PythonLanguageServer') - - def shutdown_server(check_parent_process, *args): - # pylint: disable=unused-argument - if check_parent_process: - log.debug('Shutting down server') - # Shutdown call must be done on a thread, to prevent deadlocks - stop_thread = threading.Thread(target=server.shutdown) - stop_thread.start() - - # Construct a custom wrapper class around the user's handler_class - wrapper_class = type( - handler_class.__name__ + 'Handler', - (_StreamHandlerWrapper,), - {'DELEGATE_CLASS': partial(handler_class, - check_parent_process=check_parent_process), - 'SHUTDOWN_CALL': partial(shutdown_server, check_parent_process)} - ) - - server = socketserver.TCPServer((bind_addr, port), wrapper_class, bind_and_activate=False) - server.allow_reuse_address = True - - try: - server.server_bind() - server.server_activate() - log.info('Serving %s on (%s, %s)', handler_class.__name__, bind_addr, port) - server.serve_forever() - finally: - log.info('Shutting down') - server.server_close() - - -def start_io_lang_server(rfile, wfile, check_parent_process, handler_class): - if not issubclass(handler_class, PythonLanguageServer): - raise ValueError('Handler class must be an instance of PythonLanguageServer') - log.info('Starting %s IO language server', handler_class.__name__) - server = handler_class(rfile, wfile, check_parent_process) - server.start() - - -class PythonLanguageServer(MethodDispatcher): - """ Implementation of the Microsoft VSCode Language Server Protocol - https://github.com/Microsoft/language-server-protocol/blob/master/versions/protocol-1-x.md - """ - - # pylint: disable=too-many-public-methods,redefined-builtin - - def __init__(self, rx, tx, check_parent_process=False): - self.workspace = None - self.config = None - self.root_uri = None - self.watching_thread = None - self.workspaces = {} - self.uri_workspace_mapper = {} - - self._jsonrpc_stream_reader = JsonRpcStreamReader(rx) - self._jsonrpc_stream_writer = JsonRpcStreamWriter(tx) - self._check_parent_process = check_parent_process - self._endpoint = Endpoint(self, self._jsonrpc_stream_writer.write, max_workers=MAX_WORKERS) - self._dispatchers = [] - self._shutdown = False - - def start(self): - """Entry point for the server.""" - self._jsonrpc_stream_reader.listen(self._endpoint.consume) - - def __getitem__(self, item): - """Override getitem to fallback through multiple dispatchers.""" - if self._shutdown and item != 'exit': - # exit is the only allowed method during shutdown - log.debug("Ignoring non-exit method during shutdown: %s", item) - raise KeyError - - try: - return super(PythonLanguageServer, self).__getitem__(item) - except KeyError: - # Fallback through extra dispatchers - for dispatcher in self._dispatchers: - try: - return dispatcher[item] - except KeyError: - continue - - raise KeyError() - - def m_shutdown(self, **_kwargs): - self._shutdown = True - return None - - def m_exit(self, **_kwargs): - self._endpoint.shutdown() - self._jsonrpc_stream_reader.close() - self._jsonrpc_stream_writer.close() - - def _match_uri_to_workspace(self, uri): - workspace_uri = _utils.match_uri_to_workspace(uri, self.workspaces) - return self.workspaces.get(workspace_uri, self.workspace) - - def _hook(self, hook_name, doc_uri=None, **kwargs): - """Calls hook_name and returns a list of results from all registered handlers""" - workspace = self._match_uri_to_workspace(doc_uri) - doc = workspace.get_document(doc_uri) if doc_uri else None - hook_handlers = self.config.plugin_manager.subset_hook_caller(hook_name, self.config.disabled_plugins) - return hook_handlers(config=self.config, workspace=workspace, document=doc, **kwargs) - - def capabilities(self): - server_capabilities = { - 'codeActionProvider': True, - 'codeLensProvider': { - 'resolveProvider': False, # We may need to make this configurable - }, - 'completionProvider': { - 'resolveProvider': False, # We know everything ahead of time - 'triggerCharacters': ['.'] - }, - 'documentFormattingProvider': True, - 'documentHighlightProvider': True, - 'documentRangeFormattingProvider': True, - 'documentSymbolProvider': True, - 'definitionProvider': True, - 'executeCommandProvider': { - 'commands': flatten(self._hook('pyls_commands')) - }, - 'hoverProvider': True, - 'referencesProvider': True, - 'renameProvider': True, - 'foldingRangeProvider': True, - 'signatureHelpProvider': { - 'triggerCharacters': ['(', ',', '='] - }, - 'textDocumentSync': { - 'change': lsp.TextDocumentSyncKind.INCREMENTAL, - 'save': { - 'includeText': True, - }, - 'openClose': True, - }, - 'workspace': { - 'workspaceFolders': { - 'supported': True, - 'changeNotifications': True - } - }, - 'experimental': merge(self._hook('pyls_experimental_capabilities')) - } - log.info('Server capabilities: %s', server_capabilities) - return server_capabilities - - def m_initialize(self, processId=None, rootUri=None, rootPath=None, initializationOptions=None, **_kwargs): - log.debug('Language server initialized with %s %s %s %s', processId, rootUri, rootPath, initializationOptions) - if rootUri is None: - rootUri = uris.from_fs_path(rootPath) if rootPath is not None else '' - - self.workspaces.pop(self.root_uri, None) - self.root_uri = rootUri - self.config = config.Config(rootUri, initializationOptions or {}, - processId, _kwargs.get('capabilities', {})) - self.workspace = Workspace(rootUri, self._endpoint, self.config) - self.workspaces[rootUri] = self.workspace - self._dispatchers = self._hook('pyls_dispatchers') - self._hook('pyls_initialize') - - if self._check_parent_process and processId is not None and self.watching_thread is None: - def watch_parent_process(pid): - # exit when the given pid is not alive - if not _utils.is_process_alive(pid): - log.info("parent process %s is not alive, exiting!", pid) - self.m_exit() - else: - threading.Timer(PARENT_PROCESS_WATCH_INTERVAL, watch_parent_process, args=[pid]).start() - - self.watching_thread = threading.Thread(target=watch_parent_process, args=(processId,)) - self.watching_thread.daemon = True - self.watching_thread.start() - # Get our capabilities - return {'capabilities': self.capabilities()} - - def m_initialized(self, **_kwargs): - self._hook('pyls_initialized') - - def code_actions(self, doc_uri, range, context): - return flatten(self._hook('pyls_code_actions', doc_uri, range=range, context=context)) - - def code_lens(self, doc_uri): - return flatten(self._hook('pyls_code_lens', doc_uri)) - - def completions(self, doc_uri, position): - completions = self._hook('pyls_completions', doc_uri, position=position) - return { - 'isIncomplete': False, - 'items': flatten(completions) - } - - def definitions(self, doc_uri, position): - return flatten(self._hook('pyls_definitions', doc_uri, position=position)) - - def document_symbols(self, doc_uri): - return flatten(self._hook('pyls_document_symbols', doc_uri)) - - def execute_command(self, command, arguments): - return self._hook('pyls_execute_command', command=command, arguments=arguments) - - def format_document(self, doc_uri): - return self._hook('pyls_format_document', doc_uri) - - def format_range(self, doc_uri, range): - return self._hook('pyls_format_range', doc_uri, range=range) - - def highlight(self, doc_uri, position): - return flatten(self._hook('pyls_document_highlight', doc_uri, position=position)) or None - - def hover(self, doc_uri, position): - return self._hook('pyls_hover', doc_uri, position=position) or {'contents': ''} - - @_utils.debounce(LINT_DEBOUNCE_S, keyed_by='doc_uri') - def lint(self, doc_uri, is_saved): - # Since we're debounced, the document may no longer be open - workspace = self._match_uri_to_workspace(doc_uri) - if doc_uri in workspace.documents: - workspace.publish_diagnostics( - doc_uri, - flatten(self._hook('pyls_lint', doc_uri, is_saved=is_saved)) - ) - - def references(self, doc_uri, position, exclude_declaration): - return flatten(self._hook( - 'pyls_references', doc_uri, position=position, - exclude_declaration=exclude_declaration - )) - - def rename(self, doc_uri, position, new_name): - return self._hook('pyls_rename', doc_uri, position=position, new_name=new_name) - - def signature_help(self, doc_uri, position): - return self._hook('pyls_signature_help', doc_uri, position=position) - - def folding(self, doc_uri): - return flatten(self._hook('pyls_folding_range', doc_uri)) - - def m_text_document__did_close(self, textDocument=None, **_kwargs): - workspace = self._match_uri_to_workspace(textDocument['uri']) - workspace.rm_document(textDocument['uri']) - - def m_text_document__did_open(self, textDocument=None, **_kwargs): - workspace = self._match_uri_to_workspace(textDocument['uri']) - workspace.put_document(textDocument['uri'], textDocument['text'], version=textDocument.get('version')) - self._hook('pyls_document_did_open', textDocument['uri']) - self.lint(textDocument['uri'], is_saved=True) - - def m_text_document__did_change(self, contentChanges=None, textDocument=None, **_kwargs): - workspace = self._match_uri_to_workspace(textDocument['uri']) - for change in contentChanges: - workspace.update_document( - textDocument['uri'], - change, - version=textDocument.get('version') - ) - self.lint(textDocument['uri'], is_saved=False) - - def m_text_document__did_save(self, textDocument=None, **_kwargs): - self.lint(textDocument['uri'], is_saved=True) - - def m_text_document__code_action(self, textDocument=None, range=None, context=None, **_kwargs): - return self.code_actions(textDocument['uri'], range, context) - - def m_text_document__code_lens(self, textDocument=None, **_kwargs): - return self.code_lens(textDocument['uri']) - - def m_text_document__completion(self, textDocument=None, position=None, **_kwargs): - return self.completions(textDocument['uri'], position) - - def m_text_document__definition(self, textDocument=None, position=None, **_kwargs): - return self.definitions(textDocument['uri'], position) - - def m_text_document__document_highlight(self, textDocument=None, position=None, **_kwargs): - return self.highlight(textDocument['uri'], position) - - def m_text_document__hover(self, textDocument=None, position=None, **_kwargs): - return self.hover(textDocument['uri'], position) - - def m_text_document__document_symbol(self, textDocument=None, **_kwargs): - return self.document_symbols(textDocument['uri']) - - def m_text_document__formatting(self, textDocument=None, _options=None, **_kwargs): - # For now we're ignoring formatting options. - return self.format_document(textDocument['uri']) - - def m_text_document__rename(self, textDocument=None, position=None, newName=None, **_kwargs): - return self.rename(textDocument['uri'], position, newName) - - def m_text_document__folding_range(self, textDocument=None, **_kwargs): - return self.folding(textDocument['uri']) - - def m_text_document__range_formatting(self, textDocument=None, range=None, _options=None, **_kwargs): - # Again, we'll ignore formatting options for now. - return self.format_range(textDocument['uri'], range) - - def m_text_document__references(self, textDocument=None, position=None, context=None, **_kwargs): - exclude_declaration = not context['includeDeclaration'] - return self.references(textDocument['uri'], position, exclude_declaration) - - def m_text_document__signature_help(self, textDocument=None, position=None, **_kwargs): - return self.signature_help(textDocument['uri'], position) - - def m_workspace__did_change_configuration(self, settings=None): - self.config.update((settings or {}).get('pyls', {})) - for workspace_uri in self.workspaces: - workspace = self.workspaces[workspace_uri] - workspace.update_config(settings) - for doc_uri in workspace.documents: - self.lint(doc_uri, is_saved=False) - - def m_workspace__did_change_workspace_folders(self, event=None, **_kwargs): # pylint: disable=too-many-locals - if event is None: - return - added = event.get('added', []) - removed = event.get('removed', []) - - for removed_info in removed: - if 'uri' in removed_info: - removed_uri = removed_info['uri'] - self.workspaces.pop(removed_uri, None) - - for added_info in added: - if 'uri' in added_info: - added_uri = added_info['uri'] - workspace_config = config.Config( - added_uri, self.config._init_opts, - self.config._process_id, self.config._capabilities) - workspace_config.update(self.config._settings) - self.workspaces[added_uri] = Workspace( - added_uri, self._endpoint, workspace_config) - - root_workspace_removed = any(removed_info['uri'] == self.root_uri for removed_info in removed) - workspace_added = len(added) > 0 and 'uri' in added[0] - if root_workspace_removed and workspace_added: - added_uri = added[0]['uri'] - self.root_uri = added_uri - new_root_workspace = self.workspaces[added_uri] - self.config = new_root_workspace._config - self.workspace = new_root_workspace - elif root_workspace_removed: - # NOTE: Removing the root workspace can only happen when the server - # is closed, thus the else condition of this if can never happen. - if self.workspaces: - log.debug('Root workspace deleted!') - available_workspaces = sorted(self.workspaces) - first_workspace = available_workspaces[0] - new_root_workspace = self.workspaces[first_workspace] - self.root_uri = first_workspace - self.config = new_root_workspace._config - self.workspace = new_root_workspace - - # Migrate documents that are on the root workspace and have a better - # match now - doc_uris = list(self.workspace._docs.keys()) - for uri in doc_uris: - doc = self.workspace._docs.pop(uri) - new_workspace = self._match_uri_to_workspace(uri) - new_workspace._docs[uri] = doc - - def m_workspace__did_change_watched_files(self, changes=None, **_kwargs): - changed_py_files = set() - config_changed = False - for d in (changes or []): - if d['uri'].endswith(PYTHON_FILE_EXTENSIONS): - changed_py_files.add(d['uri']) - elif d['uri'].endswith(CONFIG_FILEs): - config_changed = True - - if config_changed: - self.config.settings.cache_clear() - elif not changed_py_files: - # Only externally changed python files and lint configs may result in changed diagnostics. - return - - for workspace_uri in self.workspaces: - workspace = self.workspaces[workspace_uri] - for doc_uri in workspace.documents: - # Changes in doc_uri are already handled by m_text_document__did_save - if doc_uri not in changed_py_files: - self.lint(doc_uri, is_saved=False) - - def m_workspace__execute_command(self, command=None, arguments=None): - return self.execute_command(command, arguments) - - -def flatten(list_of_lists): - return [item for lst in list_of_lists for item in lst] - - -def merge(list_of_dicts): - return {k: v for dictionary in list_of_dicts for k, v in dictionary.items()} Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/python_lsp.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/python_lsp.py @@ -0,0 +1,445 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +from functools import partial +import logging +import os +import socketserver +import threading + +from pylsp_jsonrpc.dispatchers import MethodDispatcher +from pylsp_jsonrpc.endpoint import Endpoint +from pylsp_jsonrpc.streams import JsonRpcStreamReader, JsonRpcStreamWriter + +from . import lsp, _utils, uris +from .config import config +from .workspace import Workspace + +log = logging.getLogger(__name__) + + +LINT_DEBOUNCE_S = 0.5 # 500 ms +PARENT_PROCESS_WATCH_INTERVAL = 10 # 10 s +MAX_WORKERS = 64 +PYTHON_FILE_EXTENSIONS = ('.py', '.pyi') +CONFIG_FILEs = ('pycodestyle.cfg', 'setup.cfg', 'tox.ini', '.flake8') + + +class _StreamHandlerWrapper(socketserver.StreamRequestHandler): + """A wrapper class that is used to construct a custom handler class.""" + + delegate = None + + def setup(self): + super().setup() + self.delegate = self.DELEGATE_CLASS(self.rfile, self.wfile) + + def handle(self): + try: + self.delegate.start() + except OSError as e: + if os.name == 'nt': + # Catch and pass on ConnectionResetError when parent process + # dies + # pylint: disable=no-member, undefined-variable + if isinstance(e, WindowsError) and e.winerror == 10054: + pass + + self.SHUTDOWN_CALL() + + +def start_tcp_lang_server(bind_addr, port, check_parent_process, handler_class): + if not issubclass(handler_class, PythonLSPServer): + raise ValueError('Handler class must be an instance of PythonLSPServer') + + def shutdown_server(check_parent_process, *args): + # pylint: disable=unused-argument + if check_parent_process: + log.debug('Shutting down server') + # Shutdown call must be done on a thread, to prevent deadlocks + stop_thread = threading.Thread(target=server.shutdown) + stop_thread.start() + + # Construct a custom wrapper class around the user's handler_class + wrapper_class = type( + handler_class.__name__ + 'Handler', + (_StreamHandlerWrapper,), + {'DELEGATE_CLASS': partial(handler_class, + check_parent_process=check_parent_process), + 'SHUTDOWN_CALL': partial(shutdown_server, check_parent_process)} + ) + + server = socketserver.TCPServer((bind_addr, port), wrapper_class, bind_and_activate=False) + server.allow_reuse_address = True + + try: + server.server_bind() + server.server_activate() + log.info('Serving %s on (%s, %s)', handler_class.__name__, bind_addr, port) + server.serve_forever() + finally: + log.info('Shutting down') + server.server_close() + + +def start_io_lang_server(rfile, wfile, check_parent_process, handler_class): + if not issubclass(handler_class, PythonLSPServer): + raise ValueError('Handler class must be an instance of PythonLSPServer') + log.info('Starting %s IO language server', handler_class.__name__) + server = handler_class(rfile, wfile, check_parent_process) + server.start() + + +class PythonLSPServer(MethodDispatcher): + """ Implementation of the Microsoft VSCode Language Server Protocol + https://github.com/Microsoft/language-server-protocol/blob/master/versions/protocol-1-x.md + """ + + # pylint: disable=too-many-public-methods,redefined-builtin + + def __init__(self, rx, tx, check_parent_process=False): + self.workspace = None + self.config = None + self.root_uri = None + self.watching_thread = None + self.workspaces = {} + self.uri_workspace_mapper = {} + + self._jsonrpc_stream_reader = JsonRpcStreamReader(rx) + self._jsonrpc_stream_writer = JsonRpcStreamWriter(tx) + self._check_parent_process = check_parent_process + self._endpoint = Endpoint(self, self._jsonrpc_stream_writer.write, max_workers=MAX_WORKERS) + self._dispatchers = [] + self._shutdown = False + + def start(self): + """Entry point for the server.""" + self._jsonrpc_stream_reader.listen(self._endpoint.consume) + + def __getitem__(self, item): + """Override getitem to fallback through multiple dispatchers.""" + if self._shutdown and item != 'exit': + # exit is the only allowed method during shutdown + log.debug("Ignoring non-exit method during shutdown: %s", item) + raise KeyError + + try: + return super().__getitem__(item) + except KeyError: + # Fallback through extra dispatchers + for dispatcher in self._dispatchers: + try: + return dispatcher[item] + except KeyError: + continue + + raise KeyError() + + def m_shutdown(self, **_kwargs): + self._shutdown = True + + def m_exit(self, **_kwargs): + self._endpoint.shutdown() + self._jsonrpc_stream_reader.close() + self._jsonrpc_stream_writer.close() + + def _match_uri_to_workspace(self, uri): + workspace_uri = _utils.match_uri_to_workspace(uri, self.workspaces) + return self.workspaces.get(workspace_uri, self.workspace) + + def _hook(self, hook_name, doc_uri=None, **kwargs): + """Calls hook_name and returns a list of results from all registered handlers""" + workspace = self._match_uri_to_workspace(doc_uri) + doc = workspace.get_document(doc_uri) if doc_uri else None + hook_handlers = self.config.plugin_manager.subset_hook_caller(hook_name, self.config.disabled_plugins) + return hook_handlers(config=self.config, workspace=workspace, document=doc, **kwargs) + + def capabilities(self): + server_capabilities = { + 'codeActionProvider': True, + 'codeLensProvider': { + 'resolveProvider': False, # We may need to make this configurable + }, + 'completionProvider': { + 'resolveProvider': False, # We know everything ahead of time + 'triggerCharacters': ['.'] + }, + 'documentFormattingProvider': True, + 'documentHighlightProvider': True, + 'documentRangeFormattingProvider': True, + 'documentSymbolProvider': True, + 'definitionProvider': True, + 'executeCommandProvider': { + 'commands': flatten(self._hook('pylsp_commands')) + }, + 'hoverProvider': True, + 'referencesProvider': True, + 'renameProvider': True, + 'foldingRangeProvider': True, + 'signatureHelpProvider': { + 'triggerCharacters': ['(', ',', '='] + }, + 'textDocumentSync': { + 'change': lsp.TextDocumentSyncKind.INCREMENTAL, + 'save': { + 'includeText': True, + }, + 'openClose': True, + }, + 'workspace': { + 'workspaceFolders': { + 'supported': True, + 'changeNotifications': True + } + }, + 'experimental': merge( + self._hook('pylsp_experimental_capabilities')) + } + log.info('Server capabilities: %s', server_capabilities) + return server_capabilities + + def m_initialize(self, processId=None, rootUri=None, rootPath=None, initializationOptions=None, **_kwargs): + log.debug('Language server initialized with %s %s %s %s', processId, rootUri, rootPath, initializationOptions) + if rootUri is None: + rootUri = uris.from_fs_path(rootPath) if rootPath is not None else '' + + self.workspaces.pop(self.root_uri, None) + self.root_uri = rootUri + self.config = config.Config(rootUri, initializationOptions or {}, + processId, _kwargs.get('capabilities', {})) + self.workspace = Workspace(rootUri, self._endpoint, self.config) + self.workspaces[rootUri] = self.workspace + self._dispatchers = self._hook('pylsp_dispatchers') + self._hook('pylsp_initialize') + + if self._check_parent_process and processId is not None and self.watching_thread is None: + def watch_parent_process(pid): + # exit when the given pid is not alive + if not _utils.is_process_alive(pid): + log.info("parent process %s is not alive, exiting!", pid) + self.m_exit() + else: + threading.Timer(PARENT_PROCESS_WATCH_INTERVAL, watch_parent_process, args=[pid]).start() + + self.watching_thread = threading.Thread(target=watch_parent_process, args=(processId,)) + self.watching_thread.daemon = True + self.watching_thread.start() + # Get our capabilities + return {'capabilities': self.capabilities()} + + def m_initialized(self, **_kwargs): + self._hook('pylsp_initialized') + + def code_actions(self, doc_uri, range, context): + return flatten(self._hook('pylsp_code_actions', doc_uri, range=range, context=context)) + + def code_lens(self, doc_uri): + return flatten(self._hook('pylsp_code_lens', doc_uri)) + + def completions(self, doc_uri, position): + completions = self._hook('pylsp_completions', doc_uri, position=position) + return { + 'isIncomplete': False, + 'items': flatten(completions) + } + + def definitions(self, doc_uri, position): + return flatten(self._hook('pylsp_definitions', doc_uri, position=position)) + + def document_symbols(self, doc_uri): + return flatten(self._hook('pylsp_document_symbols', doc_uri)) + + def execute_command(self, command, arguments): + return self._hook('pylsp_execute_command', command=command, arguments=arguments) + + def format_document(self, doc_uri): + return self._hook('pylsp_format_document', doc_uri) + + def format_range(self, doc_uri, range): + return self._hook('pylsp_format_range', doc_uri, range=range) + + def highlight(self, doc_uri, position): + return flatten(self._hook('pylsp_document_highlight', doc_uri, position=position)) or None + + def hover(self, doc_uri, position): + return self._hook('pylsp_hover', doc_uri, position=position) or {'contents': ''} + + @_utils.debounce(LINT_DEBOUNCE_S, keyed_by='doc_uri') + def lint(self, doc_uri, is_saved): + # Since we're debounced, the document may no longer be open + workspace = self._match_uri_to_workspace(doc_uri) + if doc_uri in workspace.documents: + workspace.publish_diagnostics( + doc_uri, + flatten(self._hook('pylsp_lint', doc_uri, is_saved=is_saved)) + ) + + def references(self, doc_uri, position, exclude_declaration): + return flatten(self._hook( + 'pylsp_references', doc_uri, position=position, + exclude_declaration=exclude_declaration + )) + + def rename(self, doc_uri, position, new_name): + return self._hook('pylsp_rename', doc_uri, position=position, new_name=new_name) + + def signature_help(self, doc_uri, position): + return self._hook('pylsp_signature_help', doc_uri, position=position) + + def folding(self, doc_uri): + return flatten(self._hook('pylsp_folding_range', doc_uri)) + + def m_text_document__did_close(self, textDocument=None, **_kwargs): + workspace = self._match_uri_to_workspace(textDocument['uri']) + workspace.rm_document(textDocument['uri']) + + def m_text_document__did_open(self, textDocument=None, **_kwargs): + workspace = self._match_uri_to_workspace(textDocument['uri']) + workspace.put_document(textDocument['uri'], textDocument['text'], version=textDocument.get('version')) + self._hook('pylsp_document_did_open', textDocument['uri']) + self.lint(textDocument['uri'], is_saved=True) + + def m_text_document__did_change(self, contentChanges=None, textDocument=None, **_kwargs): + workspace = self._match_uri_to_workspace(textDocument['uri']) + for change in contentChanges: + workspace.update_document( + textDocument['uri'], + change, + version=textDocument.get('version') + ) + self.lint(textDocument['uri'], is_saved=False) + + def m_text_document__did_save(self, textDocument=None, **_kwargs): + self.lint(textDocument['uri'], is_saved=True) + + def m_text_document__code_action(self, textDocument=None, range=None, context=None, **_kwargs): + return self.code_actions(textDocument['uri'], range, context) + + def m_text_document__code_lens(self, textDocument=None, **_kwargs): + return self.code_lens(textDocument['uri']) + + def m_text_document__completion(self, textDocument=None, position=None, **_kwargs): + return self.completions(textDocument['uri'], position) + + def m_text_document__definition(self, textDocument=None, position=None, **_kwargs): + return self.definitions(textDocument['uri'], position) + + def m_text_document__document_highlight(self, textDocument=None, position=None, **_kwargs): + return self.highlight(textDocument['uri'], position) + + def m_text_document__hover(self, textDocument=None, position=None, **_kwargs): + return self.hover(textDocument['uri'], position) + + def m_text_document__document_symbol(self, textDocument=None, **_kwargs): + return self.document_symbols(textDocument['uri']) + + def m_text_document__formatting(self, textDocument=None, _options=None, **_kwargs): + # For now we're ignoring formatting options. + return self.format_document(textDocument['uri']) + + def m_text_document__rename(self, textDocument=None, position=None, newName=None, **_kwargs): + return self.rename(textDocument['uri'], position, newName) + + def m_text_document__folding_range(self, textDocument=None, **_kwargs): + return self.folding(textDocument['uri']) + + def m_text_document__range_formatting(self, textDocument=None, range=None, _options=None, **_kwargs): + # Again, we'll ignore formatting options for now. + return self.format_range(textDocument['uri'], range) + + def m_text_document__references(self, textDocument=None, position=None, context=None, **_kwargs): + exclude_declaration = not context['includeDeclaration'] + return self.references(textDocument['uri'], position, exclude_declaration) + + def m_text_document__signature_help(self, textDocument=None, position=None, **_kwargs): + return self.signature_help(textDocument['uri'], position) + + def m_workspace__did_change_configuration(self, settings=None): + self.config.update((settings or {}).get('pylsp', {})) + for workspace_uri in self.workspaces: + workspace = self.workspaces[workspace_uri] + workspace.update_config(settings) + for doc_uri in workspace.documents: + self.lint(doc_uri, is_saved=False) + + def m_workspace__did_change_workspace_folders(self, event=None, **_kwargs): # pylint: disable=too-many-locals + if event is None: + return + added = event.get('added', []) + removed = event.get('removed', []) + + for removed_info in removed: + if 'uri' in removed_info: + removed_uri = removed_info['uri'] + self.workspaces.pop(removed_uri, None) + + for added_info in added: + if 'uri' in added_info: + added_uri = added_info['uri'] + workspace_config = config.Config( + added_uri, self.config._init_opts, + self.config._process_id, self.config._capabilities) + workspace_config.update(self.config._settings) + self.workspaces[added_uri] = Workspace( + added_uri, self._endpoint, workspace_config) + + root_workspace_removed = any(removed_info['uri'] == self.root_uri for removed_info in removed) + workspace_added = len(added) > 0 and 'uri' in added[0] + if root_workspace_removed and workspace_added: + added_uri = added[0]['uri'] + self.root_uri = added_uri + new_root_workspace = self.workspaces[added_uri] + self.config = new_root_workspace._config + self.workspace = new_root_workspace + elif root_workspace_removed: + # NOTE: Removing the root workspace can only happen when the server + # is closed, thus the else condition of this if can never happen. + if self.workspaces: + log.debug('Root workspace deleted!') + available_workspaces = sorted(self.workspaces) + first_workspace = available_workspaces[0] + new_root_workspace = self.workspaces[first_workspace] + self.root_uri = first_workspace + self.config = new_root_workspace._config + self.workspace = new_root_workspace + + # Migrate documents that are on the root workspace and have a better + # match now + doc_uris = list(self.workspace._docs.keys()) + for uri in doc_uris: + doc = self.workspace._docs.pop(uri) + new_workspace = self._match_uri_to_workspace(uri) + new_workspace._docs[uri] = doc + + def m_workspace__did_change_watched_files(self, changes=None, **_kwargs): + changed_py_files = set() + config_changed = False + for d in (changes or []): + if d['uri'].endswith(PYTHON_FILE_EXTENSIONS): + changed_py_files.add(d['uri']) + elif d['uri'].endswith(CONFIG_FILEs): + config_changed = True + + if config_changed: + self.config.settings.cache_clear() + elif not changed_py_files: + # Only externally changed python files and lint configs may result in changed diagnostics. + return + + for workspace_uri in self.workspaces: + workspace = self.workspaces[workspace_uri] + for doc_uri in workspace.documents: + # Changes in doc_uri are already handled by m_text_document__did_save + if doc_uri not in changed_py_files: + self.lint(doc_uri, is_saved=False) + + def m_workspace__execute_command(self, command=None, arguments=None): + return self.execute_command(command, arguments) + + +def flatten(list_of_lists): + return [item for lst in list_of_lists for item in lst] + + +def merge(list_of_dicts): + return {k: v for dictionary in list_of_dicts for k, v in dictionary.items()} Index: spyder-5.0.5/external-deps/python-language-server/pyls/uris.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/uris.py +++ /dev/null @@ -1,129 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -"""A collection of URI utilities with logic built on the VSCode URI library. - -https://github.com/Microsoft/vscode-uri/blob/e59cab84f5df6265aed18ae5f43552d3eef13bb9/lib/index.ts -""" -import re -from urllib import parse -from pyls import IS_WIN - -RE_DRIVE_LETTER_PATH = re.compile(r'^\/[a-zA-Z]:') - - -def urlparse(uri): - """Parse and decode the parts of a URI.""" - scheme, netloc, path, params, query, fragment = parse.urlparse(uri) - return ( - parse.unquote(scheme), - parse.unquote(netloc), - parse.unquote(path), - parse.unquote(params), - parse.unquote(query), - parse.unquote(fragment) - ) - - -def urlunparse(parts): - """Unparse and encode parts of a URI.""" - scheme, netloc, path, params, query, fragment = parts - - # Avoid encoding the windows drive letter colon - if RE_DRIVE_LETTER_PATH.match(path): - quoted_path = path[:3] + parse.quote(path[3:]) - else: - quoted_path = parse.quote(path) - - return parse.urlunparse(( - parse.quote(scheme), - parse.quote(netloc), - quoted_path, - parse.quote(params), - parse.quote(query), - parse.quote(fragment) - )) - - -def to_fs_path(uri): - """Returns the filesystem path of the given URI. - - Will handle UNC paths and normalize windows drive letters to lower-case. Also - uses the platform specific path separator. Will *not* validate the path for - invalid characters and semantics. Will *not* look at the scheme of this URI. - """ - # scheme://netloc/path;parameters?query#fragment - scheme, netloc, path, _params, _query, _fragment = urlparse(uri) - - if netloc and path and scheme == 'file': - # unc path: file://shares/c$/far/boo - value = "//{}{}".format(netloc, path) - - elif RE_DRIVE_LETTER_PATH.match(path): - # windows drive letter: file:///C:/far/boo - value = path[1].lower() + path[2:] - - else: - # Other path - value = path - - if IS_WIN: - value = value.replace('/', '\\') - - return value - - -def from_fs_path(path): - """Returns a URI for the given filesystem path.""" - scheme = 'file' - params, query, fragment = '', '', '' - path, netloc = _normalize_win_path(path) - return urlunparse((scheme, netloc, path, params, query, fragment)) - - -def uri_with(uri, scheme=None, netloc=None, path=None, params=None, query=None, fragment=None): - """Return a URI with the given part(s) replaced. - - Parts are decoded / encoded. - """ - old_scheme, old_netloc, old_path, old_params, old_query, old_fragment = urlparse(uri) - path, _netloc = _normalize_win_path(path) - return urlunparse(( - scheme or old_scheme, - netloc or old_netloc, - path or old_path, - params or old_params, - query or old_query, - fragment or old_fragment - )) - - -def _normalize_win_path(path): - netloc = '' - - # normalize to fwd-slashes on windows, - # on other systems bwd-slaches are valid - # filename character, eg /f\oo/ba\r.txt - if IS_WIN: - path = path.replace('\\', '/') - - # check for authority as used in UNC shares - # or use the path as given - if path[:2] == '//': - idx = path.index('/', 2) - if idx == -1: - netloc = path[2:] - else: - netloc = path[2:idx] - path = path[idx:] - else: - path = path - - # Ensure that path starts with a slash - # or that it is at least a slash - if not path.startswith('/'): - path = '/' + path - - # Normalize drive paths to lower case - if RE_DRIVE_LETTER_PATH.match(path): - path = path[0] + path[1].lower() + path[2:] - - return path, netloc Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/uris.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/uris.py @@ -0,0 +1,129 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +"""A collection of URI utilities with logic built on the VSCode URI library. + +https://github.com/Microsoft/vscode-uri/blob/e59cab84f5df6265aed18ae5f43552d3eef13bb9/lib/index.ts +""" +import re +from urllib import parse +from pylsp import IS_WIN + +RE_DRIVE_LETTER_PATH = re.compile(r'^\/[a-zA-Z]:') + + +def urlparse(uri): + """Parse and decode the parts of a URI.""" + scheme, netloc, path, params, query, fragment = parse.urlparse(uri) + return ( + parse.unquote(scheme), + parse.unquote(netloc), + parse.unquote(path), + parse.unquote(params), + parse.unquote(query), + parse.unquote(fragment) + ) + + +def urlunparse(parts): + """Unparse and encode parts of a URI.""" + scheme, netloc, path, params, query, fragment = parts + + # Avoid encoding the windows drive letter colon + if RE_DRIVE_LETTER_PATH.match(path): + quoted_path = path[:3] + parse.quote(path[3:]) + else: + quoted_path = parse.quote(path) + + return parse.urlunparse(( + parse.quote(scheme), + parse.quote(netloc), + quoted_path, + parse.quote(params), + parse.quote(query), + parse.quote(fragment) + )) + + +def to_fs_path(uri): + """Returns the filesystem path of the given URI. + + Will handle UNC paths and normalize windows drive letters to lower-case. Also + uses the platform specific path separator. Will *not* validate the path for + invalid characters and semantics. Will *not* look at the scheme of this URI. + """ + # scheme://netloc/path;parameters?query#fragment + scheme, netloc, path, _params, _query, _fragment = urlparse(uri) + + if netloc and path and scheme == 'file': + # unc path: file://shares/c$/far/boo + value = "//{}{}".format(netloc, path) + + elif RE_DRIVE_LETTER_PATH.match(path): + # windows drive letter: file:///C:/far/boo + value = path[1].lower() + path[2:] + + else: + # Other path + value = path + + if IS_WIN: + value = value.replace('/', '\\') + + return value + + +def from_fs_path(path): + """Returns a URI for the given filesystem path.""" + scheme = 'file' + params, query, fragment = '', '', '' + path, netloc = _normalize_win_path(path) + return urlunparse((scheme, netloc, path, params, query, fragment)) + + +def uri_with(uri, scheme=None, netloc=None, path=None, params=None, query=None, fragment=None): + """Return a URI with the given part(s) replaced. + + Parts are decoded / encoded. + """ + old_scheme, old_netloc, old_path, old_params, old_query, old_fragment = urlparse(uri) + path, _netloc = _normalize_win_path(path) + return urlunparse(( + scheme or old_scheme, + netloc or old_netloc, + path or old_path, + params or old_params, + query or old_query, + fragment or old_fragment + )) + + +def _normalize_win_path(path): + netloc = '' + + # normalize to fwd-slashes on windows, + # on other systems bwd-slaches are valid + # filename character, eg /f\oo/ba\r.txt + if IS_WIN: + path = path.replace('\\', '/') + + # check for authority as used in UNC shares + # or use the path as given + if path[:2] == '//': + idx = path.index('/', 2) + if idx == -1: + netloc = path[2:] + else: + netloc = path[2:idx] + path = path[idx:] + + # Ensure that path starts with a slash + # or that it is at least a slash + if not path.startswith('/'): + path = '/' + path + + # Normalize drive paths to lower case + if RE_DRIVE_LETTER_PATH.match(path): + path = path[0] + path[1].lower() + path[2:] + + return path, netloc Index: spyder-5.0.5/external-deps/python-language-server/pyls/workspace.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/pyls/workspace.py +++ /dev/null @@ -1,302 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import io -import logging -import os -import re -import functools -from threading import RLock - -import jedi - -from . import lsp, uris, _utils - -log = logging.getLogger(__name__) - -# TODO: this is not the best e.g. we capture numbers -RE_START_WORD = re.compile('[A-Za-z_0-9]*$') -RE_END_WORD = re.compile('^[A-Za-z_0-9]*') - - -def lock(method): - """Define an atomic region over a method.""" - @functools.wraps(method) - def wrapper(self, *args, **kwargs): - with self._lock: - return method(self, *args, **kwargs) - return wrapper - - -class Workspace(object): - - M_PUBLISH_DIAGNOSTICS = 'textDocument/publishDiagnostics' - M_APPLY_EDIT = 'workspace/applyEdit' - M_SHOW_MESSAGE = 'window/showMessage' - - def __init__(self, root_uri, endpoint, config=None): - self._config = config - self._root_uri = root_uri - self._endpoint = endpoint - self._root_uri_scheme = uris.urlparse(self._root_uri)[0] - self._root_path = uris.to_fs_path(self._root_uri) - self._docs = {} - - # Cache jedi environments - self._environments = {} - - # Whilst incubating, keep rope private - self.__rope = None - self.__rope_config = None - - def _rope_project_builder(self, rope_config): - from rope.base.project import Project - - # TODO: we could keep track of dirty files and validate only those - if self.__rope is None or self.__rope_config != rope_config: - rope_folder = rope_config.get('ropeFolder') - self.__rope = Project(self._root_path, ropefolder=rope_folder) - self.__rope.prefs.set('extension_modules', rope_config.get('extensionModules', [])) - self.__rope.prefs.set('ignore_syntax_errors', True) - self.__rope.prefs.set('ignore_bad_imports', True) - self.__rope.validate() - return self.__rope - - @property - def documents(self): - return self._docs - - @property - def root_path(self): - return self._root_path - - @property - def root_uri(self): - return self._root_uri - - def is_local(self): - return (self._root_uri_scheme == '' or self._root_uri_scheme == 'file') and os.path.exists(self._root_path) - - def get_document(self, doc_uri): - """Return a managed document if-present, else create one pointing at disk. - - See https://github.com/Microsoft/language-server-protocol/issues/177 - """ - return self._docs.get(doc_uri) or self._create_document(doc_uri) - - def get_maybe_document(self, doc_uri): - return self._docs.get(doc_uri) - - def put_document(self, doc_uri, source, version=None): - self._docs[doc_uri] = self._create_document(doc_uri, source=source, version=version) - - def rm_document(self, doc_uri): - self._docs.pop(doc_uri) - - def update_document(self, doc_uri, change, version=None): - self._docs[doc_uri].apply_change(change) - self._docs[doc_uri].version = version - - def update_config(self, settings): - self._config.update((settings or {}).get('pyls', {})) - for doc_uri in self.documents: - self.get_document(doc_uri).update_config(settings) - - def apply_edit(self, edit): - return self._endpoint.request(self.M_APPLY_EDIT, {'edit': edit}) - - def publish_diagnostics(self, doc_uri, diagnostics): - self._endpoint.notify(self.M_PUBLISH_DIAGNOSTICS, params={'uri': doc_uri, 'diagnostics': diagnostics}) - - def show_message(self, message, msg_type=lsp.MessageType.Info): - self._endpoint.notify(self.M_SHOW_MESSAGE, params={'type': msg_type, 'message': message}) - - def source_roots(self, document_path): - """Return the source roots for the given document.""" - files = _utils.find_parents(self._root_path, document_path, ['setup.py', 'pyproject.toml']) or [] - return list({os.path.dirname(project_file) for project_file in files}) or [self._root_path] - - def _create_document(self, doc_uri, source=None, version=None): - path = uris.to_fs_path(doc_uri) - return Document( - doc_uri, - self, - source=source, - version=version, - extra_sys_path=self.source_roots(path), - rope_project_builder=self._rope_project_builder, - ) - - -class Document(object): - - def __init__(self, uri, workspace, source=None, version=None, local=True, extra_sys_path=None, - rope_project_builder=None): - self.uri = uri - self.version = version - self.path = uris.to_fs_path(uri) - self.dot_path = _utils.path_to_dot_name(self.path) - self.filename = os.path.basename(self.path) - - self._config = workspace._config - self._workspace = workspace - self._local = local - self._source = source - self._extra_sys_path = extra_sys_path or [] - self._rope_project_builder = rope_project_builder - self._lock = RLock() - - def __str__(self): - return str(self.uri) - - def _rope_resource(self, rope_config): - from rope.base import libutils - return libutils.path_to_resource(self._rope_project_builder(rope_config), self.path) - - @property - @lock - def lines(self): - return self.source.splitlines(True) - - @property - @lock - def source(self): - if self._source is None: - with io.open(self.path, 'r', encoding='utf-8') as f: - return f.read() - return self._source - - def update_config(self, settings): - self._config.update((settings or {}).get('pyls', {})) - - @lock - def apply_change(self, change): - """Apply a change to the document.""" - text = change['text'] - change_range = change.get('range') - - if not change_range: - # The whole file has changed - self._source = text - return - - start_line = change_range['start']['line'] - start_col = change_range['start']['character'] - end_line = change_range['end']['line'] - end_col = change_range['end']['character'] - - # Check for an edit occuring at the very end of the file - if start_line == len(self.lines): - self._source = self.source + text - return - - new = io.StringIO() - - # Iterate over the existing document until we hit the edit range, - # at which point we write the new text, then loop until we hit - # the end of the range and continue writing. - for i, line in enumerate(self.lines): - if i < start_line: - new.write(line) - continue - - if i > end_line: - new.write(line) - continue - - if i == start_line: - new.write(line[:start_col]) - new.write(text) - - if i == end_line: - new.write(line[end_col:]) - - self._source = new.getvalue() - - def offset_at_position(self, position): - """Return the byte-offset pointed at by the given position.""" - return position['character'] + len(''.join(self.lines[:position['line']])) - - def word_at_position(self, position): - """Get the word under the cursor returning the start and end positions.""" - if position['line'] >= len(self.lines): - return '' - - line = self.lines[position['line']] - i = position['character'] - # Split word in two - start = line[:i] - end = line[i:] - - # Take end of start and start of end to find word - # These are guaranteed to match, even if they match the empty string - m_start = RE_START_WORD.findall(start) - m_end = RE_END_WORD.findall(end) - - return m_start[0] + m_end[-1] - - @lock - def jedi_names(self, use_document_path, all_scopes=False, definitions=True, references=False): - script = self.jedi_script(use_document_path=use_document_path) - return script.get_names(all_scopes=all_scopes, definitions=definitions, - references=references) - - @lock - def jedi_script(self, position=None, use_document_path=False): - extra_paths = [] - environment_path = None - env_vars = None - - if self._config: - jedi_settings = self._config.plugin_settings('jedi', document_path=self.path) - environment_path = jedi_settings.get('environment') - extra_paths = jedi_settings.get('extra_paths') or [] - env_vars = jedi_settings.get('env_vars') - - # Drop PYTHONPATH from env_vars before creating the environment because that makes - # Jedi throw an error. - if env_vars is None: - env_vars = os.environ.copy() - env_vars.pop('PYTHONPATH', None) - - environment = self.get_enviroment(environment_path, env_vars=env_vars) if environment_path else None - sys_path = self.sys_path(environment_path, env_vars=env_vars) + extra_paths - project_path = self._workspace.root_path - - # Extend sys_path with document's path if requested - if use_document_path: - sys_path += [os.path.normpath(os.path.dirname(self.path))] - - kwargs = { - 'code': self.source, - 'path': self.path, - 'environment': environment, - 'project': jedi.Project(path=project_path, sys_path=sys_path), - } - - if position: - # Deprecated by Jedi to use in Script() constructor - kwargs += _utils.position_to_jedi_linecolumn(self, position) - - return jedi.Script(**kwargs) - - def get_enviroment(self, environment_path=None, env_vars=None): - # TODO(gatesn): #339 - make better use of jedi environments, they seem pretty powerful - if environment_path is None: - environment = jedi.api.environment.get_cached_default_environment() - else: - if environment_path in self._workspace._environments: - environment = self._workspace._environments[environment_path] - else: - environment = jedi.api.environment.create_environment(path=environment_path, - safe=False, - env_vars=env_vars) - self._workspace._environments[environment_path] = environment - - return environment - - def sys_path(self, environment_path=None, env_vars=None): - # Copy our extra sys path - # TODO: when safe to break API, use env_vars explicitly to pass to create_environment - path = list(self._extra_sys_path) - environment = self.get_enviroment(environment_path=environment_path, env_vars=env_vars) - path.extend(environment.get_sys_path()) - return path Index: spyder-5.0.5/external-deps/python-lsp-server/pylsp/workspace.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/pylsp/workspace.py @@ -0,0 +1,306 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import io +import logging +import os +import re +import functools +from threading import RLock + +import jedi + +from . import lsp, uris, _utils + +log = logging.getLogger(__name__) + +# TODO: this is not the best e.g. we capture numbers +RE_START_WORD = re.compile('[A-Za-z_0-9]*$') +RE_END_WORD = re.compile('^[A-Za-z_0-9]*') + + +def lock(method): + """Define an atomic region over a method.""" + @functools.wraps(method) + def wrapper(self, *args, **kwargs): + with self._lock: + return method(self, *args, **kwargs) + return wrapper + + +class Workspace: + + M_PUBLISH_DIAGNOSTICS = 'textDocument/publishDiagnostics' + M_APPLY_EDIT = 'workspace/applyEdit' + M_SHOW_MESSAGE = 'window/showMessage' + + def __init__(self, root_uri, endpoint, config=None): + self._config = config + self._root_uri = root_uri + self._endpoint = endpoint + self._root_uri_scheme = uris.urlparse(self._root_uri)[0] + self._root_path = uris.to_fs_path(self._root_uri) + self._docs = {} + + # Cache jedi environments + self._environments = {} + + # Whilst incubating, keep rope private + self.__rope = None + self.__rope_config = None + + def _rope_project_builder(self, rope_config): + # pylint: disable=import-outside-toplevel + from rope.base.project import Project + + # TODO: we could keep track of dirty files and validate only those + if self.__rope is None or self.__rope_config != rope_config: + rope_folder = rope_config.get('ropeFolder') + self.__rope = Project(self._root_path, ropefolder=rope_folder) + self.__rope.prefs.set('extension_modules', rope_config.get('extensionModules', [])) + self.__rope.prefs.set('ignore_syntax_errors', True) + self.__rope.prefs.set('ignore_bad_imports', True) + self.__rope.validate() + return self.__rope + + @property + def documents(self): + return self._docs + + @property + def root_path(self): + return self._root_path + + @property + def root_uri(self): + return self._root_uri + + def is_local(self): + return (self._root_uri_scheme == '' or self._root_uri_scheme == 'file') and os.path.exists(self._root_path) + + def get_document(self, doc_uri): + """Return a managed document if-present, else create one pointing at disk. + + See https://github.com/Microsoft/language-server-protocol/issues/177 + """ + return self._docs.get(doc_uri) or self._create_document(doc_uri) + + def get_maybe_document(self, doc_uri): + return self._docs.get(doc_uri) + + def put_document(self, doc_uri, source, version=None): + self._docs[doc_uri] = self._create_document(doc_uri, source=source, version=version) + + def rm_document(self, doc_uri): + self._docs.pop(doc_uri) + + def update_document(self, doc_uri, change, version=None): + self._docs[doc_uri].apply_change(change) + self._docs[doc_uri].version = version + + def update_config(self, settings): + self._config.update((settings or {}).get('pylsp', {})) + for doc_uri in self.documents: + self.get_document(doc_uri).update_config(settings) + + def apply_edit(self, edit): + return self._endpoint.request(self.M_APPLY_EDIT, {'edit': edit}) + + def publish_diagnostics(self, doc_uri, diagnostics): + self._endpoint.notify(self.M_PUBLISH_DIAGNOSTICS, params={'uri': doc_uri, 'diagnostics': diagnostics}) + + def show_message(self, message, msg_type=lsp.MessageType.Info): + self._endpoint.notify(self.M_SHOW_MESSAGE, params={'type': msg_type, 'message': message}) + + def source_roots(self, document_path): + """Return the source roots for the given document.""" + files = _utils.find_parents(self._root_path, document_path, ['setup.py', 'pyproject.toml']) or [] + return list({os.path.dirname(project_file) for project_file in files}) or [self._root_path] + + def _create_document(self, doc_uri, source=None, version=None): + path = uris.to_fs_path(doc_uri) + return Document( + doc_uri, + self, + source=source, + version=version, + extra_sys_path=self.source_roots(path), + rope_project_builder=self._rope_project_builder, + ) + + +class Document: + + def __init__(self, uri, workspace, source=None, version=None, local=True, extra_sys_path=None, + rope_project_builder=None): + self.uri = uri + self.version = version + self.path = uris.to_fs_path(uri) + self.dot_path = _utils.path_to_dot_name(self.path) + self.filename = os.path.basename(self.path) + + self._config = workspace._config + self._workspace = workspace + self._local = local + self._source = source + self._extra_sys_path = extra_sys_path or [] + self._rope_project_builder = rope_project_builder + self._lock = RLock() + + def __str__(self): + return str(self.uri) + + def _rope_resource(self, rope_config): + # pylint: disable=import-outside-toplevel + from rope.base import libutils + return libutils.path_to_resource(self._rope_project_builder(rope_config), self.path) + + @property + @lock + def lines(self): + return self.source.splitlines(True) + + @property + @lock + def source(self): + if self._source is None: + with io.open(self.path, 'r', encoding='utf-8') as f: + return f.read() + return self._source + + def update_config(self, settings): + self._config.update((settings or {}).get('pylsp', {})) + + @lock + def apply_change(self, change): + """Apply a change to the document.""" + text = change['text'] + change_range = change.get('range') + + if not change_range: + # The whole file has changed + self._source = text + return + + start_line = change_range['start']['line'] + start_col = change_range['start']['character'] + end_line = change_range['end']['line'] + end_col = change_range['end']['character'] + + # Check for an edit occuring at the very end of the file + if start_line == len(self.lines): + self._source = self.source + text + return + + new = io.StringIO() + + # Iterate over the existing document until we hit the edit range, + # at which point we write the new text, then loop until we hit + # the end of the range and continue writing. + for i, line in enumerate(self.lines): + if i < start_line: + new.write(line) + continue + + if i > end_line: + new.write(line) + continue + + if i == start_line: + new.write(line[:start_col]) + new.write(text) + + if i == end_line: + new.write(line[end_col:]) + + self._source = new.getvalue() + + def offset_at_position(self, position): + """Return the byte-offset pointed at by the given position.""" + return position['character'] + len(''.join(self.lines[:position['line']])) + + def word_at_position(self, position): + """Get the word under the cursor returning the start and end positions.""" + if position['line'] >= len(self.lines): + return '' + + line = self.lines[position['line']] + i = position['character'] + # Split word in two + start = line[:i] + end = line[i:] + + # Take end of start and start of end to find word + # These are guaranteed to match, even if they match the empty string + m_start = RE_START_WORD.findall(start) + m_end = RE_END_WORD.findall(end) + + return m_start[0] + m_end[-1] + + @lock + def jedi_names(self, use_document_path, all_scopes=False, definitions=True, references=False): + script = self.jedi_script(use_document_path=use_document_path) + return script.get_names(all_scopes=all_scopes, definitions=definitions, + references=references) + + @lock + def jedi_script(self, position=None, use_document_path=False): + extra_paths = [] + environment_path = None + env_vars = None + + if self._config: + jedi_settings = self._config.plugin_settings('jedi', document_path=self.path) + environment_path = jedi_settings.get('environment') + extra_paths = jedi_settings.get('extra_paths') or [] + env_vars = jedi_settings.get('env_vars') + + # Drop PYTHONPATH from env_vars before creating the environment because that makes + # Jedi throw an error. + if env_vars is None: + env_vars = os.environ.copy() + env_vars.pop('PYTHONPATH', None) + + environment = self.get_enviroment(environment_path, env_vars=env_vars) if environment_path else None + sys_path = self.sys_path(environment_path, env_vars=env_vars) + extra_paths + project_path = self._workspace.root_path + + # Extend sys_path with document's path if requested + if use_document_path: + sys_path += [os.path.normpath(os.path.dirname(self.path))] + + kwargs = { + 'code': self.source, + 'path': self.path, + 'environment': environment, + 'project': jedi.Project(path=project_path, sys_path=sys_path), + } + + if position: + # Deprecated by Jedi to use in Script() constructor + kwargs += _utils.position_to_jedi_linecolumn(self, position) + + return jedi.Script(**kwargs) + + def get_enviroment(self, environment_path=None, env_vars=None): + # TODO(gatesn): #339 - make better use of jedi environments, they seem pretty powerful + if environment_path is None: + environment = jedi.api.environment.get_cached_default_environment() + else: + if environment_path in self._workspace._environments: + environment = self._workspace._environments[environment_path] + else: + environment = jedi.api.environment.create_environment(path=environment_path, + safe=False, + env_vars=env_vars) + self._workspace._environments[environment_path] = environment + + return environment + + def sys_path(self, environment_path=None, env_vars=None): + # Copy our extra sys path + # TODO: when safe to break API, use env_vars explicitly to pass to create_environment + path = list(self._extra_sys_path) + environment = self.get_enviroment(environment_path=environment_path, env_vars=env_vars) + path.extend(environment.get_sys_path()) + return path Index: spyder-5.0.5/external-deps/python-language-server/setup.cfg =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/setup.cfg +++ /dev/null @@ -1,18 +0,0 @@ -[versioneer] -VCS = git -style = pep440 -versionfile_source = pyls/_version.py -versionfile_build = pyls/_version.py -tag_prefix = -parentdir_prefix = - -[pycodestyle] -ignore = E226, E722, W504 -max-line-length = 120 -exclude = test/plugins/.ropeproject,test/.ropeproject - -[tool:pytest] -testpaths = test -addopts = - --cov-report html --cov-report term --junitxml=pytest.xml - --cov pyls --cov test Index: spyder-5.0.5/external-deps/python-lsp-server/setup.cfg =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/setup.cfg @@ -0,0 +1,10 @@ +[pycodestyle] +ignore = E226, E722, W504 +max-line-length = 120 +exclude = test/plugins/.ropeproject,test/.ropeproject + +[tool:pytest] +testpaths = test +addopts = + --cov-report html --cov-report term --junitxml=pytest.xml + --cov pylsp --cov test Index: spyder-5.0.5/external-deps/python-lsp-server/setup.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/setup.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python + +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import ast +import os +from setuptools import find_packages, setup + +HERE = os.path.abspath(os.path.dirname(__file__)) + + +def get_version(module='pylsp'): + """Get version.""" + with open(os.path.join(HERE, module, '_version.py'), 'r') as f: + data = f.read() + lines = data.split('\n') + for line in lines: + if line.startswith('VERSION_INFO'): + version_tuple = ast.literal_eval(line.split('=')[-1].strip()) + version = '.'.join(map(str, version_tuple)) + break + return version + + +README = open('README.md', 'r').read() + +install_requires = [ + 'jedi>=0.17.2,<0.19.0', + 'python-lsp-jsonrpc>=1.0.0', + 'pluggy', + 'ujson>=3.0.0', + 'setuptools>=39.0.0' +] + +setup( + name='python-lsp-server', + version=get_version(), + description='Python Language Server for the Language Server Protocol', + long_description=README, + long_description_content_type='text/markdown', + url='https://github.com/python-lsp/python-lsp-server', + author='Python Language Server Contributors', + packages=find_packages(exclude=['contrib', 'docs', 'test', 'test.*']), + install_requires=install_requires, + python_requires='>=3.6', + extras_require={ + 'all': [ + 'autopep8', + 'flake8>=3.8.0', + 'mccabe>=0.6.0,<0.7.0', + 'pycodestyle>=2.7.0', + 'pydocstyle>=2.0.0', + 'pyflakes>=2.3.0,<2.4.0', + 'pylint>=2.5.0', + 'rope>=0.10.5', + 'yapf', + ], + 'autopep8': ['autopep8'], + 'flake8': ['flake8>=3.8.0'], + 'mccabe': ['mccabe>=0.6.0,<0.7.0'], + 'pycodestyle': ['pycodestyle>=2.7.0'], + 'pydocstyle': ['pydocstyle>=2.0.0'], + 'pyflakes': ['pyflakes>=2.3.0,<2.4.0'], + 'pylint': ['pylint>=2.5.0'], + 'rope': ['rope>0.10.5'], + 'yapf': ['yapf'], + 'test': ['pylint>=2.5.0', 'pytest', 'pytest-cov', 'coverage', 'numpy', + 'pandas', 'matplotlib', 'pyqt5', 'flaky'], + }, + entry_points={ + 'console_scripts': [ + 'pylsp = pylsp.__main__:main', + ], + 'pylsp': [ + 'autopep8 = pylsp.plugins.autopep8_format', + 'folding = pylsp.plugins.folding', + 'flake8 = pylsp.plugins.flake8_lint', + 'jedi_completion = pylsp.plugins.jedi_completion', + 'jedi_definition = pylsp.plugins.definition', + 'jedi_hover = pylsp.plugins.hover', + 'jedi_highlight = pylsp.plugins.highlight', + 'jedi_references = pylsp.plugins.references', + 'jedi_rename = pylsp.plugins.jedi_rename', + 'jedi_signature_help = pylsp.plugins.signature', + 'jedi_symbols = pylsp.plugins.symbols', + 'mccabe = pylsp.plugins.mccabe_lint', + 'preload = pylsp.plugins.preload_imports', + 'pycodestyle = pylsp.plugins.pycodestyle_lint', + 'pydocstyle = pylsp.plugins.pydocstyle_lint', + 'pyflakes = pylsp.plugins.pyflakes_lint', + 'pylint = pylsp.plugins.pylint_lint', + 'rope_completion = pylsp.plugins.rope_completion', + 'rope_rename = pylsp.plugins.rope_rename', + 'yapf = pylsp.plugins.yapf_format' + ] + }, +) Index: spyder-5.0.5/external-deps/python-language-server/test/__init__.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import sys -import pytest -from pyls import IS_WIN - -IS_PY3 = sys.version_info.major == 3 - -unix_only = pytest.mark.skipif(IS_WIN, reason="Unix only") -windows_only = pytest.mark.skipif(not IS_WIN, reason="Windows only") -py3_only = pytest.mark.skipif(not IS_PY3, reason="Python3 only") -py2_only = pytest.mark.skipif(IS_PY3, reason="Python2 only") Index: spyder-5.0.5/external-deps/python-lsp-server/test/__init__.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import sys +import pytest +from pylsp import IS_WIN + +IS_PY3 = sys.version_info.major == 3 + +unix_only = pytest.mark.skipif(IS_WIN, reason="Unix only") +windows_only = pytest.mark.skipif(not IS_WIN, reason="Windows only") +py3_only = pytest.mark.skipif(not IS_PY3, reason="Python3 only") +py2_only = pytest.mark.skipif(IS_PY3, reason="Python2 only") Index: spyder-5.0.5/external-deps/python-language-server/test/conftest.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/conftest.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -""" py.test configuration""" -import logging -from pyls.__main__ import LOG_FORMAT - -logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT) - - -pytest_plugins = [ - 'test.fixtures' -] Index: spyder-5.0.5/external-deps/python-lsp-server/test/conftest.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/conftest.py @@ -0,0 +1,13 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +""" py.test configuration""" +import logging +from pylsp.__main__ import LOG_FORMAT + +logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT) + + +pytest_plugins = [ + 'test.fixtures' +] Index: spyder-5.0.5/external-deps/python-language-server/test/fixtures.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/fixtures.py +++ /dev/null @@ -1,84 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import os -import sys -from mock import Mock -import pytest - -from pyls import uris -from pyls.config.config import Config -from pyls.python_ls import PythonLanguageServer -from pyls.workspace import Workspace, Document - -if sys.version_info[0] < 3: - from StringIO import StringIO -else: - from io import StringIO - -DOC_URI = uris.from_fs_path(__file__) -DOC = """import sys - -def main(): - print sys.stdin.read() -""" - - -@pytest.fixture -def pyls(tmpdir): - """ Return an initialized python LS """ - ls = PythonLanguageServer(StringIO, StringIO) - - ls.m_initialize( - processId=1, - rootUri=uris.from_fs_path(str(tmpdir)), - initializationOptions={} - ) - - return ls - - -@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 workspace_other_root_path(tmpdir): - """Return a workspace with a root_path other than tmpdir.""" - ws_path = str(tmpdir.mkdir('test123').mkdir('test456')) - ws = Workspace(uris.from_fs_path(ws_path), Mock()) - ws._config = Config(ws.root_uri, {}, 0, {}) - return ws - - -@pytest.fixture -def config(workspace): # pylint: disable=redefined-outer-name - """Return a config object.""" - return Config(workspace.root_uri, {}, 0, {}) - - -@pytest.fixture -def doc(workspace): # pylint: disable=redefined-outer-name - return Document(DOC_URI, workspace, DOC) - - -@pytest.fixture -def temp_workspace_factory(workspace): # pylint: disable=redefined-outer-name - ''' - Returns a function that creates a temporary workspace from the files dict. - The dict is in the format {"file_name": "file_contents"} - ''' - def fn(files): - def create_file(name, content): - fn = os.path.join(workspace.root_path, name) - with open(fn, 'w') as f: - f.write(content) - workspace.put_document(uris.from_fs_path(fn), content) - - for name, content in files.items(): - create_file(name, content) - return workspace - - return fn Index: spyder-5.0.5/external-deps/python-lsp-server/test/fixtures.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/fixtures.py @@ -0,0 +1,82 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import os +from io import StringIO +from unittest.mock import Mock +import pytest + +from pylsp import uris +from pylsp.config.config import Config +from pylsp.python_lsp import PythonLSPServer +from pylsp.workspace import Workspace, Document + + +DOC_URI = uris.from_fs_path(__file__) +DOC = """import sys + +def main(): + print sys.stdin.read() +""" + + +@pytest.fixture +def pylsp(tmpdir): + """ Return an initialized python LS """ + ls = PythonLSPServer(StringIO, StringIO) + + ls.m_initialize( + processId=1, + rootUri=uris.from_fs_path(str(tmpdir)), + initializationOptions={} + ) + + return ls + + +@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 workspace_other_root_path(tmpdir): + """Return a workspace with a root_path other than tmpdir.""" + ws_path = str(tmpdir.mkdir('test123').mkdir('test456')) + ws = Workspace(uris.from_fs_path(ws_path), Mock()) + ws._config = Config(ws.root_uri, {}, 0, {}) + return ws + + +@pytest.fixture +def config(workspace): # pylint: disable=redefined-outer-name + """Return a config object.""" + return Config(workspace.root_uri, {}, 0, {}) + + +@pytest.fixture +def doc(workspace): # pylint: disable=redefined-outer-name + return Document(DOC_URI, workspace, DOC) + + +@pytest.fixture +def temp_workspace_factory(workspace): # pylint: disable=redefined-outer-name + ''' + Returns a function that creates a temporary workspace from the files dict. + The dict is in the format {"file_name": "file_contents"} + ''' + def fn(files): + def create_file(name, content): + fn = os.path.join(workspace.root_path, name) + with open(fn, 'w') as f: + f.write(content) + workspace.put_document(uris.from_fs_path(fn), content) + + for name, content in files.items(): + create_file(name, content) + return workspace + + return fn Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_autopep8_format.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_autopep8_format.py +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -from pyls import uris -from pyls.plugins.autopep8_format import pyls_format_document, pyls_format_range -from pyls.workspace import Document - -DOC_URI = uris.from_fs_path(__file__) -DOC = """a = 123 - - - - -def func(): - pass -""" - -GOOD_DOC = """A = ['hello', 'world']\n""" - -INDENTED_DOC = """def foo(): - print('asdf', - file=None - ) - -bar = { 'foo': foo -} -""" - -CORRECT_INDENTED_DOC = """def foo(): - print('asdf', - file=None - ) - - -bar = {'foo': foo - } -""" - - -def test_format(config, workspace): - doc = Document(DOC_URI, workspace, DOC) - res = pyls_format_document(config, doc) - - assert len(res) == 1 - assert res[0]['newText'] == "a = 123\n\n\ndef func():\n pass\n" - - -def test_range_format(config, workspace): - doc = Document(DOC_URI, workspace, DOC) - - def_range = { - 'start': {'line': 0, 'character': 0}, - 'end': {'line': 2, 'character': 0} - } - res = pyls_format_range(config, doc, def_range) - - assert len(res) == 1 - - # Make sure the func is still badly formatted - assert res[0]['newText'] == "a = 123\n\n\n\n\ndef func():\n pass\n" - - -def test_no_change(config, workspace): - doc = Document(DOC_URI, workspace, GOOD_DOC) - assert not pyls_format_document(config, doc) - - -def test_hanging_indentation(config, workspace): - doc = Document(DOC_URI, workspace, INDENTED_DOC) - res = pyls_format_document(config, doc) - - assert len(res) == 1 - assert res[0]['newText'] == CORRECT_INDENTED_DOC Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_autopep8_format.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_autopep8_format.py @@ -0,0 +1,73 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +from pylsp import uris +from pylsp.plugins.autopep8_format import pylsp_format_document, pylsp_format_range +from pylsp.workspace import Document + +DOC_URI = uris.from_fs_path(__file__) +DOC = """a = 123 + + + + +def func(): + pass +""" + +GOOD_DOC = """A = ['hello', 'world']\n""" + +INDENTED_DOC = """def foo(): + print('asdf', + file=None + ) + +bar = { 'foo': foo +} +""" + +CORRECT_INDENTED_DOC = """def foo(): + print('asdf', + file=None + ) + + +bar = {'foo': foo + } +""" + + +def test_format(config, workspace): + doc = Document(DOC_URI, workspace, DOC) + res = pylsp_format_document(config, doc) + + assert len(res) == 1 + assert res[0]['newText'] == "a = 123\n\n\ndef func():\n pass\n" + + +def test_range_format(config, workspace): + doc = Document(DOC_URI, workspace, DOC) + + def_range = { + 'start': {'line': 0, 'character': 0}, + 'end': {'line': 2, 'character': 0} + } + res = pylsp_format_range(config, doc, def_range) + + assert len(res) == 1 + + # Make sure the func is still badly formatted + assert res[0]['newText'] == "a = 123\n\n\n\n\ndef func():\n pass\n" + + +def test_no_change(config, workspace): + doc = Document(DOC_URI, workspace, GOOD_DOC) + assert not pylsp_format_document(config, doc) + + +def test_hanging_indentation(config, workspace): + doc = Document(DOC_URI, workspace, INDENTED_DOC) + res = pylsp_format_document(config, doc) + + assert len(res) == 1 + assert res[0]['newText'] == CORRECT_INDENTED_DOC Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_completion.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_completion.py +++ /dev/null @@ -1,359 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import os -import sys - -import pytest - -from pyls import uris, lsp -from pyls.workspace import Document -from pyls.plugins.jedi_completion import pyls_completions as pyls_jedi_completions -from pyls.plugins.rope_completion import pyls_completions as pyls_rope_completions - - -PY2 = sys.version[0] == '2' -LINUX = sys.platform.startswith('linux') -CI = os.environ.get('CI') -LOCATION = os.path.realpath( - os.path.join(os.getcwd(), os.path.dirname(__file__)) -) -DOC_URI = uris.from_fs_path(__file__) -DOC = """import os -print os.path.isabs("/tmp") - -def hello(): - pass - -def _a_hello(): - pass - -class Hello(): - - @property - def world(self): - return None - - def everyone(self, a, b, c=None, d=2): - pass - -print Hello().world - -print Hello().every -""" - - -def test_rope_import_completion(config, workspace): - com_position = {'line': 0, 'character': 7} - doc = Document(DOC_URI, workspace, DOC) - items = pyls_rope_completions(config, workspace, doc, com_position) - assert items is None - - -def test_jedi_completion(config, workspace): - # Over 'i' in os.path.isabs(...) - com_position = {'line': 1, 'character': 15} - doc = Document(DOC_URI, workspace, DOC) - items = pyls_jedi_completions(config, doc, com_position) - - assert items - labels = [i['label'] for i in items] - assert 'isabs(path)' in labels - - # Test we don't throw with big character - pyls_jedi_completions(config, doc, {'line': 1, 'character': 1000}) - - -def test_jedi_completion_with_fuzzy_enabled(config, workspace): - # Over 'i' in os.path.isabs(...) - config.update({'plugins': {'jedi_completion': {'fuzzy': True}}}) - com_position = {'line': 1, 'character': 15} - doc = Document(DOC_URI, workspace, DOC) - - items = pyls_jedi_completions(config, doc, com_position) - - assert items - assert items[0]['label'] == 'commonprefix(list)' - - # Test we don't throw with big character - pyls_jedi_completions(config, doc, {'line': 1, 'character': 1000}) - - -def test_rope_completion(config, workspace): - # Over 'i' in os.path.isabs(...) - com_position = {'line': 1, 'character': 15} - workspace.put_document(DOC_URI, source=DOC) - doc = workspace.get_document(DOC_URI) - items = pyls_rope_completions(config, workspace, doc, com_position) - - assert items - assert items[0]['label'] == 'isabs' - - -def test_jedi_completion_ordering(config, workspace): - # Over the blank line - com_position = {'line': 8, 'character': 0} - doc = Document(DOC_URI, workspace, DOC) - completions = pyls_jedi_completions(config, doc, com_position) - - items = {c['label']: c['sortText'] for c in completions} - - # And that 'hidden' functions come after unhidden ones - assert items['hello()'] < items['_a_hello()'] - - -def test_jedi_property_completion(config, workspace): - # Over the 'w' in 'print Hello().world' - com_position = {'line': 18, 'character': 15} - doc = Document(DOC_URI, workspace, DOC) - completions = pyls_jedi_completions(config, doc, com_position) - - items = {c['label']: c['sortText'] for c in completions} - - # Ensure we can complete the 'world' property - assert 'world' in list(items.keys())[0] - - -def test_jedi_method_completion(config, workspace): - # Over the 'y' in 'print Hello().every' - com_position = {'line': 20, 'character': 19} - doc = Document(DOC_URI, workspace, DOC) - - config.capabilities['textDocument'] = {'completion': {'completionItem': {'snippetSupport': True}}} - config.update({'plugins': {'jedi_completion': {'include_params': True}}}) - - completions = pyls_jedi_completions(config, doc, com_position) - everyone_method = [completion for completion in completions if completion['label'] == 'everyone(a, b, c, d)'][0] - - # Ensure we only generate snippets for positional args - assert everyone_method['insertTextFormat'] == lsp.InsertTextFormat.Snippet - assert everyone_method['insertText'] == 'everyone(${1:a}, ${2:b})$0' - - # Disable param snippets - config.update({'plugins': {'jedi_completion': {'include_params': False}}}) - - completions = pyls_jedi_completions(config, doc, com_position) - everyone_method = [completion for completion in completions if completion['label'] == 'everyone(a, b, c, d)'][0] - - assert 'insertTextFormat' not in everyone_method - assert everyone_method['insertText'] == 'everyone' - - -@pytest.mark.skipif(PY2 or (sys.platform.startswith('linux') and os.environ.get('CI') is not None), - reason="Test in Python 3 and not on CIs on Linux because wheels don't work on them.") -def test_pyqt_completion(config, workspace): - # Over 'QA' in 'from PyQt5.QtWidgets import QApplication' - doc_pyqt = "from PyQt5.QtWidgets import QA" - com_position = {'line': 0, 'character': len(doc_pyqt)} - doc = Document(DOC_URI, workspace, doc_pyqt) - completions = pyls_jedi_completions(config, doc, com_position) - - assert completions is not None - - -def test_numpy_completions(config, workspace): - doc_numpy = "import numpy as np; np." - com_position = {'line': 0, 'character': len(doc_numpy)} - doc = Document(DOC_URI, workspace, doc_numpy) - items = pyls_jedi_completions(config, doc, com_position) - - assert items - assert any(['array' in i['label'] for i in items]) - - -def test_pandas_completions(config, workspace): - doc_pandas = "import pandas as pd; pd." - com_position = {'line': 0, 'character': len(doc_pandas)} - doc = Document(DOC_URI, workspace, doc_pandas) - items = pyls_jedi_completions(config, doc, com_position) - - assert items - assert any(['DataFrame' in i['label'] for i in items]) - - -def test_matplotlib_completions(config, workspace): - doc_mpl = "import matplotlib.pyplot as plt; plt." - com_position = {'line': 0, 'character': len(doc_mpl)} - doc = Document(DOC_URI, workspace, doc_mpl) - items = pyls_jedi_completions(config, doc, com_position) - - assert items - assert any(['plot' in i['label'] for i in items]) - - -def test_snippets_completion(config, workspace): - doc_snippets = 'from collections import defaultdict \na=defaultdict' - com_position = {'line': 0, 'character': 35} - doc = Document(DOC_URI, workspace, doc_snippets) - config.capabilities['textDocument'] = { - 'completion': {'completionItem': {'snippetSupport': True}}} - config.update({'plugins': {'jedi_completion': {'include_params': True}}}) - completions = pyls_jedi_completions(config, doc, com_position) - assert completions[0]['insertText'] == 'defaultdict' - - com_position = {'line': 1, 'character': len(doc_snippets)} - completions = pyls_jedi_completions(config, doc, com_position) - assert completions[0]['insertText'] == 'defaultdict($0)' - assert completions[0]['insertTextFormat'] == lsp.InsertTextFormat.Snippet - - -def test_completion_with_class_objects(config, workspace): - doc_text = 'class FOOBAR(Object): pass\nFOOB' - com_position = {'line': 1, 'character': 4} - doc = Document(DOC_URI, workspace, doc_text) - config.capabilities['textDocument'] = { - 'completion': {'completionItem': {'snippetSupport': True}}} - config.update({'plugins': {'jedi_completion': { - 'include_params': True, - 'include_class_objects': True, - }}}) - completions = pyls_jedi_completions(config, doc, com_position) - assert len(completions) == 2 - - assert completions[0]['label'] == 'FOOBAR' - assert completions[0]['kind'] == lsp.CompletionItemKind.Class - - assert completions[1]['label'] == 'FOOBAR object' - assert completions[1]['kind'] == lsp.CompletionItemKind.TypeParameter - - -def test_snippet_parsing(config, workspace): - doc = 'import numpy as np\nnp.logical_and' - completion_position = {'line': 1, 'character': 14} - doc = Document(DOC_URI, workspace, doc) - config.capabilities['textDocument'] = { - 'completion': {'completionItem': {'snippetSupport': True}}} - config.update({'plugins': {'jedi_completion': {'include_params': True}}}) - completions = pyls_jedi_completions(config, doc, completion_position) - out = 'logical_and(${1:x1}, ${2:x2})$0' - assert completions[0]['insertText'] == out - - -def test_multiline_import_snippets(config, workspace): - document = 'from datetime import(\n date,\n datetime)\na=date' - doc = Document(DOC_URI, workspace, document) - config.capabilities['textDocument'] = { - 'completion': {'completionItem': {'snippetSupport': True}}} - config.update({'plugins': {'jedi_completion': {'include_params': True}}}) - - position = {'line': 1, 'character': 5} - completions = pyls_jedi_completions(config, doc, position) - assert completions[0]['insertText'] == 'date' - - position = {'line': 2, 'character': 9} - completions = pyls_jedi_completions(config, doc, position) - assert completions[0]['insertText'] == 'datetime' - - -def test_multiline_snippets(config, workspace): - document = 'from datetime import\\\n date,\\\n datetime \na=date' - doc = Document(DOC_URI, workspace, document) - config.capabilities['textDocument'] = { - 'completion': {'completionItem': {'snippetSupport': True}}} - config.update({'plugins': {'jedi_completion': {'include_params': True}}}) - - position = {'line': 1, 'character': 5} - completions = pyls_jedi_completions(config, doc, position) - assert completions[0]['insertText'] == 'date' - - position = {'line': 2, 'character': 9} - completions = pyls_jedi_completions(config, doc, position) - assert completions[0]['insertText'] == 'datetime' - - -def test_multistatement_snippet(config, workspace): - config.capabilities['textDocument'] = { - 'completion': {'completionItem': {'snippetSupport': True}}} - config.update({'plugins': {'jedi_completion': {'include_params': True}}}) - - document = 'a = 1; from datetime import date' - doc = Document(DOC_URI, workspace, document) - position = {'line': 0, 'character': len(document)} - completions = pyls_jedi_completions(config, doc, position) - assert completions[0]['insertText'] == 'date' - - document = 'from datetime import date; a = date' - doc = Document(DOC_URI, workspace, document) - position = {'line': 0, 'character': len(document)} - completions = pyls_jedi_completions(config, doc, position) - assert completions[0]['insertText'] == 'date(${1:year}, ${2:month}, ${3:day})$0' - - -def test_jedi_completion_extra_paths(tmpdir, workspace): - # Create a tempfile with some content and pass to extra_paths - temp_doc_content = ''' -def spam(): - pass -''' - p = tmpdir.mkdir("extra_path") - extra_paths = [str(p)] - p = p.join("foo.py") - p.write(temp_doc_content) - - # Content of doc to test completion - doc_content = """import foo -foo.s""" - doc = Document(DOC_URI, workspace, doc_content) - - # After 'foo.s' without extra paths - com_position = {'line': 1, 'character': 5} - completions = pyls_jedi_completions(doc._config, doc, com_position) - assert completions is None - - # Update config extra paths - settings = {'pyls': {'plugins': {'jedi': {'extra_paths': extra_paths}}}} - doc.update_config(settings) - - # After 'foo.s' with extra paths - com_position = {'line': 1, 'character': 5} - completions = pyls_jedi_completions(doc._config, doc, com_position) - assert completions[0]['label'] == 'spam()' - - -@pytest.mark.skipif(PY2 or not LINUX or not CI, reason="tested on linux and python 3 only") -def test_jedi_completion_environment(workspace): - # Content of doc to test completion - doc_content = '''import logh -''' - doc = Document(DOC_URI, workspace, doc_content) - - # After 'import logh' with default environment - com_position = {'line': 0, 'character': 11} - - assert os.path.isdir('/tmp/pyenv/') - - settings = {'pyls': {'plugins': {'jedi': {'environment': None}}}} - doc.update_config(settings) - completions = pyls_jedi_completions(doc._config, doc, com_position) - assert completions is None - - # Update config extra environment - env_path = '/tmp/pyenv/bin/python' - settings = {'pyls': {'plugins': {'jedi': {'environment': env_path}}}} - doc.update_config(settings) - - # After 'import logh' with new environment - completions = pyls_jedi_completions(doc._config, doc, com_position) - assert completions[0]['label'] == 'loghub' - assert 'changelog generator' in completions[0]['documentation'].lower() - - -def test_document_path_completions(tmpdir, workspace_other_root_path): - # Create a dummy module out of the workspace's root_path and try to get - # completions for it in another file placed next to it. - module_content = ''' -def foo(): - pass -''' - - p = tmpdir.join("mymodule.py") - p.write(module_content) - - # Content of doc to test completion - doc_content = """import mymodule -mymodule.f""" - doc_path = str(tmpdir) + os.path.sep + 'myfile.py' - doc_uri = uris.from_fs_path(doc_path) - doc = Document(doc_uri, workspace_other_root_path, doc_content) - - com_position = {'line': 1, 'character': 10} - completions = pyls_jedi_completions(doc._config, doc, com_position) - assert completions[0]['label'] == 'foo()' Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_completion.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_completion.py @@ -0,0 +1,436 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import os +import sys + +from pathlib import Path +from typing import NamedTuple, Dict + +import pytest + +from pylsp import uris, lsp +from pylsp.workspace import Document +from pylsp.plugins.jedi_completion import pylsp_completions as pylsp_jedi_completions +from pylsp.plugins.rope_completion import pylsp_completions as pylsp_rope_completions +from pylsp._utils import JEDI_VERSION + + +PY2 = sys.version[0] == '2' +LINUX = sys.platform.startswith('linux') +CI = os.environ.get('CI') +LOCATION = os.path.realpath( + os.path.join(os.getcwd(), os.path.dirname(__file__)) +) +DOC_URI = uris.from_fs_path(__file__) +DOC = """import os +print os.path.isabs("/tmp") + +def hello(): + pass + +def _a_hello(): + pass + +class Hello(): + + @property + def world(self): + return None + + def everyone(self, a, b, c=None, d=2): + pass + +print Hello().world + +print Hello().every +""" + + +def test_rope_import_completion(config, workspace): + com_position = {'line': 0, 'character': 7} + doc = Document(DOC_URI, workspace, DOC) + items = pylsp_rope_completions(config, workspace, doc, com_position) + assert items is None + + +class TypeCase(NamedTuple): + document: str + position: dict + label: str + expected: lsp.CompletionItemKind + + +TYPE_CASES: Dict[str, TypeCase] = { + 'variable': TypeCase( + document='test = 1\ntes', + position={'line': 1, 'character': 3}, + label='test', + expected=lsp.CompletionItemKind.Variable + ), + 'function': TypeCase( + document='def test():\n pass\ntes', + position={'line': 2, 'character': 3}, + label='test()', + expected=lsp.CompletionItemKind.Function + ), + 'keyword': TypeCase( + document='fro', + position={'line': 0, 'character': 3}, + label='from', + expected=lsp.CompletionItemKind.Keyword + ), + 'file': TypeCase( + document='"' + __file__[:-2].replace('"', '\\"') + '"', + position={'line': 0, 'character': len(__file__) - 2}, + label=Path(__file__).name + '"', + expected=lsp.CompletionItemKind.File + ), + 'module': TypeCase( + document='import statis', + position={'line': 0, 'character': 13}, + label='statistics', + expected=lsp.CompletionItemKind.Module + ), + 'class': TypeCase( + document='KeyErr', + position={'line': 0, 'character': 6}, + label='KeyError', + expected=lsp.CompletionItemKind.Class + ), + 'property': TypeCase( + document=( + 'class A:\n' + ' @property\n' + ' def test(self):\n' + ' pass\n' + 'A().tes' + ), + position={'line': 4, 'character': 5}, + label='test', + expected=lsp.CompletionItemKind.Property + ) +} + + +@pytest.mark.parametrize('case', list(TYPE_CASES.values()), ids=list(TYPE_CASES.keys())) +def test_jedi_completion_type(case, config, workspace): + # property support was introduced in 0.18 + if case.expected == lsp.CompletionItemKind.Property and JEDI_VERSION.startswith('0.17'): + return + + doc = Document(DOC_URI, workspace, case.document) + items = pylsp_jedi_completions(config, doc, case.position) + items = {i['label']: i for i in items} + assert items[case.label]['kind'] == case.expected + + +def test_jedi_completion(config, workspace): + # Over 'i' in os.path.isabs(...) + com_position = {'line': 1, 'character': 15} + doc = Document(DOC_URI, workspace, DOC) + items = pylsp_jedi_completions(config, doc, com_position) + + assert items + labels = [i['label'] for i in items] + assert 'isabs(path)' in labels + + # Test we don't throw with big character + pylsp_jedi_completions(config, doc, {'line': 1, 'character': 1000}) + + +def test_jedi_completion_with_fuzzy_enabled(config, workspace): + # Over 'i' in os.path.isabs(...) + config.update({'plugins': {'jedi_completion': {'fuzzy': True}}}) + com_position = {'line': 1, 'character': 15} + doc = Document(DOC_URI, workspace, DOC) + + items = pylsp_jedi_completions(config, doc, com_position) + + assert items + assert items[0]['label'] == 'commonprefix(list)' + + # Test we don't throw with big character + pylsp_jedi_completions(config, doc, {'line': 1, 'character': 1000}) + + +def test_rope_completion(config, workspace): + # Over 'i' in os.path.isabs(...) + com_position = {'line': 1, 'character': 15} + workspace.put_document(DOC_URI, source=DOC) + doc = workspace.get_document(DOC_URI) + items = pylsp_rope_completions(config, workspace, doc, com_position) + + assert items + assert items[0]['label'] == 'isabs' + + +def test_jedi_completion_ordering(config, workspace): + # Over the blank line + com_position = {'line': 8, 'character': 0} + doc = Document(DOC_URI, workspace, DOC) + completions = pylsp_jedi_completions(config, doc, com_position) + + items = {c['label']: c['sortText'] for c in completions} + + # And that 'hidden' functions come after unhidden ones + assert items['hello()'] < items['_a_hello()'] + + +def test_jedi_property_completion(config, workspace): + # Over the 'w' in 'print Hello().world' + com_position = {'line': 18, 'character': 15} + doc = Document(DOC_URI, workspace, DOC) + completions = pylsp_jedi_completions(config, doc, com_position) + + items = {c['label']: c['sortText'] for c in completions} + + # Ensure we can complete the 'world' property + assert 'world' in list(items.keys())[0] + + +def test_jedi_method_completion(config, workspace): + # Over the 'y' in 'print Hello().every' + com_position = {'line': 20, 'character': 19} + doc = Document(DOC_URI, workspace, DOC) + + config.capabilities['textDocument'] = {'completion': {'completionItem': {'snippetSupport': True}}} + config.update({'plugins': {'jedi_completion': {'include_params': True}}}) + + completions = pylsp_jedi_completions(config, doc, com_position) + everyone_method = [completion for completion in completions if completion['label'] == 'everyone(a, b, c, d)'][0] + + # Ensure we only generate snippets for positional args + assert everyone_method['insertTextFormat'] == lsp.InsertTextFormat.Snippet + assert everyone_method['insertText'] == 'everyone(${1:a}, ${2:b})$0' + + # Disable param snippets + config.update({'plugins': {'jedi_completion': {'include_params': False}}}) + + completions = pylsp_jedi_completions(config, doc, com_position) + everyone_method = [completion for completion in completions if completion['label'] == 'everyone(a, b, c, d)'][0] + + assert 'insertTextFormat' not in everyone_method + assert everyone_method['insertText'] == 'everyone' + + +@pytest.mark.skipif(PY2 or (sys.platform.startswith('linux') and os.environ.get('CI') is not None), + reason="Test in Python 3 and not on CIs on Linux because wheels don't work on them.") +def test_pyqt_completion(config, workspace): + # Over 'QA' in 'from PyQt5.QtWidgets import QApplication' + doc_pyqt = "from PyQt5.QtWidgets import QA" + com_position = {'line': 0, 'character': len(doc_pyqt)} + doc = Document(DOC_URI, workspace, doc_pyqt) + completions = pylsp_jedi_completions(config, doc, com_position) + + assert completions is not None + + +def test_numpy_completions(config, workspace): + doc_numpy = "import numpy as np; np." + com_position = {'line': 0, 'character': len(doc_numpy)} + doc = Document(DOC_URI, workspace, doc_numpy) + items = pylsp_jedi_completions(config, doc, com_position) + + assert items + assert any('array' in i['label'] for i in items) + + +def test_pandas_completions(config, workspace): + doc_pandas = "import pandas as pd; pd." + com_position = {'line': 0, 'character': len(doc_pandas)} + doc = Document(DOC_URI, workspace, doc_pandas) + items = pylsp_jedi_completions(config, doc, com_position) + + assert items + assert any('DataFrame' in i['label'] for i in items) + + +def test_matplotlib_completions(config, workspace): + doc_mpl = "import matplotlib.pyplot as plt; plt." + com_position = {'line': 0, 'character': len(doc_mpl)} + doc = Document(DOC_URI, workspace, doc_mpl) + items = pylsp_jedi_completions(config, doc, com_position) + + assert items + assert any('plot' in i['label'] for i in items) + + +def test_snippets_completion(config, workspace): + doc_snippets = 'from collections import defaultdict \na=defaultdict' + com_position = {'line': 0, 'character': 35} + doc = Document(DOC_URI, workspace, doc_snippets) + config.capabilities['textDocument'] = { + 'completion': {'completionItem': {'snippetSupport': True}}} + config.update({'plugins': {'jedi_completion': {'include_params': True}}}) + completions = pylsp_jedi_completions(config, doc, com_position) + assert completions[0]['insertText'] == 'defaultdict' + + com_position = {'line': 1, 'character': len(doc_snippets)} + completions = pylsp_jedi_completions(config, doc, com_position) + assert completions[0]['insertText'] == 'defaultdict($0)' + assert completions[0]['insertTextFormat'] == lsp.InsertTextFormat.Snippet + + +def test_completion_with_class_objects(config, workspace): + doc_text = 'class FOOBAR(Object): pass\nFOOB' + com_position = {'line': 1, 'character': 4} + doc = Document(DOC_URI, workspace, doc_text) + config.capabilities['textDocument'] = { + 'completion': {'completionItem': {'snippetSupport': True}}} + config.update({'plugins': {'jedi_completion': { + 'include_params': True, + 'include_class_objects': True, + }}}) + completions = pylsp_jedi_completions(config, doc, com_position) + assert len(completions) == 2 + + assert completions[0]['label'] == 'FOOBAR' + assert completions[0]['kind'] == lsp.CompletionItemKind.Class + + assert completions[1]['label'] == 'FOOBAR object' + assert completions[1]['kind'] == lsp.CompletionItemKind.TypeParameter + + +def test_snippet_parsing(config, workspace): + doc = 'divmod' + completion_position = {'line': 0, 'character': 6} + doc = Document(DOC_URI, workspace, doc) + config.capabilities['textDocument'] = { + 'completion': {'completionItem': {'snippetSupport': True}}} + config.update({'plugins': {'jedi_completion': {'include_params': True}}}) + completions = pylsp_jedi_completions(config, doc, completion_position) + out = 'divmod(${1:a}, ${2:b})$0' + assert completions[0]['insertText'] == out + + +def test_multiline_import_snippets(config, workspace): + document = 'from datetime import(\n date,\n datetime)\na=date' + doc = Document(DOC_URI, workspace, document) + config.capabilities['textDocument'] = { + 'completion': {'completionItem': {'snippetSupport': True}}} + config.update({'plugins': {'jedi_completion': {'include_params': True}}}) + + position = {'line': 1, 'character': 5} + completions = pylsp_jedi_completions(config, doc, position) + assert completions[0]['insertText'] == 'date' + + position = {'line': 2, 'character': 9} + completions = pylsp_jedi_completions(config, doc, position) + assert completions[0]['insertText'] == 'datetime' + + +def test_multiline_snippets(config, workspace): + document = 'from datetime import\\\n date,\\\n datetime \na=date' + doc = Document(DOC_URI, workspace, document) + config.capabilities['textDocument'] = { + 'completion': {'completionItem': {'snippetSupport': True}}} + config.update({'plugins': {'jedi_completion': {'include_params': True}}}) + + position = {'line': 1, 'character': 5} + completions = pylsp_jedi_completions(config, doc, position) + assert completions[0]['insertText'] == 'date' + + position = {'line': 2, 'character': 9} + completions = pylsp_jedi_completions(config, doc, position) + assert completions[0]['insertText'] == 'datetime' + + +def test_multistatement_snippet(config, workspace): + config.capabilities['textDocument'] = { + 'completion': {'completionItem': {'snippetSupport': True}}} + config.update({'plugins': {'jedi_completion': {'include_params': True}}}) + + document = 'a = 1; from datetime import date' + doc = Document(DOC_URI, workspace, document) + position = {'line': 0, 'character': len(document)} + completions = pylsp_jedi_completions(config, doc, position) + assert completions[0]['insertText'] == 'date' + + document = 'from datetime import date; a = date' + doc = Document(DOC_URI, workspace, document) + position = {'line': 0, 'character': len(document)} + completions = pylsp_jedi_completions(config, doc, position) + assert completions[0]['insertText'] == 'date(${1:year}, ${2:month}, ${3:day})$0' + + +def test_jedi_completion_extra_paths(tmpdir, workspace): + # Create a tempfile with some content and pass to extra_paths + temp_doc_content = ''' +def spam(): + pass +''' + p = tmpdir.mkdir("extra_path") + extra_paths = [str(p)] + p = p.join("foo.py") + p.write(temp_doc_content) + + # Content of doc to test completion + doc_content = """import foo +foo.s""" + doc = Document(DOC_URI, workspace, doc_content) + + # After 'foo.s' without extra paths + com_position = {'line': 1, 'character': 5} + completions = pylsp_jedi_completions(doc._config, doc, com_position) + assert completions is None + + # Update config extra paths + settings = {'pylsp': {'plugins': {'jedi': {'extra_paths': extra_paths}}}} + doc.update_config(settings) + + # After 'foo.s' with extra paths + com_position = {'line': 1, 'character': 5} + completions = pylsp_jedi_completions(doc._config, doc, com_position) + assert completions[0]['label'] == 'spam()' + + +@pytest.mark.skipif(PY2 or not LINUX or not CI, reason="tested on linux and python 3 only") +def test_jedi_completion_environment(workspace): + # Content of doc to test completion + doc_content = '''import logh +''' + doc = Document(DOC_URI, workspace, doc_content) + + # After 'import logh' with default environment + com_position = {'line': 0, 'character': 11} + + assert os.path.isdir('/tmp/pyenv/') + + settings = {'pylsp': {'plugins': {'jedi': {'environment': None}}}} + doc.update_config(settings) + completions = pylsp_jedi_completions(doc._config, doc, com_position) + assert completions is None + + # Update config extra environment + env_path = '/tmp/pyenv/bin/python' + settings = {'pylsp': {'plugins': {'jedi': {'environment': env_path}}}} + doc.update_config(settings) + + # After 'import logh' with new environment + completions = pylsp_jedi_completions(doc._config, doc, com_position) + assert completions[0]['label'] == 'loghub' + assert 'changelog generator' in completions[0]['documentation'].lower() + + +def test_document_path_completions(tmpdir, workspace_other_root_path): + # Create a dummy module out of the workspace's root_path and try to get + # completions for it in another file placed next to it. + module_content = ''' +def foo(): + pass +''' + + p = tmpdir.join("mymodule.py") + p.write(module_content) + + # Content of doc to test completion + doc_content = """import mymodule +mymodule.f""" + doc_path = str(tmpdir) + os.path.sep + 'myfile.py' + doc_uri = uris.from_fs_path(doc_path) + doc = Document(doc_uri, workspace_other_root_path, doc_content) + + com_position = {'line': 1, 'character': 10} + completions = pylsp_jedi_completions(doc._config, doc, com_position) + assert completions[0]['label'] == 'foo()' Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_definitions.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_definitions.py +++ /dev/null @@ -1,57 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -from pyls import uris -from pyls.plugins.definition import pyls_definitions -from pyls.workspace import Document - - -DOC_URI = uris.from_fs_path(__file__) -DOC = """def a(): - pass - -print a() - - -class Directory(object): - def __init__(self): - self.members = dict() - - def add_member(self, id, name): - self.members[id] = name -""" - - -def test_definitions(config, workspace): - # Over 'a' in print a - cursor_pos = {'line': 3, 'character': 6} - - # The definition of 'a' - def_range = { - 'start': {'line': 0, 'character': 4}, - 'end': {'line': 0, 'character': 5} - } - - doc = Document(DOC_URI, workspace, DOC) - assert [{'uri': DOC_URI, 'range': def_range}] == pyls_definitions(config, doc, cursor_pos) - - -def test_builtin_definition(config, workspace): - # Over 'i' in dict - cursor_pos = {'line': 8, 'character': 24} - - # No go-to def for builtins - doc = Document(DOC_URI, workspace, DOC) - assert not pyls_definitions(config, doc, cursor_pos) - - -def test_assignment(config, workspace): - # Over 's' in self.members[id] - cursor_pos = {'line': 11, 'character': 19} - - # The assignment of 'self.members' - def_range = { - 'start': {'line': 8, 'character': 13}, - 'end': {'line': 8, 'character': 20} - } - - doc = Document(DOC_URI, workspace, DOC) - assert [{'uri': DOC_URI, 'range': def_range}] == pyls_definitions(config, doc, cursor_pos) Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_definitions.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_definitions.py @@ -0,0 +1,59 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +from pylsp import uris +from pylsp.plugins.definition import pylsp_definitions +from pylsp.workspace import Document + + +DOC_URI = uris.from_fs_path(__file__) +DOC = """def a(): + pass + +print a() + + +class Directory(object): + def __init__(self): + self.members = dict() + + def add_member(self, id, name): + self.members[id] = name +""" + + +def test_definitions(config, workspace): + # Over 'a' in print a + cursor_pos = {'line': 3, 'character': 6} + + # The definition of 'a' + def_range = { + 'start': {'line': 0, 'character': 4}, + 'end': {'line': 0, 'character': 5} + } + + doc = Document(DOC_URI, workspace, DOC) + assert [{'uri': DOC_URI, 'range': def_range}] == pylsp_definitions(config, doc, cursor_pos) + + +def test_builtin_definition(config, workspace): + # Over 'i' in dict + cursor_pos = {'line': 8, 'character': 24} + + # No go-to def for builtins + doc = Document(DOC_URI, workspace, DOC) + assert not pylsp_definitions(config, doc, cursor_pos) + + +def test_assignment(config, workspace): + # Over 's' in self.members[id] + cursor_pos = {'line': 11, 'character': 19} + + # The assignment of 'self.members' + def_range = { + 'start': {'line': 8, 'character': 13}, + 'end': {'line': 8, 'character': 20} + } + + doc = Document(DOC_URI, workspace, DOC) + assert [{'uri': DOC_URI, 'range': def_range}] == pylsp_definitions(config, doc, cursor_pos) Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_flake8_lint.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_flake8_lint.py +++ /dev/null @@ -1,86 +0,0 @@ -# Copyright 2019 Palantir Technologies, Inc. -import tempfile -import os -from mock import patch -from pyls import lsp, uris -from pyls.plugins import flake8_lint -from pyls.workspace import Document - - -DOC_URI = uris.from_fs_path(__file__) -DOC = """import pyls - -t = "TEST" - -def using_const(): -\ta = 8 + 9 -\treturn t -""" - - -def temp_document(doc_text, workspace): - temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False) - name = temp_file.name - temp_file.write(doc_text) - temp_file.close() - doc = Document(uris.from_fs_path(name), workspace) - - return name, doc - - -def test_flake8_unsaved(workspace): - doc = Document('', workspace, DOC) - diags = flake8_lint.pyls_lint(workspace, doc) - msg = 'F841 local variable \'a\' is assigned to but never used' - unused_var = [d for d in diags if d['message'] == msg][0] - - assert unused_var['source'] == 'flake8' - assert unused_var['code'] == 'F841' - assert unused_var['range']['start'] == {'line': 5, 'character': 1} - assert unused_var['range']['end'] == {'line': 5, 'character': 11} - assert unused_var['severity'] == lsp.DiagnosticSeverity.Warning - - -def test_flake8_lint(workspace): - try: - name, doc = temp_document(DOC, workspace) - diags = flake8_lint.pyls_lint(workspace, doc) - msg = 'F841 local variable \'a\' is assigned to but never used' - unused_var = [d for d in diags if d['message'] == msg][0] - - assert unused_var['source'] == 'flake8' - assert unused_var['code'] == 'F841' - assert unused_var['range']['start'] == {'line': 5, 'character': 1} - assert unused_var['range']['end'] == {'line': 5, 'character': 11} - assert unused_var['severity'] == lsp.DiagnosticSeverity.Warning - - finally: - os.remove(name) - - -def test_flake8_config_param(workspace): - with patch('pyls.plugins.flake8_lint.Popen') as popen_mock: - mock_instance = popen_mock.return_value - mock_instance.communicate.return_value = [bytes(), bytes()] - flake8_conf = '/tmp/some.cfg' - workspace._config.update({'plugins': {'flake8': {'config': flake8_conf}}}) - _name, doc = temp_document(DOC, workspace) - flake8_lint.pyls_lint(workspace, doc) - call_args = popen_mock.call_args.args[0] - assert 'flake8' in call_args - assert '--config={}'.format(flake8_conf) in call_args - - -def test_flake8_executable_param(workspace): - with patch('pyls.plugins.flake8_lint.Popen') as popen_mock: - mock_instance = popen_mock.return_value - mock_instance.communicate.return_value = [bytes(), bytes()] - - flake8_executable = '/tmp/flake8' - workspace._config.update({'plugins': {'flake8': {'executable': flake8_executable}}}) - - _name, doc = temp_document(DOC, workspace) - flake8_lint.pyls_lint(workspace, doc) - - call_args = popen_mock.call_args.args[0] - assert flake8_executable in call_args Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_flake8_lint.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_flake8_lint.py @@ -0,0 +1,87 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import tempfile +import os +from unittest.mock import patch +from pylsp import lsp, uris +from pylsp.plugins import flake8_lint +from pylsp.workspace import Document + + +DOC_URI = uris.from_fs_path(__file__) +DOC = """import pylsp + +t = "TEST" + +def using_const(): +\ta = 8 + 9 +\treturn t +""" + + +def temp_document(doc_text, workspace): + with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file: + name = temp_file.name + temp_file.write(doc_text) + doc = Document(uris.from_fs_path(name), workspace) + + return name, doc + + +def test_flake8_unsaved(workspace): + doc = Document('', workspace, DOC) + diags = flake8_lint.pylsp_lint(workspace, doc) + msg = 'F841 local variable \'a\' is assigned to but never used' + unused_var = [d for d in diags if d['message'] == msg][0] + + assert unused_var['source'] == 'flake8' + assert unused_var['code'] == 'F841' + assert unused_var['range']['start'] == {'line': 5, 'character': 1} + assert unused_var['range']['end'] == {'line': 5, 'character': 11} + assert unused_var['severity'] == lsp.DiagnosticSeverity.Warning + + +def test_flake8_lint(workspace): + try: + name, doc = temp_document(DOC, workspace) + diags = flake8_lint.pylsp_lint(workspace, doc) + msg = 'F841 local variable \'a\' is assigned to but never used' + unused_var = [d for d in diags if d['message'] == msg][0] + + assert unused_var['source'] == 'flake8' + assert unused_var['code'] == 'F841' + assert unused_var['range']['start'] == {'line': 5, 'character': 1} + assert unused_var['range']['end'] == {'line': 5, 'character': 11} + assert unused_var['severity'] == lsp.DiagnosticSeverity.Warning + + finally: + os.remove(name) + + +def test_flake8_config_param(workspace): + with patch('pylsp.plugins.flake8_lint.Popen') as popen_mock: + mock_instance = popen_mock.return_value + mock_instance.communicate.return_value = [bytes(), bytes()] + flake8_conf = '/tmp/some.cfg' + workspace._config.update({'plugins': {'flake8': {'config': flake8_conf}}}) + _name, doc = temp_document(DOC, workspace) + flake8_lint.pylsp_lint(workspace, doc) + (call_args,) = popen_mock.call_args[0] + assert 'flake8' in call_args + assert '--config={}'.format(flake8_conf) in call_args + + +def test_flake8_executable_param(workspace): + with patch('pylsp.plugins.flake8_lint.Popen') as popen_mock: + mock_instance = popen_mock.return_value + mock_instance.communicate.return_value = [bytes(), bytes()] + + flake8_executable = '/tmp/flake8' + workspace._config.update({'plugins': {'flake8': {'executable': flake8_executable}}}) + + _name, doc = temp_document(DOC, workspace) + flake8_lint.pylsp_lint(workspace, doc) + + (call_args,) = popen_mock.call_args[0] + assert flake8_executable in call_args Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_folding.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_folding.py +++ /dev/null @@ -1,168 +0,0 @@ -# Copyright 2019 Palantir Technologies, Inc. - -from textwrap import dedent - -from pyls import uris -from pyls.workspace import Document -from pyls.plugins.folding import pyls_folding_range - - -DOC_URI = uris.from_fs_path(__file__) -DOC = dedent(""" -def func(arg1, arg2, arg3, - arg4, arg5, default=func( - 2, 3, 4 - )): - return (2, 3, - 4, 5) - -@decorator( - param1, - param2 -) -def decorated_func(x, y, z): - if x: - return y - elif y: - return z - elif x + y > z: - return True - else: - return x - -class A(): - def method(self, x1): - def inner(): - return x1 - - if x2: - func(3, 4, 5, 6, - 7) - elif x3 < 2: - pass - else: - more_complex_func(2, 3, 4, 5, 6, - 8) - return inner - -a = 2 -operation = (a_large_variable_that_fills_all_space + - other_embarrasingly_long_variable - 2 * 3 / 5) - -(a, b, c, - d, e, f) = func(3, 4, 5, 6, - 7, 8, 9, 10) - -for i in range(0, 3): - i += 1 - while x < i: - expr = (2, 4) - a = func(expr + i, arg2, arg3, arg4, - arg5, var(2, 3, 4, - 5)) - for j in range(0, i): - if i % 2 == 1: - pass - -compren = [x for x in range(0, 3) - if x == 2] - -with open('doc', 'r') as f: - try: - f / 0 - except: - pass - finally: - raise SomeException() - -def testC(): - pass -""") - -SYNTAX_ERR = dedent(""" -def func(arg1, arg2, arg3, - arg4, arg5, default=func( - 2, 3, 4 - )): - return (2, 3, - 4, 5) - -class A(: - pass - -a = 2 -operation = (a_large_variable_that_fills_all_space + - other_embarrasingly_long_variable - 2 * 3 / - -(a, b, c, - d, e, f) = func(3, 4, 5, 6, - 7, 8, 9, 10 -a = 2 -for i in range(0, 3) - i += 1 - while x < i: - expr = (2, 4) - a = func(expr + i, arg2, arg3, arg4, - arg5, var(2, 3, 4, - 5)) - for j in range(0, i): - if i % 2 == 1: - pass -""") - - -def test_folding(workspace): - doc = Document(DOC_URI, workspace, DOC) - ranges = pyls_folding_range(doc) - expected = [{'startLine': 1, 'endLine': 6}, - {'startLine': 2, 'endLine': 3}, - {'startLine': 5, 'endLine': 6}, - {'startLine': 8, 'endLine': 11}, - {'startLine': 12, 'endLine': 20}, - {'startLine': 13, 'endLine': 14}, - {'startLine': 15, 'endLine': 16}, - {'startLine': 17, 'endLine': 18}, - {'startLine': 19, 'endLine': 20}, - {'startLine': 22, 'endLine': 35}, - {'startLine': 23, 'endLine': 35}, - {'startLine': 24, 'endLine': 25}, - {'startLine': 27, 'endLine': 29}, - {'startLine': 28, 'endLine': 29}, - {'startLine': 30, 'endLine': 31}, - {'startLine': 32, 'endLine': 34}, - {'startLine': 33, 'endLine': 34}, - {'startLine': 38, 'endLine': 39}, - {'startLine': 41, 'endLine': 43}, - {'startLine': 42, 'endLine': 43}, - {'startLine': 45, 'endLine': 54}, - {'startLine': 47, 'endLine': 51}, - {'startLine': 49, 'endLine': 51}, - {'startLine': 50, 'endLine': 51}, - {'startLine': 52, 'endLine': 54}, - {'startLine': 53, 'endLine': 54}, - {'startLine': 56, 'endLine': 57}, - {'startLine': 59, 'endLine': 65}, - {'startLine': 60, 'endLine': 61}, - {'startLine': 62, 'endLine': 63}, - {'startLine': 64, 'endLine': 65}, - {'startLine': 67, 'endLine': 68}] - assert ranges == expected - - -def test_folding_syntax_error(workspace): - doc = Document(DOC_URI, workspace, SYNTAX_ERR) - ranges = pyls_folding_range(doc) - expected = [{'startLine': 1, 'endLine': 6}, - {'startLine': 2, 'endLine': 3}, - {'startLine': 5, 'endLine': 6}, - {'startLine': 8, 'endLine': 9}, - {'startLine': 12, 'endLine': 13}, - {'startLine': 15, 'endLine': 17}, - {'startLine': 16, 'endLine': 17}, - {'startLine': 19, 'endLine': 28}, - {'startLine': 21, 'endLine': 25}, - {'startLine': 23, 'endLine': 25}, - {'startLine': 24, 'endLine': 25}, - {'startLine': 26, 'endLine': 28}, - {'startLine': 27, 'endLine': 28}] - assert ranges == expected Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_folding.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_folding.py @@ -0,0 +1,173 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import sys +from textwrap import dedent + +from pylsp import uris +from pylsp.plugins.folding import pylsp_folding_range +from pylsp.workspace import Document + +DOC_URI = uris.from_fs_path(__file__) +DOC = dedent(""" +def func(arg1, arg2, arg3, + arg4, arg5, default=func( + 2, 3, 4 + )): + return (2, 3, + 4, 5) + +@decorator( + param1, + param2 +) +def decorated_func(x, y, z): + if x: + return y + elif y: + return z + elif x + y > z: + return True + else: + return x + +class A(): + def method(self, x1): + def inner(): + return x1 + + if x2: + func(3, 4, 5, 6, + 7) + elif x3 < 2: + pass + else: + more_complex_func(2, 3, 4, 5, 6, + 8) + return inner + +a = 2 +operation = (a_large_variable_that_fills_all_space + + other_embarrasingly_long_variable - 2 * 3 / 5) + +(a, b, c, + d, e, f) = func(3, 4, 5, 6, + 7, 8, 9, 10) + +for i in range(0, 3): + i += 1 + while x < i: + expr = (2, 4) + a = func(expr + i, arg2, arg3, arg4, + arg5, var(2, 3, 4, + 5)) + for j in range(0, i): + if i % 2 == 1: + pass + +compren = [x for x in range(0, 3) + if x == 2] + +with open('doc', 'r') as f: + try: + f / 0 + except: + pass + finally: + raise SomeException() + +def testC(): + pass +""") + +SYNTAX_ERR = dedent(""" +def func(arg1, arg2, arg3, + arg4, arg5, default=func( + 2, 3, 4 + )): + return (2, 3, + 4, 5) + +class A(: + pass + +a = 2 +operation = (a_large_variable_that_fills_all_space + + other_embarrasingly_long_variable - 2 * 3 / + +(a, b, c, + d, e, f) = func(3, 4, 5, 6, + 7, 8, 9, 10 +a = 2 +for i in range(0, 3) + i += 1 + while x < i: + expr = (2, 4) + a = func(expr + i, arg2, arg3, arg4, + arg5, var(2, 3, 4, + 5)) + for j in range(0, i): + if i % 2 == 1: + pass +""") + + +def test_folding(workspace): + doc = Document(DOC_URI, workspace, DOC) + ranges = pylsp_folding_range(doc) + expected = [{'startLine': 1, 'endLine': 6}, + {'startLine': 2, 'endLine': 3}, + {'startLine': 5, 'endLine': 6}, + {'startLine': 8, 'endLine': 11}, + {'startLine': 12, 'endLine': 20}, + {'startLine': 13, 'endLine': 14}, + {'startLine': 15, 'endLine': 16}, + {'startLine': 17, 'endLine': 18}, + {'startLine': 19, 'endLine': 20}, + {'startLine': 22, 'endLine': 35}, + {'startLine': 23, 'endLine': 35}, + {'startLine': 24, 'endLine': 25}, + {'startLine': 27, 'endLine': 29}, + {'startLine': 28, 'endLine': 29}, + {'startLine': 30, 'endLine': 31}, + {'startLine': 32, 'endLine': 34}, + {'startLine': 33, 'endLine': 34}, + {'startLine': 38, 'endLine': 39}, + {'startLine': 41, 'endLine': 43}, + {'startLine': 42, 'endLine': 43}, + {'startLine': 45, 'endLine': 54}, + {'startLine': 47, 'endLine': 51}, + {'startLine': 49, 'endLine': 51}, + {'startLine': 50, 'endLine': 51}, + {'startLine': 52, 'endLine': 54}, + {'startLine': 53, 'endLine': 54}, + {'startLine': 56, 'endLine': 57}, + {'startLine': 59, 'endLine': 65}, + {'startLine': 60, 'endLine': 61}, + {'startLine': 62, 'endLine': 63}, + {'startLine': 64, 'endLine': 65}, + {'startLine': 67, 'endLine': 68}] + if sys.version_info[:2] >= (3, 9): + # the argument list of the decorator is also folded in Python >= 3.9 + expected.insert(4, {'startLine': 9, 'endLine': 10}) + + assert ranges == expected + + +def test_folding_syntax_error(workspace): + doc = Document(DOC_URI, workspace, SYNTAX_ERR) + ranges = pylsp_folding_range(doc) + expected = [{'startLine': 1, 'endLine': 6}, + {'startLine': 2, 'endLine': 3}, + {'startLine': 5, 'endLine': 6}, + {'startLine': 8, 'endLine': 9}, + {'startLine': 12, 'endLine': 13}, + {'startLine': 15, 'endLine': 17}, + {'startLine': 16, 'endLine': 17}, + {'startLine': 19, 'endLine': 28}, + {'startLine': 21, 'endLine': 25}, + {'startLine': 23, 'endLine': 25}, + {'startLine': 24, 'endLine': 25}, + {'startLine': 26, 'endLine': 28}, + {'startLine': 27, 'endLine': 28}] + assert ranges == expected Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_highlight.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_highlight.py +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -from pyls import lsp, uris -from pyls.workspace import Document -from pyls.plugins.highlight import pyls_document_highlight - - -DOC_URI = uris.from_fs_path(__file__) -DOC = """a = "hello" -a.startswith("b") -""" - - -def test_highlight(workspace): - # Over 'a' in a.startswith - cursor_pos = {'line': 1, 'character': 0} - - doc = Document(DOC_URI, workspace, DOC) - assert pyls_document_highlight(doc, cursor_pos) == [{ - 'range': { - 'start': {'line': 0, 'character': 0}, - 'end': {'line': 0, 'character': 1}, - }, - # The first usage is Write - 'kind': lsp.DocumentHighlightKind.Write - }, { - 'range': { - 'start': {'line': 1, 'character': 0}, - 'end': {'line': 1, 'character': 1}, - }, - # The second usage is Read - 'kind': lsp.DocumentHighlightKind.Read - }] - - -SYS_DOC = '''import sys -print sys.path -''' - - -def test_sys_highlight(workspace): - cursor_pos = {'line': 0, 'character': 8} - - doc = Document(DOC_URI, workspace, SYS_DOC) - assert pyls_document_highlight(doc, cursor_pos) == [{ - 'range': { - 'start': {'line': 0, 'character': 7}, - 'end': {'line': 0, 'character': 10} - }, - 'kind': lsp.DocumentHighlightKind.Write - }, { - 'range': { - 'start': {'line': 1, 'character': 6}, - 'end': {'line': 1, 'character': 9} - }, - 'kind': lsp.DocumentHighlightKind.Read - }] Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_highlight.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_highlight.py @@ -0,0 +1,58 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +from pylsp import lsp, uris +from pylsp.workspace import Document +from pylsp.plugins.highlight import pylsp_document_highlight + + +DOC_URI = uris.from_fs_path(__file__) +DOC = """a = "hello" +a.startswith("b") +""" + + +def test_highlight(workspace): + # Over 'a' in a.startswith + cursor_pos = {'line': 1, 'character': 0} + + doc = Document(DOC_URI, workspace, DOC) + assert pylsp_document_highlight(doc, cursor_pos) == [{ + 'range': { + 'start': {'line': 0, 'character': 0}, + 'end': {'line': 0, 'character': 1}, + }, + # The first usage is Write + 'kind': lsp.DocumentHighlightKind.Write + }, { + 'range': { + 'start': {'line': 1, 'character': 0}, + 'end': {'line': 1, 'character': 1}, + }, + # The second usage is Read + 'kind': lsp.DocumentHighlightKind.Read + }] + + +SYS_DOC = '''import sys +print sys.path +''' + + +def test_sys_highlight(workspace): + cursor_pos = {'line': 0, 'character': 8} + + doc = Document(DOC_URI, workspace, SYS_DOC) + assert pylsp_document_highlight(doc, cursor_pos) == [{ + 'range': { + 'start': {'line': 0, 'character': 7}, + 'end': {'line': 0, 'character': 10} + }, + 'kind': lsp.DocumentHighlightKind.Write + }, { + 'range': { + 'start': {'line': 1, 'character': 6}, + 'end': {'line': 1, 'character': 9} + }, + 'kind': lsp.DocumentHighlightKind.Read + }] Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_hover.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_hover.py +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. - -from pyls import uris -from pyls.plugins.hover import pyls_hover -from pyls.workspace import Document - -DOC_URI = uris.from_fs_path(__file__) -DOC = """ - -def main(): - \"\"\"hello world\"\"\" - pass -""" - -NUMPY_DOC = """ - -import numpy as np -np.sin - -""" - - -def test_numpy_hover(workspace): - # Over the blank line - no_hov_position = {'line': 1, 'character': 0} - # Over 'numpy' in import numpy as np - numpy_hov_position_1 = {'line': 2, 'character': 8} - # Over 'np' in import numpy as np - numpy_hov_position_2 = {'line': 2, 'character': 17} - # Over 'np' in np.sin - numpy_hov_position_3 = {'line': 3, 'character': 1} - # Over 'sin' in np.sin - numpy_sin_hov_position = {'line': 3, 'character': 4} - - doc = Document(DOC_URI, workspace, NUMPY_DOC) - - contents = '' - assert contents in pyls_hover(doc, no_hov_position)['contents'] - - contents = 'NumPy\n=====\n\nProvides\n' - assert contents in pyls_hover(doc, numpy_hov_position_1)['contents'][0] - - contents = 'NumPy\n=====\n\nProvides\n' - assert contents in pyls_hover(doc, numpy_hov_position_2)['contents'][0] - - contents = 'NumPy\n=====\n\nProvides\n' - assert contents in pyls_hover(doc, numpy_hov_position_3)['contents'][0] - - contents = 'Trigonometric sine, element-wise.\n\n' - assert contents in pyls_hover( - doc, numpy_sin_hov_position)['contents'][0] - - -def test_hover(workspace): - # Over 'main' in def main(): - hov_position = {'line': 2, 'character': 6} - # Over the blank second line - no_hov_position = {'line': 1, 'character': 0} - - doc = Document(DOC_URI, workspace, DOC) - - contents = [{'language': 'python', 'value': 'main()'}, 'hello world'] - - assert { - 'contents': contents - } == pyls_hover(doc, hov_position) - - assert {'contents': ''} == pyls_hover(doc, no_hov_position) Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_hover.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_hover.py @@ -0,0 +1,74 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +from pylsp import uris +from pylsp.plugins.hover import pylsp_hover +from pylsp.workspace import Document + +DOC_URI = uris.from_fs_path(__file__) +DOC = """ + +def main(): + \"\"\"hello world\"\"\" + pass +""" + +NUMPY_DOC = """ + +import numpy as np +np.sin + +""" + + +def test_numpy_hover(workspace): + # Over the blank line + no_hov_position = {'line': 1, 'character': 0} + # Over 'numpy' in import numpy as np + numpy_hov_position_1 = {'line': 2, 'character': 8} + # Over 'np' in import numpy as np + numpy_hov_position_2 = {'line': 2, 'character': 17} + # Over 'np' in np.sin + numpy_hov_position_3 = {'line': 3, 'character': 1} + # Over 'sin' in np.sin + numpy_sin_hov_position = {'line': 3, 'character': 4} + + doc = Document(DOC_URI, workspace, NUMPY_DOC) + + contents = '' + assert contents in pylsp_hover(doc, no_hov_position)['contents'] + + contents = 'NumPy\n=====\n\nProvides\n' + assert contents in pylsp_hover(doc, numpy_hov_position_1)['contents'][0] + + contents = 'NumPy\n=====\n\nProvides\n' + assert contents in pylsp_hover(doc, numpy_hov_position_2)['contents'][0] + + contents = 'NumPy\n=====\n\nProvides\n' + assert contents in pylsp_hover(doc, numpy_hov_position_3)['contents'][0] + + # https://github.com/davidhalter/jedi/issues/1746 + # pylint: disable=import-outside-toplevel + import numpy as np + + if np.lib.NumpyVersion(np.__version__) < '1.20.0': + contents = 'Trigonometric sine, element-wise.\n\n' + assert contents in pylsp_hover( + doc, numpy_sin_hov_position)['contents'][0] + + +def test_hover(workspace): + # Over 'main' in def main(): + hov_position = {'line': 2, 'character': 6} + # Over the blank second line + no_hov_position = {'line': 1, 'character': 0} + + doc = Document(DOC_URI, workspace, DOC) + + contents = [{'language': 'python', 'value': 'main()'}, 'hello world'] + + assert { + 'contents': contents + } == pylsp_hover(doc, hov_position) + + assert {'contents': ''} == pylsp_hover(doc, no_hov_position) Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_jedi_rename.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_jedi_rename.py +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright 2020 Palantir Technologies, Inc. -import os -import sys - -import pytest -from pyls import uris -from pyls.plugins.jedi_rename import pyls_rename -from pyls.workspace import Document - -LT_PY36 = sys.version_info.major < 3 or (sys.version_info.major == 3 and sys.version_info.minor < 6) - -DOC_NAME = 'test1.py' -DOC = '''class Test1(): - pass - -class Test2(Test1): - pass -''' - -DOC_NAME_EXTRA = 'test2.py' -DOC_EXTRA = '''from test1 import Test1 -x = Test1() -''' - - -@pytest.fixture -def tmp_workspace(temp_workspace_factory): - return temp_workspace_factory({ - DOC_NAME: DOC, - DOC_NAME_EXTRA: DOC_EXTRA - }) - - -@pytest.mark.skipif(LT_PY36, reason='Jedi refactoring isnt supported on Python 2.x/3.5') -def test_jedi_rename(tmp_workspace, config): # pylint: disable=redefined-outer-name - # rename the `Test1` class - position = {'line': 0, 'character': 6} - DOC_URI = uris.from_fs_path(os.path.join(tmp_workspace.root_path, DOC_NAME)) - doc = Document(DOC_URI, tmp_workspace) - - result = pyls_rename(config, tmp_workspace, doc, position, 'ShouldBeRenamed') - assert len(result.keys()) == 1 - - changes = result.get('documentChanges') - assert len(changes) == 2 - - assert changes[0]['textDocument']['uri'] == doc.uri - assert changes[0]['textDocument']['version'] == doc.version - assert changes[0].get('edits') == [ - { - 'range': { - 'start': {'line': 0, 'character': 0}, - 'end': {'line': 5, 'character': 0}, - }, - 'newText': 'class ShouldBeRenamed():\n pass\n\nclass Test2(ShouldBeRenamed):\n pass\n', - } - ] - path = os.path.join(tmp_workspace.root_path, DOC_NAME_EXTRA) - uri_extra = uris.from_fs_path(path) - assert changes[1]['textDocument']['uri'] == uri_extra - # This also checks whether documents not yet added via textDocument/didOpen - # but that do need to be renamed in the project have a `null` version - # number. - assert changes[1]['textDocument']['version'] is None - expected = 'from test1 import ShouldBeRenamed\nx = ShouldBeRenamed()\n' - if os.name == 'nt': - # The .write method in the temp_workspace_factory functions writes - # Windows-style line-endings. - expected = expected.replace('\n', '\r\n') - assert changes[1].get('edits') == [ - { - 'range': { - 'start': {'line': 0, 'character': 0}, - 'end': {'line': 2, 'character': 0}}, - 'newText': expected - } - ] Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_jedi_rename.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_jedi_rename.py @@ -0,0 +1,79 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import os +import sys + +import pytest +from pylsp import uris +from pylsp.plugins.jedi_rename import pylsp_rename +from pylsp.workspace import Document + +LT_PY36 = sys.version_info.major < 3 or (sys.version_info.major == 3 and sys.version_info.minor < 6) + +DOC_NAME = 'test1.py' +DOC = '''class Test1(): + pass + +class Test2(Test1): + pass +''' + +DOC_NAME_EXTRA = 'test2.py' +DOC_EXTRA = '''from test1 import Test1 +x = Test1() +''' + + +@pytest.fixture +def tmp_workspace(temp_workspace_factory): + return temp_workspace_factory({ + DOC_NAME: DOC, + DOC_NAME_EXTRA: DOC_EXTRA + }) + + +@pytest.mark.skipif(LT_PY36, reason='Jedi refactoring isnt supported on Python 2.x/3.5') +def test_jedi_rename(tmp_workspace, config): # pylint: disable=redefined-outer-name + # rename the `Test1` class + position = {'line': 0, 'character': 6} + DOC_URI = uris.from_fs_path(os.path.join(tmp_workspace.root_path, DOC_NAME)) + doc = Document(DOC_URI, tmp_workspace) + + result = pylsp_rename(config, tmp_workspace, doc, position, 'ShouldBeRenamed') + assert len(result.keys()) == 1 + + changes = result.get('documentChanges') + assert len(changes) == 2 + + assert changes[0]['textDocument']['uri'] == doc.uri + assert changes[0]['textDocument']['version'] == doc.version + assert changes[0].get('edits') == [ + { + 'range': { + 'start': {'line': 0, 'character': 0}, + 'end': {'line': 5, 'character': 0}, + }, + 'newText': 'class ShouldBeRenamed():\n pass\n\nclass Test2(ShouldBeRenamed):\n pass\n', + } + ] + path = os.path.join(tmp_workspace.root_path, DOC_NAME_EXTRA) + uri_extra = uris.from_fs_path(path) + assert changes[1]['textDocument']['uri'] == uri_extra + # This also checks whether documents not yet added via textDocument/didOpen + # but that do need to be renamed in the project have a `null` version + # number. + assert changes[1]['textDocument']['version'] is None + expected = 'from test1 import ShouldBeRenamed\nx = ShouldBeRenamed()\n' + if os.name == 'nt': + # The .write method in the temp_workspace_factory functions writes + # Windows-style line-endings. + expected = expected.replace('\n', '\r\n') + assert changes[1].get('edits') == [ + { + 'range': { + 'start': {'line': 0, 'character': 0}, + 'end': {'line': 2, 'character': 0}}, + 'newText': expected + } + ] Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_mccabe_lint.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_mccabe_lint.py +++ /dev/null @@ -1,37 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -from pyls import lsp, uris -from pyls.workspace import Document -from pyls.plugins import mccabe_lint - -DOC_URI = uris.from_fs_path(__file__) -DOC = """def hello(): -\tpass -""" - -DOC_SYNTAX_ERR = """def hello() -\tpass""" - - -def test_mccabe(config, workspace): - old_settings = config.settings - try: - config.update({'plugins': {'mccabe': {'threshold': 1}}}) - doc = Document(DOC_URI, workspace, DOC) - diags = mccabe_lint.pyls_lint(config, doc) - - assert all([d['source'] == 'mccabe' for d in diags]) - - # One we're expecting is: - msg = 'Cyclomatic complexity too high: 1 (threshold 1)' - mod_import = [d for d in diags if d['message'] == msg][0] - - assert mod_import['severity'] == lsp.DiagnosticSeverity.Warning - assert mod_import['range']['start'] == {'line': 0, 'character': 0} - assert mod_import['range']['end'] == {'line': 0, 'character': 6} - finally: - config._settings = old_settings - - -def test_mccabe_syntax_error(config, workspace): - doc = Document(DOC_URI, workspace, DOC_SYNTAX_ERR) - assert mccabe_lint.pyls_lint(config, doc) is None Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_mccabe_lint.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_mccabe_lint.py @@ -0,0 +1,39 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +from pylsp import lsp, uris +from pylsp.workspace import Document +from pylsp.plugins import mccabe_lint + +DOC_URI = uris.from_fs_path(__file__) +DOC = """def hello(): +\tpass +""" + +DOC_SYNTAX_ERR = """def hello() +\tpass""" + + +def test_mccabe(config, workspace): + old_settings = config.settings + try: + config.update({'plugins': {'mccabe': {'threshold': 1}}}) + doc = Document(DOC_URI, workspace, DOC) + diags = mccabe_lint.pylsp_lint(config, doc) + + assert all(d['source'] == 'mccabe' for d in diags) + + # One we're expecting is: + msg = 'Cyclomatic complexity too high: 1 (threshold 1)' + mod_import = [d for d in diags if d['message'] == msg][0] + + assert mod_import['severity'] == lsp.DiagnosticSeverity.Warning + assert mod_import['range']['start'] == {'line': 0, 'character': 0} + assert mod_import['range']['end'] == {'line': 0, 'character': 6} + finally: + config._settings = old_settings + + +def test_mccabe_syntax_error(config, workspace): + doc = Document(DOC_URI, workspace, DOC_SYNTAX_ERR) + assert mccabe_lint.pylsp_lint(config, doc) is None Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_pycodestyle_lint.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_pycodestyle_lint.py +++ /dev/null @@ -1,110 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import os -from pyls import lsp, uris -from pyls.workspace import Document -from pyls.plugins import pycodestyle_lint - -DOC_URI = uris.from_fs_path(__file__) -DOC = """import sys - -def hello( ): -\tpass -print("hello" - ,"world" -) - -import json - - -""" - - -def test_pycodestyle(workspace): - doc = Document(DOC_URI, workspace, DOC) - diags = pycodestyle_lint.pyls_lint(workspace, doc) - - assert all([d['source'] == 'pycodestyle' for d in diags]) - - # One we're expecting is: - msg = 'W191 indentation contains tabs' - mod_import = [d for d in diags if d['message'] == msg][0] - - assert mod_import['code'] == 'W191' - assert mod_import['severity'] == lsp.DiagnosticSeverity.Warning - assert mod_import['range']['start'] == {'line': 3, 'character': 0} - assert mod_import['range']['end'] == {'line': 3, 'character': 6} - - msg = 'W391 blank line at end of file' - mod_import = [d for d in diags if d['message'] == msg][0] - - assert mod_import['code'] == 'W391' - assert mod_import['severity'] == lsp.DiagnosticSeverity.Warning - assert mod_import['range']['start'] == {'line': 10, 'character': 0} - assert mod_import['range']['end'] == {'line': 10, 'character': 1} - - msg = "E201 whitespace after '('" - mod_import = [d for d in diags if d['message'] == msg][0] - - assert mod_import['code'] == 'E201' - assert mod_import['severity'] == lsp.DiagnosticSeverity.Warning - assert mod_import['range']['start'] == {'line': 2, 'character': 10} - assert mod_import['range']['end'] == {'line': 2, 'character': 14} - - msg = "E128 continuation line under-indented for visual indent" - mod_import = [d for d in diags if d['message'] == msg][0] - - assert mod_import['code'] == 'E128' - assert mod_import['severity'] == lsp.DiagnosticSeverity.Warning - assert mod_import['range']['start'] == {'line': 5, 'character': 1} - assert mod_import['range']['end'] == {'line': 5, 'character': 10} - - -def test_pycodestyle_config(workspace): - """ Test that we load config files properly. - - Config files are loaded in the following order: - tox.ini pep8.cfg setup.cfg pycodestyle.cfg - - Each overriding the values in the last. - - These files are first looked for in the current document's - directory and then each parent directory until any one is found - terminating at the workspace root. - - If any section called 'pycodestyle' exists that will be solely used - and any config in a 'pep8' section will be ignored - """ - doc_uri = uris.from_fs_path(os.path.join(workspace.root_path, 'test.py')) - workspace.put_document(doc_uri, DOC) - doc = workspace.get_document(doc_uri) - - # Make sure we get a warning for 'indentation contains tabs' - diags = pycodestyle_lint.pyls_lint(workspace, doc) - assert [d for d in diags if d['code'] == 'W191'] - - content = { - 'setup.cfg': ('[pycodestyle]\nignore = W191, E201, E128', True), - 'tox.ini': ('', False) - } - - for conf_file, (content, working) in list(content.items()): - # Now we'll add config file to ignore it - with open(os.path.join(workspace.root_path, conf_file), 'w+') as f: - f.write(content) - workspace._config.settings.cache_clear() - - # And make sure we don't get any warnings - diags = pycodestyle_lint.pyls_lint(workspace, doc) - assert len([d for d in diags if d['code'] == 'W191']) == (0 if working else 1) - assert len([d for d in diags if d['code'] == 'E201']) == (0 if working else 1) - assert [d for d in diags if d['code'] == 'W391'] - - os.unlink(os.path.join(workspace.root_path, conf_file)) - - # Make sure we can ignore via the PYLS config as well - workspace._config.update({'plugins': {'pycodestyle': {'ignore': ['W191', 'E201']}}}) - # And make sure we only get one warning - diags = pycodestyle_lint.pyls_lint(workspace, doc) - assert not [d for d in diags if d['code'] == 'W191'] - assert not [d for d in diags if d['code'] == 'E201'] - assert [d for d in diags if d['code'] == 'W391'] Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_pycodestyle_lint.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_pycodestyle_lint.py @@ -0,0 +1,112 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import os +from pylsp import lsp, uris +from pylsp.workspace import Document +from pylsp.plugins import pycodestyle_lint + +DOC_URI = uris.from_fs_path(__file__) +DOC = """import sys + +def hello( ): +\tpass +print("hello" + ,"world" +) + +import json + + +""" + + +def test_pycodestyle(workspace): + doc = Document(DOC_URI, workspace, DOC) + diags = pycodestyle_lint.pylsp_lint(workspace, doc) + + assert all(d['source'] == 'pycodestyle' for d in diags) + + # One we're expecting is: + msg = 'W191 indentation contains tabs' + mod_import = [d for d in diags if d['message'] == msg][0] + + assert mod_import['code'] == 'W191' + assert mod_import['severity'] == lsp.DiagnosticSeverity.Warning + assert mod_import['range']['start'] == {'line': 3, 'character': 0} + assert mod_import['range']['end'] == {'line': 3, 'character': 6} + + msg = 'W391 blank line at end of file' + mod_import = [d for d in diags if d['message'] == msg][0] + + assert mod_import['code'] == 'W391' + assert mod_import['severity'] == lsp.DiagnosticSeverity.Warning + assert mod_import['range']['start'] == {'line': 10, 'character': 0} + assert mod_import['range']['end'] == {'line': 10, 'character': 1} + + msg = "E201 whitespace after '('" + mod_import = [d for d in diags if d['message'] == msg][0] + + assert mod_import['code'] == 'E201' + assert mod_import['severity'] == lsp.DiagnosticSeverity.Warning + assert mod_import['range']['start'] == {'line': 2, 'character': 10} + assert mod_import['range']['end'] == {'line': 2, 'character': 14} + + msg = "E128 continuation line under-indented for visual indent" + mod_import = [d for d in diags if d['message'] == msg][0] + + assert mod_import['code'] == 'E128' + assert mod_import['severity'] == lsp.DiagnosticSeverity.Warning + assert mod_import['range']['start'] == {'line': 5, 'character': 1} + assert mod_import['range']['end'] == {'line': 5, 'character': 10} + + +def test_pycodestyle_config(workspace): + """ Test that we load config files properly. + + Config files are loaded in the following order: + tox.ini pep8.cfg setup.cfg pycodestyle.cfg + + Each overriding the values in the last. + + These files are first looked for in the current document's + directory and then each parent directory until any one is found + terminating at the workspace root. + + If any section called 'pycodestyle' exists that will be solely used + and any config in a 'pep8' section will be ignored + """ + doc_uri = uris.from_fs_path(os.path.join(workspace.root_path, 'test.py')) + workspace.put_document(doc_uri, DOC) + doc = workspace.get_document(doc_uri) + + # Make sure we get a warning for 'indentation contains tabs' + diags = pycodestyle_lint.pylsp_lint(workspace, doc) + assert [d for d in diags if d['code'] == 'W191'] + + content = { + 'setup.cfg': ('[pycodestyle]\nignore = W191, E201, E128', True), + 'tox.ini': ('', False) + } + + for conf_file, (content, working) in list(content.items()): + # Now we'll add config file to ignore it + with open(os.path.join(workspace.root_path, conf_file), 'w+') as f: + f.write(content) + workspace._config.settings.cache_clear() + + # And make sure we don't get any warnings + diags = pycodestyle_lint.pylsp_lint(workspace, doc) + assert len([d for d in diags if d['code'] == 'W191']) == (0 if working else 1) + assert len([d for d in diags if d['code'] == 'E201']) == (0 if working else 1) + assert [d for d in diags if d['code'] == 'W391'] + + os.unlink(os.path.join(workspace.root_path, conf_file)) + + # Make sure we can ignore via the PYLS config as well + workspace._config.update({'plugins': {'pycodestyle': {'ignore': ['W191', 'E201']}}}) + # And make sure we only get one warning + diags = pycodestyle_lint.pylsp_lint(workspace, doc) + assert not [d for d in diags if d['code'] == 'W191'] + assert not [d for d in diags if d['code'] == 'E201'] + assert [d for d in diags if d['code'] == 'W391'] Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_pydocstyle_lint.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_pydocstyle_lint.py +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import os -from pyls import lsp, uris -from pyls.workspace import Document -from pyls.plugins import pydocstyle_lint - -DOC_URI = uris.from_fs_path(os.path.join(os.path.dirname(__file__), "pydocstyle.py")) -TEST_DOC_URI = uris.from_fs_path(__file__) - -DOC = """import sys - -def hello(): -\tpass - -import json -""" - - -def test_pydocstyle(config, workspace): - doc = Document(DOC_URI, workspace, DOC) - diags = pydocstyle_lint.pyls_lint(config, doc) - - assert all([d['source'] == 'pydocstyle' for d in diags]) - - # One we're expecting is: - assert diags[0] == { - 'code': 'D100', - 'message': 'D100: Missing docstring in public module', - 'severity': lsp.DiagnosticSeverity.Warning, - 'range': { - 'start': {'line': 0, 'character': 0}, - 'end': {'line': 0, 'character': 11}, - }, - 'source': 'pydocstyle' - } - - -def test_pydocstyle_test_document(config, workspace): - # The default --match argument excludes test_* documents. - doc = Document(TEST_DOC_URI, workspace, "") - diags = pydocstyle_lint.pyls_lint(config, doc) - assert not diags - - -def test_pydocstyle_empty_source(config, workspace): - doc = Document(DOC_URI, workspace, "") - diags = pydocstyle_lint.pyls_lint(config, doc) - assert diags[0]['message'] == 'D100: Missing docstring in public module' - assert len(diags) == 1 - - -def test_pydocstyle_invalid_source(config, workspace): - doc = Document(DOC_URI, workspace, "bad syntax") - diags = pydocstyle_lint.pyls_lint(config, doc) - # We're unable to parse the file, so can't get any pydocstyle diagnostics - assert not diags Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_pydocstyle_lint.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_pydocstyle_lint.py @@ -0,0 +1,58 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import os +from pylsp import lsp, uris +from pylsp.workspace import Document +from pylsp.plugins import pydocstyle_lint + +DOC_URI = uris.from_fs_path(os.path.join(os.path.dirname(__file__), "pydocstyle.py")) +TEST_DOC_URI = uris.from_fs_path(__file__) + +DOC = """import sys + +def hello(): +\tpass + +import json +""" + + +def test_pydocstyle(config, workspace): + doc = Document(DOC_URI, workspace, DOC) + diags = pydocstyle_lint.pylsp_lint(config, doc) + + assert all(d['source'] == 'pydocstyle' for d in diags) + + # One we're expecting is: + assert diags[0] == { + 'code': 'D100', + 'message': 'D100: Missing docstring in public module', + 'severity': lsp.DiagnosticSeverity.Warning, + 'range': { + 'start': {'line': 0, 'character': 0}, + 'end': {'line': 0, 'character': 11}, + }, + 'source': 'pydocstyle' + } + + +def test_pydocstyle_test_document(config, workspace): + # The default --match argument excludes test_* documents. + doc = Document(TEST_DOC_URI, workspace, "") + diags = pydocstyle_lint.pylsp_lint(config, doc) + assert not diags + + +def test_pydocstyle_empty_source(config, workspace): + doc = Document(DOC_URI, workspace, "") + diags = pydocstyle_lint.pylsp_lint(config, doc) + assert diags[0]['message'] == 'D100: Missing docstring in public module' + assert len(diags) == 1 + + +def test_pydocstyle_invalid_source(config, workspace): + doc = Document(DOC_URI, workspace, "bad syntax") + diags = pydocstyle_lint.pylsp_lint(config, doc) + # We're unable to parse the file, so can't get any pydocstyle diagnostics + assert not diags Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_pyflakes_lint.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_pyflakes_lint.py +++ /dev/null @@ -1,62 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -from pyls import lsp, uris -from pyls.workspace import Document -from pyls.plugins import pyflakes_lint - -DOC_URI = uris.from_fs_path(__file__) -DOC = """import sys - -def hello(): -\tpass - -import json -""" - -DOC_SYNTAX_ERR = """def hello() - pass -""" - -DOC_UNDEFINED_NAME_ERR = "a = b" - - -DOC_ENCODING = u"""# encoding=utf-8 -import sys -""" - - -def test_pyflakes(workspace): - doc = Document(DOC_URI, workspace, DOC) - diags = pyflakes_lint.pyls_lint(doc) - - # One we're expecting is: - msg = '\'sys\' imported but unused' - unused_import = [d for d in diags if d['message'] == msg][0] - - assert unused_import['range']['start'] == {'line': 0, 'character': 0} - assert unused_import['severity'] == lsp.DiagnosticSeverity.Warning - - -def test_syntax_error_pyflakes(workspace): - doc = Document(DOC_URI, workspace, DOC_SYNTAX_ERR) - diag = pyflakes_lint.pyls_lint(doc)[0] - - assert diag['message'] == 'invalid syntax' - assert diag['range']['start'] == {'line': 0, 'character': 12} - assert diag['severity'] == lsp.DiagnosticSeverity.Error - - -def test_undefined_name_pyflakes(workspace): - doc = Document(DOC_URI, workspace, DOC_UNDEFINED_NAME_ERR) - diag = pyflakes_lint.pyls_lint(doc)[0] - - assert diag['message'] == 'undefined name \'b\'' - assert diag['range']['start'] == {'line': 0, 'character': 4} - assert diag['severity'] == lsp.DiagnosticSeverity.Error - - -def test_unicode_encoding(workspace): - doc = Document(DOC_URI, workspace, DOC_ENCODING) - diags = pyflakes_lint.pyls_lint(doc) - - assert len(diags) == 1 - assert diags[0]['message'] == '\'sys\' imported but unused' Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_pyflakes_lint.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_pyflakes_lint.py @@ -0,0 +1,64 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +from pylsp import lsp, uris +from pylsp.workspace import Document +from pylsp.plugins import pyflakes_lint + +DOC_URI = uris.from_fs_path(__file__) +DOC = """import sys + +def hello(): +\tpass + +import json +""" + +DOC_SYNTAX_ERR = """def hello() + pass +""" + +DOC_UNDEFINED_NAME_ERR = "a = b" + + +DOC_ENCODING = u"""# encoding=utf-8 +import sys +""" + + +def test_pyflakes(workspace): + doc = Document(DOC_URI, workspace, DOC) + diags = pyflakes_lint.pylsp_lint(doc) + + # One we're expecting is: + msg = '\'sys\' imported but unused' + unused_import = [d for d in diags if d['message'] == msg][0] + + assert unused_import['range']['start'] == {'line': 0, 'character': 0} + assert unused_import['severity'] == lsp.DiagnosticSeverity.Warning + + +def test_syntax_error_pyflakes(workspace): + doc = Document(DOC_URI, workspace, DOC_SYNTAX_ERR) + diag = pyflakes_lint.pylsp_lint(doc)[0] + + assert diag['message'] == 'invalid syntax' + assert diag['range']['start'] == {'line': 0, 'character': 12} + assert diag['severity'] == lsp.DiagnosticSeverity.Error + + +def test_undefined_name_pyflakes(workspace): + doc = Document(DOC_URI, workspace, DOC_UNDEFINED_NAME_ERR) + diag = pyflakes_lint.pylsp_lint(doc)[0] + + assert diag['message'] == 'undefined name \'b\'' + assert diag['range']['start'] == {'line': 0, 'character': 4} + assert diag['severity'] == lsp.DiagnosticSeverity.Error + + +def test_unicode_encoding(workspace): + doc = Document(DOC_URI, workspace, DOC_ENCODING) + diags = pyflakes_lint.pylsp_lint(doc) + + assert len(diags) == 1 + assert diags[0]['message'] == '\'sys\' imported but unused' Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_pylint_lint.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_pylint_lint.py +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright 2018 Google LLC. -import contextlib -import os -import tempfile - -from test import py2_only, py3_only, IS_PY3 -from pyls import lsp, uris -from pyls.workspace import Document -from pyls.plugins import pylint_lint - -DOC_URI = uris.from_fs_path(__file__) -DOC = """import sys - -def hello(): -\tpass - -import json -""" - -DOC_SYNTAX_ERR = """def hello() - pass -""" - - -@contextlib.contextmanager -def temp_document(doc_text, workspace): - try: - temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False) - name = temp_file.name - temp_file.write(doc_text) - temp_file.close() - yield Document(uris.from_fs_path(name), workspace) - finally: - os.remove(name) - - -def write_temp_doc(document, contents): - with open(document.path, 'w') as temp_file: - temp_file.write(contents) - - -def test_pylint(config, workspace): - with temp_document(DOC, workspace) as doc: - diags = pylint_lint.pyls_lint(config, doc, True) - - msg = '[unused-import] Unused import sys' - unused_import = [d for d in diags if d['message'] == msg][0] - - assert unused_import['range']['start'] == {'line': 0, 'character': 0} - assert unused_import['severity'] == lsp.DiagnosticSeverity.Warning - - if IS_PY3: - # test running pylint in stdin - config.plugin_settings('pylint')['executable'] = 'pylint' - diags = pylint_lint.pyls_lint(config, doc, True) - - msg = 'Unused import sys (unused-import)' - unused_import = [d for d in diags if d['message'] == msg][0] - - assert unused_import['range']['start'] == { - 'line': 0, - 'character': 0, - } - assert unused_import['severity'] == lsp.DiagnosticSeverity.Warning - - -@py3_only -def test_syntax_error_pylint_py3(config, workspace): - with temp_document(DOC_SYNTAX_ERR, workspace) as doc: - diag = pylint_lint.pyls_lint(config, doc, True)[0] - - assert diag['message'].startswith('[syntax-error] invalid syntax') - # Pylint doesn't give column numbers for invalid syntax. - assert diag['range']['start'] == {'line': 0, 'character': 12} - assert diag['severity'] == lsp.DiagnosticSeverity.Error - - # test running pylint in stdin - config.plugin_settings('pylint')['executable'] = 'pylint' - diag = pylint_lint.pyls_lint(config, doc, True)[0] - - assert diag['message'].startswith('invalid syntax') - # Pylint doesn't give column numbers for invalid syntax. - assert diag['range']['start'] == {'line': 0, 'character': 12} - assert diag['severity'] == lsp.DiagnosticSeverity.Error - - -@py2_only -def test_syntax_error_pylint_py2(config, workspace): - with temp_document(DOC_SYNTAX_ERR, workspace) as doc: - diag = pylint_lint.pyls_lint(config, doc, True)[0] - - assert diag['message'].startswith('[syntax-error] invalid syntax') - # Pylint doesn't give column numbers for invalid syntax. - assert diag['range']['start'] == {'line': 0, 'character': 0} - assert diag['severity'] == lsp.DiagnosticSeverity.Error - - -def test_lint_free_pylint(config, workspace): - # Can't use temp_document because it might give us a file that doesn't - # match pylint's naming requirements. We should be keeping this file clean - # though, so it works for a test of an empty lint. - assert not pylint_lint.pyls_lint( - config, Document(uris.from_fs_path(__file__), workspace), True) - - -def test_lint_caching(workspace): - # Pylint can only operate on files, not in-memory contents. We cache the - # diagnostics after a run so we can continue displaying them until the file - # is saved again. - # - # We use PylintLinter.lint directly here rather than pyls_lint so we can - # pass --disable=invalid-name to pylint, since we want a temporary file but - # need to ensure that pylint doesn't give us invalid-name when our temp - # file has capital letters in its name. - - flags = '--disable=invalid-name' - with temp_document(DOC, workspace) as doc: - # Start with a file with errors. - diags = pylint_lint.PylintLinter.lint(doc, True, flags) - assert diags - - # Fix lint errors and write the changes to disk. Run the linter in the - # in-memory mode to check the cached diagnostic behavior. - write_temp_doc(doc, '') - assert pylint_lint.PylintLinter.lint(doc, False, flags) == diags - - # Now check the on-disk behavior. - assert not pylint_lint.PylintLinter.lint(doc, True, flags) - - # Make sure the cache was properly cleared. - assert not pylint_lint.PylintLinter.lint(doc, False, flags) - - -def test_per_file_caching(config, workspace): - # Ensure that diagnostics are cached per-file. - with temp_document(DOC, workspace) as doc: - assert pylint_lint.pyls_lint(config, doc, True) - - assert not pylint_lint.pyls_lint( - config, Document(uris.from_fs_path(__file__), workspace), False) Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_pylint_lint.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_pylint_lint.py @@ -0,0 +1,142 @@ +# Copyright 2018 Google LLC. +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import contextlib +import os +import tempfile + +from test import py2_only, py3_only, IS_PY3 +from pylsp import lsp, uris +from pylsp.workspace import Document +from pylsp.plugins import pylint_lint + +DOC_URI = uris.from_fs_path(__file__) +DOC = """import sys + +def hello(): +\tpass + +import json +""" + +DOC_SYNTAX_ERR = """def hello() + pass +""" + + +@contextlib.contextmanager +def temp_document(doc_text, workspace): + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file: + name = temp_file.name + temp_file.write(doc_text) + yield Document(uris.from_fs_path(name), workspace) + finally: + os.remove(name) + + +def write_temp_doc(document, contents): + with open(document.path, 'w') as temp_file: + temp_file.write(contents) + + +def test_pylint(config, workspace): + with temp_document(DOC, workspace) as doc: + diags = pylint_lint.pylsp_lint(config, doc, True) + + msg = '[unused-import] Unused import sys' + unused_import = [d for d in diags if d['message'] == msg][0] + + assert unused_import['range']['start'] == {'line': 0, 'character': 0} + assert unused_import['severity'] == lsp.DiagnosticSeverity.Warning + + if IS_PY3: + # test running pylint in stdin + config.plugin_settings('pylint')['executable'] = 'pylint' + diags = pylint_lint.pylsp_lint(config, doc, True) + + msg = 'Unused import sys (unused-import)' + unused_import = [d for d in diags if d['message'] == msg][0] + + assert unused_import['range']['start'] == { + 'line': 0, + 'character': 0, + } + assert unused_import['severity'] == lsp.DiagnosticSeverity.Warning + + +@py3_only +def test_syntax_error_pylint_py3(config, workspace): + with temp_document(DOC_SYNTAX_ERR, workspace) as doc: + diag = pylint_lint.pylsp_lint(config, doc, True)[0] + + assert diag['message'].startswith('[syntax-error] invalid syntax') + # Pylint doesn't give column numbers for invalid syntax. + assert diag['range']['start'] == {'line': 0, 'character': 12} + assert diag['severity'] == lsp.DiagnosticSeverity.Error + + # test running pylint in stdin + config.plugin_settings('pylint')['executable'] = 'pylint' + diag = pylint_lint.pylsp_lint(config, doc, True)[0] + + assert diag['message'].startswith('invalid syntax') + # Pylint doesn't give column numbers for invalid syntax. + assert diag['range']['start'] == {'line': 0, 'character': 12} + assert diag['severity'] == lsp.DiagnosticSeverity.Error + + +@py2_only +def test_syntax_error_pylint_py2(config, workspace): + with temp_document(DOC_SYNTAX_ERR, workspace) as doc: + diag = pylint_lint.pylsp_lint(config, doc, True)[0] + + assert diag['message'].startswith('[syntax-error] invalid syntax') + # Pylint doesn't give column numbers for invalid syntax. + assert diag['range']['start'] == {'line': 0, 'character': 0} + assert diag['severity'] == lsp.DiagnosticSeverity.Error + + +def test_lint_free_pylint(config, workspace): + # Can't use temp_document because it might give us a file that doesn't + # match pylint's naming requirements. We should be keeping this file clean + # though, so it works for a test of an empty lint. + assert not pylint_lint.pylsp_lint( + config, Document(uris.from_fs_path(__file__), workspace), True) + + +def test_lint_caching(workspace): + # Pylint can only operate on files, not in-memory contents. We cache the + # diagnostics after a run so we can continue displaying them until the file + # is saved again. + # + # We use PylintLinter.lint directly here rather than pylsp_lint so we can + # pass --disable=invalid-name to pylint, since we want a temporary file but + # need to ensure that pylint doesn't give us invalid-name when our temp + # file has capital letters in its name. + + flags = '--disable=invalid-name' + with temp_document(DOC, workspace) as doc: + # Start with a file with errors. + diags = pylint_lint.PylintLinter.lint(doc, True, flags) + assert diags + + # Fix lint errors and write the changes to disk. Run the linter in the + # in-memory mode to check the cached diagnostic behavior. + write_temp_doc(doc, '') + assert pylint_lint.PylintLinter.lint(doc, False, flags) == diags + + # Now check the on-disk behavior. + assert not pylint_lint.PylintLinter.lint(doc, True, flags) + + # Make sure the cache was properly cleared. + assert not pylint_lint.PylintLinter.lint(doc, False, flags) + + +def test_per_file_caching(config, workspace): + # Ensure that diagnostics are cached per-file. + with temp_document(DOC, workspace) as doc: + assert pylint_lint.pylsp_lint(config, doc, True) + + assert not pylint_lint.pylsp_lint( + config, Document(uris.from_fs_path(__file__), workspace), False) Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_references.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_references.py +++ /dev/null @@ -1,80 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import os - -import pytest - -from pyls import uris -from pyls.workspace import Document -from pyls.plugins.references import pyls_references -from pyls._utils import PY2 - - -DOC1_NAME = 'test1.py' -DOC2_NAME = 'test2.py' - -DOC1 = """class Test1(): - pass -""" - -DOC2 = """from test1 import Test1 - -try: - Test1() -except UnicodeError: - pass -""" - - -@pytest.fixture -def tmp_workspace(temp_workspace_factory): - return temp_workspace_factory({ - DOC1_NAME: DOC1, - DOC2_NAME: DOC2, - }) - - -def test_references(tmp_workspace): # pylint: disable=redefined-outer-name - # Over 'Test1' in class Test1(): - position = {'line': 0, 'character': 8} - DOC1_URI = uris.from_fs_path(os.path.join(tmp_workspace.root_path, DOC1_NAME)) - doc1 = Document(DOC1_URI, tmp_workspace) - - refs = pyls_references(doc1, position) - - # Definition, the import and the instantiation - assert len(refs) == 3 - - # Briefly check excluding the definitions (also excludes imports, only counts uses) - no_def_refs = pyls_references(doc1, position, exclude_declaration=True) - assert len(no_def_refs) == 1 - - # Make sure our definition is correctly located - doc1_ref = [u for u in refs if u['uri'] == DOC1_URI][0] - assert doc1_ref['range']['start'] == {'line': 0, 'character': 6} - assert doc1_ref['range']['end'] == {'line': 0, 'character': 11} - - # Make sure our import is correctly located - doc2_import_ref = [u for u in refs if u['uri'] != DOC1_URI][0] - assert doc2_import_ref['range']['start'] == {'line': 0, 'character': 18} - assert doc2_import_ref['range']['end'] == {'line': 0, 'character': 23} - - doc2_usage_ref = [u for u in refs if u['uri'] != DOC1_URI][1] - assert doc2_usage_ref['range']['start'] == {'line': 3, 'character': 4} - assert doc2_usage_ref['range']['end'] == {'line': 3, 'character': 9} - - -@pytest.mark.skipif(PY2, reason="Jedi sometimes fails while checking pylint " - "example files in the modules path") -def test_references_builtin(tmp_workspace): # pylint: disable=redefined-outer-name - # Over 'UnicodeError': - position = {'line': 4, 'character': 7} - doc2_uri = uris.from_fs_path(os.path.join(str(tmp_workspace.root_path), DOC2_NAME)) - doc2 = Document(doc2_uri, tmp_workspace) - - refs = pyls_references(doc2, position) - assert len(refs) >= 1 - - expected = {'start': {'line': 4, 'character': 7}, - 'end': {'line': 4, 'character': 19}} - ranges = [r['range'] for r in refs] - assert expected in ranges Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_references.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_references.py @@ -0,0 +1,79 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import os + +import pytest + +from pylsp import uris +from pylsp.workspace import Document +from pylsp.plugins.references import pylsp_references + + +DOC1_NAME = 'test1.py' +DOC2_NAME = 'test2.py' + +DOC1 = """class Test1(): + pass +""" + +DOC2 = """from test1 import Test1 + +try: + Test1() +except UnicodeError: + pass +""" + + +@pytest.fixture +def tmp_workspace(temp_workspace_factory): + return temp_workspace_factory({ + DOC1_NAME: DOC1, + DOC2_NAME: DOC2, + }) + + +def test_references(tmp_workspace): # pylint: disable=redefined-outer-name + # Over 'Test1' in class Test1(): + position = {'line': 0, 'character': 8} + DOC1_URI = uris.from_fs_path(os.path.join(tmp_workspace.root_path, DOC1_NAME)) + doc1 = Document(DOC1_URI, tmp_workspace) + + refs = pylsp_references(doc1, position) + + # Definition, the import and the instantiation + assert len(refs) == 3 + + # Briefly check excluding the definitions (also excludes imports, only counts uses) + no_def_refs = pylsp_references(doc1, position, exclude_declaration=True) + assert len(no_def_refs) == 1 + + # Make sure our definition is correctly located + doc1_ref = [u for u in refs if u['uri'] == DOC1_URI][0] + assert doc1_ref['range']['start'] == {'line': 0, 'character': 6} + assert doc1_ref['range']['end'] == {'line': 0, 'character': 11} + + # Make sure our import is correctly located + doc2_import_ref = [u for u in refs if u['uri'] != DOC1_URI][0] + assert doc2_import_ref['range']['start'] == {'line': 0, 'character': 18} + assert doc2_import_ref['range']['end'] == {'line': 0, 'character': 23} + + doc2_usage_ref = [u for u in refs if u['uri'] != DOC1_URI][1] + assert doc2_usage_ref['range']['start'] == {'line': 3, 'character': 4} + assert doc2_usage_ref['range']['end'] == {'line': 3, 'character': 9} + + +def test_references_builtin(tmp_workspace): # pylint: disable=redefined-outer-name + # Over 'UnicodeError': + position = {'line': 4, 'character': 7} + doc2_uri = uris.from_fs_path(os.path.join(str(tmp_workspace.root_path), DOC2_NAME)) + doc2 = Document(doc2_uri, tmp_workspace) + + refs = pylsp_references(doc2, position) + assert len(refs) >= 1 + + expected = {'start': {'line': 4, 'character': 7}, + 'end': {'line': 4, 'character': 19}} + ranges = [r['range'] for r in refs] + assert expected in ranges Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_rope_rename.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_rope_rename.py +++ /dev/null @@ -1,44 +0,0 @@ -import os - -import pytest -from pyls import uris -from pyls.plugins.rope_rename import pyls_rename -from pyls.workspace import Document - -DOC_NAME = "test1.py" -DOC = """class Test1(): - pass - -class Test2(Test1): - pass -""" - - -@pytest.fixture -def tmp_workspace(temp_workspace_factory): - return temp_workspace_factory({DOC_NAME: DOC}) - - -def test_rope_rename(tmp_workspace, config): # pylint: disable=redefined-outer-name - position = {"line": 0, "character": 6} - DOC_URI = uris.from_fs_path(os.path.join(tmp_workspace.root_path, DOC_NAME)) - doc = Document(DOC_URI, tmp_workspace) - - result = pyls_rename(config, tmp_workspace, doc, position, "ShouldBeRenamed") - assert len(result.keys()) == 1 - - changes = result.get("documentChanges") - assert len(changes) == 1 - changes = changes[0] - - # Note that this test differs from test_jedi_rename, because rope does not - # seem to modify files that haven't been opened with textDocument/didOpen. - assert changes.get("edits") == [ - { - "range": { - "start": {"line": 0, "character": 0}, - "end": {"line": 5, "character": 0}, - }, - "newText": "class ShouldBeRenamed():\n pass\n\nclass Test2(ShouldBeRenamed):\n pass\n", - } - ] Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_rope_rename.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_rope_rename.py @@ -0,0 +1,47 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import os + +import pytest +from pylsp import uris +from pylsp.plugins.rope_rename import pylsp_rename +from pylsp.workspace import Document + +DOC_NAME = "test1.py" +DOC = """class Test1(): + pass + +class Test2(Test1): + pass +""" + + +@pytest.fixture +def tmp_workspace(temp_workspace_factory): + return temp_workspace_factory({DOC_NAME: DOC}) + + +def test_rope_rename(tmp_workspace, config): # pylint: disable=redefined-outer-name + position = {"line": 0, "character": 6} + DOC_URI = uris.from_fs_path(os.path.join(tmp_workspace.root_path, DOC_NAME)) + doc = Document(DOC_URI, tmp_workspace) + + result = pylsp_rename(config, tmp_workspace, doc, position, "ShouldBeRenamed") + assert len(result.keys()) == 1 + + changes = result.get("documentChanges") + assert len(changes) == 1 + changes = changes[0] + + # Note that this test differs from test_jedi_rename, because rope does not + # seem to modify files that haven't been opened with textDocument/didOpen. + assert changes.get("edits") == [ + { + "range": { + "start": {"line": 0, "character": 0}, + "end": {"line": 5, "character": 0}, + }, + "newText": "class ShouldBeRenamed():\n pass\n\nclass Test2(ShouldBeRenamed):\n pass\n", + } + ] Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_signature.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_signature.py +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import pytest -from pyls import uris -from pyls.plugins import signature -from pyls.workspace import Document - -DOC_URI = uris.from_fs_path(__file__) -DOC = """import sys - -def main(param1, param2): - \"\"\" Main docstring - - Args: - param1 (str): Docs for param1 - \"\"\" - raise Exception() - -main( -""" - -MULTI_LINE_DOC = """import sys - -def main(param1=None, - param2=None, - param3=None, - param4=None, - param5=None, - param6=None, - param7=None, - param8=None): - \"\"\" Main docstring - - Args: - param1 (str): Docs for param1 - \"\"\" - raise Exception() - -main( -""" - - -def test_no_signature(workspace): - # Over blank line - sig_position = {'line': 9, 'character': 0} - doc = Document(DOC_URI, workspace, DOC) - - sigs = signature.pyls_signature_help(doc, sig_position)['signatures'] - assert not sigs - - -def test_signature(workspace): - # Over '( ' in main( - sig_position = {'line': 10, 'character': 5} - doc = Document(DOC_URI, workspace, DOC) - - sig_info = signature.pyls_signature_help(doc, sig_position) - - sigs = sig_info['signatures'] - assert len(sigs) == 1 - assert sigs[0]['label'] == 'main(param1, param2)' - assert sigs[0]['parameters'][0]['label'] == 'param1' - assert sigs[0]['parameters'][0]['documentation'] == 'Docs for param1' - - assert sig_info['activeParameter'] == 0 - - -def test_multi_line_signature(workspace): - # Over '( ' in main( - sig_position = {'line': 17, 'character': 5} - doc = Document(DOC_URI, workspace, MULTI_LINE_DOC) - - sig_info = signature.pyls_signature_help(doc, sig_position) - - sigs = sig_info['signatures'] - assert len(sigs) == 1 - assert sigs[0]['label'] == ( - 'main(param1=None, param2=None, param3=None, param4=None, ' - 'param5=None, param6=None, param7=None, param8=None)' - ) - assert sigs[0]['parameters'][0]['label'] == 'param1' - assert sigs[0]['parameters'][0]['documentation'] == 'Docs for param1' - - assert sig_info['activeParameter'] == 0 - - -@pytest.mark.parametrize('regex,doc', [ - (signature.SPHINX, " :param test: parameter docstring"), - (signature.EPYDOC, " @param test: parameter docstring"), - (signature.GOOGLE, " test (str): parameter docstring") -]) -def test_docstring_params(regex, doc): - m = regex.match(doc) - assert m.group('param') == "test" - assert m.group('doc') == "parameter docstring" Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_signature.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_signature.py @@ -0,0 +1,96 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import pytest +from pylsp import uris +from pylsp.plugins import signature +from pylsp.workspace import Document + +DOC_URI = uris.from_fs_path(__file__) +DOC = """import sys + +def main(param1, param2): + \"\"\" Main docstring + + Args: + param1 (str): Docs for param1 + \"\"\" + raise Exception() + +main( +""" + +MULTI_LINE_DOC = """import sys + +def main(param1=None, + param2=None, + param3=None, + param4=None, + param5=None, + param6=None, + param7=None, + param8=None): + \"\"\" Main docstring + + Args: + param1 (str): Docs for param1 + \"\"\" + raise Exception() + +main( +""" + + +def test_no_signature(workspace): + # Over blank line + sig_position = {'line': 9, 'character': 0} + doc = Document(DOC_URI, workspace, DOC) + + sigs = signature.pylsp_signature_help(doc, sig_position)['signatures'] + assert not sigs + + +def test_signature(workspace): + # Over '( ' in main( + sig_position = {'line': 10, 'character': 5} + doc = Document(DOC_URI, workspace, DOC) + + sig_info = signature.pylsp_signature_help(doc, sig_position) + + sigs = sig_info['signatures'] + assert len(sigs) == 1 + assert sigs[0]['label'] == 'main(param1, param2)' + assert sigs[0]['parameters'][0]['label'] == 'param1' + assert sigs[0]['parameters'][0]['documentation'] == 'Docs for param1' + + assert sig_info['activeParameter'] == 0 + + +def test_multi_line_signature(workspace): + # Over '( ' in main( + sig_position = {'line': 17, 'character': 5} + doc = Document(DOC_URI, workspace, MULTI_LINE_DOC) + + sig_info = signature.pylsp_signature_help(doc, sig_position) + + sigs = sig_info['signatures'] + assert len(sigs) == 1 + assert sigs[0]['label'] == ( + 'main(param1=None, param2=None, param3=None, param4=None, ' + 'param5=None, param6=None, param7=None, param8=None)' + ) + assert sigs[0]['parameters'][0]['label'] == 'param1' + assert sigs[0]['parameters'][0]['documentation'] == 'Docs for param1' + + assert sig_info['activeParameter'] == 0 + + +@pytest.mark.parametrize('regex,doc', [ + (signature.SPHINX, " :param test: parameter docstring"), + (signature.EPYDOC, " @param test: parameter docstring"), + (signature.GOOGLE, " test (str): parameter docstring") +]) +def test_docstring_params(regex, doc): + m = regex.match(doc) + assert m.group('param') == "test" + assert m.group('doc') == "parameter docstring" Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_symbols.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_symbols.py +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import os -import sys - -import pytest - -from pyls import uris -from pyls.plugins.symbols import pyls_document_symbols -from pyls.lsp import SymbolKind -from pyls.workspace import Document - - -PY2 = sys.version[0] == '2' -LINUX = sys.platform.startswith('linux') -CI = os.environ.get('CI') -DOC_URI = uris.from_fs_path(__file__) -DOC = """import sys - -a = 'hello' - -class B: - def __init__(self): - x = 2 - self.y = x - -def main(x): - y = 2 * x - return y - -""" - - -def helper_check_symbols_all_scope(symbols): - # All eight symbols (import sys, a, B, __init__, x, y, main, y) - assert len(symbols) == 8 - - def sym(name): - return [s for s in symbols if s['name'] == name][0] - - # Check we have some sane mappings to VSCode constants - assert sym('a')['kind'] == SymbolKind.Variable - assert sym('B')['kind'] == SymbolKind.Class - assert sym('__init__')['kind'] == SymbolKind.Method - assert sym('main')['kind'] == SymbolKind.Function - - # Not going to get too in-depth here else we're just testing Jedi - assert sym('a')['location']['range']['start'] == {'line': 2, 'character': 0} - - -def test_symbols(config, workspace): - doc = Document(DOC_URI, workspace, DOC) - config.update({'plugins': {'jedi_symbols': {'all_scopes': False}}}) - symbols = pyls_document_symbols(config, doc) - - # All four symbols (import sys, a, B, main) - # y is not in the root scope, it shouldn't be returned - assert len(symbols) == 5 - - def sym(name): - return [s for s in symbols if s['name'] == name][0] - - # Check we have some sane mappings to VSCode constants - assert sym('a')['kind'] == SymbolKind.Variable - assert sym('B')['kind'] == SymbolKind.Class - assert sym('main')['kind'] == SymbolKind.Function - - # Not going to get too in-depth here else we're just testing Jedi - assert sym('a')['location']['range']['start'] == {'line': 2, 'character': 0} - - # Ensure that the symbol range spans the whole definition - assert sym('main')['location']['range']['start'] == {'line': 9, 'character': 0} - assert sym('main')['location']['range']['end'] == {'line': 12, 'character': 0} - - -def test_symbols_all_scopes(config, workspace): - doc = Document(DOC_URI, workspace, DOC) - symbols = pyls_document_symbols(config, doc) - helper_check_symbols_all_scope(symbols) - - -@pytest.mark.skipif(PY2 or not LINUX or not CI, reason="tested on linux and python 3 only") -def test_symbols_all_scopes_with_jedi_environment(workspace): - doc = Document(DOC_URI, workspace, DOC) - - # Update config extra environment - env_path = '/tmp/pyenv/bin/python' - settings = {'pyls': {'plugins': {'jedi': {'environment': env_path}}}} - doc.update_config(settings) - symbols = pyls_document_symbols(doc._config, doc) - helper_check_symbols_all_scope(symbols) Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_symbols.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_symbols.py @@ -0,0 +1,92 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import os +import sys + +import pytest + +from pylsp import uris +from pylsp.plugins.symbols import pylsp_document_symbols +from pylsp.lsp import SymbolKind +from pylsp.workspace import Document + + +PY2 = sys.version[0] == '2' +LINUX = sys.platform.startswith('linux') +CI = os.environ.get('CI') +DOC_URI = uris.from_fs_path(__file__) +DOC = """import sys + +a = 'hello' + +class B: + def __init__(self): + x = 2 + self.y = x + +def main(x): + y = 2 * x + return y + +""" + + +def helper_check_symbols_all_scope(symbols): + # All eight symbols (import sys, a, B, __init__, x, y, main, y) + assert len(symbols) == 8 + + def sym(name): + return [s for s in symbols if s['name'] == name][0] + + # Check we have some sane mappings to VSCode constants + assert sym('a')['kind'] == SymbolKind.Variable + assert sym('B')['kind'] == SymbolKind.Class + assert sym('__init__')['kind'] == SymbolKind.Method + assert sym('main')['kind'] == SymbolKind.Function + + # Not going to get too in-depth here else we're just testing Jedi + assert sym('a')['location']['range']['start'] == {'line': 2, 'character': 0} + + +def test_symbols(config, workspace): + doc = Document(DOC_URI, workspace, DOC) + config.update({'plugins': {'jedi_symbols': {'all_scopes': False}}}) + symbols = pylsp_document_symbols(config, doc) + + # All four symbols (import sys, a, B, main) + # y is not in the root scope, it shouldn't be returned + assert len(symbols) == 5 + + def sym(name): + return [s for s in symbols if s['name'] == name][0] + + # Check we have some sane mappings to VSCode constants + assert sym('a')['kind'] == SymbolKind.Variable + assert sym('B')['kind'] == SymbolKind.Class + assert sym('main')['kind'] == SymbolKind.Function + + # Not going to get too in-depth here else we're just testing Jedi + assert sym('a')['location']['range']['start'] == {'line': 2, 'character': 0} + + # Ensure that the symbol range spans the whole definition + assert sym('main')['location']['range']['start'] == {'line': 9, 'character': 0} + assert sym('main')['location']['range']['end'] == {'line': 12, 'character': 0} + + +def test_symbols_all_scopes(config, workspace): + doc = Document(DOC_URI, workspace, DOC) + symbols = pylsp_document_symbols(config, doc) + helper_check_symbols_all_scope(symbols) + + +@pytest.mark.skipif(PY2 or not LINUX or not CI, reason="tested on linux and python 3 only") +def test_symbols_all_scopes_with_jedi_environment(workspace): + doc = Document(DOC_URI, workspace, DOC) + + # Update config extra environment + env_path = '/tmp/pyenv/bin/python' + settings = {'pylsp': {'plugins': {'jedi': {'environment': env_path}}}} + doc.update_config(settings) + symbols = pylsp_document_symbols(doc._config, doc) + helper_check_symbols_all_scope(symbols) Index: spyder-5.0.5/external-deps/python-language-server/test/plugins/test_yapf_format.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/plugins/test_yapf_format.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -from pyls import uris -from pyls.plugins.yapf_format import pyls_format_document, pyls_format_range -from pyls.workspace import Document - -DOC_URI = uris.from_fs_path(__file__) -DOC = """A = [ - 'h', 'w', - - 'a' - ] - -B = ['h', - - -'w'] -""" - -GOOD_DOC = """A = ['hello', 'world']\n""" - - -def test_format(workspace): - doc = Document(DOC_URI, workspace, DOC) - res = pyls_format_document(doc) - - assert len(res) == 1 - assert res[0]['newText'] == "A = ['h', 'w', 'a']\n\nB = ['h', 'w']\n" - - -def test_range_format(workspace): - doc = Document(DOC_URI, workspace, DOC) - - def_range = { - 'start': {'line': 0, 'character': 0}, - 'end': {'line': 4, 'character': 10} - } - res = pyls_format_range(doc, def_range) - - assert len(res) == 1 - - # Make sure B is still badly formatted - assert res[0]['newText'] == "A = ['h', 'w', 'a']\n\nB = ['h',\n\n\n'w']\n" - - -def test_no_change(workspace): - doc = Document(DOC_URI, workspace, GOOD_DOC) - assert not pyls_format_document(doc) - - -def test_config_file(tmpdir, workspace): - # a config file in the same directory as the source file will be used - conf = tmpdir.join('.style.yapf') - conf.write('[style]\ncolumn_limit = 14') - src = tmpdir.join('test.py') - doc = Document(uris.from_fs_path(src.strpath), workspace, DOC) - - # A was split on multiple lines because of column_limit from config file - assert pyls_format_document(doc)[0]['newText'] == "A = [\n 'h', 'w',\n 'a'\n]\n\nB = ['h', 'w']\n" Index: spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_yapf_format.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/plugins/test_yapf_format.py @@ -0,0 +1,60 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +from pylsp import uris +from pylsp.plugins.yapf_format import pylsp_format_document, pylsp_format_range +from pylsp.workspace import Document + +DOC_URI = uris.from_fs_path(__file__) +DOC = """A = [ + 'h', 'w', + + 'a' + ] + +B = ['h', + + +'w'] +""" + +GOOD_DOC = """A = ['hello', 'world']\n""" + + +def test_format(workspace): + doc = Document(DOC_URI, workspace, DOC) + res = pylsp_format_document(doc) + + assert len(res) == 1 + assert res[0]['newText'] == "A = ['h', 'w', 'a']\n\nB = ['h', 'w']\n" + + +def test_range_format(workspace): + doc = Document(DOC_URI, workspace, DOC) + + def_range = { + 'start': {'line': 0, 'character': 0}, + 'end': {'line': 4, 'character': 10} + } + res = pylsp_format_range(doc, def_range) + + assert len(res) == 1 + + # Make sure B is still badly formatted + assert res[0]['newText'] == "A = ['h', 'w', 'a']\n\nB = ['h',\n\n\n'w']\n" + + +def test_no_change(workspace): + doc = Document(DOC_URI, workspace, GOOD_DOC) + assert not pylsp_format_document(doc) + + +def test_config_file(tmpdir, workspace): + # a config file in the same directory as the source file will be used + conf = tmpdir.join('.style.yapf') + conf.write('[style]\ncolumn_limit = 14') + src = tmpdir.join('test.py') + doc = Document(uris.from_fs_path(src.strpath), workspace, DOC) + + # A was split on multiple lines because of column_limit from config file + assert pylsp_format_document(doc)[0]['newText'] == "A = [\n 'h', 'w',\n 'a'\n]\n\nB = ['h', 'w']\n" Index: spyder-5.0.5/external-deps/python-language-server/test/test_document.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/test_document.py +++ /dev/null @@ -1,99 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -from test.fixtures import DOC_URI, DOC -from pyls.workspace import Document - - -def test_document_props(doc): - assert doc.uri == DOC_URI - assert doc.source == DOC - - -def test_document_lines(doc): - assert len(doc.lines) == 4 - assert doc.lines[0] == 'import sys\n' - - -def test_document_source_unicode(workspace): - document_mem = Document(DOC_URI, workspace, u'my source') - document_disk = Document(DOC_URI, workspace) - assert isinstance(document_mem.source, type(document_disk.source)) - - -def test_offset_at_position(doc): - assert doc.offset_at_position({'line': 0, 'character': 8}) == 8 - assert doc.offset_at_position({'line': 1, 'character': 5}) == 16 - assert doc.offset_at_position({'line': 2, 'character': 0}) == 12 - assert doc.offset_at_position({'line': 2, 'character': 4}) == 16 - assert doc.offset_at_position({'line': 4, 'character': 0}) == 51 - - -def test_word_at_position(doc): - """ Return the position under the cursor (or last in line if past the end) """ - # import sys - assert doc.word_at_position({'line': 0, 'character': 8}) == 'sys' - # Past end of import sys - assert doc.word_at_position({'line': 0, 'character': 1000}) == 'sys' - # Empty line - assert doc.word_at_position({'line': 1, 'character': 5}) == '' - # def main(): - assert doc.word_at_position({'line': 2, 'character': 0}) == 'def' - # Past end of file - assert doc.word_at_position({'line': 4, 'character': 0}) == '' - - -def test_document_empty_edit(workspace): - doc = Document('file:///uri', workspace, u'') - doc.apply_change({ - 'range': { - 'start': {'line': 0, 'character': 0}, - 'end': {'line': 0, 'character': 0} - }, - 'text': u'f' - }) - assert doc.source == u'f' - - -def test_document_line_edit(workspace): - doc = Document('file:///uri', workspace, u'itshelloworld') - doc.apply_change({ - 'text': u'goodbye', - 'range': { - 'start': {'line': 0, 'character': 3}, - 'end': {'line': 0, 'character': 8} - } - }) - assert doc.source == u'itsgoodbyeworld' - - -def test_document_multiline_edit(workspace): - old = [ - "def hello(a, b):\n", - " print a\n", - " print b\n" - ] - doc = Document('file:///uri', workspace, u''.join(old)) - doc.apply_change({'text': u'print a, b', 'range': { - 'start': {'line': 1, 'character': 4}, - 'end': {'line': 2, 'character': 11} - }}) - assert doc.lines == [ - "def hello(a, b):\n", - " print a, b\n" - ] - - -def test_document_end_of_file_edit(workspace): - old = [ - "print 'a'\n", - "print 'b'\n" - ] - doc = Document('file:///uri', workspace, u''.join(old)) - doc.apply_change({'text': u'o', 'range': { - 'start': {'line': 2, 'character': 0}, - 'end': {'line': 2, 'character': 0} - }}) - assert doc.lines == [ - "print 'a'\n", - "print 'b'\n", - "o", - ] Index: spyder-5.0.5/external-deps/python-lsp-server/test/test_document.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/test_document.py @@ -0,0 +1,101 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +from test.fixtures import DOC_URI, DOC +from pylsp.workspace import Document + + +def test_document_props(doc): + assert doc.uri == DOC_URI + assert doc.source == DOC + + +def test_document_lines(doc): + assert len(doc.lines) == 4 + assert doc.lines[0] == 'import sys\n' + + +def test_document_source_unicode(workspace): + document_mem = Document(DOC_URI, workspace, u'my source') + document_disk = Document(DOC_URI, workspace) + assert isinstance(document_mem.source, type(document_disk.source)) + + +def test_offset_at_position(doc): + assert doc.offset_at_position({'line': 0, 'character': 8}) == 8 + assert doc.offset_at_position({'line': 1, 'character': 5}) == 16 + assert doc.offset_at_position({'line': 2, 'character': 0}) == 12 + assert doc.offset_at_position({'line': 2, 'character': 4}) == 16 + assert doc.offset_at_position({'line': 4, 'character': 0}) == 51 + + +def test_word_at_position(doc): + """ Return the position under the cursor (or last in line if past the end) """ + # import sys + assert doc.word_at_position({'line': 0, 'character': 8}) == 'sys' + # Past end of import sys + assert doc.word_at_position({'line': 0, 'character': 1000}) == 'sys' + # Empty line + assert doc.word_at_position({'line': 1, 'character': 5}) == '' + # def main(): + assert doc.word_at_position({'line': 2, 'character': 0}) == 'def' + # Past end of file + assert doc.word_at_position({'line': 4, 'character': 0}) == '' + + +def test_document_empty_edit(workspace): + doc = Document('file:///uri', workspace, u'') + doc.apply_change({ + 'range': { + 'start': {'line': 0, 'character': 0}, + 'end': {'line': 0, 'character': 0} + }, + 'text': u'f' + }) + assert doc.source == u'f' + + +def test_document_line_edit(workspace): + doc = Document('file:///uri', workspace, u'itshelloworld') + doc.apply_change({ + 'text': u'goodbye', + 'range': { + 'start': {'line': 0, 'character': 3}, + 'end': {'line': 0, 'character': 8} + } + }) + assert doc.source == u'itsgoodbyeworld' + + +def test_document_multiline_edit(workspace): + old = [ + "def hello(a, b):\n", + " print a\n", + " print b\n" + ] + doc = Document('file:///uri', workspace, u''.join(old)) + doc.apply_change({'text': u'print a, b', 'range': { + 'start': {'line': 1, 'character': 4}, + 'end': {'line': 2, 'character': 11} + }}) + assert doc.lines == [ + "def hello(a, b):\n", + " print a, b\n" + ] + + +def test_document_end_of_file_edit(workspace): + old = [ + "print 'a'\n", + "print 'b'\n" + ] + doc = Document('file:///uri', workspace, u''.join(old)) + doc.apply_change({'text': u'o', 'range': { + 'start': {'line': 2, 'character': 0}, + 'end': {'line': 2, 'character': 0} + }}) + assert doc.lines == [ + "print 'a'\n", + "print 'b'\n", + "o", + ] Index: spyder-5.0.5/external-deps/python-language-server/test/test_language_server.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/test_language_server.py +++ /dev/null @@ -1,115 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import os -import time -import multiprocessing -import sys -from threading import Thread - -from pyls_jsonrpc.exceptions import JsonRpcMethodNotFound -import pytest - -from pyls.python_ls import start_io_lang_server, PythonLanguageServer - -CALL_TIMEOUT = 10 -PY2 = sys.version_info[0] == 2 -PY3 = sys.version_info[0] == 3 - - -def start_client(client): - client.start() - - -class _ClientServer(object): - """ A class to setup a client/server pair """ - def __init__(self, check_parent_process=False): - # Client to Server pipe - csr, csw = os.pipe() - # Server to client pipe - scr, scw = os.pipe() - - if os.name == 'nt': - ParallelKind = Thread - else: - if sys.version_info[:2] >= (3, 8): - ParallelKind = multiprocessing.get_context("fork").Process # pylint: disable=no-member - else: - ParallelKind = multiprocessing.Process - - self.process = ParallelKind(target=start_io_lang_server, args=( - os.fdopen(csr, 'rb'), os.fdopen(scw, 'wb'), check_parent_process, PythonLanguageServer - )) - self.process.start() - - self.client = PythonLanguageServer(os.fdopen(scr, 'rb'), os.fdopen(csw, 'wb'), start_io_lang_server) - self.client_thread = Thread(target=start_client, args=[self.client]) - self.client_thread.daemon = True - self.client_thread.start() - - -@pytest.fixture -def client_server(): - """ A fixture that sets up a client/server pair and shuts down the server - This client/server pair does not support checking parent process aliveness - """ - client_server_pair = _ClientServer() - - yield client_server_pair.client - - shutdown_response = client_server_pair.client._endpoint.request('shutdown').result(timeout=CALL_TIMEOUT) - assert shutdown_response is None - client_server_pair.client._endpoint.notify('exit') - - -@pytest.fixture -def client_exited_server(): - """ A fixture that sets up a client/server pair that support checking parent process aliveness - and assert the server has already exited - """ - client_server_pair = _ClientServer(True) - - # yield client_server_pair.client - yield client_server_pair - - assert client_server_pair.process.is_alive() is False - - -def test_initialize(client_server): # pylint: disable=redefined-outer-name - response = client_server._endpoint.request('initialize', { - 'rootPath': os.path.dirname(__file__), - 'initializationOptions': {} - }).result(timeout=CALL_TIMEOUT) - assert 'capabilities' in response - - -@pytest.mark.skipif(os.name == 'nt' or (sys.platform.startswith('linux') and PY3), - reason='Skipped on win and fails on linux >=3.6') -def test_exit_with_parent_process_died(client_exited_server): # pylint: disable=redefined-outer-name - # language server should have already exited before responding - lsp_server, mock_process = client_exited_server.client, client_exited_server.process - # with pytest.raises(Exception): - lsp_server._endpoint.request('initialize', { - 'processId': mock_process.pid, - 'rootPath': os.path.dirname(__file__), - 'initializationOptions': {} - }).result(timeout=CALL_TIMEOUT) - - mock_process.terminate() - time.sleep(CALL_TIMEOUT) - assert not client_exited_server.client_thread.is_alive() - - -@pytest.mark.skipif(sys.platform.startswith('linux') and PY3, - reason='Fails on linux and py3') -def test_not_exit_without_check_parent_process_flag(client_server): # pylint: disable=redefined-outer-name - response = client_server._endpoint.request('initialize', { - 'processId': 1234, - 'rootPath': os.path.dirname(__file__), - 'initializationOptions': {} - }).result(timeout=CALL_TIMEOUT) - assert 'capabilities' in response - - -@pytest.mark.skipif(bool(os.environ.get('CI')), reason='This test is hanging on CI') -def test_missing_message(client_server): # pylint: disable=redefined-outer-name - with pytest.raises(JsonRpcMethodNotFound): - client_server._endpoint.request('unknown_method').result(timeout=CALL_TIMEOUT) Index: spyder-5.0.5/external-deps/python-lsp-server/test/test_language_server.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/test_language_server.py @@ -0,0 +1,117 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import os +import time +import multiprocessing +import sys +from threading import Thread + +from pylsp_jsonrpc.exceptions import JsonRpcMethodNotFound +import pytest + +from pylsp.python_lsp import start_io_lang_server, PythonLSPServer + +CALL_TIMEOUT = 10 +PY2 = sys.version_info[0] == 2 +PY3 = sys.version_info[0] == 3 + + +def start_client(client): + client.start() + + +class _ClientServer: + """ A class to setup a client/server pair """ + def __init__(self, check_parent_process=False): + # Client to Server pipe + csr, csw = os.pipe() + # Server to client pipe + scr, scw = os.pipe() + + if os.name == 'nt': + ParallelKind = Thread + else: + if sys.version_info[:2] >= (3, 8): + ParallelKind = multiprocessing.get_context("fork").Process + else: + ParallelKind = multiprocessing.Process + + self.process = ParallelKind(target=start_io_lang_server, args=( + os.fdopen(csr, 'rb'), os.fdopen(scw, 'wb'), check_parent_process, PythonLSPServer + )) + self.process.start() + + self.client = PythonLSPServer(os.fdopen(scr, 'rb'), os.fdopen(csw, 'wb'), start_io_lang_server) + self.client_thread = Thread(target=start_client, args=[self.client]) + self.client_thread.daemon = True + self.client_thread.start() + + +@pytest.fixture +def client_server(): + """ A fixture that sets up a client/server pair and shuts down the server + This client/server pair does not support checking parent process aliveness + """ + client_server_pair = _ClientServer() + + yield client_server_pair.client + + shutdown_response = client_server_pair.client._endpoint.request('shutdown').result(timeout=CALL_TIMEOUT) + assert shutdown_response is None + client_server_pair.client._endpoint.notify('exit') + + +@pytest.fixture +def client_exited_server(): + """ A fixture that sets up a client/server pair that support checking parent process aliveness + and assert the server has already exited + """ + client_server_pair = _ClientServer(True) + + # yield client_server_pair.client + yield client_server_pair + + assert client_server_pair.process.is_alive() is False + + +def test_initialize(client_server): # pylint: disable=redefined-outer-name + response = client_server._endpoint.request('initialize', { + 'rootPath': os.path.dirname(__file__), + 'initializationOptions': {} + }).result(timeout=CALL_TIMEOUT) + assert 'capabilities' in response + + +@pytest.mark.skipif(os.name == 'nt' or (sys.platform.startswith('linux') and PY3), + reason='Skipped on win and fails on linux >=3.6') +def test_exit_with_parent_process_died(client_exited_server): # pylint: disable=redefined-outer-name + # language server should have already exited before responding + lsp_server, mock_process = client_exited_server.client, client_exited_server.process + # with pytest.raises(Exception): + lsp_server._endpoint.request('initialize', { + 'processId': mock_process.pid, + 'rootPath': os.path.dirname(__file__), + 'initializationOptions': {} + }).result(timeout=CALL_TIMEOUT) + + mock_process.terminate() + time.sleep(CALL_TIMEOUT) + assert not client_exited_server.client_thread.is_alive() + + +@pytest.mark.skipif(sys.platform.startswith('linux') and PY3, + reason='Fails on linux and py3') +def test_not_exit_without_check_parent_process_flag(client_server): # pylint: disable=redefined-outer-name + response = client_server._endpoint.request('initialize', { + 'processId': 1234, + 'rootPath': os.path.dirname(__file__), + 'initializationOptions': {} + }).result(timeout=CALL_TIMEOUT) + assert 'capabilities' in response + + +@pytest.mark.skipif(bool(os.environ.get('CI')), reason='This test is hanging on CI') +def test_missing_message(client_server): # pylint: disable=redefined-outer-name + with pytest.raises(JsonRpcMethodNotFound): + client_server._endpoint.request('unknown_method').result(timeout=CALL_TIMEOUT) Index: spyder-5.0.5/external-deps/python-language-server/test/test_uris.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/test_uris.py +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -from test import unix_only, windows_only -import pytest -from pyls import uris - - -@unix_only -@pytest.mark.parametrize('uri,path', [ - ('file:///foo/bar#frag', '/foo/bar'), - ('file:/foo/bar#frag', '/foo/bar'), - ('file:/foo/space%20%3Fbar#frag', '/foo/space ?bar'), -]) -def test_to_fs_path(uri, path): - assert uris.to_fs_path(uri) == path - - -@windows_only -@pytest.mark.parametrize('uri,path', [ - ('file:///c:/far/boo', 'c:\\far\\boo'), - ('file:///C:/far/boo', 'c:\\far\\boo'), - ('file:///C:/far/space%20%3Fboo', 'c:\\far\\space ?boo'), -]) -def test_win_to_fs_path(uri, path): - assert uris.to_fs_path(uri) == path - - -@unix_only -@pytest.mark.parametrize('path,uri', [ - ('/foo/bar', 'file:///foo/bar'), - ('/foo/space ?bar', 'file:///foo/space%20%3Fbar'), -]) -def test_from_fs_path(path, uri): - assert uris.from_fs_path(path) == uri - - -@windows_only -@pytest.mark.parametrize('path,uri', [ - ('c:\\far\\boo', 'file:///c:/far/boo'), - ('C:\\far\\space ?boo', 'file:///c:/far/space%20%3Fboo') -]) -def test_win_from_fs_path(path, uri): - assert uris.from_fs_path(path) == uri - - -@pytest.mark.parametrize('uri,kwargs,new_uri', [ - ('file:///foo/bar', {'path': '/baz/boo'}, 'file:///baz/boo'), - ('file:///D:/hello%20world.py', {'path': 'D:/hello universe.py'}, 'file:///d:/hello%20universe.py') -]) -def test_uri_with(uri, kwargs, new_uri): - assert uris.uri_with(uri, **kwargs) == new_uri Index: spyder-5.0.5/external-deps/python-lsp-server/test/test_uris.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/test_uris.py @@ -0,0 +1,52 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +from test import unix_only, windows_only +import pytest +from pylsp import uris + + +@unix_only +@pytest.mark.parametrize('uri,path', [ + ('file:///foo/bar#frag', '/foo/bar'), + ('file:/foo/bar#frag', '/foo/bar'), + ('file:/foo/space%20%3Fbar#frag', '/foo/space ?bar'), +]) +def test_to_fs_path(uri, path): + assert uris.to_fs_path(uri) == path + + +@windows_only +@pytest.mark.parametrize('uri,path', [ + ('file:///c:/far/boo', 'c:\\far\\boo'), + ('file:///C:/far/boo', 'c:\\far\\boo'), + ('file:///C:/far/space%20%3Fboo', 'c:\\far\\space ?boo'), +]) +def test_win_to_fs_path(uri, path): + assert uris.to_fs_path(uri) == path + + +@unix_only +@pytest.mark.parametrize('path,uri', [ + ('/foo/bar', 'file:///foo/bar'), + ('/foo/space ?bar', 'file:///foo/space%20%3Fbar'), +]) +def test_from_fs_path(path, uri): + assert uris.from_fs_path(path) == uri + + +@windows_only +@pytest.mark.parametrize('path,uri', [ + ('c:\\far\\boo', 'file:///c:/far/boo'), + ('C:\\far\\space ?boo', 'file:///c:/far/space%20%3Fboo') +]) +def test_win_from_fs_path(path, uri): + assert uris.from_fs_path(path) == uri + + +@pytest.mark.parametrize('uri,kwargs,new_uri', [ + ('file:///foo/bar', {'path': '/baz/boo'}, 'file:///baz/boo'), + ('file:///D:/hello%20world.py', {'path': 'D:/hello universe.py'}, 'file:///d:/hello%20universe.py') +]) +def test_uri_with(uri, kwargs, new_uri): + assert uris.uri_with(uri, **kwargs) == new_uri Index: spyder-5.0.5/external-deps/python-language-server/test/test_utils.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/test_utils.py +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import time - -import mock -from flaky import flaky - -from pyls import _utils - - -@flaky -def test_debounce(): - interval = 0.1 - obj = mock.Mock() - - @_utils.debounce(0.1) - def call_m(): - obj() - - assert not obj.mock_calls - - call_m() - call_m() - call_m() - assert not obj.mock_calls - - time.sleep(interval * 2) - assert len(obj.mock_calls) == 1 - - call_m() - time.sleep(interval * 2) - assert len(obj.mock_calls) == 2 - - -@flaky -def test_debounce_keyed_by(): - interval = 0.1 - obj = mock.Mock() - - @_utils.debounce(0.1, keyed_by='key') - def call_m(key): - obj(key) - - assert not obj.mock_calls - - call_m(1) - call_m(2) - call_m(3) - assert not obj.mock_calls - - time.sleep(interval * 2) - obj.assert_has_calls([ - mock.call(1), - mock.call(2), - mock.call(3), - ], any_order=True) - assert len(obj.mock_calls) == 3 - - call_m(1) - call_m(1) - call_m(1) - time.sleep(interval * 2) - assert len(obj.mock_calls) == 4 - - -def test_list_to_string(): - assert _utils.list_to_string("string") == "string" - assert _utils.list_to_string(["a", "r", "r", "a", "y"]) == "a,r,r,a,y" - - -def test_find_parents(tmpdir): - subsubdir = tmpdir.ensure_dir("subdir", "subsubdir") - path = subsubdir.ensure("path.py") - test_cfg = tmpdir.ensure("test.cfg") - - assert _utils.find_parents(tmpdir.strpath, path.strpath, ["test.cfg"]) == [test_cfg.strpath] - - -def test_merge_dicts(): - assert _utils.merge_dicts( - {'a': True, 'b': {'x': 123, 'y': {'hello': 'world'}}}, - {'a': False, 'b': {'y': [], 'z': 987}} - ) == {'a': False, 'b': {'x': 123, 'y': [], 'z': 987}} - - -def test_clip_column(): - assert _utils.clip_column(0, [], 0) == 0 - assert _utils.clip_column(2, ['123'], 0) == 2 - assert _utils.clip_column(3, ['123'], 0) == 3 - assert _utils.clip_column(5, ['123'], 0) == 3 - assert _utils.clip_column(0, ['\n', '123'], 0) == 0 - assert _utils.clip_column(1, ['\n', '123'], 0) == 0 - assert _utils.clip_column(2, ['123\n', '123'], 0) == 2 - assert _utils.clip_column(3, ['123\n', '123'], 0) == 3 - assert _utils.clip_column(4, ['123\n', '123'], 1) == 3 Index: spyder-5.0.5/external-deps/python-lsp-server/test/test_utils.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/test_utils.py @@ -0,0 +1,96 @@ +# Copyright 2017-2020 Palantir Technologies, Inc. +# Copyright 2021- Python Language Server Contributors. + +import time + +import unittest.mock as mock +from flaky import flaky + +from pylsp import _utils + + +@flaky +def test_debounce(): + interval = 0.1 + obj = mock.Mock() + + @_utils.debounce(0.1) + def call_m(): + obj() + + assert not obj.mock_calls + + call_m() + call_m() + call_m() + assert not obj.mock_calls + + time.sleep(interval * 2) + assert len(obj.mock_calls) == 1 + + call_m() + time.sleep(interval * 2) + assert len(obj.mock_calls) == 2 + + +@flaky +def test_debounce_keyed_by(): + interval = 0.1 + obj = mock.Mock() + + @_utils.debounce(0.1, keyed_by='key') + def call_m(key): + obj(key) + + assert not obj.mock_calls + + call_m(1) + call_m(2) + call_m(3) + assert not obj.mock_calls + + time.sleep(interval * 2) + obj.assert_has_calls([ + mock.call(1), + mock.call(2), + mock.call(3), + ], any_order=True) + assert len(obj.mock_calls) == 3 + + call_m(1) + call_m(1) + call_m(1) + time.sleep(interval * 2) + assert len(obj.mock_calls) == 4 + + +def test_list_to_string(): + assert _utils.list_to_string("string") == "string" + assert _utils.list_to_string(["a", "r", "r", "a", "y"]) == "a,r,r,a,y" + + +def test_find_parents(tmpdir): + subsubdir = tmpdir.ensure_dir("subdir", "subsubdir") + path = subsubdir.ensure("path.py") + test_cfg = tmpdir.ensure("test.cfg") + + assert _utils.find_parents(tmpdir.strpath, path.strpath, ["test.cfg"]) == [test_cfg.strpath] + + +def test_merge_dicts(): + assert _utils.merge_dicts( + {'a': True, 'b': {'x': 123, 'y': {'hello': 'world'}}}, + {'a': False, 'b': {'y': [], 'z': 987}} + ) == {'a': False, 'b': {'x': 123, 'y': [], 'z': 987}} + + +def test_clip_column(): + assert _utils.clip_column(0, [], 0) == 0 + assert _utils.clip_column(2, ['123'], 0) == 2 + assert _utils.clip_column(3, ['123'], 0) == 3 + assert _utils.clip_column(5, ['123'], 0) == 3 + assert _utils.clip_column(0, ['\n', '123'], 0) == 0 + assert _utils.clip_column(1, ['\n', '123'], 0) == 0 + assert _utils.clip_column(2, ['123\n', '123'], 0) == 2 + assert _utils.clip_column(3, ['123\n', '123'], 0) == 3 + assert _utils.clip_column(4, ['123\n', '123'], 1) == 3 Index: spyder-5.0.5/external-deps/python-language-server/test/test_workspace.py =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/test/test_workspace.py +++ /dev/null @@ -1,264 +0,0 @@ -# Copyright 2017 Palantir Technologies, Inc. -import os -import sys - -import pytest - -from pyls import uris - -PY2 = sys.version_info.major == 2 - -if PY2: - import pathlib2 as pathlib -else: - import pathlib - - -DOC_URI = uris.from_fs_path(__file__) - - -def path_as_uri(path): - return pathlib.Path(os.path.abspath(path)).as_uri() - - -def test_local(pyls): - """ Since the workspace points to the test directory """ - assert pyls.workspace.is_local() - - -def test_put_document(pyls): - pyls.workspace.put_document(DOC_URI, 'content') - assert DOC_URI in pyls.workspace._docs - - -def test_get_document(pyls): - pyls.workspace.put_document(DOC_URI, 'TEXT') - assert pyls.workspace.get_document(DOC_URI).source == 'TEXT' - - -def test_get_missing_document(tmpdir, pyls): - source = 'TEXT' - doc_path = tmpdir.join("test_document.py") - doc_path.write(source) - doc_uri = uris.from_fs_path(str(doc_path)) - assert pyls.workspace.get_document(doc_uri).source == 'TEXT' - - -def test_rm_document(pyls): - pyls.workspace.put_document(DOC_URI, 'TEXT') - assert pyls.workspace.get_document(DOC_URI).source == 'TEXT' - pyls.workspace.rm_document(DOC_URI) - assert pyls.workspace.get_document(DOC_URI)._source is None - - -@pytest.mark.parametrize('metafiles', [('setup.py',), ('pyproject.toml',), ('setup.py', 'pyproject.toml')]) -def test_non_root_project(pyls, metafiles): - repo_root = os.path.join(pyls.workspace.root_path, 'repo-root') - os.mkdir(repo_root) - project_root = os.path.join(repo_root, 'project-root') - os.mkdir(project_root) - - for metafile in metafiles: - with open(os.path.join(project_root, metafile), 'w+') as f: - f.write('# ' + metafile) - - test_uri = uris.from_fs_path(os.path.join(project_root, 'hello/test.py')) - pyls.workspace.put_document(test_uri, 'assert True') - test_doc = pyls.workspace.get_document(test_uri) - assert project_root in test_doc.sys_path() - - -def test_root_project_with_no_setup_py(pyls): - """Default to workspace root.""" - workspace_root = pyls.workspace.root_path - test_uri = uris.from_fs_path(os.path.join(workspace_root, 'hello/test.py')) - pyls.workspace.put_document(test_uri, 'assert True') - test_doc = pyls.workspace.get_document(test_uri) - assert workspace_root in test_doc.sys_path() - - -def test_multiple_workspaces(tmpdir, pyls): - workspace1_dir = tmpdir.mkdir('workspace1') - workspace2_dir = tmpdir.mkdir('workspace2') - file1 = workspace1_dir.join('file1.py') - file2 = workspace2_dir.join('file1.py') - file1.write('import os') - file2.write('import sys') - - msg = { - 'uri': path_as_uri(str(file1)), - 'version': 1, - 'text': 'import os' - } - - pyls.m_text_document__did_open(textDocument=msg) - assert msg['uri'] in pyls.workspace._docs - - added_workspaces = [{'uri': path_as_uri(str(x))} - for x in (workspace1_dir, workspace2_dir)] - event = {'added': added_workspaces, 'removed': []} - pyls.m_workspace__did_change_workspace_folders(event) - - for workspace in added_workspaces: - assert workspace['uri'] in pyls.workspaces - - workspace1_uri = added_workspaces[0]['uri'] - assert msg['uri'] not in pyls.workspace._docs - assert msg['uri'] in pyls.workspaces[workspace1_uri]._docs - - msg = { - 'uri': path_as_uri(str(file2)), - 'version': 1, - 'text': 'import sys' - } - pyls.m_text_document__did_open(textDocument=msg) - - workspace2_uri = added_workspaces[1]['uri'] - assert msg['uri'] in pyls.workspaces[workspace2_uri]._docs - - event = {'added': [], 'removed': [added_workspaces[0]]} - pyls.m_workspace__did_change_workspace_folders(event) - assert workspace1_uri not in pyls.workspaces - - -def test_multiple_workspaces_wrong_removed_uri(pyls, tmpdir): - workspace = {'uri': str(tmpdir.mkdir('Test123'))} - event = {'added': [], 'removed': [workspace]} - pyls.m_workspace__did_change_workspace_folders(event) - assert workspace['uri'] not in pyls.workspaces - - -def test_root_workspace_changed(pyls, tmpdir): - test_uri = str(tmpdir.mkdir('Test123')) - pyls.root_uri = test_uri - pyls.workspace._root_uri = test_uri - - workspace1 = {'uri': test_uri} - workspace2 = {'uri': str(tmpdir.mkdir('NewTest456'))} - - event = {'added': [workspace2], 'removed': [workspace1]} - pyls.m_workspace__did_change_workspace_folders(event) - - assert workspace2['uri'] == pyls.workspace._root_uri - assert workspace2['uri'] == pyls.root_uri - - -def test_root_workspace_not_changed(pyls, tmpdir): - # removed uri != root_uri - test_uri_1 = str(tmpdir.mkdir('Test12')) - pyls.root_uri = test_uri_1 - pyls.workspace._root_uri = test_uri_1 - workspace1 = {'uri': str(tmpdir.mkdir('Test1234'))} - workspace2 = {'uri': str(tmpdir.mkdir('NewTest456'))} - event = {'added': [workspace2], 'removed': [workspace1]} - pyls.m_workspace__did_change_workspace_folders(event) - assert test_uri_1 == pyls.workspace._root_uri - assert test_uri_1 == pyls.root_uri - # empty 'added' list - test_uri_2 = str(tmpdir.mkdir('Test123')) - new_root_uri = workspace2['uri'] - pyls.root_uri = test_uri_2 - pyls.workspace._root_uri = test_uri_2 - workspace1 = {'uri': test_uri_2} - event = {'added': [], 'removed': [workspace1]} - pyls.m_workspace__did_change_workspace_folders(event) - assert new_root_uri == pyls.workspace._root_uri - assert new_root_uri == pyls.root_uri - # empty 'removed' list - event = {'added': [workspace1], 'removed': []} - pyls.m_workspace__did_change_workspace_folders(event) - assert new_root_uri == pyls.workspace._root_uri - assert new_root_uri == pyls.root_uri - # 'added' list has no 'uri' - workspace2 = {'TESTuri': 'Test1234'} - event = {'added': [workspace2], 'removed': [workspace1]} - pyls.m_workspace__did_change_workspace_folders(event) - assert new_root_uri == pyls.workspace._root_uri - assert new_root_uri == pyls.root_uri - - -def test_root_workspace_removed(tmpdir, pyls): - workspace1_dir = tmpdir.mkdir('workspace1') - workspace2_dir = tmpdir.mkdir('workspace2') - root_uri = pyls.root_uri - - # Add workspaces to the pyls - added_workspaces = [{'uri': path_as_uri(str(x))} - for x in (workspace1_dir, workspace2_dir)] - event = {'added': added_workspaces, 'removed': []} - pyls.m_workspace__did_change_workspace_folders(event) - - # Remove the root workspace - removed_workspaces = [{'uri': root_uri}] - event = {'added': [], 'removed': removed_workspaces} - pyls.m_workspace__did_change_workspace_folders(event) - - # Assert that the first of the workspaces (in alphabetical order) is now - # the root workspace - assert pyls.root_uri == path_as_uri(str(workspace1_dir)) - assert pyls.workspace._root_uri == path_as_uri(str(workspace1_dir)) - - -@pytest.mark.skipif(os.name == 'nt', reason="Fails on Windows") -def test_workspace_loads_pycodestyle_config(pyls, tmpdir): - workspace1_dir = tmpdir.mkdir('Test123') - pyls.root_uri = str(workspace1_dir) - pyls.workspace._root_uri = str(workspace1_dir) - - # Test that project settings are loaded - workspace2_dir = tmpdir.mkdir('NewTest456') - cfg = workspace2_dir.join("pycodestyle.cfg") - cfg.write( - "[pycodestyle]\n" - "max-line-length = 1000" - ) - - workspace1 = {'uri': str(workspace1_dir)} - workspace2 = {'uri': str(workspace2_dir)} - - event = {'added': [workspace2], 'removed': [workspace1]} - pyls.m_workspace__did_change_workspace_folders(event) - - seetings = pyls.workspaces[str(workspace2_dir)]._config.settings() - assert seetings['plugins']['pycodestyle']['maxLineLength'] == 1000 - - # Test that project settings prevail over server ones. - server_settings = {'pyls': {'plugins': {'pycodestyle': {'maxLineLength': 10}}}} - pyls.m_workspace__did_change_configuration(server_settings) - assert seetings['plugins']['pycodestyle']['maxLineLength'] == 1000 - - # Test switching to another workspace with different settings - workspace3_dir = tmpdir.mkdir('NewTest789') - cfg1 = workspace3_dir.join("pycodestyle.cfg") - cfg1.write( - "[pycodestyle]\n" - "max-line-length = 20" - ) - - workspace3 = {'uri': str(workspace3_dir)} - - event = {'added': [workspace3], 'removed': [workspace2]} - pyls.m_workspace__did_change_workspace_folders(event) - - seetings = pyls.workspaces[str(workspace3_dir)]._config.settings() - assert seetings['plugins']['pycodestyle']['maxLineLength'] == 20 - - -def test_settings_of_added_workspace(pyls, tmpdir): - test_uri = str(tmpdir.mkdir('Test123')) - pyls.root_uri = test_uri - pyls.workspace._root_uri = test_uri - - # Set some settings for the server. - server_settings = {'pyls': {'plugins': {'jedi': {'environment': '/usr/bin/python3'}}}} - pyls.m_workspace__did_change_configuration(server_settings) - - # Create a new workspace. - workspace1 = {'uri': str(tmpdir.mkdir('NewTest456'))} - event = {'added': [workspace1]} - pyls.m_workspace__did_change_workspace_folders(event) - - # Assert settings are inherited from the server config. - workspace1_object = pyls.workspaces[workspace1['uri']] - workspace1_jedi_settings = workspace1_object._config.plugin_settings('jedi') - assert workspace1_jedi_settings == server_settings['pyls']['plugins']['jedi'] Index: spyder-5.0.5/external-deps/python-lsp-server/test/test_workspace.py =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/test/test_workspace.py @@ -0,0 +1,256 @@ +# Copyright 2017 Palantir Technologies, Inc. +import os +import pathlib + +import pytest +from pylsp import uris + + +DOC_URI = uris.from_fs_path(__file__) + + +def path_as_uri(path): + return pathlib.Path(os.path.abspath(path)).as_uri() + + +def test_local(pylsp): + """ Since the workspace points to the test directory """ + assert pylsp.workspace.is_local() + + +def test_put_document(pylsp): + pylsp.workspace.put_document(DOC_URI, 'content') + assert DOC_URI in pylsp.workspace._docs + + +def test_get_document(pylsp): + pylsp.workspace.put_document(DOC_URI, 'TEXT') + assert pylsp.workspace.get_document(DOC_URI).source == 'TEXT' + + +def test_get_missing_document(tmpdir, pylsp): + source = 'TEXT' + doc_path = tmpdir.join("test_document.py") + doc_path.write(source) + doc_uri = uris.from_fs_path(str(doc_path)) + assert pylsp.workspace.get_document(doc_uri).source == 'TEXT' + + +def test_rm_document(pylsp): + pylsp.workspace.put_document(DOC_URI, 'TEXT') + assert pylsp.workspace.get_document(DOC_URI).source == 'TEXT' + pylsp.workspace.rm_document(DOC_URI) + assert pylsp.workspace.get_document(DOC_URI)._source is None + + +@pytest.mark.parametrize('metafiles', [('setup.py',), ('pyproject.toml',), ('setup.py', 'pyproject.toml')]) +def test_non_root_project(pylsp, metafiles): + repo_root = os.path.join(pylsp.workspace.root_path, 'repo-root') + os.mkdir(repo_root) + project_root = os.path.join(repo_root, 'project-root') + os.mkdir(project_root) + + for metafile in metafiles: + with open(os.path.join(project_root, metafile), 'w+') as f: + f.write('# ' + metafile) + + test_uri = uris.from_fs_path(os.path.join(project_root, 'hello/test.py')) + pylsp.workspace.put_document(test_uri, 'assert True') + test_doc = pylsp.workspace.get_document(test_uri) + assert project_root in test_doc.sys_path() + + +def test_root_project_with_no_setup_py(pylsp): + """Default to workspace root.""" + workspace_root = pylsp.workspace.root_path + test_uri = uris.from_fs_path(os.path.join(workspace_root, 'hello/test.py')) + pylsp.workspace.put_document(test_uri, 'assert True') + test_doc = pylsp.workspace.get_document(test_uri) + assert workspace_root in test_doc.sys_path() + + +def test_multiple_workspaces(tmpdir, pylsp): + workspace1_dir = tmpdir.mkdir('workspace1') + workspace2_dir = tmpdir.mkdir('workspace2') + file1 = workspace1_dir.join('file1.py') + file2 = workspace2_dir.join('file1.py') + file1.write('import os') + file2.write('import sys') + + msg = { + 'uri': path_as_uri(str(file1)), + 'version': 1, + 'text': 'import os' + } + + pylsp.m_text_document__did_open(textDocument=msg) + assert msg['uri'] in pylsp.workspace._docs + + added_workspaces = [{'uri': path_as_uri(str(x))} + for x in (workspace1_dir, workspace2_dir)] + event = {'added': added_workspaces, 'removed': []} + pylsp.m_workspace__did_change_workspace_folders(event) + + for workspace in added_workspaces: + assert workspace['uri'] in pylsp.workspaces + + workspace1_uri = added_workspaces[0]['uri'] + assert msg['uri'] not in pylsp.workspace._docs + assert msg['uri'] in pylsp.workspaces[workspace1_uri]._docs + + msg = { + 'uri': path_as_uri(str(file2)), + 'version': 1, + 'text': 'import sys' + } + pylsp.m_text_document__did_open(textDocument=msg) + + workspace2_uri = added_workspaces[1]['uri'] + assert msg['uri'] in pylsp.workspaces[workspace2_uri]._docs + + event = {'added': [], 'removed': [added_workspaces[0]]} + pylsp.m_workspace__did_change_workspace_folders(event) + assert workspace1_uri not in pylsp.workspaces + + +def test_multiple_workspaces_wrong_removed_uri(pylsp, tmpdir): + workspace = {'uri': str(tmpdir.mkdir('Test123'))} + event = {'added': [], 'removed': [workspace]} + pylsp.m_workspace__did_change_workspace_folders(event) + assert workspace['uri'] not in pylsp.workspaces + + +def test_root_workspace_changed(pylsp, tmpdir): + test_uri = str(tmpdir.mkdir('Test123')) + pylsp.root_uri = test_uri + pylsp.workspace._root_uri = test_uri + + workspace1 = {'uri': test_uri} + workspace2 = {'uri': str(tmpdir.mkdir('NewTest456'))} + + event = {'added': [workspace2], 'removed': [workspace1]} + pylsp.m_workspace__did_change_workspace_folders(event) + + assert workspace2['uri'] == pylsp.workspace._root_uri + assert workspace2['uri'] == pylsp.root_uri + + +def test_root_workspace_not_changed(pylsp, tmpdir): + # removed uri != root_uri + test_uri_1 = str(tmpdir.mkdir('Test12')) + pylsp.root_uri = test_uri_1 + pylsp.workspace._root_uri = test_uri_1 + workspace1 = {'uri': str(tmpdir.mkdir('Test1234'))} + workspace2 = {'uri': str(tmpdir.mkdir('NewTest456'))} + event = {'added': [workspace2], 'removed': [workspace1]} + pylsp.m_workspace__did_change_workspace_folders(event) + assert test_uri_1 == pylsp.workspace._root_uri + assert test_uri_1 == pylsp.root_uri + # empty 'added' list + test_uri_2 = str(tmpdir.mkdir('Test123')) + new_root_uri = workspace2['uri'] + pylsp.root_uri = test_uri_2 + pylsp.workspace._root_uri = test_uri_2 + workspace1 = {'uri': test_uri_2} + event = {'added': [], 'removed': [workspace1]} + pylsp.m_workspace__did_change_workspace_folders(event) + assert new_root_uri == pylsp.workspace._root_uri + assert new_root_uri == pylsp.root_uri + # empty 'removed' list + event = {'added': [workspace1], 'removed': []} + pylsp.m_workspace__did_change_workspace_folders(event) + assert new_root_uri == pylsp.workspace._root_uri + assert new_root_uri == pylsp.root_uri + # 'added' list has no 'uri' + workspace2 = {'TESTuri': 'Test1234'} + event = {'added': [workspace2], 'removed': [workspace1]} + pylsp.m_workspace__did_change_workspace_folders(event) + assert new_root_uri == pylsp.workspace._root_uri + assert new_root_uri == pylsp.root_uri + + +def test_root_workspace_removed(tmpdir, pylsp): + workspace1_dir = tmpdir.mkdir('workspace1') + workspace2_dir = tmpdir.mkdir('workspace2') + root_uri = pylsp.root_uri + + # Add workspaces to the pylsp + added_workspaces = [{'uri': path_as_uri(str(x))} + for x in (workspace1_dir, workspace2_dir)] + event = {'added': added_workspaces, 'removed': []} + pylsp.m_workspace__did_change_workspace_folders(event) + + # Remove the root workspace + removed_workspaces = [{'uri': root_uri}] + event = {'added': [], 'removed': removed_workspaces} + pylsp.m_workspace__did_change_workspace_folders(event) + + # Assert that the first of the workspaces (in alphabetical order) is now + # the root workspace + assert pylsp.root_uri == path_as_uri(str(workspace1_dir)) + assert pylsp.workspace._root_uri == path_as_uri(str(workspace1_dir)) + + +@pytest.mark.skipif(os.name == 'nt', reason="Fails on Windows") +def test_workspace_loads_pycodestyle_config(pylsp, tmpdir): + workspace1_dir = tmpdir.mkdir('Test123') + pylsp.root_uri = str(workspace1_dir) + pylsp.workspace._root_uri = str(workspace1_dir) + + # Test that project settings are loaded + workspace2_dir = tmpdir.mkdir('NewTest456') + cfg = workspace2_dir.join("pycodestyle.cfg") + cfg.write( + "[pycodestyle]\n" + "max-line-length = 1000" + ) + + workspace1 = {'uri': str(workspace1_dir)} + workspace2 = {'uri': str(workspace2_dir)} + + event = {'added': [workspace2], 'removed': [workspace1]} + pylsp.m_workspace__did_change_workspace_folders(event) + + seetings = pylsp.workspaces[str(workspace2_dir)]._config.settings() + assert seetings['plugins']['pycodestyle']['maxLineLength'] == 1000 + + # Test that project settings prevail over server ones. + server_settings = {'pylsp': {'plugins': {'pycodestyle': {'maxLineLength': 10}}}} + pylsp.m_workspace__did_change_configuration(server_settings) + assert seetings['plugins']['pycodestyle']['maxLineLength'] == 1000 + + # Test switching to another workspace with different settings + workspace3_dir = tmpdir.mkdir('NewTest789') + cfg1 = workspace3_dir.join("pycodestyle.cfg") + cfg1.write( + "[pycodestyle]\n" + "max-line-length = 20" + ) + + workspace3 = {'uri': str(workspace3_dir)} + + event = {'added': [workspace3], 'removed': [workspace2]} + pylsp.m_workspace__did_change_workspace_folders(event) + + seetings = pylsp.workspaces[str(workspace3_dir)]._config.settings() + assert seetings['plugins']['pycodestyle']['maxLineLength'] == 20 + + +def test_settings_of_added_workspace(pylsp, tmpdir): + test_uri = str(tmpdir.mkdir('Test123')) + pylsp.root_uri = test_uri + pylsp.workspace._root_uri = test_uri + + # Set some settings for the server. + server_settings = {'pylsp': {'plugins': {'jedi': {'environment': '/usr/bin/python3'}}}} + pylsp.m_workspace__did_change_configuration(server_settings) + + # Create a new workspace. + workspace1 = {'uri': str(tmpdir.mkdir('NewTest456'))} + event = {'added': [workspace1]} + pylsp.m_workspace__did_change_workspace_folders(event) + + # Assert settings are inherited from the server config. + workspace1_object = pylsp.workspaces[workspace1['uri']] + workspace1_jedi_settings = workspace1_object._config.plugin_settings('jedi') + assert workspace1_jedi_settings == server_settings['pylsp']['plugins']['jedi'] Index: spyder-5.0.5/installers/Windows/installer.py =================================================================== --- spyder-5.0.5.orig/installers/Windows/installer.py +++ spyder-5.0.5/installers/Windows/installer.py @@ -44,7 +44,7 @@ ASSETS_URL = os.environ.get( 'releases/download/0.0.1/assets.zip') # Packages to remove from the requirements for example pip or -# external direct dependencies (python-language-server spyder-kernels) +# external direct dependencies (python-lsp-server spyder-kernels) UNWANTED_PACKAGES = os.environ.get('UNWANTED_PACKAGES', '').split() @@ -55,12 +55,12 @@ SKIP_PACKAGES = os.environ.get('SKIP_PAC # Packages to be added to the packages section regardless wheel checks or # packages skipped, for example external direct dependencies -# (spyder-kernels python-language-server) +# (spyder-kernels python-lsp-server) ADD_PACKAGES = os.environ.get('ADD_PACKAGES', '').split() # Packages to be installed using the editable flag -# (python-language-server in PRs) +# (python-lsp-server in PRs) INSTALL_EDITABLE_PACKAGES = os.environ.get( 'INSTALL_EDITABLE_PACKAGES', '').split() Index: spyder-5.0.5/installers/macOS/setup.py =================================================================== --- spyder-5.0.5.orig/installers/macOS/setup.py +++ spyder-5.0.5/installers/macOS/setup.py @@ -97,11 +97,11 @@ def make_app_bundle(dist_dir, make_lite= Note: only applicable to not-Lite build pygments : ModuleNotFoundError: No module named 'pygments.formatters.latex' - pyls : - <path>/Contents/MacOS/python: No module named pyls + pylsp : + <path>/Contents/MacOS/python: No module named pylsp Note: still occurs in alias mode - pyls_black : - Mandatory: pyls_black >=0.4.6 : None (NOK) + pylsp_black : + Mandatory: python-pyls-black >=1.0.0 : None (NOK) pyls_spyder : Mandatory: pyls_spyder >=0.1.1 : None (NOK) qtawesome : @@ -144,8 +144,8 @@ def make_app_bundle(dist_dir, make_lite= logger.info('Creating %s app bundle...', build_type) PACKAGES = ['alabaster', 'astroid', 'docutils', 'blib2to3', 'IPython', - 'jedi', 'jinja2', 'keyring', 'parso', 'pygments', 'pyls', - 'pyls_black', 'pyls_spyder', 'qtawesome', 'setuptools', + 'jedi', 'jinja2', 'keyring', 'parso', 'pygments', 'pylsp', + 'pylsp_black', 'pyls_spyder', 'qtawesome', 'setuptools', 'sphinx', 'spyder', 'spyder_kernels', 'textdistance', ] INCLUDES = ['_sitebuiltins', # required for IPython help() Index: spyder-5.0.5/requirements/conda.txt =================================================================== --- spyder-5.0.5.orig/requirements/conda.txt +++ spyder-5.0.5/requirements/conda.txt @@ -21,13 +21,13 @@ pexpect >=4.4.0 pickleshare >=0.4 psutil >=5.3 pygments >=2.0 -pylint >=1.0 -pyls-black >=0.4.6 -pyls-spyder >=0.3.2,<0.4.0 +pylint >=2.5.0 +python-lsp-black >=1.0.0 +pyls-spyder >=0.4.0 pyqt <5.13 -# There's no need to set a version for python-language-server +# There's no need to set a version for python-lsp-server # because we install it from master for our tests. -python-language-server +python-lsp-server pyxdg >=0.26 pyzmq >=17 qdarkstyle =3.0.2 Index: spyder-5.0.5/setup.py =================================================================== --- spyder-5.0.5.orig/setup.py +++ spyder-5.0.5/setup.py @@ -221,12 +221,12 @@ install_requires = [ 'pickleshare>=0.4', 'psutil>=5.3', 'pygments>=2.0', - 'pylint>=1.0', - 'pyls-black>=0.4.6', - 'pyls-spyder>=0.3.2,<0.4.0', + 'pylint>=2.5.0', + 'python-lsp-black>=1.0.0', + 'pyls-spyder>=0.4.0', 'pyqt5<5.13', 'pyqtwebengine<5.13', - 'python-language-server[all]>=0.36.2,<1.0.0', + 'python-lsp-server[all]>=1.0.0', 'pyxdg>=0.26;platform_system=="Linux"', 'pyzmq>=17', 'qdarkstyle==3.0.2', Index: spyder-5.0.5/spyder/app/tests/test_mainwindow.py =================================================================== --- spyder-5.0.5.orig/spyder/app/tests/test_mainwindow.py +++ spyder-5.0.5/spyder/app/tests/test_mainwindow.py @@ -2681,7 +2681,7 @@ def test_preferences_change_interpreter( # Check original pyls configuration lsp = main_window.completions.get_provider('lsp') config = lsp.generate_python_config() - jedi = config['configurations']['pyls']['plugins']['jedi'] + jedi = config['configurations']['pylsp']['plugins']['jedi'] assert jedi['environment'] is None assert jedi['extra_paths'] == [] @@ -2696,7 +2696,7 @@ def test_preferences_change_interpreter( # Check updated pyls configuration config = lsp.generate_python_config() - jedi = config['configurations']['pyls']['plugins']['jedi'] + jedi = config['configurations']['pylsp']['plugins']['jedi'] assert jedi['environment'] == sys.executable assert jedi['extra_paths'] == [] Index: spyder-5.0.5/spyder/config/lsp.py =================================================================== --- spyder-5.0.5.orig/spyder/config/lsp.py +++ spyder-5.0.5/spyder/config/lsp.py @@ -21,14 +21,14 @@ Notes: # Default json config for the lsp # ============================================================================= PYTHON_CONFIG = { - 'cmd': 'pyls', + 'cmd': 'pylsp', 'args': '--host {host} --port {port} --tcp', 'host': '127.0.0.1', 'port': 2087, 'external': False, 'stdio': False, 'configurations': { - 'pyls': { + 'pylsp': { 'configurationSources': [ "pycodestyle", "pyflakes"], 'plugins': { Index: spyder-5.0.5/spyder/dependencies.py =================================================================== --- spyder-5.0.5.orig/spyder/dependencies.py +++ spyder-5.0.5/spyder/dependencies.py @@ -51,10 +51,10 @@ PEXPECT_REQVER = '>=4.4.0' PICKLESHARE_REQVER = '>=0.4' PSUTIL_REQVER = '>=5.3' PYGMENTS_REQVER = '>=2.0' -PYLINT_REQVER = '>=1.0' -PYLS_REQVER = '>=0.36.2;<1.0.0' -PYLS_BLACK_REQVER = '>=0.4.6' -PYLS_SPYDER_REQVER = '>=0.3.2;<0.4.0' +PYLINT_REQVER = '>=2.5.0' +PYLSP_REQVER = '>=1.0.0' +PYLSP_BLACK_REQVER = '>=1.0.0' +PYLS_SPYDER_REQVER = '>=0.4.0' PYXDG_REQVER = '>=0.26' PYZMQ_REQVER = '>=17' QDARKSTYLE_REQVER = '=3.0.2' @@ -174,18 +174,18 @@ DESCRIPTIONS = [ 'package_name': "pylint", 'features': _("Static code analysis"), 'required_version': PYLINT_REQVER}, - {'modname': 'pyls', - 'package_name': 'python-language-server', + {'modname': 'pylsp', + 'package_name': 'python-lsp-server', 'features': _("Code completion and linting for the Editor"), - 'required_version': PYLS_REQVER}, - {'modname': 'pyls_black', - 'package_name': 'pyls-black', + 'required_version': PYLSP_REQVER}, + {'modname': 'pylsp_black', + 'package_name': 'python-lsp-black', 'features': _("Autoformat Python files in the Editor with the Black " "package"), - 'required_version': PYLS_BLACK_REQVER}, + 'required_version': PYLSP_BLACK_REQVER}, {'modname': 'pyls_spyder', 'package_name': 'pyls-spyder', - 'features': _('Spyder plugin for the Python Language Server'), + 'features': _('Spyder plugin for the Python LSP Server'), 'required_version': PYLS_SPYDER_REQVER}, {'modname': "xdg", 'package_name': "pyxdg", Index: spyder-5.0.5/spyder/plugins/completion/providers/languageserver/provider.py =================================================================== --- spyder-5.0.5.orig/spyder/plugins/completion/providers/languageserver/provider.py +++ spyder-5.0.5/spyder/plugins/completion/providers/languageserver/provider.py @@ -73,7 +73,7 @@ class LanguageServerProvider(SpyderCompl ('pydocstyle/match', '(?!test_).*\\.py'), ('pydocstyle/match_dir', '[^\\.].*'), ('advanced/enabled', False), - ('advanced/module', 'pyls'), + ('advanced/module', 'pylsp'), ('advanced/host', '127.0.0.1'), ('advanced/port', 2087), ('advanced/external', False), @@ -695,7 +695,7 @@ class LanguageServerProvider(SpyderCompl python_config = PYTHON_CONFIG.copy() # Server options - cmd = self.get_conf('advanced/module', 'pyls') + cmd = self.get_conf('advanced/module', 'pylsp') host = self.get_conf('advanced/host', '127.0.0.1') port = self.get_conf('advanced/port', 2087) @@ -825,7 +825,7 @@ class LanguageServerProvider(SpyderCompl python_config['host'] = host python_config['port'] = port - plugins = python_config['configurations']['pyls']['plugins'] + plugins = python_config['configurations']['pylsp']['plugins'] plugins['pycodestyle'].update(pycodestyle) plugins['pyflakes'].update(pyflakes) plugins['pydocstyle'].update(pydocstyle) Index: spyder-5.0.5/spyder/plugins/editor/widgets/tests/assets/autopep8_range.py =================================================================== --- spyder-5.0.5.orig/spyder/plugins/editor/widgets/tests/assets/autopep8_range.py +++ spyder-5.0.5/spyder/plugins/editor/widgets/tests/assets/autopep8_range.py @@ -10,11 +10,13 @@ import os;import sys # %% functions def d(): - def inner(): return 2 + def inner(): + return 2 + return inner -# ---- func 1 and 2 +# ---- func 1 and 2 def func1(): for i in range(3): print(i) @@ -23,9 +25,9 @@ def func1(): def func2(): if True: pass -# ---- other functions +# ---- other functions def a(): pass Index: spyder-5.0.5/spyder/plugins/editor/widgets/tests/assets/autopep8_result.py =================================================================== --- spyder-5.0.5.orig/spyder/plugins/editor/widgets/tests/assets/autopep8_result.py +++ spyder-5.0.5/spyder/plugins/editor/widgets/tests/assets/autopep8_result.py @@ -11,11 +11,13 @@ import sys # %% functions def d(): - def inner(): return 2 + def inner(): + return 2 + return inner -# ---- func 1 and 2 +# ---- func 1 and 2 def func1(): for i in range(3): print(i) @@ -24,9 +26,9 @@ def func1(): def func2(): if True: pass -# ---- other functions +# ---- other functions def a(): pass Index: spyder-5.0.5/spyder/plugins/editor/widgets/tests/conftest.py =================================================================== --- spyder-5.0.5.orig/spyder/plugins/editor/widgets/tests/conftest.py +++ spyder-5.0.5/spyder/plugins/editor/widgets/tests/conftest.py @@ -147,7 +147,7 @@ def mock_completions_codeeditor(qtbot_mo @pytest.fixture def completions_codeeditor(completion_plugin_all_started, qtbot_module, - request, capsys): + request, capsys, tmp_path): """CodeEditor instance with LSP services activated.""" # Create a CodeEditor instance editor = codeeditor_factory() @@ -164,10 +164,13 @@ def completions_codeeditor(completion_pl editor.sig_perform_completion_request.connect( completion_plugin.send_request) - editor.filename = 'test.py' + file_path = tmp_path / 'test.py' + file_path.write_text('') + + editor.filename = str(file_path) editor.language = 'Python' - completion_plugin.register_file('python', 'test.py', editor) + completion_plugin.register_file('python', str(file_path), editor) editor.start_completion_services() editor.register_completion_capabilities(capabilities) Index: spyder-5.0.5/spyder/plugins/editor/widgets/tests/test_formatting.py =================================================================== --- spyder-5.0.5.orig/spyder/plugins/editor/widgets/tests/test_formatting.py +++ spyder-5.0.5/spyder/plugins/editor/widgets/tests/test_formatting.py @@ -7,6 +7,7 @@ """Tests for code formatting.""" # Standard library imports +import os import os.path as osp # Third party imports @@ -22,6 +23,14 @@ from spyder.config.manager import CONF HERE = osp.dirname(osp.abspath(__file__)) ASSETS = osp.join(HERE, 'assets') +autopep8 = pytest.param( + 'autopep8', + marks=pytest.mark.skipif( + os.name == 'nt', + reason='autopep8 produces a different output on Windows' + ) +) + def get_formatter_values(formatter, range_fmt=False): suffix = 'range' if range_fmt else 'result' @@ -39,7 +48,7 @@ def get_formatter_values(formatter, rang @pytest.mark.slow @pytest.mark.order(1) -@pytest.mark.parametrize('formatter', ['autopep8', 'yapf', 'black']) +@pytest.mark.parametrize('formatter', [autopep8, 'yapf', 'black']) def test_document_formatting(formatter, completions_codeeditor, qtbot): """Validate text autoformatting via autopep8, yapf or black.""" code_editor, completion_plugin = completions_codeeditor @@ -72,7 +81,8 @@ def test_document_formatting(formatter, @pytest.mark.slow @pytest.mark.order(1) -@pytest.mark.parametrize('formatter', ['autopep8', 'yapf', 'black']) +@pytest.mark.parametrize( + 'formatter', [autopep8, 'yapf', 'black']) def test_document_range_formatting(formatter, completions_codeeditor, qtbot): """Validate text range autoformatting.""" code_editor, completion_plugin = completions_codeeditor Index: spyder-5.0.5/spyder/tests/test_dependencies_in_sync.py =================================================================== --- spyder-5.0.5.orig/spyder/tests/test_dependencies_in_sync.py +++ spyder-5.0.5/spyder/tests/test_dependencies_in_sync.py @@ -208,7 +208,7 @@ def test_dependencies_for_binder_in_sync # There's no need to test for this because we install it # from master in some cases. for req in [spyder_env, spyder_reqs]: - req.pop('python-language-server') + req.pop('python-lsp-server') # Check that the requirement files match the environment yaml file full_reqs = {} @@ -229,7 +229,7 @@ def test_dependencies_for_spyder_dialog_ # a subrepo for them or we're installing them from master. for req in [spyder_deps, spyder_reqs]: req.pop('spyder-kernels') - req.pop('python-language-server') + req.pop('python-lsp-server') if 'pyqt' in spyder_reqs: spyder_reqs.pop('pyqt') @@ -255,7 +255,7 @@ def test_dependencies_for_spyder_setup_i # a subrepo for them or we're installing them from master. for req in [spyder_reqs, spyder_setup]: req.pop('spyder-kernels') - req.pop('python-language-server') + req.pop('python-lsp-server') if 'pyqtwebengine' in spyder_setup: spyder_setup.pop('pyqtwebengine') Index: spyder-5.0.5/spyder/utils/programs.py =================================================================== --- spyder-5.0.5.orig/spyder/utils/programs.py +++ spyder-5.0.5/spyder/utils/programs.py @@ -846,8 +846,12 @@ def check_version(actver, version, cmp_o def get_module_version(module_name): """Return module version or None if version can't be retrieved.""" - mod = __import__(module_name) - ver = getattr(mod, '__version__', getattr(mod, 'VERSION', None)) + ver = None + try: + mod = __import__(module_name) + ver = getattr(mod, '__version__', getattr(mod, 'VERSION', None)) + except ModuleNotFoundError: + pass if not ver: ver = get_package_version(module_name) return ver Index: spyder-5.0.5/spyder/utils/tests/test_programs.py =================================================================== --- spyder-5.0.5.orig/spyder/utils/tests/test_programs.py +++ spyder-5.0.5/spyder/utils/tests/test_programs.py @@ -291,7 +291,7 @@ def test_get_package_version(): def test_get_module_version(): # pyls_black should not have a __version__ attribute, so tests that the # fallback mechanism to get_package_version is working - assert get_module_version('pyls_black') + assert get_module_version('python_lsp_black') if __name__ == '__main__': Index: spyder-5.0.5/external-deps/python-language-server/.github/workflows/release.yml =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/.github/workflows/release.yml +++ /dev/null @@ -1,44 +0,0 @@ -name: PyLS Release - -on: - release: - types: - - created - - -jobs: - build: - name: Linux Py${{ matrix.PYTHON_VERSION }} - runs-on: ubuntu-latest - env: - CI: 'true' - OS: 'linux' - PYTHON_VERSION: ${{ matrix.PYTHON_VERSION }} - strategy: - fail-fast: false - matrix: - PYTHON_VERSION: ['3.8'] - timeout-minutes: 10 - steps: - - uses: actions/cache@v1 - with: - path: ~/.cache/pip - key: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip-${{ hashFiles('setup.py') }} - restore-keys: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip- - - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - uses: actions/setup-python@v2 - with: - python-version: ${{ matrix.PYTHON_VERSION }} - architecture: 'x64' - - run: python -m pip install --upgrade pip setuptools wheel twine - - name: Build and publish python-language-server - env: - TWINE_USERNAME: __token__ - TWINE_PASSWORD: ${{ secrets.PYPI_PYLS_TOKEN }} - run: | - python setup.py bdist_wheel --universal - python setup.py sdist - python -m twine check dist/* - python -m twine upload dist/* Index: spyder-5.0.5/external-deps/python-language-server/.gitignore =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/.gitignore +++ /dev/null @@ -1,114 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# IntelliJ -*.iml -*.ipr -*.iws -.idea/ -out/ - -# C extensions -*.so - -# Distribution / packaging -.Python -env/ -env3/ -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -*.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.xml -.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/ - -# IPython Notebook -.ipynb_checkpoints - -# pyenv -.python-version - -# celery beat schedule file -celerybeat-schedule - -# dotenv -.env - -# virtualenv -venv/ -ENV/ - -# Spyder project settings -.spyderproject - -# Rope project settings -.ropeproject - -# JavaScript -**/*.vscode/ - -# vim -*.sw[mnopqrs] - -# Idea -.idea/ - -# Merge orig files -*.orig - -# Special files -.DS_Store Index: spyder-5.0.5/external-deps/python-language-server/.policy.yml =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/.policy.yml +++ /dev/null @@ -1,100 +0,0 @@ -# Excavator auto-updates this file. Please contribute improvements to the central template. - -policy: - approval: - - or: - - one admin or contributor has approved - - two admins have approved - - changelog only and contributor approval - - fixing excavator - - excavator only touched baseline, circle, gradle files, godel files, docker-compose-rule config or versions.props - - excavator only touched config files - - bots updated package.json and lock files - disapproval: - requires: - organizations: [ "palantir" ] - -approval_rules: - - name: one admin or contributor has approved - options: - allow_contributor: true - requires: - count: 1 - admins: true - - - name: two admins have approved - options: - allow_contributor: true - requires: - count: 2 - admins: true - - - name: changelog only and contributor approval - options: - allow_contributor: true - requires: - count: 1 - admins: true - if: - only_changed_files: - paths: - - "changelog/@unreleased/.*\\.yml" - - - name: fixing excavator - options: - allow_contributor: true - requires: - count: 1 - admins: true - if: - has_author_in: - users: [ "svc-excavator-bot" ] - - - name: excavator only touched baseline, circle, gradle files, godel files, docker-compose-rule config or versions.props - requires: - count: 0 - if: - has_author_in: - users: [ "svc-excavator-bot" ] - only_changed_files: - # product-dependencies.lock should never go here, to force review of all product (SLS) dependency changes - # this way excavator cannot change the deployability of a service or product via auto-merge - paths: - - "changelog/@unreleased/.*\\.yml" - - "^\\.baseline/.*$" - - "^\\.circleci/.*$" - - "^\\.docker-compose-rule\\.yml$" - - "^.*gradle$" - - "^gradle/wrapper/.*" - - "^gradlew$" - - "^gradlew.bat$" - - "^gradle.properties$" - - "^settings.gradle$" - - "^godelw$" - - "^godel/config/godel.properties$" - - "^versions.props$" - - "^versions.lock$" - - - name: excavator only touched config files - requires: - count: 0 - if: - has_author_in: - users: [ "svc-excavator-bot" ] - only_changed_files: - paths: - - "^\\..*.yml$" - - "^\\.github/.*$" - - - name: bots updated package.json and lock files - requires: - count: 0 - if: - has_author_in: - users: - - "svc-excavator-bot" - - "dependabot[bot]" - only_changed_files: - paths: - - "^.*yarn.lock$" - - "^.*package.json$" Index: spyder-5.0.5/external-deps/python-language-server/scripts/circle/pypi.sh =================================================================== --- spyder-5.0.5.orig/external-deps/python-language-server/scripts/circle/pypi.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash -e - -if [ -z "$CI" ]; then - echo "Will only continue on CI" - exit -fi - -# build package and upload to private pypi index -rm -f ~/.pypirc -echo "[distutils]" >> ~/.pypirc -echo "index-servers = pypi-private" >> ~/.pypirc -echo "[pypi-private]" >> ~/.pypirc -echo "repository=https://$PYPI_HOST" >> ~/.pypirc -echo "username=$PYPI_USERNAME" >> ~/.pypirc -echo "password=$PYPI_PASSWORD" >> ~/.pypirc - -python setup.py bdist_wheel sdist upload -r pypi-private Index: spyder-5.0.5/external-deps/python-lsp-server/.github/workflows/release.yml =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/.github/workflows/release.yml @@ -0,0 +1,44 @@ +name: PyLS Release + +on: + release: + types: + - created + + +jobs: + build: + name: Linux Py${{ matrix.PYTHON_VERSION }} + runs-on: ubuntu-latest + env: + CI: 'true' + OS: 'linux' + PYTHON_VERSION: ${{ matrix.PYTHON_VERSION }} + strategy: + fail-fast: false + matrix: + PYTHON_VERSION: ['3.8'] + timeout-minutes: 10 + steps: + - uses: actions/cache@v1 + with: + path: ~/.cache/pip + key: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip-${{ hashFiles('setup.py') }} + restore-keys: ${{ runner.os }}-${{ matrix.PYTHON_VERSION }}-pip- + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + - uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.PYTHON_VERSION }} + architecture: 'x64' + - run: python -m pip install --upgrade pip setuptools wheel twine + - name: Build and publish python-language-server + env: + TWINE_USERNAME: __token__ + TWINE_PASSWORD: ${{ secrets.PYPI_PYLS_TOKEN }} + run: | + python setup.py bdist_wheel --universal + python setup.py sdist + python -m twine check dist/* + python -m twine upload dist/* Index: spyder-5.0.5/external-deps/python-lsp-server/.gitignore =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/.gitignore @@ -0,0 +1,114 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ +out/ + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +env3/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.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.xml +.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/ + +# IPython Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# dotenv +.env + +# virtualenv +venv/ +ENV/ + +# Spyder project settings +.spyderproject + +# Rope project settings +.ropeproject + +# JavaScript +**/*.vscode/ + +# vim +*.sw[mnopqrs] + +# Idea +.idea/ + +# Merge orig files +*.orig + +# Special files +.DS_Store Index: spyder-5.0.5/external-deps/python-lsp-server/.policy.yml =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/.policy.yml @@ -0,0 +1,100 @@ +# Excavator auto-updates this file. Please contribute improvements to the central template. + +policy: + approval: + - or: + - one admin or contributor has approved + - two admins have approved + - changelog only and contributor approval + - fixing excavator + - excavator only touched baseline, circle, gradle files, godel files, docker-compose-rule config or versions.props + - excavator only touched config files + - bots updated package.json and lock files + disapproval: + requires: + organizations: [ "palantir" ] + +approval_rules: + - name: one admin or contributor has approved + options: + allow_contributor: true + requires: + count: 1 + admins: true + + - name: two admins have approved + options: + allow_contributor: true + requires: + count: 2 + admins: true + + - name: changelog only and contributor approval + options: + allow_contributor: true + requires: + count: 1 + admins: true + if: + only_changed_files: + paths: + - "changelog/@unreleased/.*\\.yml" + + - name: fixing excavator + options: + allow_contributor: true + requires: + count: 1 + admins: true + if: + has_author_in: + users: [ "svc-excavator-bot" ] + + - name: excavator only touched baseline, circle, gradle files, godel files, docker-compose-rule config or versions.props + requires: + count: 0 + if: + has_author_in: + users: [ "svc-excavator-bot" ] + only_changed_files: + # product-dependencies.lock should never go here, to force review of all product (SLS) dependency changes + # this way excavator cannot change the deployability of a service or product via auto-merge + paths: + - "changelog/@unreleased/.*\\.yml" + - "^\\.baseline/.*$" + - "^\\.circleci/.*$" + - "^\\.docker-compose-rule\\.yml$" + - "^.*gradle$" + - "^gradle/wrapper/.*" + - "^gradlew$" + - "^gradlew.bat$" + - "^gradle.properties$" + - "^settings.gradle$" + - "^godelw$" + - "^godel/config/godel.properties$" + - "^versions.props$" + - "^versions.lock$" + + - name: excavator only touched config files + requires: + count: 0 + if: + has_author_in: + users: [ "svc-excavator-bot" ] + only_changed_files: + paths: + - "^\\..*.yml$" + - "^\\.github/.*$" + + - name: bots updated package.json and lock files + requires: + count: 0 + if: + has_author_in: + users: + - "svc-excavator-bot" + - "dependabot[bot]" + only_changed_files: + paths: + - "^.*yarn.lock$" + - "^.*package.json$" Index: spyder-5.0.5/external-deps/python-lsp-server/scripts/circle/pypi.sh =================================================================== --- /dev/null +++ spyder-5.0.5/external-deps/python-lsp-server/scripts/circle/pypi.sh @@ -0,0 +1,17 @@ +#!/bin/bash -e + +if [ -z "$CI" ]; then + echo "Will only continue on CI" + exit +fi + +# build package and upload to private pypi index +rm -f ~/.pypirc +echo "[distutils]" >> ~/.pypirc +echo "index-servers = pypi-private" >> ~/.pypirc +echo "[pypi-private]" >> ~/.pypirc +echo "repository=https://$PYPI_HOST" >> ~/.pypirc +echo "username=$PYPI_USERNAME" >> ~/.pypirc +echo "password=$PYPI_PASSWORD" >> ~/.pypirc + +python setup.py bdist_wheel sdist upload -r pypi-private
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor