blob: d372fe50df3209a69e37c79ca58141c45893683e [file] [log] [blame]
Steve Dower0cd63912018-12-10 18:52:57 -08001"""
2Generates a layout of Python for Windows from a build.
3
4See python make_layout.py --help for usage.
5"""
6
7__author__ = "Steve Dower <steve.dower@python.org>"
8__version__ = "3.8"
9
10import argparse
11import functools
12import os
13import re
14import shutil
15import subprocess
16import sys
17import tempfile
18import zipfile
19
20from pathlib import Path
21
22if __name__ == "__main__":
23 # Started directly, so enable relative imports
24 __path__ = [str(Path(__file__).resolve().parent)]
25
26from .support.appxmanifest import *
27from .support.catalog import *
28from .support.constants import *
29from .support.filesets import *
30from .support.logging import *
31from .support.options import *
32from .support.pip import *
33from .support.props import *
34
35BDIST_WININST_FILES_ONLY = FileNameSet("wininst-*", "bdist_wininst.py")
36BDIST_WININST_STUB = "PC/layout/support/distutils.command.bdist_wininst.py"
37
38TEST_PYDS_ONLY = FileStemSet("xxlimited", "_ctypes_test", "_test*")
39TEST_DIRS_ONLY = FileNameSet("test", "tests")
40
41IDLE_DIRS_ONLY = FileNameSet("idlelib")
42
43TCLTK_PYDS_ONLY = FileStemSet("tcl*", "tk*", "_tkinter")
44TCLTK_DIRS_ONLY = FileNameSet("tkinter", "turtledemo")
45TCLTK_FILES_ONLY = FileNameSet("turtle.py")
46
47VENV_DIRS_ONLY = FileNameSet("venv", "ensurepip")
48
Steve Dower59c2aa22018-12-27 12:44:25 -080049EXCLUDE_FROM_PYDS = FileStemSet("python*", "pyshellext", "vcruntime*")
Steve Dower0cd63912018-12-10 18:52:57 -080050EXCLUDE_FROM_LIB = FileNameSet("*.pyc", "__pycache__", "*.pickle")
51EXCLUDE_FROM_PACKAGED_LIB = FileNameSet("readme.txt")
52EXCLUDE_FROM_COMPILE = FileNameSet("badsyntax_*", "bad_*")
53EXCLUDE_FROM_CATALOG = FileSuffixSet(".exe", ".pyd", ".dll")
54
55REQUIRED_DLLS = FileStemSet("libcrypto*", "libssl*")
56
57LIB2TO3_GRAMMAR_FILES = FileNameSet("Grammar.txt", "PatternGrammar.txt")
58
59PY_FILES = FileSuffixSet(".py")
60PYC_FILES = FileSuffixSet(".pyc")
61CAT_FILES = FileSuffixSet(".cat")
62CDF_FILES = FileSuffixSet(".cdf")
63
64DATA_DIRS = FileNameSet("data")
65
66TOOLS_DIRS = FileNameSet("scripts", "i18n", "pynche", "demo", "parser")
67TOOLS_FILES = FileSuffixSet(".py", ".pyw", ".txt")
68
69
70def get_lib_layout(ns):
71 def _c(f):
72 if f in EXCLUDE_FROM_LIB:
73 return False
74 if f.is_dir():
75 if f in TEST_DIRS_ONLY:
76 return ns.include_tests
77 if f in TCLTK_DIRS_ONLY:
78 return ns.include_tcltk
79 if f in IDLE_DIRS_ONLY:
80 return ns.include_idle
81 if f in VENV_DIRS_ONLY:
82 return ns.include_venv
83 else:
84 if f in TCLTK_FILES_ONLY:
85 return ns.include_tcltk
86 if f in BDIST_WININST_FILES_ONLY:
87 return ns.include_bdist_wininst
88 return True
89
90 for dest, src in rglob(ns.source / "Lib", "**/*", _c):
91 yield dest, src
92
93 if not ns.include_bdist_wininst:
94 src = ns.source / BDIST_WININST_STUB
95 yield Path("distutils/command/bdist_wininst.py"), src
96
97
98def get_tcltk_lib(ns):
99 if not ns.include_tcltk:
100 return
101
102 tcl_lib = os.getenv("TCL_LIBRARY")
103 if not tcl_lib or not os.path.isdir(tcl_lib):
104 try:
105 with open(ns.build / "TCL_LIBRARY.env", "r", encoding="utf-8-sig") as f:
106 tcl_lib = f.read().strip()
107 except FileNotFoundError:
108 pass
109 if not tcl_lib or not os.path.isdir(tcl_lib):
110 warn("Failed to find TCL_LIBRARY")
111 return
112
113 for dest, src in rglob(Path(tcl_lib).parent, "**/*"):
114 yield "tcl/{}".format(dest), src
115
116
117def get_layout(ns):
118 def in_build(f, dest="", new_name=None):
119 n, _, x = f.rpartition(".")
120 n = new_name or n
121 src = ns.build / f
122 if ns.debug and src not in REQUIRED_DLLS:
123 if not src.stem.endswith("_d"):
124 src = src.parent / (src.stem + "_d" + src.suffix)
125 if not n.endswith("_d"):
126 n += "_d"
127 f = n + "." + x
128 yield dest + n + "." + x, src
129 if ns.include_symbols:
130 pdb = src.with_suffix(".pdb")
131 if pdb.is_file():
132 yield dest + n + ".pdb", pdb
133 if ns.include_dev:
134 lib = src.with_suffix(".lib")
135 if lib.is_file():
136 yield "libs/" + n + ".lib", lib
137
138 if ns.include_appxmanifest:
139 yield from in_build("python_uwp.exe", new_name="python")
140 yield from in_build("pythonw_uwp.exe", new_name="pythonw")
141 else:
142 yield from in_build("python.exe", new_name="python")
143 yield from in_build("pythonw.exe", new_name="pythonw")
144
145 yield from in_build(PYTHON_DLL_NAME)
146
147 if ns.include_launchers and ns.include_appxmanifest:
148 if ns.include_pip:
149 yield from in_build("python_uwp.exe", new_name="pip")
150 if ns.include_idle:
151 yield from in_build("pythonw_uwp.exe", new_name="idle")
152
153 if ns.include_stable:
154 yield from in_build(PYTHON_STABLE_DLL_NAME)
155
156 for dest, src in rglob(ns.build, "vcruntime*.dll"):
157 yield dest, src
158
159 for dest, src in rglob(ns.build, ("*.pyd", "*.dll")):
160 if src.stem.endswith("_d") != bool(ns.debug) and src not in REQUIRED_DLLS:
161 continue
162 if src in EXCLUDE_FROM_PYDS:
163 continue
164 if src in TEST_PYDS_ONLY and not ns.include_tests:
165 continue
166 if src in TCLTK_PYDS_ONLY and not ns.include_tcltk:
167 continue
168
169 yield from in_build(src.name, dest="" if ns.flat_dlls else "DLLs/")
170
171 if ns.zip_lib:
172 zip_name = PYTHON_ZIP_NAME
173 yield zip_name, ns.temp / zip_name
174 else:
175 for dest, src in get_lib_layout(ns):
176 yield "Lib/{}".format(dest), src
177
178 if ns.include_venv:
179 yield from in_build("venvlauncher.exe", "Lib/venv/scripts/nt/", "python")
180 yield from in_build("venvwlauncher.exe", "Lib/venv/scripts/nt/", "pythonw")
181
182 if ns.include_tools:
183
184 def _c(d):
185 if d.is_dir():
186 return d in TOOLS_DIRS
187 return d in TOOLS_FILES
188
189 for dest, src in rglob(ns.source / "Tools", "**/*", _c):
190 yield "Tools/{}".format(dest), src
191
192 if ns.include_underpth:
193 yield PYTHON_PTH_NAME, ns.temp / PYTHON_PTH_NAME
194
195 if ns.include_dev:
196
197 def _c(d):
198 if d.is_dir():
199 return d.name != "internal"
200 return True
201
202 for dest, src in rglob(ns.source / "Include", "**/*.h", _c):
203 yield "include/{}".format(dest), src
204 src = ns.source / "PC" / "pyconfig.h"
205 yield "include/pyconfig.h", src
206
207 for dest, src in get_tcltk_lib(ns):
208 yield dest, src
209
210 if ns.include_pip:
211 pip_dir = get_pip_dir(ns)
212 if not pip_dir.is_dir():
213 log_warning("Failed to find {} - pip will not be included", pip_dir)
214 else:
215 pkg_root = "packages/{}" if ns.zip_lib else "Lib/site-packages/{}"
216 for dest, src in rglob(pip_dir, "**/*"):
217 if src in EXCLUDE_FROM_LIB or src in EXCLUDE_FROM_PACKAGED_LIB:
218 continue
219 yield pkg_root.format(dest), src
220
221 if ns.include_chm:
222 for dest, src in rglob(ns.doc_build / "htmlhelp", PYTHON_CHM_NAME):
223 yield "Doc/{}".format(dest), src
224
225 if ns.include_html_doc:
226 for dest, src in rglob(ns.doc_build / "html", "**/*"):
227 yield "Doc/html/{}".format(dest), src
228
229 if ns.include_props:
230 for dest, src in get_props_layout(ns):
231 yield dest, src
232
233 for dest, src in get_appx_layout(ns):
234 yield dest, src
235
236 if ns.include_cat:
237 if ns.flat_dlls:
238 yield ns.include_cat.name, ns.include_cat
239 else:
240 yield "DLLs/{}".format(ns.include_cat.name), ns.include_cat
241
242
Steve Dower872bd2b2019-01-08 02:38:01 -0800243def _compile_one_py(src, dest, name, optimize, checked=True):
Steve Dower0cd63912018-12-10 18:52:57 -0800244 import py_compile
245
246 if dest is not None:
247 dest = str(dest)
248
Steve Dower872bd2b2019-01-08 02:38:01 -0800249 mode = (
250 py_compile.PycInvalidationMode.CHECKED_HASH
251 if checked
252 else py_compile.PycInvalidationMode.UNCHECKED_HASH
253 )
254
Steve Dower0cd63912018-12-10 18:52:57 -0800255 try:
256 return Path(
257 py_compile.compile(
258 str(src),
259 dest,
260 str(name),
261 doraise=True,
262 optimize=optimize,
Steve Dower872bd2b2019-01-08 02:38:01 -0800263 invalidation_mode=mode,
Steve Dower0cd63912018-12-10 18:52:57 -0800264 )
265 )
266 except py_compile.PyCompileError:
267 log_warning("Failed to compile {}", src)
268 return None
269
270
Steve Dower872bd2b2019-01-08 02:38:01 -0800271def _py_temp_compile(src, ns, dest_dir=None, checked=True):
Steve Dower0cd63912018-12-10 18:52:57 -0800272 if not ns.precompile or src not in PY_FILES or src.parent in DATA_DIRS:
273 return None
274
275 dest = (dest_dir or ns.temp) / (src.stem + ".py")
Steve Dower872bd2b2019-01-08 02:38:01 -0800276 return _compile_one_py(src, dest.with_suffix(".pyc"), dest, optimize=2, checked=checked)
Steve Dower0cd63912018-12-10 18:52:57 -0800277
278
Steve Dower872bd2b2019-01-08 02:38:01 -0800279def _write_to_zip(zf, dest, src, ns, checked=True):
280 pyc = _py_temp_compile(src, ns, checked=checked)
Steve Dower0cd63912018-12-10 18:52:57 -0800281 if pyc:
282 try:
283 zf.write(str(pyc), dest.with_suffix(".pyc"))
284 finally:
285 try:
286 pyc.unlink()
287 except:
288 log_exception("Failed to delete {}", pyc)
289 return
290
291 if src in LIB2TO3_GRAMMAR_FILES:
292 from lib2to3.pgen2.driver import load_grammar
293
294 tmp = ns.temp / src.name
295 try:
296 shutil.copy(src, tmp)
297 load_grammar(str(tmp))
298 for f in ns.temp.glob(src.stem + "*.pickle"):
299 zf.write(str(f), str(dest.parent / f.name))
300 try:
301 f.unlink()
302 except:
303 log_exception("Failed to delete {}", f)
304 except:
305 log_exception("Failed to compile {}", src)
306 finally:
307 try:
308 tmp.unlink()
309 except:
310 log_exception("Failed to delete {}", tmp)
311
312 zf.write(str(src), str(dest))
313
314
315def generate_source_files(ns):
316 if ns.zip_lib:
317 zip_name = PYTHON_ZIP_NAME
318 zip_path = ns.temp / zip_name
319 if zip_path.is_file():
320 zip_path.unlink()
321 elif zip_path.is_dir():
322 log_error(
323 "Cannot create zip file because a directory exists by the same name"
324 )
325 return
326 log_info("Generating {} in {}", zip_name, ns.temp)
327 ns.temp.mkdir(parents=True, exist_ok=True)
328 with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
329 for dest, src in get_lib_layout(ns):
Steve Dower872bd2b2019-01-08 02:38:01 -0800330 _write_to_zip(zf, dest, src, ns, checked=False)
Steve Dower0cd63912018-12-10 18:52:57 -0800331
332 if ns.include_underpth:
333 log_info("Generating {} in {}", PYTHON_PTH_NAME, ns.temp)
334 ns.temp.mkdir(parents=True, exist_ok=True)
335 with open(ns.temp / PYTHON_PTH_NAME, "w", encoding="utf-8") as f:
336 if ns.zip_lib:
337 print(PYTHON_ZIP_NAME, file=f)
338 if ns.include_pip:
339 print("packages", file=f)
340 else:
341 print("Lib", file=f)
342 print("Lib/site-packages", file=f)
343 if not ns.flat_dlls:
344 print("DLLs", file=f)
345 print(".", file=f)
346 print(file=f)
347 print("# Uncomment to run site.main() automatically", file=f)
348 print("#import site", file=f)
349
350 if ns.include_appxmanifest:
351 log_info("Generating AppxManifest.xml in {}", ns.temp)
352 ns.temp.mkdir(parents=True, exist_ok=True)
353
354 with open(ns.temp / "AppxManifest.xml", "wb") as f:
355 f.write(get_appxmanifest(ns))
356
357 with open(ns.temp / "_resources.xml", "wb") as f:
358 f.write(get_resources_xml(ns))
359
360 if ns.include_pip:
361 pip_dir = get_pip_dir(ns)
362 if not (pip_dir / "pip").is_dir():
363 log_info("Extracting pip to {}", pip_dir)
364 pip_dir.mkdir(parents=True, exist_ok=True)
365 extract_pip_files(ns)
366
367 if ns.include_props:
368 log_info("Generating {} in {}", PYTHON_PROPS_NAME, ns.temp)
369 ns.temp.mkdir(parents=True, exist_ok=True)
370 with open(ns.temp / PYTHON_PROPS_NAME, "wb") as f:
371 f.write(get_props(ns))
372
373
374def _create_zip_file(ns):
375 if not ns.zip:
376 return None
377
378 if ns.zip.is_file():
379 try:
380 ns.zip.unlink()
381 except OSError:
382 log_exception("Unable to remove {}", ns.zip)
383 sys.exit(8)
384 elif ns.zip.is_dir():
385 log_error("Cannot create ZIP file because {} is a directory", ns.zip)
386 sys.exit(8)
387
388 ns.zip.parent.mkdir(parents=True, exist_ok=True)
389 return zipfile.ZipFile(ns.zip, "w", zipfile.ZIP_DEFLATED)
390
391
392def copy_files(files, ns):
393 if ns.copy:
394 ns.copy.mkdir(parents=True, exist_ok=True)
395
396 try:
397 total = len(files)
398 except TypeError:
399 total = None
400 count = 0
401
402 zip_file = _create_zip_file(ns)
403 try:
404 need_compile = []
405 in_catalog = []
406
407 for dest, src in files:
408 count += 1
409 if count % 10 == 0:
410 if total:
411 log_info("Processed {:>4} of {} files", count, total)
412 else:
413 log_info("Processed {} files", count)
414 log_debug("Processing {!s}", src)
415
416 if (
417 ns.precompile
418 and src in PY_FILES
419 and src not in EXCLUDE_FROM_COMPILE
420 and src.parent not in DATA_DIRS
421 and os.path.normcase(str(dest)).startswith(os.path.normcase("Lib"))
422 ):
423 if ns.copy:
424 need_compile.append((dest, ns.copy / dest))
425 else:
426 (ns.temp / "Lib" / dest).parent.mkdir(parents=True, exist_ok=True)
427 shutil.copy2(src, ns.temp / "Lib" / dest)
428 need_compile.append((dest, ns.temp / "Lib" / dest))
429
430 if src not in EXCLUDE_FROM_CATALOG:
431 in_catalog.append((src.name, src))
432
433 if ns.copy:
434 log_debug("Copy {} -> {}", src, ns.copy / dest)
435 (ns.copy / dest).parent.mkdir(parents=True, exist_ok=True)
436 try:
437 shutil.copy2(src, ns.copy / dest)
438 except shutil.SameFileError:
439 pass
440
441 if ns.zip:
442 log_debug("Zip {} into {}", src, ns.zip)
443 zip_file.write(src, str(dest))
444
445 if need_compile:
446 for dest, src in need_compile:
447 compiled = [
448 _compile_one_py(src, None, dest, optimize=0),
449 _compile_one_py(src, None, dest, optimize=1),
450 _compile_one_py(src, None, dest, optimize=2),
451 ]
452 for c in compiled:
453 if not c:
454 continue
455 cdest = Path(dest).parent / Path(c).relative_to(src.parent)
456 if ns.zip:
457 log_debug("Zip {} into {}", c, ns.zip)
458 zip_file.write(c, str(cdest))
459 in_catalog.append((cdest.name, cdest))
460
461 if ns.catalog:
462 # Just write out the CDF now. Compilation and signing is
463 # an extra step
464 log_info("Generating {}", ns.catalog)
465 ns.catalog.parent.mkdir(parents=True, exist_ok=True)
466 write_catalog(ns.catalog, in_catalog)
467
468 finally:
469 if zip_file:
470 zip_file.close()
471
472
473def main():
474 parser = argparse.ArgumentParser()
475 parser.add_argument("-v", help="Increase verbosity", action="count")
476 parser.add_argument(
477 "-s",
478 "--source",
479 metavar="dir",
480 help="The directory containing the repository root",
481 type=Path,
482 default=None,
483 )
484 parser.add_argument(
485 "-b", "--build", metavar="dir", help="Specify the build directory", type=Path
486 )
487 parser.add_argument(
488 "--doc-build",
489 metavar="dir",
490 help="Specify the docs build directory",
491 type=Path,
492 default=None,
493 )
494 parser.add_argument(
495 "--copy",
496 metavar="directory",
497 help="The name of the directory to copy an extracted layout to",
498 type=Path,
499 default=None,
500 )
501 parser.add_argument(
502 "--zip",
503 metavar="file",
504 help="The ZIP file to write all files to",
505 type=Path,
506 default=None,
507 )
508 parser.add_argument(
509 "--catalog",
510 metavar="file",
511 help="The CDF file to write catalog entries to",
512 type=Path,
513 default=None,
514 )
515 parser.add_argument(
516 "--log",
517 metavar="file",
518 help="Write all operations to the specified file",
519 type=Path,
520 default=None,
521 )
522 parser.add_argument(
523 "-t",
524 "--temp",
525 metavar="file",
526 help="A temporary working directory",
527 type=Path,
528 default=None,
529 )
530 parser.add_argument(
531 "-d", "--debug", help="Include debug build", action="store_true"
532 )
533 parser.add_argument(
534 "-p",
535 "--precompile",
536 help="Include .pyc files instead of .py",
537 action="store_true",
538 )
539 parser.add_argument(
540 "-z", "--zip-lib", help="Include library in a ZIP file", action="store_true"
541 )
542 parser.add_argument(
543 "--flat-dlls", help="Does not create a DLLs directory", action="store_true"
544 )
545 parser.add_argument(
546 "-a",
547 "--include-all",
548 help="Include all optional components",
549 action="store_true",
550 )
551 parser.add_argument(
552 "--include-cat",
553 metavar="file",
554 help="Specify the catalog file to include",
555 type=Path,
556 default=None,
557 )
558 for opt, help in get_argparse_options():
559 parser.add_argument(opt, help=help, action="store_true")
560
561 ns = parser.parse_args()
562 update_presets(ns)
563
564 ns.source = ns.source or (Path(__file__).resolve().parent.parent.parent)
565 ns.build = ns.build or Path(sys.executable).parent
566 ns.temp = ns.temp or Path(tempfile.mkdtemp())
567 ns.doc_build = ns.doc_build or (ns.source / "Doc" / "build")
568 if not ns.source.is_absolute():
569 ns.source = (Path.cwd() / ns.source).resolve()
570 if not ns.build.is_absolute():
571 ns.build = (Path.cwd() / ns.build).resolve()
572 if not ns.temp.is_absolute():
573 ns.temp = (Path.cwd() / ns.temp).resolve()
574 if not ns.doc_build.is_absolute():
575 ns.doc_build = (Path.cwd() / ns.doc_build).resolve()
576 if ns.include_cat and not ns.include_cat.is_absolute():
577 ns.include_cat = (Path.cwd() / ns.include_cat).resolve()
578
579 if ns.copy and not ns.copy.is_absolute():
580 ns.copy = (Path.cwd() / ns.copy).resolve()
581 if ns.zip and not ns.zip.is_absolute():
582 ns.zip = (Path.cwd() / ns.zip).resolve()
583 if ns.catalog and not ns.catalog.is_absolute():
584 ns.catalog = (Path.cwd() / ns.catalog).resolve()
585
586 configure_logger(ns)
587
588 log_info(
589 """OPTIONS
590Source: {ns.source}
591Build: {ns.build}
592Temp: {ns.temp}
593
594Copy to: {ns.copy}
595Zip to: {ns.zip}
596Catalog: {ns.catalog}""",
597 ns=ns,
598 )
599
600 if ns.include_idle and not ns.include_tcltk:
601 log_warning("Assuming --include-tcltk to support --include-idle")
602 ns.include_tcltk = True
603
604 try:
605 generate_source_files(ns)
606 files = list(get_layout(ns))
607 copy_files(files, ns)
608 except KeyboardInterrupt:
609 log_info("Interrupted by Ctrl+C")
610 return 3
611 except SystemExit:
612 raise
613 except:
614 log_exception("Unhandled error")
615
616 if error_was_logged():
617 log_error("Errors occurred.")
618 return 1
619
620
621if __name__ == "__main__":
622 sys.exit(int(main() or 0))