Skip to content

Commit b9b6bd5

Browse files
committed
Port the migration script to Python
Since this is used to update Python projects, it is safe to assume Python will be available. Using Python is more portable, so hopefully the migration script will work more consistently across different OSs. Signed-off-by: Leandro Lucarella <[email protected]>
1 parent 772b73e commit b9b6bd5

9 files changed

+260
-87
lines changed
+107
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
#!/usr/bin/env python3
2+
# License: MIT
3+
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH
4+
5+
"""Script to migrate existing projects to new versions of the cookiecutter template.
6+
7+
This script migrates existing projects to new versions of the cookiecutter
8+
template, removing the need to completely regenerate the project from
9+
scratch.
10+
11+
To run it, the simplest way is to fetch it from GitHub and run it directly:
12+
13+
curl -sSL https://raw.githubusercontent.com/frequenz-floss/frequenz-repo-config-python/<tag>/cookiecutter/migrate.py | python3
14+
15+
Make sure to replace the `<tag>` to the version you want to migrate to in the URL.
16+
17+
For jumping multiple versions you should run the script multiple times, once
18+
for each version.
19+
20+
And remember to follow any manual instructions for each run.
21+
""" # noqa: E501
22+
23+
import os
24+
import subprocess
25+
import tempfile
26+
from pathlib import Path
27+
from typing import SupportsIndex
28+
29+
30+
def main() -> None:
31+
"""Run the migration steps."""
32+
# Add a separation line like this one after each migration step.
33+
print("=" * 72)
34+
35+
36+
def apply_patch(patch_content: str) -> None:
37+
"""Apply a patch using the patch utility."""
38+
subprocess.run(["patch", "-p1"], input=patch_content.encode(), check=True)
39+
40+
41+
def replace_file_contents_atomically( # noqa; DOC501
42+
filepath: str | Path,
43+
old: str,
44+
new: str,
45+
count: SupportsIndex = -1,
46+
*,
47+
content: str | None = None,
48+
) -> None:
49+
"""Replace a file atomically with new content.
50+
51+
Args:
52+
filepath: The path to the file to replace.
53+
old: The string to replace.
54+
new: The string to replace it with.
55+
count: The maximum number of occurrences to replace. If negative, all occurrences are
56+
replaced.
57+
content: The content to replace. If not provided, the file is read from disk.
58+
59+
The replacement is done atomically by writing to a temporary file and
60+
then moving it to the target location.
61+
"""
62+
if isinstance(filepath, str):
63+
filepath = Path(filepath)
64+
65+
if content is None:
66+
content = filepath.read_text(encoding="utf-8")
67+
68+
content = content.replace(old, new, count)
69+
70+
# Create temporary file in the same directory to ensure atomic move
71+
tmp_dir = filepath.parent
72+
73+
# pylint: disable-next=consider-using-with
74+
tmp = tempfile.NamedTemporaryFile(mode="w", dir=tmp_dir, delete=False)
75+
76+
try:
77+
# Copy original file permissions
78+
st = os.stat(filepath)
79+
80+
# Write the new content
81+
tmp.write(content)
82+
83+
# Ensure all data is written to disk
84+
tmp.flush()
85+
os.fsync(tmp.fileno())
86+
tmp.close()
87+
88+
# Copy original file permissions to the new file
89+
os.chmod(tmp.name, st.st_mode)
90+
91+
# Perform atomic replace
92+
os.rename(tmp.name, filepath)
93+
94+
except BaseException:
95+
# Clean up the temporary file in case of errors
96+
tmp.close()
97+
os.unlink(tmp.name)
98+
raise
99+
100+
101+
def manual_step(message: str) -> None:
102+
"""Print a manual step message in yellow."""
103+
print(f"\033[0;33m>>> {message}\033[0m")
104+
105+
106+
if __name__ == "__main__":
107+
main()

.github/cookiecutter-migrate.template.sh

-30
This file was deleted.

CONTRIBUTING.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ These are the steps to create a new release:
187187

188188
```sh
189189
cp .github/RELEASE_NOTES.template.md RELEASE_NOTES.md
190-
cp .github/cookiecutter-migrate.template.sh cookiecutter/migrate.sh
190+
cp .github/cookiecutter-migrate.template.py cookiecutter/migrate.py
191191
```
192192

