-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathenv_utils.py
More file actions
69 lines (56 loc) · 1.9 KB
/
env_utils.py
File metadata and controls
69 lines (56 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from __future__ import annotations
import json
import os
import subprocess
from pathlib import Path
def load_env_file(path: Path) -> dict[str, str]:
"""Load a simple .env file without overriding existing process env."""
loaded: dict[str, str] = {}
if not path.exists() or not path.is_file():
return loaded
for raw_line in path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[len("export ") :].strip()
if "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
value = value.strip().strip('"').strip("'")
if not key:
continue
if key not in os.environ:
os.environ[key] = value
loaded[key] = os.environ[key]
return loaded
def merged_environment(base_env: dict[str, str], overrides: dict[str, str]) -> dict[str, str]:
merged = dict(base_env)
merged.update(overrides)
return merged
def read_json(path: Path) -> dict[str, object] | list[object] | str | int | float | bool | None:
return json.loads(path.read_text(encoding="utf-8"))
def git_head(path: Path) -> str | None:
proc = subprocess.run(
["git", "-C", str(path), "rev-parse", "HEAD"],
capture_output=True,
text=True,
check=False,
)
if proc.returncode != 0:
return None
return proc.stdout.strip() or None
def safe_version_from_package_json(path: Path) -> str | None:
if not path.exists() or not path.is_file():
return None
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return None
if not isinstance(data, dict):
return None
version = data.get("version")
if isinstance(version, str):
return version
return None