|
2 | 2 |
|
3 | 3 | import os |
4 | 4 | import regex |
5 | | -import sys |
6 | 5 |
|
7 | 6 |
|
8 | 7 | class Config: |
| 8 | + # Dict from filepath to file contents |
| 9 | + config_cache: dict[str, list[str]] = {} |
| 10 | + |
9 | 11 | def __init__(self, directory, file_name): |
10 | 12 | """Constructor for Config object. |
11 | 13 |
|
@@ -34,22 +36,23 @@ def read_file(directory, file_name): |
34 | 36 | Returns tuple of file name and list containing file contents or triggers |
35 | 37 | program exit. |
36 | 38 | """ |
37 | | - file_found = False |
38 | | - while not file_found: |
| 39 | + while True: |
| 40 | + filepath = os.path.join(directory, file_name) |
39 | 41 | try: |
40 | | - with open(directory + os.sep + file_name, "r") as file_contents: |
41 | | - file_found = True |
42 | | - return ( |
43 | | - os.path.join(directory, file_name), |
44 | | - file_contents.read().splitlines(), |
45 | | - ) |
| 42 | + # If filepath in config cache, return cached version instead |
| 43 | + if filepath in Config.config_cache: |
| 44 | + return filepath, Config.config_cache[filepath] |
| 45 | + |
| 46 | + with open(filepath, "r") as file_contents: |
| 47 | + contents = file_contents.read().splitlines() |
| 48 | + Config.config_cache[filepath] = contents |
| 49 | + return filepath, contents |
46 | 50 | except OSError as e: |
47 | 51 | # .git files are ignored, which are created within submodules |
48 | 52 | if os.path.isdir(directory + os.sep + ".git"): |
49 | | - print( |
50 | | - f"Error: config file '{file_name}' not found in '{directory}'" |
51 | | - ) |
52 | | - raise e |
| 53 | + raise OSError( |
| 54 | + f"config file '{file_name}' not found in '{directory}'" |
| 55 | + ) from e |
53 | 56 | directory = os.path.dirname(directory) |
54 | 57 |
|
55 | 58 | def group(self, group_name): |
|
0 commit comments