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