Skip to content

Commit 1ed4097

Browse files
FEAT: Adding the parse_console_sections function to main.py
1 parent d985e44 commit 1ed4097

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

Games Collection Manager/main.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,70 @@ def calculate_execution_time(start_time, finish_time=None):
358358
return f"{seconds}s" # Fallback: only seconds
359359

360360

361+
def parse_console_sections(lines: list, filepath: str) -> list:
362+
"""
363+
Parse raw TXT file lines into a list of console section dictionaries.
364+
365+
Each dictionary contains keys:
366+
- "name": console name string
367+
- "games": list of normalized game line strings (sorted alphabetically)
368+
369+
:param lines: List of raw line strings from the TXT file.
370+
:param filepath: Source file path used for warning messages during parsing.
371+
:return: List of console section dictionaries with normalized and sorted game entries.
372+
"""
373+
374+
try: # Wrap parsing logic for safe execution
375+
sections = [] # Initialize list of parsed console sections
376+
current_console = None # Track currently active console name
377+
current_games = [] # Accumulate game lines for the current console
378+
379+
header_titles = [
380+
"-- Games Collection:",
381+
"-- Owned:",
382+
"-- Total:",
383+
"-- Icons:"
384+
]
385+
386+
for raw_line in lines: # Iterate all raw lines from the file
387+
stripped = raw_line.strip() # Normalize whitespace for pattern matching
388+
389+
# Skip global header lines
390+
if any(stripped.startswith(title) for title in header_titles):
391+
continue # Skip header block lines
392+
393+
if stripped.startswith("-- ") and ":" in stripped: # Detect console section header line
394+
if current_console is not None: # Flush previous console section before starting new one
395+
sections.append({"name": current_console, "games": current_games}) # Append completed section
396+
current_games = [] # Reset game accumulator for the next section
397+
398+
header_body = stripped[3:].strip() # Extract body after "-- " prefix
399+
console_name = header_body.split(":")[0].strip() # Extract console name before the colon
400+
current_console = console_name # Set active console to parsed name
401+
402+
elif stripped.startswith("- ") or (stripped.startswith("-") and not stripped.startswith("--")): # Detect game entry line
403+
if current_console is None: # Skip orphaned game lines without a parent console section
404+
print(f"{BackgroundColors.YELLOW}Warning: Game line found before any console section — skipping. File: {BackgroundColors.CYAN}{filepath}{BackgroundColors.YELLOW}, Line: {BackgroundColors.CYAN}{stripped}{Style.RESET_ALL}") # Log warning
405+
continue # Skip orphaned line
406+
407+
normalized = normalize_game_line(stripped, filepath, current_console) # Normalize and validate game line
408+
409+
if normalized: # Append only valid normalized game lines
410+
current_games.append(normalized) # Accumulate valid game line
411+
412+
if current_console is not None: # Flush final console section after loop ends
413+
sections.append({"name": current_console, "games": current_games}) # Append last section
414+
415+
for section in sections: # Sort games alphabetically within each console section
416+
section["games"] = sorted(section["games"], key=lambda line: line[2:].lower()) # Sort by game name case-insensitively
417+
418+
return sections # Return fully parsed and sorted sections
419+
420+
except Exception as e: # Catch unexpected parsing errors
421+
print(f"{BackgroundColors.RED}Error parsing console sections in {BackgroundColors.CYAN}{filepath}{BackgroundColors.RED}: {e}{Style.RESET_ALL}") # Log error
422+
return [] # Return empty list on failure
423+
424+
361425
def compute_console_counters(games: list) -> tuple:
362426
"""
363427
Compute owned and total counters for a list of normalized game lines.

0 commit comments

Comments
 (0)