spyglass/app/database.py

53 lines
1.4 KiB
Python
Raw Normal View History

2024-02-04 02:44:48 +01:00
import os
import shelve as shelf
import platform
from pathlib import Path
from utils import die
class Shelf:
def __init__(self, filename: str):
self.file: Path = None
self.db = None
os_type: str = platform.system()
if os_type == 'Linux':
self.file = os.environ.get('HOME') + '/.local/share/' + filename
elif os_type == 'Windows':
self.file = os.environ.get('APPDATA') + filename
else:
die('OS not supported', 2)
def __enter__(self):
# Open the shelf and load data into self.db
self.db = shelf.open(self.file, writeback=True)
return self
def __exit__(self, exc_type, exc_value, traceback):
# Save any updates to the shelf
if self.db is not None:
self.db.sync()
self.db.close()
def update(self, entries: dict):
db_values = self.db.values()
if db_values:
dirs, projects, _ = db_values
new_dirs, new_projects, _ = entries.values()
for dir in new_dirs:
if dir not in dirs:
self.db['dirs'].append(dir)
for project in new_projects:
if project not in projects:
self.db['projects'].append(project)
else:
for k, v in entries.items():
self.db[k] = v