This commit is contained in:
root committed 2026-06-06 12:36:25 +00:00
1 parent 206997510c
commit 251bd3e65f
14 files changed
+836

No files matched your search

+66
View File
@@ -0,0 +1,66 @@
"""Storage module for JSON file persistence.
This module provides the Storage class that handles reading and writing
todo items to a JSON file located at ~/.todo_cli/todos.json.
"""
import json
import os
from typing import List, Dict, Any
class Storage:
"""Handles persistent storage of todo items in a JSON file.
Attributes:
file_path: The absolute path to the JSON storage file.
"""
def __init__(self, file_path: str = None) -> None:
"""Initialize Storage with a file path.
If no file_path is provided, defaults to ~/.todo_cli/todos.json.
Args:
file_path: Optional custom path for the JSON file.
"""
if file_path is None:
home_dir = os.path.expanduser("~")
self.file_path = os.path.join(home_dir, ".todo_cli", "todos.json")
else:
self.file_path = file_path
def load(self) -> List[Dict[str, Any]]:
"""Load todo items from the JSON file.
Returns:
A list of dictionaries representing todo items.
Returns an empty list if the file does not exist or is corrupted.
"""
if not os.path.exists(self.file_path):
return []
try:
with open(self.file_path, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
return data
else:
return []
except (json.JSONDecodeError, IOError):
return []
def save(self, data: List[Dict[str, Any]]) -> None:
"""Save a list of todo item dictionaries to the JSON file.
Creates the directory structure if it does not exist.
Args:
data: A list of dictionaries representing todo items to persist.
"""
directory = os.path.dirname(self.file_path)
if directory:
os.makedirs(directory, exist_ok=True)
with open(self.file_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)