Skip to content

Commit efd90be

Browse files
committed
Cache config file contents
1 parent a3b854c commit efd90be

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

wpiformat/wpiformat/config.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
"""This class is for handling wpiformat config files."""
22

33
import os
4-
import sys
54

65
import regex
76

87

98
class Config:
9+
# Dict from filepath to file contents
10+
config_cache: dict[str, list[str]] = {}
11+
1012
def __init__(self, directory, file_name):
1113
"""Constructor for Config object.
1214
@@ -35,22 +37,23 @@ def read_file(directory, file_name):
3537
Returns tuple of file name and list containing file contents or triggers
3638
program exit.
3739
"""
38-
file_found = False
39-
while not file_found:
40+
while True:
41+
filepath = os.path.join(directory, file_name)
4042
try:
41-
with open(directory + os.sep + file_name, "r") as file_contents:
42-
file_found = True
43-
return (
44-
os.path.join(directory, file_name),
45-
file_contents.read().splitlines(),
46-
)
43+
# If filepath in config cache, return cached version instead
44+
if filepath in Config.config_cache:
45+
return filepath, Config.config_cache[filepath]
46+
47+
with open(filepath, "r") as file_contents:
48+
contents = file_contents.read().splitlines()
49+
Config.config_cache[filepath] = contents
50+
return filepath, contents
4751
except OSError as e:
4852
# .git files are ignored, which are created within submodules
4953
if os.path.isdir(directory + os.sep + ".git"):
50-
print(
51-
f"error: config file '{file_name}' not found in '{directory}'"
52-
)
53-
raise e
54+
raise OSError(
55+
f"config file '{file_name}' not found in '{directory}'"
56+
) from e
5457
directory = os.path.dirname(directory)
5558

5659
def group(self, group_name):

0 commit comments

Comments
 (0)