Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit e3ec918

Browse filesBrowse files
authored
Merge pull request #1529 from stonebig/master
use a generic utils.replace_in_file() to prepare 7zip scripts
2 parents c0c7404 + 3910176 commit e3ec918
Copy full SHA for e3ec918

File tree

Expand file treeCollapse file tree

2 files changed

+28
-61
lines changed
Filter options
Expand file treeCollapse file tree

2 files changed

+28
-61
lines changed

‎make.py

Copy file name to clipboardExpand all lines: make.py
+5-30Lines changed: 5 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -32,29 +32,6 @@ def find_7zip_executable() -> str:
3232
return str(executable_path)
3333
raise RuntimeError("7ZIP is not installed on this computer.")
3434

35-
def replace_lines_in_file(filepath: Path, replacements: list[tuple[str, str]]):
36-
"""
37-
Replaces lines in a file that start with a given prefix.
38-
Args:
39-
filepath: Path to the file to modify.
40-
replacements: A list of tuples, where each tuple contains:
41-
- The prefix of the line to replace (str).
42-
- The new text for the line (str).
43-
"""
44-
with open(filepath, "r") as f:
45-
lines = f.readlines()
46-
updated_lines = lines.copy() # Create a mutable copy of lines
47-
48-
for index, line in enumerate(lines):
49-
for prefix, new_text in replacements:
50-
start_prefix = f"set {prefix}=" if not prefix.startswith("!") else prefix
51-
if line.startswith(start_prefix):
52-
updated_lines[index] = f"{start_prefix}{new_text}\n"
53-
54-
with open(filepath, "w") as f:
55-
f.writelines(updated_lines)
56-
print(f"Updated 7-zip script: {filepath}")
57-
5835
def build_installer_7zip(script_template_path: Path, output_script_path: Path, replacements: list[tuple[str, str]]):
5936
"""
6037
Creates a 7-Zip installer script by copying a template and applying text replacements.
@@ -64,15 +41,13 @@ def build_installer_7zip(script_template_path: Path, output_script_path: Path, r
6441
output_script_path: Path to save the generated 7-Zip script.
6542
replacements: A list of tuples for text replacements (prefix, new_text).
6643
"""
67-
shutil.copy(script_template_path, output_script_path)
68-
6944
# Standard replacements for all 7zip scripts
7045
data_to_replace = [
71-
("PORTABLE_DIR", str(PORTABLE_DIRECTORY)),
72-
("SEVENZIP_EXE", find_7zip_executable()),
73-
] + replacements
74-
75-
replace_lines_in_file(output_script_path, data_to_replace)
46+
("PORTABLE_DIR=", f"PORTABLE_DIR={PORTABLE_DIRECTORY}& rem "),
47+
("SEVENZIP_EXE=", f"SEVENZIP_EXE={find_7zip_executable()}& rem "),
48+
] + [(f"{a}=", f"{a}={b}& rem ") for a, b in replacements]
49+
50+
utils.replace_in_file(script_template_path, data_to_replace, output_script_path)
7651

7752
try:
7853
# Execute the generated 7-Zip script, with stdout=sys.stderr to see 7zip compressing

‎winpython/utils.py

Copy file name to clipboardExpand all lines: winpython/utils.py
+23-31Lines changed: 23 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -394,29 +394,31 @@ def guess_encoding(csv_file):
394394
except:
395395
return [locale.getdefaultlocale()[1], "utf-8"]
396396

397+
def replace_in_file(filepath: Path, replacements: list[tuple[str, str]], filedest: Path = None, verbose=False):
398+
"""
399+
Replaces strings in a file
400+
Args:
401+
filepath: Path to the file to modify.
402+
replacements: A list of tuples of ('old string 'new string')
403+
filedest: optional output file, otherwise will be filepath
404+
"""
405+
the_encoding = guess_encoding(filepath)[0]
406+
with open(filepath, "r", encoding=the_encoding) as f:
407+
content = f.read()
408+
new_content = content
409+
for old_text, new_text in replacements:
410+
new_content = new_content.replace(old_text, new_text)
411+
outfile = filedest if filedest else filepath
412+
if new_content != content or str(outfile) != str(filepath):
413+
with open(outfile, "w", encoding=the_encoding) as f:
414+
f.write(new_content)
415+
if verbose:
416+
print(f"patched {filepath} into {outfile} !")
397417

398418
def patch_sourcefile(fname, in_text, out_text, silent_mode=False):
399419
"""Replace a string in a source file"""
400-
import io
401-
402420
if Path(fname).is_file() and not in_text == out_text:
403-
the_encoding = guess_encoding(fname)[0]
404-
with io.open(fname, 'r', encoding=the_encoding) as fh:
405-
content = fh.read()
406-
new_content = content.replace(in_text, out_text)
407-
if not new_content == content:
408-
if not silent_mode:
409-
print(
410-
"patching ",
411-
fname,
412-
"from",
413-
in_text,
414-
"to",
415-
out_text,
416-
)
417-
with io.open(fname, 'wt', encoding=the_encoding) as fh:
418-
fh.write(new_content)
419-
421+
replace_in_file(Path(fname), [(in_text , out_text)], verbose=True)
420422

421423
def _create_temp_dir():
422424
"""Create a temporary directory and remove it at exit"""
@@ -480,8 +482,7 @@ def buildflit_wininst(
480482
copy_to=None,
481483
verbose=False,
482484
):
483-
"""Build Wheel from Python package located in *root*
484-
with flit"""
485+
"""Build Wheel from Python package located in *root*with flit"""
485486
if python_exe is None:
486487
python_exe = sys.executable
487488
assert Path(python_exe).is_file()
@@ -531,16 +532,7 @@ def buildflit_wininst(
531532
dst_fname = str(Path(copy_to) / distname)
532533
shutil.move(src_fname, dst_fname)
533534
if verbose:
534-
print(
535-
(
536-
f"Move: {src_fname} --> {dst_fname}"
537-
)
538-
)
539-
# remove tempo dir 'root' no more needed
540-
#try:
541-
# shutil.rmtree(root, onexc=onerror)
542-
#except TypeError: # before 3.12
543-
# shutil.rmtree(root, onerror=onerror)
535+
print(f"Move: {src_fname} --> {dst_fname}")
544536
return dst_fname
545537

546538

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.