|
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 | 1 | import json
|
8 |
| -import yaml |
9 | 2 | from pathlib import Path
|
10 | 3 |
|
11 | 4 | # Update the .env file with the answers from the .copier-answers.yml file
|
12 | 5 | # without using Jinja2 templates in the .env file, this way the code works as is
|
13 | 6 | # without needing Copier, but if Copier is used, the .env file will be updated
|
14 | 7 | 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 |
| - |
| 8 | +answers_path = Path(__file__).parent / ".copier-answers.yml" |
| 9 | +answers = json.loads(answers_path.read_text()) |
23 | 10 | 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() |
| 11 | +env_content = env_path.read_text() |
34 | 12 |
|
35 |
| -# Update the .env file |
36 | 13 | lines = []
|
| 14 | + |
37 | 15 | for line in env_content.splitlines():
|
38 |
| - line_updated = False |
39 | 16 | for key, value in answers.items():
|
40 | 17 | upper_key = key.upper()
|
41 | 18 | if line.startswith(f"{upper_key}="):
|
42 |
| - content = f'{upper_key}="{value}"' if isinstance(value, str) and " " in value else f"{upper_key}={value}" |
43 |
| - lines.append(content) |
44 |
| - line_updated = True |
| 19 | + if " " in value: |
| 20 | + content = f"{upper_key}={value!r}" |
| 21 | + else: |
| 22 | + content = f"{upper_key}={value}" |
| 23 | + new_line = line.replace(line, content) |
| 24 | + lines.append(new_line) |
45 | 25 | break
|
46 |
| - if not line_updated: |
| 26 | + else: |
47 | 27 | lines.append(line)
|
48 | 28 |
|
49 |
| -# Write the updated .env file |
50 |
| -with open(env_path, "w") as f: |
51 |
| - f.write("\n".join(lines)) |
52 |
| - |
53 |
| -print(f"Updated {env_path} with values from Copier answers.") |
| 29 | +env_path.write_text("\n".join(lines)) |
0 commit comments