Skip to content

Commit f0a5d81

Browse files
authored
Merge pull request #1530 from stonebig/master
simplify utils.py syntax using github copilote of 2025-04-06
2 parents e3ec918 + 634a0c9 commit f0a5d81

File tree

1 file changed

+35
-76
lines changed

1 file changed

+35
-76
lines changed

winpython/utils.py

+35-76
Original file line numberDiff line numberDiff line change
@@ -413,12 +413,14 @@ def replace_in_file(filepath: Path, replacements: list[tuple[str, str]], filedes
413413
with open(outfile, "w", encoding=the_encoding) as f:
414414
f.write(new_content)
415415
if verbose:
416-
print(f"patched {filepath} into {outfile} !")
416+
print(f"patched from {Path(filepath).name} into {outfile} !")
417417

418418
def patch_sourcefile(fname, in_text, out_text, silent_mode=False):
419419
"""Replace a string in a source file"""
420+
if not silent_mode:
421+
print(f"patching {fname} from {in_text} to {out_text}")
420422
if Path(fname).is_file() and not in_text == out_text:
421-
replace_in_file(Path(fname), [(in_text , out_text)], verbose=True)
423+
replace_in_file(Path(fname), [(in_text , out_text)])
422424

423425
def _create_temp_dir():
424426
"""Create a temporary directory and remove it at exit"""
@@ -429,26 +431,18 @@ def _create_temp_dir():
429431
)
430432
return tmpdir
431433

432-
433434
def extract_archive(fname, targetdir=None, verbose=False):
434435
"""Extract .zip, .exe (considered to be a zip archive) or .tar.gz archive
435436
to a temporary directory (if targetdir is None).
436437
Return the temporary directory path"""
437-
if targetdir is None:
438-
targetdir = _create_temp_dir()
439-
else:
440-
try:
441-
Path(targetdir).mkdir(parents=True, exist_ok=True)
442-
except:
443-
pass
438+
targetdir = targetdir or create_temp_dir()
439+
Path(targetdir).mkdir(parents=True, exist_ok=True)
444440
if Path(fname).suffix in ('.zip', '.exe'):
445441
obj = zipfile.ZipFile(fname, mode="r")
446442
elif fname.endswith('.tar.gz'):
447443
obj = tarfile.open(fname, mode='r:gz')
448444
else:
449-
raise RuntimeError(
450-
f"Unsupported archive filename {fname}"
451-
)
445+
raise RuntimeError(f"Unsupported archive filename {fname}")
452446
obj.extractall(path=targetdir)
453447
return targetdir
454448

@@ -468,13 +462,11 @@ def extract_archive(fname, targetdir=None, verbose=False):
468462

469463

470464
def get_source_package_infos(fname):
471-
"""Return a tuple (name, version) of the Python source package"""
472-
if fname[-4:] == '.whl':
465+
"""Return a tuple (name, version) of the Python source package."""
466+
if fname.endswith('.whl'):
473467
return Path(fname).name.split("-")[:2]
474468
match = re.match(SOURCE_PATTERN, Path(fname).name)
475-
if match is not None:
476-
return match.groups()[:2]
477-
469+
return match.groups()[:2] if match else None
478470

