Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
_dotenv.py55 linesDownload Raw Back to utils
1# AI-generated module (ChatGPT)2import re3 4 5def load_dotenv(dotenv_str: str, environ: dict[str, str] | None = None) -> dict[str, str]:6    """7    Parse a DOTENV-format string and return a dictionary of key-value pairs.8    Handles quoted values, comments, export keyword, and blank lines.9    """10    env: dict[str, str] = {}11    line_pattern = re.compile(12        r"""13        ^\s*14        (?:export[^\S\n]+)?               # optional export15        ([A-Za-z_][A-Za-z0-9_]*)          # key16        [^\S\n]*(=)?[^\S\n]*17        (                                 # value group18            (?:19                '(?:\\'|[^'])*'           # single-quoted value20                | \"(?:\\\"|[^\"])*\"     # double-quoted value21                | [^#\n\r]+?              # unquoted value22            )23        )?24        [^\S\n]*(?:\#.*)?$                # optional inline comment25    """,26        re.VERBOSE,27    )28 29    for line in dotenv_str.splitlines():30        line = line.strip()31        if not line or line.startswith("#"):32            continue  # Skip comments and empty lines33 34        match = line_pattern.match(line)35        if match:36            key = match.group(1)37            val = None38            if match.group(2):  # if there is '='39                raw_val = match.group(3) or ""40                val = raw_val.strip()41                # Remove surrounding quotes if quoted42                if (val.startswith('"') and val.endswith('"')) or (val.startswith("'") and val.endswith("'")):43                    val = val[1:-1]44                    val = val.replace(r"\n", "\n").replace(r"\t", "\t").replace(r"\"", '"').replace(r"\\", "\\")45                    if raw_val.startswith('"'):46                        val = val.replace(r"\$", "$")  # only in double quotes47            elif environ is not None:48                # Get it from the current environment49                val = environ.get(key)50 51            if val is not None:52                env[key] = val53 54    return env55