fix(config): treat empty .env values with inline # comments as empty
All checks were successful
Publish Python Package to Gitea / publish (push) Successful in 32s
All checks were successful
Publish Python Package to Gitea / publish (push) Successful in 32s
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from typing import Any
|
||||
|
||||
@@ -15,6 +16,29 @@ _user_env_cache: dict[str, str] | None = None
|
||||
_example_defaults_cache: dict[str, str] | None = None
|
||||
|
||||
|
||||
def _parse_env_value(raw_value: str) -> str:
|
||||
"""Parse one .env value: strip quotes / trailing comments; empty+# → \"\"."""
|
||||
value = raw_value if raw_value is not None else ""
|
||||
stripped = value.strip()
|
||||
if not stripped:
|
||||
return ""
|
||||
|
||||
# Quoted values keep interior content (including #).
|
||||
if len(stripped) >= 2 and stripped[0] == stripped[-1] and stripped[0] in ('"', "'"):
|
||||
return stripped[1:-1]
|
||||
|
||||
# Unquoted: ``KEY= # comment`` or ``KEY=# comment`` must be empty, not the comment text.
|
||||
# Also strip ``KEY=value # comment``. Keep ``KEY=https://x/#y`` (no whitespace before #).
|
||||
if re.search(r"(^|\s)#", value):
|
||||
# Split at first whitespace-#-comment or whole-value comment.
|
||||
m = re.match(r"^(.*?)\s+#.*$", value)
|
||||
if m is not None:
|
||||
return m.group(1).strip()
|
||||
if stripped.startswith("#"):
|
||||
return ""
|
||||
return stripped
|
||||
|
||||
|
||||
def _parse_env_file(path: str) -> dict[str, str]:
|
||||
"""标准库手写 .env 解析(不引 python-dotenv)。"""
|
||||
result: dict[str, str] = {}
|
||||
@@ -29,14 +53,9 @@ def _parse_env_file(path: str) -> dict[str, str]:
|
||||
continue
|
||||
key, _, value = line.partition("=")
|
||||
key = key.strip()
|
||||
value = value.strip()
|
||||
if not key:
|
||||
continue
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
|
||||
value = value[1:-1]
|
||||
elif " #" in value:
|
||||
value = value.split(" #", 1)[0].strip()
|
||||
result[key] = value
|
||||
result[key] = _parse_env_value(value)
|
||||
return result
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user