479471
def buildflit_wininst(
480472
root,
@@ -522,9 +514,8 @@ def buildflit_wininst(
522514
if match is not None:
523515
break
524516
else:
525-
raise RuntimeError(
526-
f"Build failed: not a pure Python package? {distdir}"
527-
)
517+
raise RuntimeError(f"Build failed: not a pure Python package? {distdir}")
518+
528519
src_fname = str(Path(distdir) / distname)
529520
if copy_to is None:
530521
return src_fname
@@ -583,16 +574,9 @@ def direct_pip_install(
583574
return src_fname
584575

585576

586-
def do_script(
587-
this_script,
588-
python_exe=None,
589-
copy_to=None,
590-
verbose=False,
591-
install_options=None,
592-
):
593-
"""Execute a script (get-pip typically)"""
594-
if python_exe is None:
595-
python_exe = sys.executable
577+
def do_script(this_script, python_exe=None, copy_to=None, verbose=False, install_options=None):
578+
"""Execute a script (get-pip typically)."""
579+
python_exe = python_exe or sys.executable
596580
myroot = os.path.dirname(python_exe)
597581

598582
# cmd = [python_exe, myroot + r'\Scripts\pip-script.py', 'install']
@@ -618,49 +602,36 @@ def do_script(
618602
p.stdout.close()
619603
p.stderr.close()
620604
if verbose:
621-
print("Executed " , cmd)
605+
print("Executed ", cmd)
622606
return 'ok'
623607

624608
def columns_width(list_of_lists):
625-
"""return the maximum string length of each column of a list of list"""
626-
if not isinstance(list_of_lists, list):
627-
return [0]
628-
629-
# Transpose the list of lists using zip
630-
transposed_lists = list(zip(*list_of_lists))
631-
# Calculate the maximum width for each column
632-
column_widths = [max(len(str(item)) for item in sublist) for sublist in transposed_lists]
633-
return column_widths
609+
"""Return the maximum string length of each column of a list of lists."""
610+
if not isinstance(list_of_lists, list):
611+
return [0]
612+
return [max(len(str(item)) for item in sublist) for sublist in zip(*list_of_lists)]
634613

635614
def formatted_list(list_of_list, full=False, max_width=70):
636-
"""format a list_of_list to fix length columns"""
637-
columns_size = columns_width(list_of_list)
638-
nb_columns = len(columns_size)
639-
640-
# normalize each columns to columns_size[col] width, in the limit of max_width
641-
642-
zz = [
643-
list(
644-
line[col].ljust(columns_size[col])[:max_width] for col in range(nb_columns)
645-
)
646-
for line in list_of_list
647-
]
648-
return zz
615+
"""Format a list_of_list to fixed length columns."""
616+
columns_size = columns_width(list_of_list)
617+
columns = range(len(columns_size))
618+
return [list(line[col].ljust(columns_size[col])[:max_width] for col in columns) for line in list_of_list]
649619

650620
def normalize(this):
651-
"""apply https://peps.python.org/pep-0503/#normalized-names"""
621+
"""Apply PEP 503 normalization to the string."""
652622
return re.sub(r"[-_.]+", "-", this).lower()
653623

654624
def get_package_metadata(database, name):
655-
"""Extract infos (description, url) from the local database"""
656-
DATA_PATH = str(Path(sys.modules['winpython'].__file__).parent /'data')
625+
"""Extract infos (description, url) from the local database."""
626+
DATA_PATH = str(Path(sys.modules['winpython'].__file__).parent / 'data')
657627
db = cp.ConfigParser()
658628
filepath = Path(database) if Path(database).is_absolute() else Path(DATA_PATH) / database
659-
db.read_file(open(str(filepath), encoding = guess_encoding(filepath)[0]))
660-
my_metadata = dict(
661-
description="",
662-
url="https://pypi.org/project/" + name,
663-
)
629+
db.read_file(open(str(filepath), encoding=guess_encoding(filepath)[0]))
630+
631+
my_metadata = {
632+
"description": "",
633+
"url": f"https://pypi.org/project/{name}",
634+
}
664635
for key in my_metadata:
665636
# wheel replace '-' per '_' in key
666637
for name2 in (name, normalize(name)):
@@ -672,23 +643,11 @@ def get_package_metadata(database, name):
672643

673644
return my_metadata
674645

675-
676646
if __name__ == '__main__':
677-
678647
print_box("Test")
679648
dname = sys.prefix
680649
print((dname + ':', '\n', get_python_infos(dname)))
681-
# dname = r'E:\winpython\sandbox\python-2.7.3'
682-
# print dname+':', '\n', get_python_infos(dname)
683650

684651
tmpdir = r'D:\Tests\winpython_tests'
685-
Path(tmpdir).mkdir(parents=True, exist_ok=True)
686-
print(
687-
(
688-
extract_archive(
689-
str(Path(r'D:\WinP\bd37') / 'packages.win-amd64' /
690-
'python-3.7.3.amd64.zip'),
691-
tmpdir,
692-
)
693-
)
694-
)
652+
Path(tmpdir).mkdir(parents=True, exist_ok=True)
653+
print(extract_archive(str(Path(r'D:\WinP\bd37') / 'packages.win-amd64' / 'python-3.7.3.amd64.zip'), tmpdir))

0 commit comments

Comments
 (0)