import json import os from loop_claude.outcome import Failure def make_private(folder): mask = os.umask(0o077) try: os.makedirs(folder, exist_ok=True) finally: os.umask(mask) def replace_json(path, data, **dump): return replace_file(path, json.dumps(data, **dump).encode()) def replace_file(path, data): staged = f"{path}.{os.getpid()}" try: mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600 with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as handle: os.fchmod(handle.fileno(), mode) handle.write(data) os.replace(staged, path) except OSError as failure: if os.path.exists(staged): os.remove(staged) return Failure(failure.strerror) return None