Skip to content

Commit

Permalink
fix potential bug with multi str replace
Browse files Browse the repository at this point in the history
  • Loading branch information
tomsilver committed Aug 25, 2024
1 parent f178239 commit 1238421
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions apply_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,22 @@
"""

import json
import re
import shutil
import subprocess
from pathlib import Path


def _multi_replace(substitutions: dict[str, str], text: str) -> str:
# Use re to replace everything in one pass, avoiding issues with the user's
# new values getting matched to my old values.
rep = dict((re.escape(k), v) for k, v in substitutions.items())
pattern = re.compile("|".join(rep.keys()))
return pattern.sub(lambda m: rep[re.escape(m.group(0))], text)


def _replace_all_occurences(
old: str,
new: str,
substitutions: dict[str, str],
exclude: set[Path] | None = None,
) -> None:
if exclude is None:
Expand All @@ -30,7 +38,7 @@ def _replace_all_occurences(
continue
with file_path.open("r", encoding="utf-8") as fp:
file_contents = fp.read()
updated_contents = file_contents.replace(old, new)
updated_contents = _multi_replace(substitutions, file_contents)
if updated_contents != file_contents:
with file_path.open("w", encoding="utf-8") as file:
file.write(updated_contents)
Expand Down Expand Up @@ -99,10 +107,9 @@ def _main() -> None:
"3.10": f"3.{python_subversion}",
"310": f"3{python_subversion}",
}
for old, new in substitutions.items():
_replace_all_occurences(
old, new, exclude={outer_dir / "apply_configuration.py", config_file}
)
_replace_all_occurences(
substitutions, exclude={outer_dir / "apply_configuration.py", config_file}
)

# Rename the package repo.
subprocess.run(["mv", "src/python_starter", f"src/{package_name}"], check=True)
Expand Down

0 comments on commit 1238421

Please sign in to comment.