Skip to content

Commit 43c5160

Browse files
Add .copier/update_dotenv.py script
1 parent 05f7c75 commit 43c5160

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

.copier/update_dotenv.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#!/usr/bin/env python3
2+
"""
3+
This script updates the .env file with values from the Copier answers.
4+
It allows the .env file to be a regular file (not a template) that works with or without Copier.
5+
"""
6+
7+
from pathlib import Path
8+
import json
9+
import yaml
10+
11+
# Update the .env file with the answers from the .copier-answers.yml file
12+
# without using Jinja2 templates in the .env file, this way the code works as is
13+
# without needing Copier, but if Copier is used, the .env file will be updated
14+
root_path = Path(__file__).parent.parent
15+
answers_path = root_path / ".copier-answers.yml"
16+
17+
# Load the answers from YAML format
18+
with open(answers_path, "r") as f:
19+
answers_yaml = f.read()
20+
# Convert YAML to Python dict
21+
answers = yaml.safe_load(answers_yaml)
22+
23+
env_path = root_path / ".env"
24+
if not env_path.exists():
25+
env_example_path = root_path / ".env.example"
26+
if env_example_path.exists():
27+
with open(env_example_path, "r") as f:
28+
env_content = f.read()
29+
else:
30+
env_content = ""
31+
else:
32+
with open(env_path, "r") as f:
33+
env_content = f.read()
34+
35+
# Update the .env file
36+
lines = []
37+
for line in env_content.splitlines():
38+
line_updated = False
39+
for key, value in answers.items():
40+
upper_key = key.upper()
41+
if line.startswith(f"{upper_key}="):
42+
if isinstance(value, str) and " " in value:
43+
content = f'{upper_key}="{value}"'
44+
else:
45+
content = f"{upper_key}={value}"
46+
lines.append(content)
47+
line_updated = True
48+
break
49+
if not line_updated:
50+
lines.append(line)
51+
52+
# Write the updated .env file
53+
with open(env_path, "w") as f:
54+
f.write("\n".join(lines))
55+
56+
print(f"Updated {env_path} with values from Copier answers.")

0 commit comments

Comments
 (0)