blob: 82d0536ca920b3878c96ab913e5efba2eccbdb9e [file] [log] [blame]
Steve Dower468a15a2018-12-06 21:09:20 -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
49EXCLUDE_FROM_PYDS = FileStemSet("python*", "pyshellext")
50EXCLUDE_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 yield from in_build("python_uwp.exe", new_name="python")
139 yield from in_build("pythonw_uwp.exe", new_name="pythonw")
140
141 yield from in_build(PYTHON_DLL_NAME)
142
143 if ns.include_launchers:
144 if ns.include_pip:
145 yield from in_build("python_uwp.exe", new_name="pip")
146 if ns.include_idle:
147 yield from in_build("pythonw_uwp.exe", new_name="idle")
148
149 if ns.include_stable:
150 yield from in_build(PYTHON_STABLE_DLL_NAME)
151
152 for dest, src in rglob(ns.build, "vcruntime*.dll"):
153 yield dest, src
154
155 for dest, src in rglob(ns.build, ("*.pyd", "*.dll")):
156 if src.stem.endswith("_d") != bool(ns.debug) and src not in REQUIRED_DLLS:
157 continue
158 if src in EXCLUDE_FROM_PYDS:
159 continue
160 if src in TEST_PYDS_ONLY and not ns.include_tests:
161 continue
162 if src in TCLTK_PYDS_ONLY and not ns.include_tcltk:
163 continue
164
165 yield from in_build(src.name, dest="" if ns.flat_dlls else "DLLs/")
166
167 if ns.zip_lib:
168 zip_name = PYTHON_ZIP_NAME
169 yield zip_name, ns.temp / zip_name
170 else:
171 for dest, src in get_lib_layout(ns):
172 yield "Lib/{}".format(dest), src
173
174 if ns.include_venv:
175 yield from in_build("venvlauncher.exe", "Lib/venv/scripts/nt/", "python")
176 yield from in_build("venvwlauncher.exe", "Lib/venv/scripts/nt/", "pythonw")
177
178 if ns.include_tools:
179
180 def _c(d):
181 if d.is_dir():
182 return d in TOOLS_DIRS
183 return d in TOOLS_FILES
184
185 for dest, src in rglob(ns.source / "Tools", "**/*", _c):
186 yield "Tools/{}".format(dest), src
187
188 if ns.include_underpth:
189 yield PYTHON_PTH_NAME, ns.temp / PYTHON_PTH_NAME
190
191 if ns.include_dev:
192
193 def _c(d):
194 if d.is_dir():
195 return d.name != "internal"
196 return True
197
198 for dest, src in rglob(ns.source / "Include", "**/*.h", _c):
199 yield "include/{}".format(dest), src
200 src = ns.source / "PC" / "pyconfig.h"
201 yield "include/pyconfig.h", src
202
203 for dest, src in get_tcltk_lib(ns):
204 yield dest, src
205
206 if ns.include_pip:
207 pip_dir = get_pip_dir(ns)
208 if not pip_dir.is_dir():
209 log_warning("Failed to find {} - pip will not be included", pip_dir)
210 else:
211 pkg_root = "packages/{}" if ns.zip_lib else "Lib/site-packages/{}"
212 for dest, src in rglob(pip_dir, "**/*"):
213 if src in EXCLUDE_FROM_LIB or src in EXCLUDE_FROM_PACKAGED_LIB:
214 continue
215 yield pkg_root.format(dest), src
216
217 if ns.include_chm:
218 for dest, src in rglob(ns.doc_build / "htmlhelp", PYTHON_CHM_NAME):
219 yield "Doc/{}".format(dest), src
220
221 if ns.include_html_doc:
222 for dest, src in rglob(ns.doc_build / "html", "**/*"):
223 yield "Doc/html/{}".format(dest), src
224
225 if ns.include_props:
226 for dest, src in get_props_layout(ns):
227 yield dest, src
228
229 for dest, src in get_appx_layout(ns):
230 yield dest, src
231
232 if ns.include_cat:
233 if ns.flat_dlls:
234 yield ns.include_cat.name, ns.include_cat
235 else:
236 yield "DLLs/{}".format(ns.include_cat.name), ns.include_cat
237
238
239def _compile_one_py(src, dest, name, optimize):
240 import py_compile
241
242 if dest is not None:
243 dest = str(dest)
244
245 try:
246 return Path(
247 py_compile.compile(
248 str(src),
249 dest,
250 str(name),
251 doraise=True,
252 optimize=optimize,
253 invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH,
254 )
255 )
256 except py_compile.PyCompileError:
257 log_warning("Failed to compile {}", src)
258 return None
259
260
261def _py_temp_compile(src, ns, dest_dir=None):
262 if not ns.precompile or src not in PY_FILES or src.parent in DATA_DIRS:
263 return None
264
265 dest = (dest_dir or ns.temp) / (src.stem + ".py")
266 return _compile_one_py(src, dest.with_suffix(".pyc"), dest, optimize=2)
267
268
269def _write_to_zip(zf, dest, src, ns):
270 pyc = _py_temp_compile(src, ns)
271 if pyc:
272 try:
273 zf.write(str(pyc), dest.with_suffix(".pyc"))
274 finally:
275 try:
276 pyc.unlink()
277 except:
278 log_exception("Failed to delete {}", pyc)
279 return
280
281 if src in LIB2TO3_GRAMMAR_FILES:
282 from lib2to3.pgen2.driver import load_grammar
283
284 tmp = ns.temp / src.name
285 try:
286 shutil.copy(src, tmp)
287 load_grammar(str(tmp))
288 for f in ns.temp.glob(src.stem + "*.pickle"):
289 zf.write(str(f), str(dest.parent / f.name))
290 try:
291 f.unlink()
292 except:
293 log_exception("Failed to delete {}", f)
294 except:
295 log_exception("Failed to compile {}", src)
296 finally:
297 try:
298 tmp.unlink()
299 except:
300 log_exception("Failed to delete {}", tmp)
301
302 zf.write(str(src), str(dest))
303
304
305def generate_source_files(ns):
306 if ns.zip_lib:
307 zip_name = PYTHON_ZIP_NAME
308 zip_path = ns.temp / zip_name
309 if zip_path.is_file():
310 zip_path.unlink()
311 elif zip_path.is_dir():
312 log_error(
313 "Cannot create zip file because a directory exists by the same name"
314 )
315 return
316 log_info("Generating {} in {}", zip_name, ns.temp)
317 ns.temp.mkdir(parents=True, exist_ok=True)
318 with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
319 for dest, src in get_lib_layout(ns):
320 _write_to_zip(zf, dest, src, ns)
321
322 if ns.include_underpth:
323 log_info("Generating {} in {}", PYTHON_PTH_NAME, ns.temp)
324 ns.temp.mkdir(parents=True, exist_ok=True)
325 with open(ns.temp / PYTHON_PTH_NAME, "w", encoding="utf-8") as f:
326 if ns.zip_lib:
327 print(PYTHON_ZIP_NAME, file=f)
328 if ns.include_pip:
329 print("packages", file=f)
330 else:
331 print("Lib", file=f)
332 print("Lib/site-packages", file=f)
333 if not ns.flat_dlls:
334 print("DLLs", file=f)
335 print(".", file=f)
336 print(file=f)
337 print("# Uncomment to run site.main() automatically", file=f)
338 print("#import site", file=f)
339
340 if ns.include_appxmanifest:
341 log_info("Generating AppxManifest.xml in {}", ns.temp)
342 ns.temp.mkdir(parents=True, exist_ok=True)
343
344 with open(ns.temp / "AppxManifest.xml", "wb") as f:
345 f.write(get_appxmanifest(ns))
346
347 with open(ns.temp / "_resources.xml", "wb") as f:
348 f.write(get_resources_xml(ns))
349
350 if ns.include_pip:
351 pip_dir = get_pip_dir(ns)
352 if not (pip_dir / "pip").is_dir():
353 log_info("Extracting pip to {}", pip_dir)
354 pip_dir.mkdir(parents=True, exist_ok=True)
355 extract_pip_files(ns)
356
357 if ns.include_props:
358 log_info("Generating {} in {}", PYTHON_PROPS_NAME, ns.temp)
359 ns.temp.mkdir(parents=True, exist_ok=True)
360 with open(ns.temp / PYTHON_PROPS_NAME, "wb") as f:
361 f.write(get_props(ns))
362
363
364def _create_zip_file(ns):
365 if not ns.zip:
366 return None
367
368 if ns.zip.is_file():
369 try:
370 ns.zip.unlink()
371 except OSError:
372 log_exception("Unable to remove {}", ns.zip)
373 sys.exit(8)
374 elif ns.zip.is_dir():
375 log_error("Cannot create ZIP file because {} is a directory", ns.zip)
376 sys.exit(8)
377
378 ns.zip.parent.mkdir(parents=True, exist_ok=True)
379 return zipfile.ZipFile(ns.zip, "w", zipfile.ZIP_DEFLATED)
380
381
382def copy_files(files, ns):
383 if ns.copy:
384 ns.copy.mkdir(parents=True, exist_ok=True)
385
386 try:
387 total = len(files)
388 except TypeError:
389 total = None
390 count = 0
391
392 zip_file = _create_zip_file(ns)
393 try:
394 need_compile = []
395 in_catalog = []
396
397 for dest, src in files:
398 count += 1
399 if count % 10 == 0:
400 if total:
401 log_info("Processed {:>4} of {} files", count, total)
402 else:
403 log_info("Processed {} files", count)
404 log_debug("Processing {!s}", src)
405
406 if (
407 ns.precompile
408 and src in PY_FILES
409 and src not in EXCLUDE_FROM_COMPILE
410 and src.parent not in DATA_DIRS
411 and os.path.normcase(str(dest)).startswith(os.path.normcase("Lib"))
412 ):
413 if ns.copy:
414 need_compile.append((dest, ns.copy / dest))
415 else:
416 (ns.temp / "Lib" / dest).parent.mkdir(parents=True, exist_ok=True)
417 shutil.copy2(src, ns.temp / "Lib" / dest)
418 need_compile.append((dest, ns.temp / "Lib" / dest))
419
420 if src not in EXCLUDE_FROM_CATALOG:
421 in_catalog.append((src.name, src))
422
423 if ns.copy:
424 log_debug("Copy {} -> {}", src, ns.copy / dest)
425 (ns.copy / dest).parent.mkdir(parents=True, exist_ok=True)
426 try:
427 shutil.copy2(src, ns.copy / dest)
428 except shutil.SameFileError:
429 pass
430
431 if ns.zip:
432 log_debug("Zip {} into {}", src, ns.zip)
433 zip_file.write(src, str(dest))
434
435 if need_compile:
436 for dest, src in need_compile:
437 compiled = [
438 _compile_one_py(src, None, dest, optimize=0),
439 _compile_one_py(src, None, dest, optimize=1),
440 _compile_one_py(src, None, dest, optimize=2),
441 ]
442 for c in compiled:
443 if not c:
444 continue
445 cdest = Path(dest).parent / Path(c).relative_to(src.parent)
446 if ns.zip:
447 log_debug("Zip {} into {}", c, ns.zip)
448 zip_file.write(c, str(cdest))
449 in_catalog.append((cdest.name, cdest))
450
451 if ns.catalog:
452 # Just write out the CDF now. Compilation and signing is
453 # an extra step
454 log_info("Generating {}", ns.catalog)
455 ns.catalog.parent.mkdir(parents=True, exist_ok=True)
456 write_catalog(ns.catalog, in_catalog)
457
458 finally:
459 if zip_file:
460 zip_file.close()
461
462
463def main():
464 parser = argparse.ArgumentParser()
465 parser.add_argument("-v", help="Increase verbosity", action="count")
466 parser.add_argument(
467 "-s",
468 "--source",
469 metavar="dir",
470 help="The directory containing the repository root",
471 type=Path,
472 default=None,
473 )
474 parser.add_argument(
475 "-b", "--build", metavar="dir", help="Specify the build directory", type=Path
476 )
477 parser.add_argument(
478 "--doc-build",
479 metavar="dir",
480 help="Specify the docs build directory",
481 type=Path,
482 default=None,
483 )
484 parser.add_argument(
485 "--copy",
486 metavar="directory",
487 help="The name of the directory to copy an extracted layout to",
488 type=Path,
489 default=None,
490 )
491 parser.add_argument(
492 "--zip",
493 metavar="file",
494 help="The ZIP file to write all files to",
495 type=Path,
496 default=None,
497 )
498 parser.add_argument(
499 "--catalog",
500 metavar="file",
501 help="The CDF file to write catalog entries to",
502 type=Path,
503 default=None,
504 )
505 parser.add_argument(
506 "--log",
507 metavar="file",
508 help="Write all operations to the specified file",
509 type=Path,
510 default=None,
511 )
512 parser.add_argument(
513 "-t",
514 "--temp",
515 metavar="file",
516 help="A temporary working directory",
517 type=Path,
518 default=None,
519 )
520 parser.add_argument(
521 "-d", "--debug", help="Include debug build", action="store_true"
522 )
523 parser.add_argument(
524 "-p",
525 "--precompile",
526 help="Include .pyc files instead of .py",
527 action="store_true",
528 )
529 parser.add_argument(
530 "-z", "--zip-lib", help="Include library in a ZIP file", action="store_true"
531 )
532 parser.add_argument(
533 "--flat-dlls", help="Does not create a DLLs directory", action="store_true"
534 )
535 parser.add_argument(
536 "-a",
537 "--include-all",
538 help="Include all optional components",
539 action="store_true",
540 )
541 parser.add_argument(
542 "--include-cat",
543 metavar="file",
544 help="Specify the catalog file to include",
545 type=Path,
546 default=None,
547 )
548 for opt, help in get_argparse_options():
549 parser.add_argument(opt, help=help, action="store_true")
550
551 ns = parser.parse_args()
552 update_presets(ns)
553
554 ns.source = ns.source or (Path(__file__).resolve().parent.parent.parent)
555 ns.build = ns.build or Path(sys.executable).parent
556 ns.temp = ns.temp or Path(tempfile.mkdtemp())
557 ns.doc_build = ns.doc_build or (ns.source / "Doc" / "build")
558 if not ns.source.is_absolute():
559 ns.source = (Path.cwd() / ns.source).resolve()
560 if not ns.build.is_absolute():
561 ns.build = (Path.cwd() / ns.build).resolve()
562 if not ns.temp.is_absolute():
563 ns.temp = (Path.cwd() / ns.temp).resolve()
564 if not ns.doc_build.is_absolute():
565 ns.doc_build = (Path.cwd() / ns.doc_build).resolve()
566 if ns.include_cat and not ns.include_cat.is_absolute():
567 ns.include_cat = (Path.cwd() / ns.include_cat).resolve()
568
569 if ns.copy and not ns.copy.is_absolute():
570 ns.copy = (Path.cwd() / ns.copy).resolve()
571 if ns.zip and not ns.zip.is_absolute():
572 ns.zip = (Path.cwd() / ns.zip).resolve()
573 if ns.catalog and not ns.catalog.is_absolute():
574 ns.catalog = (Path.cwd() / ns.catalog).resolve()
575
576 configure_logger(ns)
577
578 log_info(
579 """OPTIONS
580Source: {ns.source}
581Build: {ns.build}
582Temp: {ns.temp}
583
584Copy to: {ns.copy}
585Zip to: {ns.zip}
586Catalog: {ns.catalog}""",
587 ns=ns,
588 )
589
590 if ns.include_idle and not ns.include_tcltk:
591 log_warning("Assuming --include-tcltk to support --include-idle")
592 ns.include_tcltk = True
593
594 try:
595 generate_source_files(ns)
596 files = list(get_layout(ns))
597 copy_files(files, ns)
598 except KeyboardInterrupt:
599 log_info("Interrupted by Ctrl+C")
600 return 3
601 except SystemExit:
602 raise
603 except:
604 log_exception("Unhandled error")
605
606 if error_was_logged():
607 log_error("Errors occurred.")
608 return 1
609
610
611if __name__ == "__main__":
612 sys.exit(int(main() or 0))