|
1 | 1 | """This class is for handling wpiformat config files."""
|
2 | 2 |
|
3 | 3 | import os
|
4 |
| -import sys |
5 | 4 |
|
6 | 5 | import regex
|
7 | 6 |
|
8 | 7 |
|
9 | 8 | class Config:
|
| 9 | + # Dict from filepath to file contents |
| 10 | + config_cache: dict[str, list[str]] = {} |
| 11 | + |
10 | 12 | def __init__(self, directory, file_name):
|
11 | 13 | """Constructor for Config object.
|
12 | 14 |
|
@@ -35,22 +37,23 @@ def read_file(directory, file_name):
|
35 | 37 | Returns tuple of file name and list containing file contents or triggers
|
36 | 38 | program exit.
|
37 | 39 | """
|
38 |
| - file_found = False |
39 |
| - while not file_found: |
| 40 | + while True: |
| 41 | + filepath = os.path.join(directory, file_name) |
40 | 42 | 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 |
47 | 51 | except OSError as e:
|
48 | 52 | # .git files are ignored, which are created within submodules
|
49 | 53 | 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 |
54 | 57 | directory = os.path.dirname(directory)
|
55 | 58 |
|
56 | 59 | def group(self, group_name):
|
|
0 commit comments