Skip to content

Commit

Permalink
Adds ignore patterns and some bug fixes (#239)
Browse files Browse the repository at this point in the history
  • Loading branch information
karthiknadig committed Oct 20, 2023
1 parent ed1ea42 commit 4329677
Show file tree
Hide file tree
Showing 22 changed files with 857 additions and 719 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@ If you want to disable flake8, you can [disable this extension](https://code.vis
| Settings | Default | Description |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| flake8.args | `[]` | Custom arguments passed to `flake8`. E.g `"flake8.args" = ["--config=<file>"]` |
| flake8.cwd | `${workspaceFolder}` | This setting specifies the working directory for `flake8`. By default, it uses the root directory of the workspace `${workspaceFolder}`. If you want `flake8` to operate within the directory of the file currently being linted, you can set this to `${fileDirname}`. |
| flake8.severity | `{ "convention": "Information", "error": "Error", "fatal": "Error", "refactor": "Hint", "warning": "Warning", "info": "Information" }` | Controls mapping of severity from `flake8` to VS Code severity when displaying in the problems window. You can override specific `flake8` error codes `{ "convention": "Information", "error": "Error", "fatal": "Error", "refactor": "Hint", "warning": "Warning", "W0611": "Error", "undefined-variable": "Warning" }` |
| flake8.logLevel | `error` | Sets the tracing level for the extension. |
| flake8.path | `[]` | Setting to provide custom `flake8` executable. This will slow down linting, since we will have to run `flake8` executable every time or file save or open. Example 1: `["~/global_env/flake8"]` Example 2: `["conda", "run", "-n", "lint_env", "python", "-m", "flake8"]` |
| flake8.interpreter | `[]` | Path to a python interpreter to use to run the linter server. When set to `[]`, the interpreter for the workspace is obtained from `ms-python.python` extension. If set to some path, that path takes precedence, and the Python extension is not queried for the interpreter. |
| flake8.importStrategy | `useBundled` | Setting to choose where to load `flake8` from. `useBundled` picks flake8 bundled with the extension. `fromEnvironment` uses `flake8` available in the environment. |
| flake8.showNotification | `off` | Setting to control when a notification is shown. |
| flake8.ignorePatterns | `[]` | Glob patterns used to exclude files and directories from being linted. |

## Commands

Expand Down
1 change: 0 additions & 1 deletion bundled/tool/_debug_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ def update_sys_path(path_to_add: str) -> None:

update_sys_path(debugger_path)

# pylint: disable=wrong-import-position,import-error
import debugpy

# 5678 is the default port, If you need to change it update it here
Expand Down
55 changes: 50 additions & 5 deletions bundled/tool/lsp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import pathlib
import re
import sys
import sysconfig
import traceback
from typing import Any, Callable, Dict, List, Optional, Sequence, Union

Expand All @@ -25,6 +26,26 @@ def update_sys_path(path_to_add: str, strategy: str) -> None:
sys.path.append(path_to_add)


# **********************************************************
# Update PATH before running anything.
# **********************************************************
def update_environ_path() -> None:
"""Update PATH environment variable with the 'scripts' directory.
Windows: .venv/Scripts
Linux/MacOS: .venv/bin
"""
scripts = sysconfig.get_path("scripts")
paths_variants = ["Path", "PATH"]

for var_name in paths_variants:
if var_name in os.environ:
paths = os.environ[var_name].split(os.pathsep)
if scripts not in paths:
paths.insert(0, scripts)
os.environ[var_name] = os.pathsep.join(paths)
break


# Ensure that we can import LSP libraries, and other bundled libraries.
BUNDLE_DIR = pathlib.Path(__file__).parent.parent
# Always use bundled server files.
Expand All @@ -33,6 +54,7 @@ def update_sys_path(path_to_add: str, strategy: str) -> None:
os.fspath(BUNDLE_DIR / "libs"),
os.getenv("LS_IMPORT_STRATEGY", "useBundled"),
)
update_environ_path()

# **********************************************************
# Imports needed for the language server goes below this.
Expand Down Expand Up @@ -435,6 +457,7 @@ def _get_global_defaults():
"W": "Warning",
},
),
"ignorePatterns": [],
"importStrategy": GLOBAL_SETTINGS.get("importStrategy", "useBundled"),
"showNotifications": GLOBAL_SETTINGS.get("showNotifications", "off"),
}
Expand Down Expand Up @@ -495,6 +518,19 @@ def _get_settings_by_document(document: workspace.Document | None):
# *****************************************************
# Internal execution APIs.
# *****************************************************
def get_cwd(settings: Dict[str, Any], document: Optional[workspace.Document]) -> str:
"""Returns cwd for the given settings and document."""
if settings["cwd"] == "${workspaceFolder}":
return settings["workspaceFS"]

if settings["cwd"] == "${fileDirname}":
if document is not None:
return os.fspath(pathlib.Path(document.path).parent)
return settings["workspaceFS"]

return settings["cwd"]


def _run_tool_on_document(
document: workspace.Document,
use_stdin: bool = False,
Expand All @@ -505,19 +541,28 @@ def _run_tool_on_document(
if use_stdin is true then contents of the document is passed to the
tool via stdin.
"""
# deep copy here to prevent accidentally updating global settings.
settings = copy.deepcopy(_get_settings_by_document(document))

if str(document.uri).startswith("vscode-notebook-cell"):
log_warning(f"Skipping notebook cells [Not Supported]: {str(document.uri)}")
return None

if utils.is_stdlib_file(document.path):
log_warning(f"Skipping standard library file: {document.path}")
log_warning(
f"Skipping standard library file (stdlib excluded): {document.path}"
)

return None

# deep copy here to prevent accidentally updating global settings.
settings = copy.deepcopy(_get_settings_by_document(document))
if utils.is_match(settings["ignorePatterns"], document.path):
log_warning(
f"Skipping file due to `flake8.ignorePatterns` match: {document.path}"
)
return None

code_workspace = settings["workspaceFS"]
cwd = settings["cwd"]
cwd = get_cwd(settings, document)

use_path = False
use_rpc = False
Expand Down Expand Up @@ -599,7 +644,7 @@ def _run_tool_on_document(
def _run_tool(extra_args: Sequence[str], settings: Dict[str, Any]) -> utils.RunResult:
"""Runs tool."""
code_workspace = settings["workspaceFS"]
cwd = settings["cwd"]
cwd = get_cwd(settings, None)

use_path = False
use_rpc = False
Expand Down
7 changes: 7 additions & 0 deletions bundled/tool/lsp_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ def is_stdlib_file(file_path: str) -> bool:
return any(normalized_path.startswith(path) for path in _stdlib_paths)


def is_match(patterns: List[str], file_path: str) -> bool:
"""Returns true if the file matches one of the glob patterns."""
if not patterns:
return False
return any(pathlib.Path(file_path).match(pattern) for pattern in patterns)


class RunResult:
"""Object to hold result from running tool."""

Expand Down
Loading

0 comments on commit 4329677

Please sign in to comment.