0ptr/nullptr/store.py

74 lines
1.8 KiB
Python
Raw Normal View History

from nullptr.models.base import Base
from nullptr.models.waypoint import Waypoint
from nullptr.models.sector import Sector
from nullptr.models.system import System
from nullptr.models.agent import Agent
2023-06-09 20:20:46 +00:00
from os.path import isfile, dirname, isdir
import os
import json
from .util import *
2023-06-09 11:19:47 +00:00
class Store:
2023-06-09 20:20:46 +00:00
def __init__(self, data_dir):
self.data_dir = data_dir
self.data = {}
def path(self, obj):
return os.path.join(self.data_dir, obj.path())
def load(self, obj):
path = self.path(obj)
if not isfile(path):
return obj
with open(path) as f:
data = json.load(f)
data['store'] = self
2023-06-10 17:39:32 +00:00
data['dirty'] = False
2023-06-09 20:20:46 +00:00
obj.__dict__ = data
2023-06-09 20:20:46 +00:00
def store(self, obj):
path = self.path(obj)
path_dir = dirname(path)
data = obj.dict()
if not isdir(path_dir):
os.makedirs(path_dir, exist_ok=True)
with open(path, 'w') as f:
json.dump(data, f, indent=2)
obj.dirty = False
def get(self, typ, symbol):
obj = typ(symbol, self)
self.load(obj)
self.data[symbol] = obj
return obj
2023-06-10 18:49:50 +00:00
def update(self, typ, symbol, data):
obj = self.get(typ, symbol)
obj.update(data)
return obj
def update_list(self, typ, lst):
return [self.update(typ, mg(d, 'symbol'), d) for d in lst]
2023-06-10 17:39:32 +00:00
def all(self, path, typ):
if hasattr(path, 'path'):
path = path.path()
path = os.path.join(self.data_dir, path)
if not isdir(path):
return
ext = '.' + typ.ext()
for f in os.listdir(path):
fil = os.path.join(path, f)
if not isfile(fil):
continue
if not fil.endswith(ext):
continue
symbol = f[:-len(ext)]
yield self.get(typ, symbol)
2023-06-09 20:20:46 +00:00
def flush(self):
for obj in self.data.values():
2023-06-10 17:39:32 +00:00
if obj.dirty:
self.store(obj)