From 3cc64f514fbd671111b5c90bf2e025aa21042b86 Mon Sep 17 00:00:00 2001 From: Sven Sager Date: Sun, 20 Apr 2025 15:04:11 +0200 Subject: [PATCH] feat(dbus): Add `grep` function to search for patterns in a file The new `grep` function reads a specified file and returns lines containing a given pattern. It handles file not found errors and logs unexpected exceptions, improving resilience in file operations. --- .../dbus_middleware1/dbus_helper.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/revpi_middleware/dbus_middleware1/dbus_helper.py b/src/revpi_middleware/dbus_middleware1/dbus_helper.py index 23bcd2e..62dd766 100644 --- a/src/revpi_middleware/dbus_middleware1/dbus_helper.py +++ b/src/revpi_middleware/dbus_middleware1/dbus_helper.py @@ -41,3 +41,38 @@ def extend_interface(*args) -> str: the provided segments. """ return ".".join([REVPI_DBUS_NAME, *args]) + + +def grep(pattern, filename): + """ + Searches for lines in a file that contain a given pattern and returns them as a list. + + The function reads lines from the specified file and checks whether each line + contains the provided pattern. It returns a list of lines that match the + pattern. If the file is not found, an empty list is returned. Any other + exceptions during the file reading process are caught and logged. + + Args: + pattern (str): The substring to search for within the file's lines. + filename (str): The path to the file that will be searched. + + Returns: + list[str]: A list containing lines that include the provided pattern, with + leading and trailing spaces removed. + + Raises: + FileNotFoundError: This error is caught if the file specified is not + found. + Exception: Any unforeseen exception during file operations is caught and + logged. + """ + try: + with open(filename, "r") as file: + # Gibt alle Zeilen zurück, die das Muster enthalten + matching_lines = [line.strip() for line in file if pattern in line] + return matching_lines + except FileNotFoundError: + return [] + except Exception as e: + log.error(f"Error reading file: {e}") + return []