From 3f28c0b58c0e89c64d7d064d845e3863e2f5ca92 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Wed, 16 Aug 2023 13:48:03 -0700 Subject: [PATCH] Cache config file contents --- wpiformat/wpiformat/__init__.py | 3 +++ wpiformat/wpiformat/config.py | 29 ++++++++++++++++------------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/wpiformat/wpiformat/__init__.py b/wpiformat/wpiformat/__init__.py index 5935a4d..91347c0 100644 --- a/wpiformat/wpiformat/__init__.py +++ b/wpiformat/wpiformat/__init__.py @@ -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'.") diff --git a/wpiformat/wpiformat/config.py b/wpiformat/wpiformat/config.py index ca8d9b5..8260f5b 100644 --- a/wpiformat/wpiformat/config.py +++ b/wpiformat/wpiformat/config.py @@ -1,12 +1,14 @@ """This class is for handling wpiformat config files.""" import os -import sys import regex class Config: + # Dict from filepath to file contents + config_cache: dict[str, list[str]] = {} + def __init__(self, directory, file_name): """Constructor for Config object. @@ -35,22 +37,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):