Merge pull request #954 from NousResearch/hermes/hermes-20ea56c0
fix(config): atomic write for .env to prevent API key loss on crash
This commit is contained in:
commit
09b1de5f71
1 changed files with 14 additions and 2 deletions
|
|
@ -17,6 +17,7 @@ import platform
|
||||||
import stat
|
import stat
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
import tempfile
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Dict, Any, Optional, List, Tuple
|
from typing import Dict, Any, Optional, List, Tuple
|
||||||
|
|
||||||
|
|
@ -958,8 +959,19 @@ def save_env_value(key: str, value: str):
|
||||||
lines[-1] += "\n"
|
lines[-1] += "\n"
|
||||||
lines.append(f"{key}={value}\n")
|
lines.append(f"{key}={value}\n")
|
||||||
|
|
||||||
with open(env_path, 'w', **write_kw) as f:
|
fd, tmp_path = tempfile.mkstemp(dir=str(env_path.parent), suffix='.tmp', prefix='.env_')
|
||||||
f.writelines(lines)
|
try:
|
||||||
|
with os.fdopen(fd, 'w', **write_kw) as f:
|
||||||
|
f.writelines(lines)
|
||||||
|
f.flush()
|
||||||
|
os.fsync(f.fileno())
|
||||||
|
os.replace(tmp_path, env_path)
|
||||||
|
except BaseException:
|
||||||
|
try:
|
||||||
|
os.unlink(tmp_path)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
_secure_file(env_path)
|
_secure_file(env_path)
|
||||||
|
|
||||||
# Restrict .env permissions to owner-only (contains API keys)
|
# Restrict .env permissions to owner-only (contains API keys)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue