42 lines
1.2 KiB
Python
42 lines
1.2 KiB
Python
#! /usr/bin/env python3
|
|
import os
|
|
import sys
|
|
from xdg import XDG_CONFIG_HOME, XDG_DATA_HOME
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
CONFIG_DIR = os.path.join(XDG_CONFIG_HOME, "schmeckels")
|
|
DATA_DIR = os.path.join(XDG_DATA_HOME, "schmeckels")
|
|
|
|
|
|
def create_dirs():
|
|
for directory in [CONFIG_DIR, DATA_DIR]:
|
|
try:
|
|
os.mkdir(directory)
|
|
except FileExistsError:
|
|
pass
|
|
|
|
|
|
def build_database_filename(profile_name):
|
|
return f"{DATA_DIR}/{profile_name}.db"
|
|
|
|
|
|
def get_session(profile_name):
|
|
if not profile_name:
|
|
count = len(os.listdir(DATA_DIR))
|
|
if count == 1:
|
|
filename = f"{DATA_DIR}/{os.listdir(DATA_DIR)[0]}"
|
|
else:
|
|
print("--profile is required when you have more than one database.")
|
|
sys.exit(1)
|
|
else:
|
|
filename = build_database_filename(profile_name)
|
|
|
|
print(filename)
|
|
if os.path.exists(filename) and os.path.isfile(filename):
|
|
engine = create_engine(f"sqlite:///{filename}")
|
|
Session = sessionmaker(bind=engine)
|
|
return Session()
|
|
else:
|
|
print(f"No database for profile '{profile_name}'. Did you run 'init'?")
|
|
sys.exit(1)
|