Skip to content

Commit d378232

Browse files
authored
Merge pull request #1544 from stonebig/master
handpicked suggestions from Mistral AI
2 parents 4841716 + 26d3f24 commit d378232

File tree

3 files changed

+57
-82
lines changed

3 files changed

+57
-82
lines changed

make.py

Lines changed: 28 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,13 @@ def build_installer_7zip(script_template_path: Path, output_script_path: Path, r
4646
("PORTABLE_DIR=", f"PORTABLE_DIR={PORTABLE_DIRECTORY}& rem "),
4747
("SEVENZIP_EXE=", f"SEVENZIP_EXE={find_7zip_executable()}& rem "),
4848
] + [(f"{a}=", f"{a}={b}& rem ") for a, b in replacements]
49-
49+
5050
utils.replace_in_file(script_template_path, data_to_replace, output_script_path)
5151

5252
try:
5353
# Execute the generated 7-Zip script, with stdout=sys.stderr to see 7zip compressing
54-
command = f'"{output_script_path}"'
55-
print(f"Executing 7-Zip script: {command}")
56-
subprocess.run(command, shell=True, check=True, stderr=sys.stderr, stdout=sys.stderr)
54+
print(f'Executing 7-Zip script: "{output_script_path}"')
55+
subprocess.run(f'"{output_script_path}"', shell=True, check=True, stderr=sys.stderr, stdout=sys.stderr)
5756
except subprocess.CalledProcessError as e:
5857
print(f"Error executing 7-Zip script: {e}", file=sys.stderr)
5958

