"""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