Files

35 lines
1.3 KiB
Python

"""Reads the credentials a tool needs from an env file: KEY=value lines that only the file's owner may read."""
import pathlib
from failure import Failure
def read_env(path: pathlib.Path, keys: tuple[str, ...], secret: str) -> dict[str, str] | Failure:
"""The value of each of keys in path. secret names what the file holds, such as `an API token`, for the Failure that says who may read it."""
try:
mode = path.stat().st_mode
text = path.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"{path} does not exist; it needs {', '.join(keys[:-1])} and {keys[-1]}")
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"cannot read {path}: {failure}")
if mode & 0o077:
return Failure(f"{path} holds {secret}, so only its owner may read it; run chmod 600 {path}")
values = parse_env(text)
if missing := [key for key in keys if not values.get(key)]:
return Failure(f"{path} lacks {' and '.join(missing)}")
return {key: values[key] for key in keys}
def parse_env(text: str) -> dict[str, str]:
values = {}
for line in text.splitlines():
key, equals, value = line.partition("=")
if not equals or key.lstrip().startswith("#"):
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
value = value[1:-1]
values[key.strip()] = value
return values