From f3467c879c6491e00f9cdb4eae48a407aef39b2b Mon Sep 17 00:00:00 2001 From: Nicholas Kalar Date: Sat, 22 Nov 2025 13:53:03 -0500 Subject: [PATCH] Added update_json and refactor --- src/FileHandler.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/FileHandler.py b/src/FileHandler.py index ee720e2..e674058 100644 --- a/src/FileHandler.py +++ b/src/FileHandler.py @@ -5,9 +5,9 @@ from dotenv import load_dotenv load_dotenv() -file_path = os.getenv("file_path") +file_path = os.getenv("file_path") if os.getenv("file_path") else "./checklist.md" -def read_json() -> dict: +def read_json() -> dict | None: try: with open("./src/json/ingredients.json", "rt") as file: return json.load(file) @@ -15,15 +15,20 @@ def read_json() -> dict: print("Could not find or read file.") def update_json(meals: dict): - print("TODO: Add update logic") + try: + with open("./src/json/ingredients.json", "w") as file: + json.dump(meals, file, indent=4) + except Exception as e: + print(f"Unable to write data to file. {e}") -def get_selected_meals(meals: dict) -> dict: +def get_selected_meals(meals: dict) -> dict | None: meal_json = read_json() selected_meals = {} - for meal in meals: - if meal in meal_json: - selected_meals[meal] = meal_json[meal] - return selected_meals + if meal_json: + for meal in meals: + if meal in meal_json: + selected_meals[meal] = meal_json[meal] + return selected_meals def combine_ingredients(meals: dict) -> dict: combined_ingredients = {} @@ -37,9 +42,6 @@ def combine_ingredients(meals: dict) -> dict: return combined_ingredients def write_checklist(data: dict) -> None: - if os.path.exists(file_path): - os.remove(file_path) - try: with open(file_path, 'w') as checklist: for ingredient, details in data.items():