From 6dcab81bacd437764d082cf6f36a0c511e27204e Mon Sep 17 00:00:00 2001 From: Justin Campbell Date: Thu, 17 Jun 2021 13:32:14 -0400 Subject: [PATCH] Refactor params to snake_case and update docstring --- src/webqueue2api/parser/item.py | 86 +++++++++++++++++---------------- 1 file changed, 44 insertions(+), 42 deletions(-) diff --git a/src/webqueue2api/parser/item.py b/src/webqueue2api/parser/item.py index d4c599f..ed9b387 100644 --- a/src/webqueue2api/parser/item.py +++ b/src/webqueue2api/parser/item.py @@ -20,23 +20,26 @@ class Item: Example: # Create an Item (ce100) - >>> item = Item("ce", 100) + `item = Item("ce", 100)` Attributes: - lastUpdated: An ISO 8601 formatted time string showing the last time the file was updated according to the filesystem. + queue: The name of the queue the Item is in. + number: The number of the Item. + path: The path to the Item on the filesystem. + last_updated: An ISO 8601 formatted time string showing the last time the file was updated according to the filesystem. headers: A list of dictionaries containing header keys and values. content: A list of section dictionaries. - isLocked: A boolean showing whether or not a lockfile for the item is present. - userEmail: The email address of the person who this item is from. - userName: The real name of the person who this item is from. - userAlias: The Purdue career account alias of the person this item is from. - assignedTo: The Purdue career account alias of the person this item is assigned to + is_locked: A boolean showing whether or not a lockfile for the item is present. + user_email: The email address of the person who this item is from. + user_name: The real name of the person who this item is from. + user_alias: The Purdue career account alias of the person this item is from. + assigned_to: The Purdue career account alias of the person this item is assigned to subject: The subject of the original message for this item. status: The most recent status update for the item. priority: The most recent priority for this item. department: The most recent department for this item. - dateReceived: The date this item was created. - jsonData: A JSON serializable representation of the Item. + date_received: The date this item was created. + json_data: A JSON serializable representation of the Item. Raises: ItemDoesNotExistError: If an item does not exist on the filesystem. @@ -50,45 +53,44 @@ def __init__(self, queue: str, number: int) -> None: except ValueError: raise ValueError(f"Could not convert {number} to an integer") - self.__path = Path(config.queue_directory, self.queue, str(self.number)) - if not self.__path.exists(): - raise ItemDoesNotExistError(str(self.__path)) + self.path = Path(config.queue_directory, self.queue, str(self.number)) + if not self.path.exists(): + raise ItemDoesNotExistError(str(self.path)) - self.lastUpdated = self.__getLastUpdated() - self.__rawItem = self.__getRawItem() + self.last_updated = self.__getLastUpdated() + self.__raw_tem = self.__getRawItem() self.headers = self.__parseHeaders() self.content = self.__parseSections() - self.isLocked = self.__isLocked() - self.userEmail = self.__parseFromData(data="userEmail") - self.userName = self.__parseFromData(data="userName") - self.userAlias = self.__getUserAlias() - self.assignedTo = self.__getMostRecentHeaderByType("Assigned-To") + self.is_locked = self.__isLocked() + self.user_email = self.__parseFromData(data="userEmail") + self.user_name = self.__parseFromData(data="userName") + self.user_alias = self.__getUserAlias() + self.assigned_to = self.__getMostRecentHeaderByType("Assigned-To") self.subject = self.__getMostRecentHeaderByType("Subject") self.status = self.__getMostRecentHeaderByType("Status") self.priority = self.__getMostRecentHeaderByType("Priority") self.department = self.__getMostRecentHeaderByType("Department") self.building = self.__getMostRecentHeaderByType("Building") - self.dateReceived = self.__getFormattedDate( - self.__getMostRecentHeaderByType("Date")) + self.date_received = self.__getFormattedDate(self.__getMostRecentHeaderByType("Date")) # TODO: Autopopulate jsonData w/ __dir__() command. Exclude `^_` and `jsonData`. self.jsonData = { "queue": self.queue, "number": self.number, - "lastUpdated": self.lastUpdated, + "lastUpdated": self.last_updated, "headers": self.headers, "content": self.content, - "isLocked": self.isLocked, - "userEmail": self.userEmail, - "userName": self.userName, - "userAlias": self.userAlias, - "assignedTo": self.assignedTo, + "isLocked": self.is_locked, + "userEmail": self.user_email, + "userName": self.user_name, + "userAlias": self.user_alias, + "assignedTo": self.assigned_to, "subject": self.subject, "status": self.status, "priority": self.priority, "department": self.department, "building": self.building, - "dateReceived": self.dateReceived + "dateReceived": self.date_received } def __getLastUpdated(self) -> str: @@ -101,7 +103,7 @@ def __getLastUpdated(self) -> str: str: last modified time of item reported by the filesystem in mm-dd-yy hh:mm am/pm format. """ # TODO: Simplify this code block by allowing __getFormattedDate to accept milliseconds since the epoch. - unixTime = os.path.getmtime(self.__path) + unixTime = os.path.getmtime(self.path) formattedTime = time.strftime( '%m-%d-%y %I:%M %p', time.localtime(unixTime)) return self.__getFormattedDate(formattedTime) @@ -112,7 +114,7 @@ def __getRawItem(self) -> list: Returns: list: List of all the lines in the item file """ - with open(self.__path, errors="replace") as file: + with open(self.path, errors="replace") as file: return file.readlines() def __getHeaderBoundary(self) -> int: @@ -126,7 +128,7 @@ def __getHeaderBoundary(self) -> int: Returns: int: line number where the Item headers end """ - for lineNumber, line in enumerate(self.__rawItem): + for lineNumber, line in enumerate(self.__raw_tem): if line == "\n": return lineNumber @@ -153,7 +155,7 @@ def __parseHeaders(self) -> list: # QTime-Updated-By: campb303 queuePrefixPattern = re.compile(r"\[.*?\] {1}") for lineNumber in range(self.__getHeaderBoundary()): - line = self.__rawItem[lineNumber] + line = self.__raw_tem[lineNumber] lineHasQueuePrefix = queuePrefixPattern.match(line) if lineHasQueuePrefix: @@ -193,7 +195,7 @@ def __parseSections(self) -> list: sections = [] contentStart = self.__getHeaderBoundary() + 1 - contentEnd = len(self.__rawItem) - 1 + contentEnd = len(self.__raw_tem) - 1 # List of assignments for the item assignementLsit = self.__assignmentParsing(contentStart) @@ -209,7 +211,7 @@ def __parseSections(self) -> list: return sections # Checks for Directory Identifiers - if self.__rawItem[contentStart] == "\n" and self.__rawItem[contentStart + 1].startswith("\t"): + if self.__raw_tem[contentStart] == "\n" and self.__raw_tem[contentStart + 1].startswith("\t"): directoryStartLine = contentStart + 1 @@ -240,7 +242,7 @@ def __parseSections(self) -> list: # and the line number of any delimiters as well as the type for lineNumber in range(contentStart, contentEnd + 1): - line = self.__rawItem[lineNumber] + line = self.__raw_tem[lineNumber] # Looks for a starting delimiter and explicity excludes the reply-from-user ending delimiter if (line.startswith("*** Edited by: ") or @@ -283,10 +285,10 @@ def __parseSections(self) -> list: for boundary in sectionBoundaries: # Sets line to the first line of the boundary (which is always the delimiter) - line = self.__rawItem[boundary["start"]] + line = self.__raw_tem[boundary["start"]] # Returns all of the lines within the current section - sectionContent = self.__rawItem[boundary["start"]: boundary["end"]] + sectionContent = self.__raw_tem[boundary["start"]: boundary["end"]] # Appends an initial message dictionary to sections if boundary["type"] == "initial_message": @@ -392,7 +394,7 @@ def __directoryParsing(self, directoryStartLine: int) -> dict: while True: # Returns the line number at directory start line - info = self.__rawItem[directoryStartLine] + info = self.__raw_tem[directoryStartLine] # Breaks the loop if it encountrs a newline, signifying the end of the directory information if info == "\n": @@ -491,7 +493,7 @@ def __assignmentParsing(self, contentStart: int) -> list: # Parses the header looking for assignment delimeters and stores info into their respective variables for headerContent in range(0, contentStart): - line = self.__rawItem[headerContent] + line = self.__raw_tem[headerContent] # Gets who the Item was assigned to if line.startswith("Assigned-To: "): @@ -1003,7 +1005,7 @@ def __errorParsing(self, line: str, lineNum: int, expectedSyntax: str) -> dict: str(datetime.datetime.now())) # Item filepath - errorDictionary["file_path"] = str(self.__path) + errorDictionary["file_path"] = str(self.path) # Expected value errorDictionary["expected"] = expectedSyntax @@ -1068,7 +1070,7 @@ def __isLocked(self) -> Union[str, bool]: Returns: Union[str, bool]: String with info about lock if true, bool False if false """ - lockFile = str(self.__path) + ".lck" + lockFile = str(self.path) + ".lck" if os.path.exists(lockFile): with open(lockFile) as file: lockInfo = file.readline().split(" ") @@ -1142,7 +1144,7 @@ def __getUserAlias(self) -> str: try: - emailUser, emailDomain = self.userEmail.split("@") + emailUser, emailDomain = self.user_email.split("@") # Returns an error parse if the self.useremail doesn't contain exactally one "@" symbol except ValueError: