blob: 8dbe83e4f443053cffda0de1d870906428d9a8a2 [file] [log] [blame]
Steve Dowerf70fdd22015-04-14 18:34:04 -04001import argparse
Steve Dower08b18172015-08-04 16:02:40 -07002import py_compile
Steve Dowerf70fdd22015-04-14 18:34:04 -04003import re
4import sys
5import shutil
Steve Dowerae69de62015-09-09 19:32:45 -07006import stat
Steve Dowerf70fdd22015-04-14 18:34:04 -04007import os
8import tempfile
9
Steve Dowerf0888cd2016-11-23 10:23:47 -080010from itertools import chain
Steve Dowerf70fdd22015-04-14 18:34:04 -040011from pathlib import Path
12from zipfile import ZipFile, ZIP_DEFLATED
13import subprocess
14
15TKTCL_RE = re.compile(r'^(_?tk|tcl).+\.(pyd|dll)', re.IGNORECASE)
Steve Dower33128c82016-06-27 09:34:18 -070016DEBUG_RE = re.compile(r'_d\.(pyd|dll|exe|pdb|lib)$', re.IGNORECASE)
Steve Dowerf70fdd22015-04-14 18:34:04 -040017PYTHON_DLL_RE = re.compile(r'python\d\d?\.dll$', re.IGNORECASE)
18
Steve Dower33128c82016-06-27 09:34:18 -070019DEBUG_FILES = {
20 '_ctypes_test',
21 '_testbuffer',
22 '_testcapi',
Steve Dower4782ab32016-10-29 09:23:39 -070023 '_testconsole',
Steve Dower33128c82016-06-27 09:34:18 -070024 '_testimportmultiple',
25 '_testmultiphase',
26 'xxlimited',
27 'python3_dstub',
28}
29
Steve Dower2495faf2015-09-22 15:03:54 -070030EXCLUDE_FROM_LIBRARY = {
31 '__pycache__',
32 'ensurepip',
33 'idlelib',
34 'pydoc_data',
35 'site-packages',
36 'tkinter',
37 'turtledemo',
Steve Dower10cabcb2016-01-16 13:44:43 -080038 'venv',
Steve Dower2495faf2015-09-22 15:03:54 -070039}
40
41EXCLUDE_FILE_FROM_LIBRARY = {
42 'bdist_wininst.py',
43}
44
Steve Dower33128c82016-06-27 09:34:18 -070045EXCLUDE_FILE_FROM_LIBS = {
Steve Dower2a943012016-11-23 11:42:35 -080046 'liblzma',
Steve Dower33128c82016-06-27 09:34:18 -070047 'ssleay',
48 'libeay',
49 'python3stub',
50}
51
Steve Dower4db86bc2016-09-09 09:17:35 -070052EXCLUDED_FILES = {
53 'pyshellext',
54}
55
Steve Dowerf70fdd22015-04-14 18:34:04 -040056def is_not_debug(p):
Steve Dower6b4c63d2015-05-02 15:32:14 -070057 if DEBUG_RE.search(p.name):
58 return False
59
60 if TKTCL_RE.search(p.name):
61 return False
62
Steve Dower4db86bc2016-09-09 09:17:35 -070063 return p.stem.lower() not in DEBUG_FILES and p.stem.lower() not in EXCLUDED_FILES
Steve Dowerf70fdd22015-04-14 18:34:04 -040064
65def is_not_debug_or_python(p):
66 return is_not_debug(p) and not PYTHON_DLL_RE.search(p.name)
67
68def include_in_lib(p):
69 name = p.name.lower()
70 if p.is_dir():
Steve Dower2495faf2015-09-22 15:03:54 -070071 if name in EXCLUDE_FROM_LIBRARY:
Steve Dowerf70fdd22015-04-14 18:34:04 -040072 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040073 if name == 'test' and p.parts[-2].lower() == 'lib':
74 return False
Steve Dower2495faf2015-09-22 15:03:54 -070075 if name in {'test', 'tests'} and p.parts[-3].lower() == 'lib':
76 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040077 return True
78
Steve Dower2495faf2015-09-22 15:03:54 -070079 if name in EXCLUDE_FILE_FROM_LIBRARY:
80 return False
81
Steve Dower777af302015-04-19 19:50:35 -070082 suffix = p.suffix.lower()
Steve Dower2495faf2015-09-22 15:03:54 -070083 return suffix not in {'.pyc', '.pyo', '.exe'}
Steve Dowerf70fdd22015-04-14 18:34:04 -040084
Steve Dower33128c82016-06-27 09:34:18 -070085def include_in_libs(p):
86 if not is_not_debug(p):
87 return False
88
89 return p.stem.lower() not in EXCLUDE_FILE_FROM_LIBS
90
Steve Dowerf70fdd22015-04-14 18:34:04 -040091def include_in_tools(p):
92 if p.is_dir() and p.name.lower() in {'scripts', 'i18n', 'pynche', 'demo', 'parser'}:
93 return True
94
95 return p.suffix.lower() in {'.py', '.pyw', '.txt'}
96
Steve Dowered51b262016-09-17 12:54:06 -070097BASE_NAME = 'python{0.major}{0.minor}'.format(sys.version_info)
98
Steve Dowerf70fdd22015-04-14 18:34:04 -040099FULL_LAYOUT = [
Steve Dower41fca9d2016-09-12 13:29:58 -0700100 ('/', 'PCBuild/$arch', 'python.exe', is_not_debug),
101 ('/', 'PCBuild/$arch', 'pythonw.exe', is_not_debug),
Steve Dowered51b262016-09-17 12:54:06 -0700102 ('/', 'PCBuild/$arch', 'python{}.dll'.format(sys.version_info.major), is_not_debug),
103 ('/', 'PCBuild/$arch', '{}.dll'.format(BASE_NAME), is_not_debug),
Steve Dower41fca9d2016-09-12 13:29:58 -0700104 ('DLLs/', 'PCBuild/$arch', '*.pyd', is_not_debug),
105 ('DLLs/', 'PCBuild/$arch', '*.dll', is_not_debug_or_python),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400106 ('include/', 'include', '*.h', None),
107 ('include/', 'PC', 'pyconfig.h', None),
108 ('Lib/', 'Lib', '**/*', include_in_lib),
Steve Dower41fca9d2016-09-12 13:29:58 -0700109 ('libs/', 'PCBuild/$arch', '*.lib', include_in_libs),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400110 ('Tools/', 'Tools', '**/*', include_in_tools),
111]
112
Steve Dowerf70fdd22015-04-14 18:34:04 -0400113EMBED_LAYOUT = [
Steve Dower41fca9d2016-09-12 13:29:58 -0700114 ('/', 'PCBuild/$arch', 'python*.exe', is_not_debug),
115 ('/', 'PCBuild/$arch', '*.pyd', is_not_debug),
116 ('/', 'PCBuild/$arch', '*.dll', is_not_debug),
Steve Dowered51b262016-09-17 12:54:06 -0700117 ('{}.zip'.format(BASE_NAME), 'Lib', '**/*', include_in_lib),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400118]
119
Steve Dowerfcbe1df2015-09-08 21:39:01 -0700120if os.getenv('DOC_FILENAME'):
121 FULL_LAYOUT.append(('Doc/', 'Doc/build/htmlhelp', os.getenv('DOC_FILENAME'), None))
122if os.getenv('VCREDIST_PATH'):
123 FULL_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
124 EMBED_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
125
Steve Dower8c1cee92015-05-02 21:38:26 -0700126def copy_to_layout(target, rel_sources):
Steve Dowerf70fdd22015-04-14 18:34:04 -0400127 count = 0
128
129 if target.suffix.lower() == '.zip':
130 if target.exists():
131 target.unlink()
132
133 with ZipFile(str(target), 'w', ZIP_DEFLATED) as f:
Steve Dower315b7482015-08-05 11:34:50 -0700134 with tempfile.TemporaryDirectory() as tmpdir:
135 for s, rel in rel_sources:
136 if rel.suffix.lower() == '.py':
137 pyc = Path(tmpdir) / rel.with_suffix('.pyc').name
138 try:
139 py_compile.compile(str(s), str(pyc), str(rel), doraise=True, optimize=2)
140 except py_compile.PyCompileError:
141 f.write(str(s), str(rel))
142 else:
143 f.write(str(pyc), str(rel.with_suffix('.pyc')))
Steve Dower08b18172015-08-04 16:02:40 -0700144 else:
Steve Dower315b7482015-08-05 11:34:50 -0700145 f.write(str(s), str(rel))
146 count += 1
Steve Dowerf70fdd22015-04-14 18:34:04 -0400147
148 else:
149 for s, rel in rel_sources:
Steve Dowerae69de62015-09-09 19:32:45 -0700150 dest = target / rel
Steve Dowerf70fdd22015-04-14 18:34:04 -0400151 try:
Steve Dowerae69de62015-09-09 19:32:45 -0700152 dest.parent.mkdir(parents=True)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400153 except FileExistsError:
154 pass
Steve Dowerae69de62015-09-09 19:32:45 -0700155 if dest.is_file():
156 dest.chmod(stat.S_IWRITE)
157 shutil.copy(str(s), str(dest))
158 if dest.is_file():
159 dest.chmod(stat.S_IWRITE)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400160 count += 1
161
162 return count
163
164def rglob(root, pattern, condition):
165 dirs = [root]
166 recurse = pattern[:3] in {'**/', '**\\'}
167 while dirs:
168 d = dirs.pop(0)
169 for f in d.glob(pattern[3:] if recurse else pattern):
170 if recurse and f.is_dir() and (not condition or condition(f)):
171 dirs.append(f)
172 elif f.is_file() and (not condition or condition(f)):
173 yield f, f.relative_to(root)
174
175def main():
176 parser = argparse.ArgumentParser()
177 parser.add_argument('-s', '--source', metavar='dir', help='The directory containing the repository root', type=Path)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700178 parser.add_argument('-o', '--out', metavar='file', help='The name of the output archive', type=Path, default=None)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400179 parser.add_argument('-t', '--temp', metavar='dir', help='A directory to temporarily extract files into', type=Path, default=None)
180 parser.add_argument('-e', '--embed', help='Create an embedding layout', action='store_true', default=False)
Steve Dower41fca9d2016-09-12 13:29:58 -0700181 parser.add_argument('-a', '--arch', help='Specify the architecture to use (win32/amd64)', type=str, default="win32")
Steve Dowerf70fdd22015-04-14 18:34:04 -0400182 ns = parser.parse_args()
183
Steve Dower33f73102016-06-24 10:32:15 -0700184 source = ns.source or (Path(__file__).resolve().parent.parent.parent)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400185 out = ns.out
Steve Dower41fca9d2016-09-12 13:29:58 -0700186 arch = ns.arch
Steve Dowerf70fdd22015-04-14 18:34:04 -0400187 assert isinstance(source, Path)
Steve Dower33f73102016-06-24 10:32:15 -0700188 assert not out or isinstance(out, Path)
Steve Dower41fca9d2016-09-12 13:29:58 -0700189 assert isinstance(arch, str)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400190
191 if ns.temp:
192 temp = ns.temp
193 delete_temp = False
194 else:
195 temp = Path(tempfile.mkdtemp())
196 delete_temp = True
197
Steve Dower33f73102016-06-24 10:32:15 -0700198 if out:
199 try:
200 out.parent.mkdir(parents=True)
201 except FileExistsError:
202 pass
Steve Dowerf70fdd22015-04-14 18:34:04 -0400203 try:
204 temp.mkdir(parents=True)
205 except FileExistsError:
206 pass
207
208 layout = EMBED_LAYOUT if ns.embed else FULL_LAYOUT
209
210 try:
211 for t, s, p, c in layout:
Steve Dower2a943012016-11-23 11:42:35 -0800212 fs = source / s.replace("$arch", arch)
Steve Dowerf0888cd2016-11-23 10:23:47 -0800213 files = rglob(fs, p, c)
214 extra_files = []
215 if s == 'Lib' and p == '**/*':
216 extra_files.append((
Steve Dowere711cc02016-12-11 14:35:07 -0800217 source / 'tools' / 'msi' / 'distutils.command.bdist_wininst.py',
218 Path('distutils') / 'command' / 'bdist_wininst.py'
Steve Dowerf0888cd2016-11-23 10:23:47 -0800219 ))
220 copied = copy_to_layout(temp / t.rstrip('/'), chain(files, extra_files))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400221 print('Copied {} files'.format(copied))
222
Steve Dower41fca9d2016-09-12 13:29:58 -0700223 if ns.embed:
Steve Dowered51b262016-09-17 12:54:06 -0700224 with open(str(temp / (BASE_NAME + '._pth')), 'w') as f:
225 print(BASE_NAME + '.zip', file=f)
Steve Dower41fca9d2016-09-12 13:29:58 -0700226 print('.', file=f)
Steve Dowered51b262016-09-17 12:54:06 -0700227 print('', file=f)
228 print('# Uncomment to run site.main() automatically', file=f)
229 print('#import site', file=f)
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700230
Steve Dower33f73102016-06-24 10:32:15 -0700231 if out:
232 total = copy_to_layout(out, rglob(temp, '**/*', None))
233 print('Wrote {} files to {}'.format(total, out))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400234 finally:
235 if delete_temp:
236 shutil.rmtree(temp, True)
237
238
239if __name__ == "__main__":
240 sys.exit(int(main() or 0))