solution
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Создать локальный .env для lab4 без вывода секретов; работает в PowerShell."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def initialize(path: Path):
|
||||
"""Сохранить существующие значения, заполнить отсутствующие настройки."""
|
||||
lines = path.read_text(encoding="utf-8-sig").splitlines() if path.exists() else []
|
||||
values = {}
|
||||
positions = {}
|
||||
for index, line in enumerate(lines):
|
||||
if line.strip() and not line.lstrip().startswith("#") and "=" in line:
|
||||
key, value = line.split("=", 1)
|
||||
values[key.strip()] = value.strip()
|
||||
positions.setdefault(key.strip(), []).append(index)
|
||||
|
||||
defaults = {
|
||||
"POSTGRES_USER": "messenger",
|
||||
"POSTGRES_PASSWORD": secrets.token_hex(24),
|
||||
"POSTGRES_DB": "messenger",
|
||||
"SESSION_TTL_SECONDS": "3600",
|
||||
"CACHE_URL": "redis://redis:6379/0",
|
||||
"LOG_LEVEL": "WARNING",
|
||||
"API_IMAGE": "mtusi-messenger:lab4",
|
||||
"MINIO_ROOT_USER": "minio-root",
|
||||
"MINIO_ROOT_PASSWORD": secrets.token_hex(32),
|
||||
"S3_BUCKET": "attachments",
|
||||
"S3_ACCESS_KEY": "api_" + secrets.token_hex(8),
|
||||
"S3_SECRET_KEY": secrets.token_hex(20),
|
||||
}
|
||||
changed = []
|
||||
for key, default in defaults.items():
|
||||
existing = values.get(key, "")
|
||||
upgrade_image = key == "API_IMAGE" and existing == "mtusi-messenger:lab3"
|
||||
if key in values and existing and not existing.startswith("CHANGE_ME") and not upgrade_image:
|
||||
continue
|
||||
# An explicitly empty CACHE_URL means the optional cache is disabled.
|
||||
if key == "CACHE_URL" and key in values:
|
||||
continue
|
||||
if key in positions:
|
||||
for index in positions[key]:
|
||||
lines[index] = key + "=" + default
|
||||
else:
|
||||
lines.append(key + "=" + default)
|
||||
changed.append(key)
|
||||
if changed or not path.exists():
|
||||
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
if os.name != "nt":
|
||||
path.chmod(0o600)
|
||||
return changed
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", type=Path, default=ROOT / ".env")
|
||||
args = parser.parse_args()
|
||||
changed = initialize(args.output)
|
||||
print(".env: " + ("обновлены настройки " + ", ".join(changed) if changed else "уже настроен"))
|
||||
print("Существующий пароль PostgreSQL сохранён; значения секретов не выводятся.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user