193193
Commit the new release notes and migration script, and create a PR (this step

RELEASE_NOTES.md

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
* Update the SDK dependency to `1.0.0rc901`.
2727
* Change `edit_uri` default branch to v0.x.x in mkdocs.yml.
2828
* Added a new default option `asyncio_default_fixture_loop_scope = "function"` for `pytest-asyncio` as not providing a value is deprecated.
29+
* The migration script is now written in Python, so it should be (hopefully) more compatible with different OSes.
2930

3031
## Bug Fixes
3132

cookiecutter/migrate.py

+141
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
#!/usr/bin/env python3
2+
# License: MIT
3+
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH
4+
5+
"""Script to migrate existing projects to new versions of the cookiecutter template.
6+
7+
This script migrates existing projects to new versions of the cookiecutter
8+
template, removing the need to completely regenerate the project from
9+
scratch.
10+
11+
To run it, the simplest way is to fetch it from GitHub and run it directly:
12+
13+
curl -sSL https://raw.githubusercontent.com/frequenz-floss/frequenz-repo-config-python/v0.10.0/cookiecutter/migrate.py | python3
14+
15+
Make sure the version you want to migrate to is correct in the URL.
16+
17+
For jumping multiple versions you should run the script multiple times, once
18+
for each version.
19+
20+
And remember to follow any manual instructions for each run.
21+
""" # noqa: E501
22+
23+
import os
24+
import subprocess
25+
import tempfile
26+
from pathlib import Path
27+
from typing import SupportsIndex
28+
29+
30+
def apply_patch(patch_content: str) -> None:
31+
"""Apply a patch using the patch utility."""
32+
subprocess.run(["patch", "-p1"], input=patch_content.encode(), check=True)
33+
34+
35+
def replace_file_contents_atomically( # noqa; DOC501
36+
filepath: str | Path,
37+
old: str,
38+
new: str,
39+
count: SupportsIndex = -1,
40+
*,
41+
content: str | None = None,
42+
) -> None:
43+
"""Replace a file atomically with new content.
44+
45+
Args:
46+
filepath: The path to the file to replace.
47+
old: The string to replace.
48+
new: The string to replace it with.
49+
count: The maximum number of occurrences to replace. If negative, all occurrences are
50+
replaced.
51+
content: The content to replace. If not provided, the file is read from disk.
52+
53+
The replacement is done atomically by writing to a temporary file and
54+
then moving it to the target location.
55+
"""
56+
if isinstance(filepath, str):
57+
filepath = Path(filepath)
58+
59+
if content is None:
60+
content = filepath.read_text(encoding="utf-8")
61+
62+
content = content.replace(old, new, count)
63+
64+
# Create temporary file in the same directory to ensure atomic move
65+
tmp_dir = filepath.parent
66+
67+
# pylint: disable-next=consider-using-with
68+
tmp = tempfile.NamedTemporaryFile(mode="w", dir=tmp_dir, delete=False)
69+
70+
try:
71+
# Copy original file permissions
72+
st = os.stat(filepath)
73+
74+
# Write the new content
75+
tmp.write(content)
76+
77+
# Ensure all data is written to disk
78+
tmp.flush()
79+
os.fsync(tmp.fileno())
80+
tmp.close()
81+
82+
# Copy original file permissions to the new file
83+
os.chmod(tmp.name, st.st_mode)
84+
85+
# Perform atomic replace
86+
os.rename(tmp.name, filepath)
87+
88+
except BaseException:
89+
# Clean up the temporary file in case of errors
90+
tmp.close()
91+
os.unlink(tmp.name)
92+
raise
93+
94+
95+
def main() -> None:
96+
"""Run the migration steps."""
97+
# Dependabot patch
98+
dependabot_yaml = Path(".github/dependabot.yml")
99+
print(f"{dependabot_yaml}: Add new grouping for actions/*-artifact updates.")
100+
if dependabot_yaml.read_text(encoding="utf-8").find("actions/*-artifact") == -1:
101+
apply_patch(
102+
"""\
103+
--- a/.github/dependabot.yml
104+
+++ b/.github/dependabot.yml
105+
@@ -39,3 +39,11 @@ updates:
106+
labels:
107+
- "part:tooling"
108+
- "type:tech-debt"
109+
+ groups:
110+
+ compatible:
111+
+ update-types:
112+
+ - "minor"
113+
+ - "patch"
114+
+ artifacts:
115+
+ patterns:
116+
+ - "actions/*-artifact"
117+
"""
118+
)
119+
else:
120+
print(f"{dependabot_yaml}: seems to be already up-to-date.")
121+
print("=" * 72)
122+
123+
# Fix labeler configuration
124+
labeler_yml = ".github/labeler.yml"
125+
print(f"{labeler_yml}: Fix the labeler configuration example.")
126+
replace_file_contents_atomically(
127+
labeler_yml, "all-glob-to-all-file", "all-globs-to-all-files"
128+
)
129+
print("=" * 72)
130+
131+
# Add a separation line like this one after each migration step.
132+
print("=" * 72)
133+
134+
135+
def manual_step(message: str) -> None:
136+
"""Print a manual step message in yellow."""
137+
print(f"\033[0;33m>>> {message}\033[0m")
138+
139+
140+
if __name__ == "__main__":
141+
main()

cookiecutter/migrate.sh

-53
This file was deleted.

docs/user-guide/update-an-existing-project.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ The easiest way to run the migration script is to fetch it from GitHub and run
2222
it directly.
2323

2424
```sh
25-
curl -sSL https://raw.githubusercontent.com/frequenz-floss/frequenz-repo-config-python/{{ ref_name }}/cookiecutter/migrate.sh \
26-
| sh
25+
curl -sSL https://raw.githubusercontent.com/frequenz-floss/frequenz-repo-config-python/{{ ref_name }}/cookiecutter/migrate.py \
26+
| python3
2727
```
2828

2929
Make sure that the version (`{{ ref_name }}`) matches the

noxfile.py

+1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
[
1212
"cookiecutter/hooks",
1313
"cookiecutter/local_extensions.py",
14+
"cookiecutter/migrate.py",
1415
]
1516
)
1617
nox.configure(config)

pyproject.toml

+7-1
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,13 @@ include = '\.pyi?$'
128128
[tool.isort]
129129
profile = "black"
130130
line_length = 88
131-
src_paths = ["benchmarks", "examples", "src", "tests"]
131+
src_paths = [
132+
"benchmarks",
133+
"examples",
134+
"src",
135+
"tests",
136+
"cookiecutter/migrate.py",
137+
]
132138

133139
[tool.flake8]
134140
# We give some flexibility to go over 88, there are cases like long URLs or

0 commit comments

Comments
 (0)