Skip to content

Commit 1f9731b

Browse files
authored
NO-JIRA: chore(ruff): fix indentation and linting in the checked code so that ruff passes (#1009)
* NO-JIRA: chore(ruff): fix indentation and linting in the checked code so that ruff passes * apply ruff autofixes * apply ruff --unsafe-fixes * G004 Logging statement uses f-string * UP035 `typing.ContextManager` is deprecated, use `contextlib.AbstractContextManager` instead * PLE0604 Invalid object in `__all__`, must contain only strings * N815 Variable `volumePath` in class scope should not be mixedCase * PLE0604 Invalid object in `__all__`, must contain only strings * N818 Exception name `WaitException` should be named with an Error suffix * B904 Within an `except` clause, raise exceptions with `raise ... from err` or `raise ... from None` to distinguish them from errors in exception handling * # ruff: noqa: PLC0415 `import` should be at the top-level of a file * PLE0604 Invalid object in `__all__`, must contain only strings * B008 Do not perform function call `os.getcwd` in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable * PLR0911 Too many return statements (9 > 6) * N801 Class name `ANNOTATION_TYPE` should use CapWords convention * PLR0914 Too many local variables (19/15) * PLE0604 Invalid object in `__all__`, must contain only strings * RUF013 PEP 484 prohibits implicit `Optional` * PYI034 `__enter__` methods in classes like `TestFrame` usually return `self` at runtime * PLC2801 Unnecessary dunder call to `__enter__` * N803 Argument name `HASH_N` should be lowercase * suppress what remains * undo unreadable reformat
1 parent 21a77ad commit 1f9731b

28 files changed

+949
-879
lines changed

.editorconfig

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,6 @@ trim_trailing_whitespace = true
1010

1111
[Makefile]
1212
indent_style = tab
13+
14+
[*.py]
15+
max_line_length = 120

.pre-commit-config.yaml

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,18 @@ repos:
66
rev: 0.6.13
77
hooks:
88
- id: uv-lock
9-
# # https://github.com/astral-sh/ruff-pre-commit
10-
# - repo: https://github.com/astral-sh/ruff-pre-commit
11-
# rev: v0.11.4
12-
# hooks:
13-
# - id: ruff
14-
# types_or: [python, pyi]
15-
# args: [ --fix ]
16-
# files: 'ci/.*|tests/.*'
17-
# - id: ruff-format
18-
# types_or: [python, pyi]
19-
# files: 'ci/.*|tests/.*'
20-
# # https://pre-commit.com/#new-hooks
9+
# https://github.com/astral-sh/ruff-pre-commit
10+
- repo: https://github.com/astral-sh/ruff-pre-commit
11+
rev: v0.11.4
12+
hooks:
13+
- id: ruff
14+
types_or: [python, pyi]
15+
args: [--fix]
16+
files: 'ci/.*|tests/.*'
17+
- id: ruff-format
18+
types_or: [python, pyi]
19+
files: 'ci/.*|tests/.*'
20+
# https://pre-commit.com/#new-hooks
2121
- repo: local
2222
hooks:
2323
# https://github.com/microsoft/pyright/issues/3612

ci/cached-builds/gen_gha_matrix_jobs.py

Lines changed: 54 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@
44
import enum
55
import json
66
import logging
7-
import platform
8-
import subprocess
97
import os
108
import pathlib
9+
import platform
1110
import re
11+
import subprocess
1212
import sys
1313
import unittest
1414

@@ -25,36 +25,43 @@
2525

2626
def parse_makefile(target: str, makefile_dir: pathlib.Path | str) -> str:
2727
# Check if the operating system is macOS
28-
if platform.system() == 'Darwin':
29-
make_command = 'gmake'
28+
if platform.system() == "Darwin":
29+
make_command = "gmake"
3030
else:
31-
make_command = 'make'
31+
make_command = "make"
3232

3333
try:
3434
# Run the make (or gmake) command and capture the output
35-
result = subprocess.run([make_command, '-nps', target],
36-
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
37-
check=True, cwd=makefile_dir)
35+
result = subprocess.run(
36+
[make_command, "-nps", target],
37+
capture_output=True,
38+
text=True,
39+
check=True,
40+
cwd=makefile_dir,
41+
)
3842
except subprocess.CalledProcessError as e:
3943
# Handle errors if the make command fails
40-
print(f'{make_command} failed with return code: {e.returncode}:\n{e.stderr}', file=sys.stderr)
44+
print(f"{make_command} failed with return code: {e.returncode}:\n{e.stderr}", file=sys.stderr)
4145
raise
4246
except Exception as e:
4347
# Handle any other exceptions
44-
print(f'Error occurred attempting to parse Makefile:\n{str(e)}', file=sys.stderr)
48+
print(f"Error occurred attempting to parse Makefile:\n{e!s}", file=sys.stderr)
4549
raise
4650

4751
return result.stdout
4852

4953

50-
def extract_image_targets(makefile_dir: pathlib.Path | str = os.getcwd()) -> list[str]:
51-
makefile_all_target = 'all-images'
54+
def extract_image_targets(makefile_dir: pathlib.Path | str | None = None) -> list[str]:
55+
if makefile_dir is None:
56+
makefile_dir = os.getcwd()
57+
58+
makefile_all_target = "all-images"
5259

5360
output = parse_makefile(target=makefile_all_target, makefile_dir=makefile_dir)
5461

5562
# Extract the 'all-images' entry and its values
5663
all_images = []
57-
match = re.search(rf'^{makefile_all_target}:\s+(.*)$', output, re.MULTILINE)
64+
match = re.search(rf"^{makefile_all_target}:\s+(.*)$", output, re.MULTILINE)
5865
if match:
5966
all_images = match.group(1).split()
6067

@@ -74,18 +81,26 @@ def main() -> None:
7481
logging.basicConfig(level=logging.DEBUG, stream=sys.stderr)
7582

7683
argparser = argparse.ArgumentParser()
77-
argparser.add_argument("--from-ref", type=str, required=False,
78-
help="Git ref of the base branch (to determine changed files)")
79-
argparser.add_argument("--to-ref", type=str, required=False,
80-
help="Git ref of the PR branch (to determine changed files)")
81-
argparser.add_argument("--rhel-images", type=RhelImages, required=False, default=RhelImages.INCLUDE, nargs='?',
82-
help="Whether to `include` rhel images or `exclude` them or `include-only` them")
84+
argparser.add_argument(
85+
"--from-ref", type=str, required=False, help="Git ref of the base branch (to determine changed files)"
86+
)
87+
argparser.add_argument(
88+
"--to-ref", type=str, required=False, help="Git ref of the PR branch (to determine changed files)"
89+
)
90+
argparser.add_argument(
91+
"--rhel-images",
92+
type=RhelImages,
93+
required=False,
94+
default=RhelImages.INCLUDE,
95+
nargs="?",
96+
help="Whether to `include` rhel images or `exclude` them or `include-only` them",
97+
)
8398
args = argparser.parse_args()
8499

85100
targets = extract_image_targets()
86101

87102
if args.from_ref:
88-
logging.info(f"Skipping targets not modified in the PR")
103+
logging.info("Skipping targets not modified in the PR")
89104
changed_files = gha_pr_changed_files.list_changed_files(args.from_ref, args.to_ref)
90105
targets = gha_pr_changed_files.filter_out_unchanged(targets, changed_files)
91106

@@ -100,14 +115,14 @@ def main() -> None:
100115

101116
# https://stackoverflow.com/questions/66025220/paired-values-in-github-actions-matrix
102117
output = [
103-
"matrix=" + json.dumps({
104-
"include": [
105-
{"target": target, "subscription": "rhel" in target} for target in targets
106-
],
107-
}, separators=(',', ':')),
108-
"has_jobs=" + json.dumps(
109-
len(targets) > 0, separators=(',', ':')
118+
"matrix="
119+
+ json.dumps(
120+
{
121+
"include": [{"target": target, "subscription": "rhel" in target} for target in targets],
122+
},
123+
separators=(",", ":"),
110124
),
125+
"has_jobs=" + json.dumps(len(targets) > 0, separators=(",", ":")),
111126
]
112127

113128
print("targets", targets)
@@ -118,10 +133,10 @@ def main() -> None:
118133
for entry in output:
119134
print(entry, file=f)
120135
else:
121-
logging.info(f"Not running on Github Actions, won't produce GITHUB_OUTPUT")
136+
logging.info("Not running on Github Actions, won't produce GITHUB_OUTPUT")
122137

123138

124-
if __name__ == '__main__':
139+
if __name__ == "__main__":
125140
main()
126141

127142

@@ -132,7 +147,7 @@ def test_select_changed_targets_dockerfile(self):
132147
changed_files = ["jupyter/datascience/ubi9-python-3.11/Dockerfile.cpu"]
133148

134149
targets = gha_pr_changed_files.filter_out_unchanged(targets, changed_files)
135-
assert set(targets) == {'jupyter-datascience-ubi9-python-3.11'}
150+
assert set(targets) == {"jupyter-datascience-ubi9-python-3.11"}
136151

137152
def test_select_changed_targets_shared_file(self):
138153
targets = extract_image_targets(makefile_dir=project_dir)
@@ -145,10 +160,12 @@ def test_select_changed_targets_shared_file(self):
145160
# also being returned. Odds of this inefficiency noticably "hurting us" is low - so of the opinion we can
146161
# simply treat this as technical debt.
147162
targets = gha_pr_changed_files.filter_out_unchanged(targets, changed_files)
148-
assert set(targets) == {'jupyter-minimal-ubi9-python-3.11',
149-
'cuda-jupyter-minimal-ubi9-python-3.11',
150-
'cuda-jupyter-pytorch-ubi9-python-3.11',
151-
'runtime-cuda-pytorch-ubi9-python-3.11',
152-
'cuda-jupyter-tensorflow-ubi9-python-3.11',
153-
'rocm-jupyter-minimal-ubi9-python-3.11',
154-
'runtime-cuda-tensorflow-ubi9-python-3.11'}
163+
assert set(targets) == {
164+
"jupyter-minimal-ubi9-python-3.11",
165+
"cuda-jupyter-minimal-ubi9-python-3.11",
166+
"cuda-jupyter-pytorch-ubi9-python-3.11",
167+
"runtime-cuda-pytorch-ubi9-python-3.11",
168+
"cuda-jupyter-tensorflow-ubi9-python-3.11",
169+
"rocm-jupyter-minimal-ubi9-python-3.11",
170+
"runtime-cuda-tensorflow-ubi9-python-3.11",
171+
}

ci/cached-builds/gha_pr_changed_files.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1+
import fnmatch
12
import json
23
import logging
34
import os
4-
import fnmatch
55
import pathlib
66
import re
77
import shutil
@@ -13,16 +13,17 @@
1313

1414

1515
def get_github_token() -> str:
16-
github_token = os.environ['GITHUB_TOKEN']
16+
github_token = os.environ["GITHUB_TOKEN"]
1717
return github_token
1818

1919

2020
def list_changed_files(from_ref: str, to_ref: str) -> list[str]:
2121
logging.debug("Getting list of changed files from git diff")
2222

2323
# https://github.com/red-hat-data-services/notebooks/pull/361: add -- in case to_ref matches a file name in the repo
24-
files = subprocess.check_output(["git", "diff", "--name-only", from_ref, to_ref, '--'],
25-
encoding='utf-8').splitlines()
24+
files = subprocess.check_output(
25+
["git", "diff", "--name-only", from_ref, to_ref, "--"], encoding="utf-8"
26+
).splitlines()
2627

2728
logging.debug(f"Determined {len(files)} changed files: {files[:100]} (..., printing up to 100 files)")
2829
return files
@@ -34,8 +35,9 @@ def _query_build(make_target: str, query: str) -> str:
3435
pattern = re.compile(r"#\*# " + query + r": <(?P<result>[^>]+)> #\(MACHINE-PARSED LINE\)#\*#\.\.\.")
3536
try:
3637
logging.debug(f"Running make in --just-print mode for target {make_target}")
37-
for line in subprocess.check_output([MAKE, make_target, "--just-print"], encoding="utf-8",
38-
cwd=PROJECT_ROOT).splitlines():
38+
for line in subprocess.check_output(
39+
[MAKE, make_target, "--just-print"], encoding="utf-8", cwd=PROJECT_ROOT
40+
).splitlines():
3941
if m := pattern.match(line):
4042
results.append(m["result"])
4143
except subprocess.CalledProcessError as e:
@@ -61,7 +63,7 @@ def find_dockerfiles(directory: str) -> list:
6163
"""Finds and returns a list of files matching the pattern 'Dockerfile*' in the specified directory."""
6264
matching_files = []
6365
for filename in os.listdir(directory):
64-
if fnmatch.fnmatch(filename, 'Dockerfile*') and filename != 'Dockerfile.konflux':
66+
if fnmatch.fnmatch(filename, "Dockerfile*") and filename != "Dockerfile.konflux":
6567
matching_files.append(filename)
6668
return matching_files
6769

@@ -77,8 +79,9 @@ def should_build_target(changed_files: list[str], target_directory: str) -> str:
7779
# detect change in any of the files outside
7880
dockerfiles = find_dockerfiles(target_directory)
7981
for dockerfile in dockerfiles:
80-
stdout = subprocess.check_output([PROJECT_ROOT / "bin/buildinputs", target_directory + "/" + dockerfile],
81-
text=True, cwd=PROJECT_ROOT)
82+
stdout = subprocess.check_output(
83+
[PROJECT_ROOT / "bin/buildinputs", target_directory + "/" + dockerfile], text=True, cwd=PROJECT_ROOT
84+
)
8285
logging.debug(f"{target_directory=} {dockerfile=} {stdout=}")
8386
if stdout == "\n":
8487
# no dependencies
@@ -107,8 +110,10 @@ class SelfTests(unittest.TestCase):
107110
def test_list_changed_files(self):
108111
"""This is PR #556 in opendatahub-io/notebooks"""
109112
changed_files = list_changed_files(from_ref="4d4841f", to_ref="2c36c11")
110-
assert set(changed_files) == {'codeserver/ubi9-python-3.9/Dockerfile',
111-
'codeserver/ubi9-python-3.9/run-code-server.sh'}
113+
assert set(changed_files) == {
114+
"codeserver/ubi9-python-3.9/Dockerfile",
115+
"codeserver/ubi9-python-3.9/run-code-server.sh",
116+
}
112117

113118
def test_get_build_directory(self):
114119
directory = get_build_directory("rocm-jupyter-pytorch-ubi9-python-3.11")

ci/cached-builds/has_tests.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,14 @@
1616

1717
class Args(argparse.Namespace):
1818
"""Type annotation to have autocompletion for args"""
19+
1920
target: str
2021

2122

2223
def main() -> None:
2324
parser = argparse.ArgumentParser("make_test.py")
2425
parser.add_argument("--target", type=str)
25-
args = typing.cast(Args, parser.parse_args())
26+
args = typing.cast("Args", parser.parse_args())
2627

2728
has_tests = check_tests(args.target)
2829

@@ -34,11 +35,13 @@ def main() -> None:
3435

3536

3637
def check_tests(target: str) -> bool:
37-
if target.startswith("rocm-jupyter-minimal-") or target.startswith("rocm-jupyter-datascience-"):
38+
if target.startswith(("rocm-jupyter-minimal-", "rocm-jupyter-datascience-")):
3839
return False # we don't have specific tests for -minimal-, ... in ci-operator/config
3940

4041
build_directory = gha_pr_changed_files.get_build_directory(target)
41-
kustomization = pathlib.Path(gha_pr_changed_files.PROJECT_ROOT) / build_directory / "kustomize/base/kustomization.yaml"
42+
kustomization = (
43+
pathlib.Path(gha_pr_changed_files.PROJECT_ROOT) / build_directory / "kustomize/base/kustomization.yaml"
44+
)
4245

4346
return kustomization.is_file()
4447

0 commit comments

Comments
 (0)