Skip to content

Commit 6c7e548

Browse files
walacglemco
authored andcommitted
rv/rvgen: use context managers for file operations
Replace manual file open and close operations with context managers throughout the rvgen codebase. The previous implementation used explicit open() and close() calls, which could lead to resource leaks if exceptions occurred between opening and closing the file handles. This change affects three file operations: reading DOT specification files in the automata parser, reading template files in the generator base class, and writing generated monitor files. All now use the with statement to ensure proper resource cleanup even in error conditions. Context managers provide automatic cleanup through the with statement, which guarantees that file handles are closed when the with block exits regardless of whether an exception occurred. This follows PEP 343 recommendations and is the standard Python idiom for resource management. The change also reduces code verbosity while improving safety and maintainability. Signed-off-by: Wander Lairson Costa <wander@redhat.com> Reviewed-by: Nam Cao <namcao@linutronix.de> Reviewed-by: Gabriele Monaco <gmonaco@redhat.com> Link: https://lore.kernel.org/r/20260223162407.147003-7-wander@redhat.com Signed-off-by: Gabriele Monaco <gmonaco@redhat.com>
1 parent c4258d8 commit 6c7e548

2 files changed

Lines changed: 6 additions & 12 deletions

File tree

tools/verification/rvgen/rvgen/automata.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -91,13 +91,11 @@ def __open_dot(self) -> list[str]:
9191
cursor = 0
9292
dot_lines = []
9393
try:
94-
dot_file = open(self.__dot_path)
94+
with open(self.__dot_path) as dot_file:
95+
dot_lines = dot_file.read().splitlines()
9596
except OSError as exc:
9697
raise AutomataError(exc.strerror) from exc
9798

98-
dot_lines = dot_file.read().splitlines()
99-
dot_file.close()
100-
10199
# checking the first line:
102100
line = dot_lines[cursor].split()
103101

tools/verification/rvgen/rvgen/generator.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,8 @@ def __fill_rv_kernel_dir(self):
5151
raise FileNotFoundError("Could not find the rv directory, do you have the kernel source installed?")
5252

5353
def _read_file(self, path):
54-
fd = open(path, 'r')
55-
56-
content = fd.read()
57-
58-
fd.close()
54+
with open(path, 'r') as fd:
55+
content = fd.read()
5956
return content
6057

6158
def _read_template_file(self, file):
@@ -199,9 +196,8 @@ def __create_directory(self):
199196
return
200197

201198
def __write_file(self, file_name, content):
202-
file = open(file_name, 'w')
203-
file.write(content)
204-
file.close()
199+
with open(file_name, 'w') as file:
200+
file.write(content)
205201

206202
def _create_file(self, file_name, content):
207203
path = f"{self.name}/{file_name}"

0 commit comments

Comments
 (0)