Skip to content

Commit

Permalink
Cache config file contents
Browse files Browse the repository at this point in the history
  • Loading branch information
calcmogul committed May 6, 2024
1 parent ebbb6ae commit c966d2c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
3 changes: 3 additions & 0 deletions wpiformat/wpiformat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,9 @@ def proc_pipeline(name):
try:
config_file = Config(os.path.dirname(name), ".wpiformat")
except OSError:
print(
"Warning: '.wpiformat' file not found. Looking for deprecated '.styleguide' file."
)
# TODO: Remove handling for deprecated .styleguide file
config_file = Config(os.path.dirname(name), ".styleguide")
print("Warning: found deprecated '.styleguide' file. Rename to '.wpiformat'.")
Expand Down
29 changes: 16 additions & 13 deletions wpiformat/wpiformat/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

import os
import regex
import sys


class Config:
# Dict from filepath to file contents
config_cache: dict[str, list[str]] = {}

def __init__(self, directory, file_name):
"""Constructor for Config object.
Expand Down Expand Up @@ -34,22 +36,23 @@ def read_file(directory, file_name):
Returns tuple of file name and list containing file contents or triggers
program exit.
"""
file_found = False
while not file_found:
while True:
filepath = os.path.join(directory, file_name)
try:
with open(directory + os.sep + file_name, "r") as file_contents:
file_found = True
return (
os.path.join(directory, file_name),
file_contents.read().splitlines(),
)
# If filepath in config cache, return cached version instead
if filepath in Config.config_cache:
return filepath, Config.config_cache[filepath]

with open(filepath, "r") as file_contents:
contents = file_contents.read().splitlines()
Config.config_cache[filepath] = contents
return filepath, contents
except OSError as e:
# .git files are ignored, which are created within submodules
if os.path.isdir(directory + os.sep + ".git"):
print(
f"Error: config file '{file_name}' not found in '{directory}'"
)
raise e
raise OSError(
f"config file '{file_name}' not found in '{directory}'"
) from e
directory = os.path.dirname(directory)

def group(self, group_name):
Expand Down

0 comments on commit c966d2c

Please sign in to comment.