Skip to content

Commit 462b9bf

Browse files
Enable explicit Ruff check rules (#23741)
Co-authored-by: Rafał <[email protected]>
1 parent a5c539d commit 462b9bf

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

69 files changed

+893
-1046
lines changed

build/ci/addEnvPath.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33

44
#Adds the virtual environment's executable path to json file
55

6-
import json,sys
6+
import json
7+
import sys
78
import os.path
89
jsonPath = sys.argv[1]
910
key = sys.argv[2]

build/update_ext_version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def main(package_json: pathlib.Path, argv: Sequence[str]) -> None:
8686
raise ValueError(
8787
f"Major version [{major}] must be the current year [{current_year}].",
8888
f"If changing major version after new year's, change to {current_year}.1.0",
89-
f"Minor version must be updated based on release or pre-release channel.",
89+
"Minor version must be updated based on release or pre-release channel.",
9090
)
9191

9292
if args.release and not is_even(minor):

python_files/create_conda.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -48,19 +48,19 @@ def parse_args(argv: Sequence[str]) -> argparse.Namespace:
4848

4949

5050
def file_exists(path: Union[str, pathlib.PurePath]) -> bool:
51-
return os.path.exists(path)
51+
return os.path.exists(path) # noqa: PTH110
5252

5353

5454
def conda_env_exists(name: Union[str, pathlib.PurePath]) -> bool:
55-
return os.path.exists(CWD / name)
55+
return os.path.exists(CWD / name) # noqa: PTH110
5656

5757

5858
def run_process(args: Sequence[str], error_message: str) -> None:
5959
try:
6060
print("Running: " + " ".join(args))
61-
subprocess.run(args, cwd=os.getcwd(), check=True)
62-
except subprocess.CalledProcessError:
63-
raise VenvError(error_message)
61+
subprocess.run(args, cwd=os.getcwd(), check=True) # noqa: PTH109
62+
except subprocess.CalledProcessError as exc:
63+
raise VenvError(error_message) from exc
6464

6565

6666
def get_conda_env_path(name: str) -> str:
@@ -89,11 +89,10 @@ def install_packages(env_path: str) -> None:
8989

9090

9191
def add_gitignore(name: str) -> None:
92-
git_ignore = os.fspath(CWD / name / ".gitignore")
93-
if not file_exists(git_ignore):
94-
print(f"Creating: {git_ignore}")
95-
with open(git_ignore, "w") as f:
96-
f.write("*")
92+
git_ignore = CWD / name / ".gitignore"
93+
if not git_ignore.is_file():
94+
print(f"Creating: {os.fsdecode(git_ignore)}")
95+
git_ignore.write_text("*")
9796

9897

9998
def main(argv: Optional[Sequence[str]] = None) -> None:

python_files/create_microvenv.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ class MicroVenvError(Exception):
2020
def run_process(args: Sequence[str], error_message: str) -> None:
2121
try:
2222
print("Running: " + " ".join(args))
23-
subprocess.run(args, cwd=os.getcwd(), check=True)
24-
except subprocess.CalledProcessError:
25-
raise MicroVenvError(error_message)
23+
subprocess.run(args, cwd=os.getcwd(), check=True) # noqa: PTH109
24+
except subprocess.CalledProcessError as exc:
25+
raise MicroVenvError(error_message) from exc
2626

2727

2828
def parse_args(argv: Sequence[str]) -> argparse.Namespace:

python_files/create_venv.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -89,9 +89,9 @@ def venv_exists(name: str) -> bool:
8989
def run_process(args: Sequence[str], error_message: str) -> None:
9090
try:
9191
print("Running: " + " ".join(args))
92-
subprocess.run(args, cwd=os.getcwd(), check=True)
93-
except subprocess.CalledProcessError:
94-
raise VenvError(error_message)
92+
subprocess.run(args, cwd=os.getcwd(), check=True) # noqa: PTH109
93+
except subprocess.CalledProcessError as exc:
94+
raise VenvError(error_message) from exc
9595

9696

9797
def get_venv_path(name: str) -> str:
@@ -136,10 +136,9 @@ def upgrade_pip(venv_path: str) -> None:
136136

137137
def add_gitignore(name: str) -> None:
138138
git_ignore = CWD / name / ".gitignore"
139-
if not file_exists(git_ignore):
140-
print("Creating: " + os.fspath(git_ignore))
141-
with open(git_ignore, "w") as f:
142-
f.write("*")
139+
if git_ignore.is_file():
140+
print("Creating:", os.fspath(git_ignore))
141+
git_ignore.write_text("*")
143142

144143

145144
def download_pip_pyz(name: str):
@@ -148,13 +147,10 @@ def download_pip_pyz(name: str):
148147

149148
try:
150149
with url_lib.urlopen(url) as response:
151-
pip_pyz_path = os.fspath(CWD / name / "pip.pyz")
152-
with open(pip_pyz_path, "wb") as out_file:
153-
data = response.read()
154-
out_file.write(data)
155-
out_file.flush()
156-
except Exception:
157-
raise VenvError("CREATE_VENV.DOWNLOAD_PIP_FAILED")
150+
pip_pyz_path = CWD / name / "pip.pyz"
151+
pip_pyz_path.write_bytes(data=response.read())
152+
except Exception as exc:
153+
raise VenvError("CREATE_VENV.DOWNLOAD_PIP_FAILED") from exc
158154

159155

160156
def install_pip(name: str):

python_files/download_get_pip.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
# Licensed under the MIT License.
33

44
import json
5-
import os
65
import pathlib
76
import urllib.request as url_lib
7+
88
from packaging.version import parse as version_parser
99

1010
EXTENSION_ROOT = pathlib.Path(__file__).parent.parent
@@ -14,20 +14,20 @@
1414

1515

1616
def _get_package_data():
17-
json_uri = "https://pypi.org/pypi/{0}/json".format(PIP_PACKAGE)
17+
json_uri = f"https://pypi.org/pypi/{PIP_PACKAGE}/json"
1818
# Response format: https://warehouse.readthedocs.io/api-reference/json/#project
1919
# Release metadata format: https://github.com/pypa/interoperability-peps/blob/master/pep-0426-core-metadata.rst
2020
with url_lib.urlopen(json_uri) as response:
2121
return json.loads(response.read())
2222

2323

2424
def _download_and_save(root, version):
25-
root = os.getcwd() if root is None or root == "." else root
25+
root = pathlib.Path.cwd() if root is None or root == "." else pathlib.Path(root)
2626
url = f"https://raw.githubusercontent.com/pypa/get-pip/{version}/public/get-pip.py"
2727
print(url)
2828
with url_lib.urlopen(url) as response:
2929
data = response.read()
30-
get_pip_file = pathlib.Path(root) / "get-pip.py"
30+
get_pip_file = root / "get-pip.py"
3131
get_pip_file.write_bytes(data)
3232

3333

python_files/get_output_via_markers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@
1818
del sys.argv[0]
1919
exec(code, ns, ns)
2020
elif module.startswith("-m"):
21-
moduleName = sys.argv[2]
21+
module_name = sys.argv[2]
2222
sys.argv = sys.argv[2:] # It should begin with the module name.
23-
runpy.run_module(moduleName, run_name="__main__", alter_sys=True)
23+
runpy.run_module(module_name, run_name="__main__", alter_sys=True)
2424
elif module.endswith(".py"):
2525
sys.argv = sys.argv[1:]
2626
runpy.run_path(module, run_name="__main__")

python_files/installed_check.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,7 @@ def parse_args(argv: Optional[Sequence[str]] = None):
3636
def parse_requirements(line: str) -> Optional[Requirement]:
3737
try:
3838
req = Requirement(line.strip("\\"))
39-
if req.marker is None:
40-
return req
41-
elif req.marker.evaluate():
39+
if req.marker is None or req.marker.evaluate():
4240
return req
4341
except Exception:
4442
pass

python_files/linter.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import subprocess
22
import sys
33

4-
54
linter_settings = {
65
"pylint": {
76
"args": ["--reports=n", "--output-format=json"],

python_files/normalizeSelection.py

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,11 @@ def split_lines(source):
2121

2222

2323
def _get_statements(selection):
24-
"""
25-
Process a multiline selection into a list of its top-level statements.
24+
"""Process a multiline selection into a list of its top-level statements.
25+
2626
This will remove empty newlines around and within the selection, dedent it,
2727
and split it using the result of `ast.parse()`.
2828
"""
29-
3029
# Remove blank lines within the selection to prevent the REPL from thinking the block is finished.
3130
lines = (line for line in split_lines(selection) if line.strip() != "")
3231

@@ -57,7 +56,7 @@ def _get_statements(selection):
5756
# Also, not all AST objects can have decorators.
5857
if hasattr(node, "decorator_list") and sys.version_info >= (3, 8):
5958
# Using getattr instead of node.decorator_list or pyright will complain about an unknown member.
60-
line_end -= len(getattr(node, "decorator_list"))
59+
line_end -= len(getattr(node, "decorator_list")) # noqa: B009
6160
ends.append(line_end)
6261
ends.append(len(lines))
6362

@@ -74,7 +73,7 @@ def _get_statements(selection):
7473
# Special handling of decorators similar to what's above.
7574
if hasattr(node, "decorator_list") and sys.version_info >= (3, 8):
7675
# Using getattr instead of node.decorator_list or pyright will complain about an unknown member.
77-
start -= len(getattr(node, "decorator_list"))
76+
start -= len(getattr(node, "decorator_list")) # noqa: B009
7877
block = "\n".join(lines[start:end])
7978

8079
# If the block is multiline, add an extra newline character at its end.
@@ -134,26 +133,24 @@ def normalize_lines(selection):
134133

135134

136135
def check_exact_exist(top_level_nodes, start_line, end_line):
137-
exact_nodes = []
138-
for node in top_level_nodes:
139-
if node.lineno == start_line and node.end_lineno == end_line:
140-
exact_nodes.append(node)
136+
return [
137+
node
138+
for node in top_level_nodes
139+
if node.lineno == start_line and node.end_lineno == end_line
140+
]
141141

142-
return exact_nodes
143142

143+
def traverse_file(whole_file_content, start_line, end_line, was_highlighted): # noqa: ARG001
144+
"""Intended to traverse through a user's given file content and find, collect all appropriate lines that should be sent to the REPL in case of smart selection.
144145
145-
def traverse_file(wholeFileContent, start_line, end_line, was_highlighted):
146-
"""
147-
Intended to traverse through a user's given file content and find, collect all appropriate lines
148-
that should be sent to the REPL in case of smart selection.
149146
This could be exact statement such as just a single line print statement,
150147
or a multiline dictionary, or differently styled multi-line list comprehension, etc.
151148
Then call the normalize_lines function to normalize our smartly selected code block.
152149
"""
153150
parsed_file_content = None
154151

155152
try:
156-
parsed_file_content = ast.parse(wholeFileContent)
153+
parsed_file_content = ast.parse(whole_file_content)
157154
except Exception:
158155
# Handle case where user is attempting to run code where file contains deprecated Python code.
159156
# Let typescript side know and show warning message.
@@ -192,8 +189,7 @@ def traverse_file(wholeFileContent, start_line, end_line, was_highlighted):
192189
ast.ExceptHandler,
193190
)
194191
if isinstance(node, ast_types_with_nodebody) and isinstance(node.body, Iterable):
195-
for child_nodes in node.body:
196-
top_level_nodes.append(child_nodes)
192+
top_level_nodes.extend(node.body)
197193

198194
exact_nodes = check_exact_exist(top_level_nodes, start_line, end_line)
199195

@@ -202,7 +198,7 @@ def traverse_file(wholeFileContent, start_line, end_line, was_highlighted):
202198
which_line_next = 0
203199
for same_line_node in exact_nodes:
204200
should_run_top_blocks.append(same_line_node)
205-
smart_code += f"{ast.get_source_segment(wholeFileContent, same_line_node)}\n"
201+
smart_code += f"{ast.get_source_segment(whole_file_content, same_line_node)}\n"
206202
which_line_next = get_next_block_lineno(should_run_top_blocks)
207203
return {
208204
"normalized_smart_result": smart_code,
@@ -216,7 +212,7 @@ def traverse_file(wholeFileContent, start_line, end_line, was_highlighted):
216212
if start_line == top_node.lineno and end_line == top_node.end_lineno:
217213
should_run_top_blocks.append(top_node)
218214

219-
smart_code += f"{ast.get_source_segment(wholeFileContent, top_node)}\n"
215+
smart_code += f"{ast.get_source_segment(whole_file_content, top_node)}\n"
220216
break # If we found exact match, don't waste computation in parsing extra nodes.
221217
elif start_line >= top_node.lineno and end_line <= top_node.end_lineno:
222218
# Case to apply smart selection for multiple line.
@@ -231,7 +227,7 @@ def traverse_file(wholeFileContent, start_line, end_line, was_highlighted):
231227

232228
should_run_top_blocks.append(top_node)
233229

234-
smart_code += str(ast.get_source_segment(wholeFileContent, top_node))
230+
smart_code += str(ast.get_source_segment(whole_file_content, top_node))
235231
smart_code += "\n"
236232

237233
normalized_smart_result = normalize_lines(smart_code)
@@ -262,7 +258,7 @@ def get_next_block_lineno(which_line_next):
262258
raw = stdin.read()
263259
contents = json.loads(raw.decode("utf-8"))
264260
# Empty highlight means user has not explicitly selected specific text.
265-
empty_Highlight = contents.get("emptyHighlight", False)
261+
empty_highlight = contents.get("emptyHighlight", False)
266262

267263
# We also get the activeEditor selection start line and end line from the typescript VS Code side.
268264
# Remember to add 1 to each of the received since vscode starts line counting from 0 .
@@ -273,12 +269,12 @@ def get_next_block_lineno(which_line_next):
273269
data = None
274270
which_line_next = 0
275271

276-
if empty_Highlight and contents.get("smartSendSettingsEnabled"):
272+
if empty_highlight and contents.get("smartSendSettingsEnabled"):
277273
result = traverse_file(
278274
contents["wholeFileContent"],
279275
vscode_start_line,
280276
vscode_end_line,
281-
not empty_Highlight,
277+
not empty_highlight,
282278
)
283279
normalized = result["normalized_smart_result"]
284280
which_line_next = result["which_line_next"]

0 commit comments

Comments
 (0)