Files
spectra/spectra/trigger.py

64 lines
1.4 KiB
Python

import json
import os
import threading
_TRIGGER_LOCK = threading.Lock()
def cache_dir():
env = os.environ.get("SPECTRA_CACHE_DIR")
if env:
os.makedirs(env, exist_ok=True)
return env
try:
d = "/var/cache/spectra"
os.makedirs(d, exist_ok=True)
return d
except PermissionError:
d = os.path.expanduser("~/.cache/spectra")
os.makedirs(d, exist_ok=True)
return d
def _trigger_path():
return os.path.join(cache_dir(), "trigger.json")
def write_trigger(data):
path = _trigger_path()
with _TRIGGER_LOCK:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
json.dump(data, f)
def read_trigger():
path = _trigger_path()
try:
with _TRIGGER_LOCK:
with open(path) as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return None
def clear_trigger():
path = _trigger_path()
with _TRIGGER_LOCK:
try:
os.remove(path)
except FileNotFoundError:
pass
def read_and_clear_trigger():
path = _trigger_path()
with _TRIGGER_LOCK:
try:
with open(path) as f:
data = json.load(f)
os.remove(path)
return data
except (FileNotFoundError, json.JSONDecodeError):
return None