@@ -76,11 +75,9 @@ def copy_items(source_directories: list[Path], target_directory: Path, verbose:
7675

7776
def parse_list_argument(argument_value: str | list[str], separator=" ") -> list[str]:
7877
"""Parse a separated list argument into a list of strings."""
79-
if argument_value is None:
78+
if not argument_value:
8079
return []
81-
if isinstance(argument_value, str):
82-
return argument_value.split(separator)
83-
return list(argument_value)
80+
return argument_value.split(separator) if isinstance(argument_value, str) else list(argument_value)
8481

8582
class WinPythonDistributionBuilder:
8683
"""Builds a WinPython distribution."""
@@ -163,20 +160,17 @@ def _get_installed_tools_markdown(self) -> str:
163160

164161
def get_tool_path(relative_path):
165162
path = self.winpython_directory / relative_path if self.winpython_directory else None
166-
return path if path and (path.is_file() or path.is_dir()) else None
163+
return path if path and path.exists() else None
167164

168165
if nodejs_path := get_tool_path(self.NODEJS_RELATIVE_PATH):
169-
node_version = utils.get_nodejs_version(nodejs_path)
170-
npm_version = utils.get_npmjs_version(nodejs_path)
171-
installed_tools += [("Nodejs", node_version), ("npmjs", npm_version)]
166+
installed_tools.append(("Nodejs", utils.get_nodejs_version(nodejs_path)))
167+
installed_tools.append(("npmjs", utils.get_npmjs_version(nodejs_path)))
172168

173-
if pandoc_executable := get_tool_path("t/pandoc.exe"):
174-
pandoc_version = utils.get_pandoc_version(str(pandoc_executable.parent))
175-
installed_tools.append(("Pandoc", pandoc_version))
169+
if pandoc_exe := get_tool_path("t/pandoc.exe"):
170+
installed_tools.append(("Pandoc", utils.get_pandoc_version(str(pandoc_exe.parent))))
176171

177-
if vscode_executable := get_tool_path("t/VSCode/Code.exe"):
178-
vscode_version = utils.getFileProperties(str(vscode_executable))["FileVersion"]
179-
installed_tools.append(("VSCode", vscode_version))
172+
if vscode_exe := get_tool_path("t/VSCode/Code.exe"):
173+
installed_tools.append(("VSCode", utils.getFileProperties(str(vscode_exe))["FileVersion"]))
180174

181175
tool_lines = []
182176
for name, version in installed_tools:
@@ -187,7 +181,7 @@ def get_tool_path(relative_path):
187181

188182
def _get_installed_packages_markdown(self) -> str:
189183
"""Generates Markdown for installed packages section in package index."""
190-
if self.distribution is None:
184+
if not self.distribution:
191185
return "" # Distribution not initialized yet.
192186
self.installed_packages = self.distribution.get_installed_packages(update=True)
193187
package_lines = [
@@ -204,25 +198,20 @@ def winpython_version_name(self) -> str:
204198
@property
205199
def python_full_version(self) -> str:
206200
"""Retrieves the Python full version string from the distribution."""
207-
if self.distribution is None:
208-
return "0.0.0" # Placeholder before initialization
209-
return utils.get_python_long_version(self.distribution.target)
201+
return utils.get_python_long_version(self.distribution.target) if self.distribution else "0.0.0"
210202

211203
@property
212204
def python_executable_directory(self) -> str:
213205
"""Returns the directory containing the Python executable."""
214-
python_path_directory = self.winpython_directory / self.python_directory_name if self.winpython_directory else None
215-
if python_path_directory and python_path_directory.is_dir():
216-
return str(python_path_directory)
217-
python_path_executable = self.winpython_directory / self.python_name if self.winpython_directory else None
218-
return str(python_path_executable) if python_path_executable else ""
206+
if self.winpython_directory:
207+
python_path_directory = self.winpython_directory / self.python_directory_name
208+
return str(python_path_directory) if python_path_directory.is_dir() else str(self.winpython_directory / self.python_name)
209+
return ""
219210

220211
@property
221212
def architecture_bits(self) -> int:
222213
"""Returns the architecture (32 or 64 bits) of the distribution."""
223-
if self.distribution:
224-
return self.distribution.architecture
225-
return 64
214+
return self.distribution.architecture if self.distribution else 64
226215

227216
def create_installer_7zip(self, installer_type: str = ".exe"):
228217
"""Creates a WinPython installer using 7-Zip: ".exe", ".7z", ".zip")"""
@@ -241,7 +230,6 @@ def create_installer_7zip(self, installer_type: str = ".exe"):
241230
("RELEASELEVEL", self.release_level),
242231
("INSTALLER_OPTION", installer_type),
243232
]
244-
245233
build_installer_7zip(PORTABLE_DIRECTORY / template_name, self.target_directory / output_name, replacements)
246234

247235
def _print_action(self, text: str):
@@ -351,9 +339,9 @@ def build(self, rebuild: bool = True, requirements_files_list=None, winpy_dirnam
351339

352340
def rebuild_winpython_package(source_directory: Path, target_directory: Path, architecture: int = 64, verbose: bool = False):
353341
"""Rebuilds the winpython package from source using flit."""
354-
for filename in os.listdir(target_directory):
355-
if filename.startswith("winpython-") and filename.endswith((".exe", ".whl", ".gz")):
356-
os.remove(Path(target_directory) / filename)
342+
for file in target_directory.glob("winpython-*"):
343+
if file.suffix in (".exe", ".whl", ".gz"):
344+
file.unlink()
357345
utils.buildflit_wininst(source_directory, copy_to=target_directory, verbose=verbose)
358346

359347
def make_all(build_number: int, release_level: str, pyver: str, architecture: int, basedir: Path,
@@ -391,14 +379,14 @@ def make_all(build_number: int, release_level: str, pyver: str, architecture: in
391379
find_links_dirs_list = parse_list_argument(find_links, ",")
392380
requirements_files_list = [Path(f) for f in parse_list_argument(requirements, ",") if f]
393381
find_links_options = [f"--find-links={link}" for link in find_links_dirs_list + [source_dirs]]
394-
build_directory = str(Path(basedir) / ("bu" + flavor))
382+
build_directory = Path(basedir) / ("bu" + flavor)
395383

396384
if rebuild:
397385
utils.print_box(f"Making WinPython {architecture}bits at {Path(basedir) / ('bu' + flavor)}")
398-
os.makedirs(Path(build_directory), exist_ok=True)
386+
os.makedirs(build_directory, exist_ok=True)
399387
# use source_dirs as the directory to re-build Winpython wheel
400388
winpython_source_dir = Path(__file__).resolve().parent
401-
rebuild_winpython_package(winpython_source_dir, source_dirs, architecture, verbose)
389+
rebuild_winpython_package(winpython_source_dir, Path(source_dirs), architecture, verbose)
402390

403391
builder = WinPythonDistributionBuilder(
404392
build_number, release_level, build_directory, wheels_directory=source_dirs,
@@ -420,11 +408,11 @@ def make_all(build_number: int, release_level: str, pyver: str, architecture: in
420408

421409
builder.build(rebuild=rebuild, requirements_files_list=requirements_files_list, winpy_dirname=winpython_dirname)
422410

423-
if ".zip" in str(create_installer).lower():
411+
if ".zip" in create_installer.lower():
424412
builder.create_installer_7zip(".zip")
425-
if ".7z" in str(create_installer).lower():
413+
if ".7z" in create_installer.lower():
426414
builder.create_installer_7zip(".7z")
427-
if "7zip" in str(create_installer).lower():
415+
if "7zip" in create_installer.lower():
428416
builder.create_installer_7zip(".exe")
429417

430418
if __name__ == "__main__":

winpython/utils.py

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,6 @@ def patch_shebang_line(fname, pad=b" ", to_movable=True, targetdir=""):
213213
"""Remove absolute path to python.exe in shebang lines in binary files, or re-add it."""
214214
target_dir = targetdir if to_movable else os.path.abspath(os.path.join(os.path.dirname(fname), r"..")) + "\\"
215215
executable = sys.executable
216-
217216
shebang_line = re.compile(rb"""(#!.*pythonw?\.exe)"?""") # Python3+
218217
if "pypy3" in sys.executable:
219218
shebang_line = re.compile(rb"""(#!.*pypy3w?\.exe)"?""") # Pypy3+
@@ -239,12 +238,9 @@ def patch_shebang_line(fname, pad=b" ", to_movable=True, targetdir=""):
239238
def patch_shebang_line_py(fname, to_movable=True, targetdir=""):
240239
"""Changes shebang line in '.py' file to relative or absolue path"""
241240
import fileinput
242-
if to_movable:
243-
exec_path = r'#!.\python.exe'
244-
if 'pypy3' in sys.executable: # PyPy !
245-
exec_path = r'#!.\pypy3.exe'
246-
else:
247-
exec_path = '#!' + sys.executable
241+
exec_path = r'#!.\python.exe' if to_movable else '#!' + sys.executable
242+
if 'pypy3' in sys.executable:
243+
exec_path = r'#!.\pypy3.exe' if to_movable else exec_path
248244
for line in fileinput.input(fname, inplace=True):
249245
if re.match(r'^#\!.*python\.exe$', line) or re.match(r'^#\!.*pypy3\.exe$', line):
250246
print(exec_path)
@@ -253,18 +249,16 @@ def patch_shebang_line_py(fname, to_movable=True, targetdir=""):
253249

254250
def guess_encoding(csv_file):
255251
"""guess the encoding of the given file"""
256-
# UTF_8_BOM = "\xEF\xBB\xBF"
257252
with open(csv_file, "rb") as f:
258253
data = f.read(5)
259254
if data.startswith(b"\xEF\xBB\xBF"): # UTF-8 with a "BOM" (normally no BOM in utf-8)
260255
return ["utf-8-sig"]
261-
else: # in Windows, guessing utf-8 doesn't work, so we have to try
262-
try:
263-
with open(csv_file, encoding="utf-8") as f:
264-
preview = f.read(222222)
265-
return ["utf-8"]
266-
except:
267-
return [locale.getdefaultlocale()[1], "utf-8"]
256+
try:
257+
with open(csv_file, encoding="utf-8") as f:
258+
preview = f.read(222222)
259+
return ["utf-8"]
260+
except:
261+
return [locale.getdefaultlocale()[1], "utf-8"]
268262

269263
def replace_in_file(filepath: Path, replacements: list[tuple[str, str]], filedest: Path = None, verbose=False):
270264
"""
@@ -290,9 +284,9 @@ def replace_in_file(filepath: Path, replacements: list[tuple[str, str]], filedes
290284
def patch_sourcefile(fname, in_text, out_text, silent_mode=False):
291285
"""Replace a string in a source file."""
292286
if not silent_mode:
293-
print(f"patching {fname} from {in_text} to {out_text}")
294-
if Path(fname).is_file() and not in_text == out_text:
295-
replace_in_file(Path(fname), [(in_text , out_text)])
287+
print(f"patching {fname} from {in_text} to {out_text}")
288+
if Path(fname).is_file() and in_text != out_text:
289+
replace_in_file(Path(fname), [(in_text, out_text)])
296290

297291
def _create_temp_dir():
298292
"""Create a temporary directory and remove it at exit"""
@@ -324,7 +318,7 @@ def get_source_package_infos(fname):
324318
def buildflit_wininst(root, python_exe=None, copy_to=None, verbose=False):
325319
"""Build Wheel from Python package located in *root* with flit."""
326320
python_exe = python_exe or sys.executable
327-
cmd = [python_exe, '-m' ,'flit', 'build']
321+
cmd = [python_exe, '-m', 'flit', 'build']
328322
if verbose:
329323
subprocess.call(cmd, cwd=root)
330324
else:
@@ -362,7 +356,7 @@ def direct_pip_install(fname, python_exe=None, verbose=False, install_options=No
362356
python_exe = python_exe or sys.executable
363357
myroot = str(Path(python_exe).parent)
364358

365-
cmd = [python_exe, "-m", "pip", "install"] + (install_options or []) +[fname]
359+
cmd = [python_exe, "-m", "pip", "install"] + (install_options or []) + [fname]
366360
if not verbose:
367361
process = subprocess.Popen(cmd, cwd=myroot, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
368362
stdout, stderr = process.communicate()
@@ -416,7 +410,7 @@ def get_package_metadata(database, name):
416410
db = cp.ConfigParser()
417411
filepath = Path(database) if Path(database).is_absolute() else Path(DATA_PATH) / database
418412
db.read_file(open(str(filepath), encoding=guess_encoding(filepath)[0]))
419-
413+
420414
my_metadata = {
421415
"description": "",
422416
"url": f"https://pypi.org/project/{name}",

winpython/wppm.py

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -144,12 +144,12 @@ def patch_standard_packages(self, package_name="", to_movable=True):
144144
import filecmp
145145

146146
# 'pywin32' minimal post-install (pywin32_postinstall.py do too much)
147-
if package_name.lower() == "pywin32" or package_name == "":
147+
if package_name.lower() in ("", "pywin32"):
148148
origin = Path(self.target) / "site-packages" / "pywin32_system32"
149149
destin = Path(self.target)
150150
if origin.is_dir():
151151
for name in os.listdir(origin):
152-
here, there = (origin / name), (destin / name)
152+
here, there = origin / name, destin / name
153153
if not there.exists() or not filecmp.cmp(here, there):
154154
shutil.copyfile(here, there)
155155
# 'pip' to do movable launchers (around line 100) !!!!
@@ -162,7 +162,7 @@ def patch_standard_packages(self, package_name="", to_movable=True):
162162
sheb_mov1 = " executable = os.path.join(os.path.basename(get_executable()))"
163163
sheb_mov2 = " executable = os.path.join('..',os.path.basename(get_executable()))"
164164

165-
the_place = Path(self.target ) / "lib" / "site-packages" / "pip" / "_vendor" / "distlib" / "scripts.py"
165+
the_place = Path(self.target) / "lib" / "site-packages" / "pip" / "_vendor" / "distlib" / "scripts.py"
166166
print(the_place)
167167
if to_movable:
168168
utils.patch_sourcefile(the_place, sheb_fix, sheb_mov1)
@@ -173,7 +173,7 @@ def patch_standard_packages(self, package_name="", to_movable=True):
173173

174174
# create movable launchers for previous package installations
175175
self.patch_all_shebang(to_movable=to_movable)
176-
if package_name.lower() == "spyder" or package_name == "":
176+
if package_name.lower() in ("", "spyder"):
177177
# spyder don't goes on internet without I ask
178178
utils.patch_sourcefile(
179179
Path(self.target) / "lib" / "site-packages" / "spyder" / "config" /"main.py",
@@ -202,14 +202,13 @@ def handle_specific_packages(self, package):
202202
"%WINPYDIR%\python.exe" "%WINPYDIR%\Lib\site-packages\package.name\uic\pyuic.py" %1 %2 %3 %4 %5 %6 %7 %8 %9"""
203203
# PyPy adaption: python.exe or pypy3.exe
204204
my_exec = Path(utils.get_python_executable(self.target)).name
205-
tmp_string = tmp_string.replace("python.exe", my_exec)
206-
self.create_file(package, f"pyuic{package.name[-1]}.bat", "Scripts", tmp_string.replace("package.name", package.name))
205+
tmp_string = tmp_string.replace("python.exe", my_exec).replace("package.name", package.name)
206+
self.create_file(package, f"pyuic{package.name[-1]}.bat", "Scripts", tmp_string)
207207
# Adding missing __init__.py files (fixes Issue 8)
208208
uic_path = str(Path("Lib") / "site-packages" / package.name / "uic")
209209
for dirname in ("Loader", "port_v2", "port_v3"):
210210
self.create_file(package, "__init__.py", str(Path(uic_path) / dirname), "")
211211

212-
213212
def _print(self, package: Package, action: str):
214213
"""Print package-related action text."""
215214
text = f"{action} {package.name} {package.version}"
@@ -232,7 +231,6 @@ def uninstall(self, package):
232231
subprocess.call([this_exec, "-m", "pip", "uninstall", package.name, "-y"], cwd=self.target)
233232
self._print_done()
234233

235-
236234
def install_bdist_direct(self, package, install_options=None):
237235
"""Install a package directly !"""
238236
self._print(package,f"Installing {package.fname.split('.')[-1]}")
@@ -250,22 +248,17 @@ def install_bdist_direct(self, package, install_options=None):
250248
package = Package(fname)
251249
self._print_done()
252250

253-
254251
def main(test=False):
255252
if test:
256-
sbdir = str(Path(__file__).parents[0].parent.parent.parent / "sandbox")
257-
tmpdir = str(Path(sbdir) / "tobedeleted")
258-
259-
fname = str(Path(sbdir) / "VTK-5.10.0-Qt-4.7.4.win32-py2.7.exe")
260-
print(Package(fname))
253+
sbdir = Path(__file__).parents[0].parent.parent.parent / "sandbox"
254+
tmpdir = sbdir / "tobedeleted"
255+
fname = sbdir / "VTK-5.10.0-Qt-4.7.4.win32-py2.7.exe")
256+
print(Package(str(fname)))
261257
sys.exit()
262-
target = str(
263-
Path(utils.BASE_DIR) / "build" / "winpython-2.7.3" / "python-2.7.3"
264-
)
265-
fname = str(Path(utils.BASE_DIR) / "packages.src" / "docutils-0.9.1.tar.gz")
266-
267-
dist = Distribution(target, verbose=True)
268-
pack = Package(fname)
258+
target = Path(utils.BASE_DIR) / "build" / "winpython-2.7.3" / "python-2.7.3"
259+
fname = Path(utils.BASE_DIR) / "packages.src" / "docutils-0.9.1.tar.gz"
260+
dist = Distribution(str(target), verbose=True)
261+
pack = Package(str(fname))
269262
print(pack.description)
270263
# dist.install(pack)
271264
# dist.uninstall(pack)

0 commit comments

Comments
 (0)