Files
python-helpers/python_helpers/env.py
T
slawek 9f56b3ee19 Add initial implementation of Python helpers and CLI tools
- Create .gitignore to exclude build artifacts
- Add README.md with project description and installation instructions
- Implement pyproject.toml for package metadata and script entry points
- Add console output helpers for command-line scripts
- Implement environment file loading functionality
- Add JSON file I/O helpers
- Create token decoder CLI for decoding JWT claims
- Implement serve-markdown CLI for serving Markdown files as HTML
2026-09-06 19:15:54 +02:00

34 lines
1.3 KiB
Python

"""Environment file helpers for command-line scripts."""
import os
from python_helpers.console import fail
def load_env_file(path):
"""Load a docker-style environment file into the process environment.
Blank lines and lines whose first non-blank character is # are ignored; a # anywhere
else is part of the value. A NAME=VALUE line sets the variable, overriding any value
already in the environment; a bare NAME line leaves the inherited value in place.
Values are taken literally, without quote removal or variable interpolation. An empty
name, or one containing whitespace, is an error.
Args:
path: path to the environment file.
"""
try:
with open(path, encoding="utf-8") as env_file:
lines = env_file.read().splitlines()
except OSError as error:
fail(f"Could not read '{path}': {error}")
for number, line in enumerate(lines, start=1):
if not line.strip() or line.lstrip().startswith("#"):
continue
name, separator, value = line.partition("=")
if not name or any(character.isspace() for character in name):
fail(f"{path}: line {number}: variable '{name}' is empty or contains whitespace")
if separator:
os.environ[name] = value