blob: 710e4a5c23ee289b12e415f6687131499b7f9134 [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__',
Steve Dower2495faf2015-09-22 15:03:54 -070032 'idlelib',
33 'pydoc_data',
34 'site-packages',
35 'tkinter',
36 'turtledemo',
Steve Dower52884772017-02-06 14:11:34 -080037}
38
39EXCLUDE_FROM_EMBEDDABLE_LIBRARY = {
40 'ensurepip',
Steve Dower10cabcb2016-01-16 13:44:43 -080041 'venv',
Steve Dower2495faf2015-09-22 15:03:54 -070042}
43
44EXCLUDE_FILE_FROM_LIBRARY = {
45 'bdist_wininst.py',
46}
47
Steve Dower33128c82016-06-27 09:34:18 -070048EXCLUDE_FILE_FROM_LIBS = {
Steve Dower2a943012016-11-23 11:42:35 -080049 'liblzma',
Steve Dower33128c82016-06-27 09:34:18 -070050 'ssleay',
51 'libeay',
52 'python3stub',
53}
54
Steve Dower4db86bc2016-09-09 09:17:35 -070055EXCLUDED_FILES = {
56 'pyshellext',
57}
58
Steve Dowerf70fdd22015-04-14 18:34:04 -040059def is_not_debug(p):
Steve Dower6b4c63d2015-05-02 15:32:14 -070060 if DEBUG_RE.search(p.name):
61 return False
62
63 if TKTCL_RE.search(p.name):
64 return False
65
Steve Dower4db86bc2016-09-09 09:17:35 -070066 return p.stem.lower() not in DEBUG_FILES and p.stem.lower() not in EXCLUDED_FILES
Steve Dowerf70fdd22015-04-14 18:34:04 -040067
68def is_not_debug_or_python(p):
69 return is_not_debug(p) and not PYTHON_DLL_RE.search(p.name)
70
71def include_in_lib(p):
72 name = p.name.lower()
73 if p.is_dir():
Steve Dower2495faf2015-09-22 15:03:54 -070074 if name in EXCLUDE_FROM_LIBRARY:
Steve Dowerf70fdd22015-04-14 18:34:04 -040075 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040076 if name == 'test' and p.parts[-2].lower() == 'lib':
77 return False
Steve Dower2495faf2015-09-22 15:03:54 -070078 if name in {'test', 'tests'} and p.parts[-3].lower() == 'lib':
79 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040080 return True
81
Steve Dower2495faf2015-09-22 15:03:54 -070082 if name in EXCLUDE_FILE_FROM_LIBRARY:
83 return False
84
Steve Dower777af302015-04-19 19:50:35 -070085 suffix = p.suffix.lower()
Steve Dower2495faf2015-09-22 15:03:54 -070086 return suffix not in {'.pyc', '.pyo', '.exe'}
Steve Dowerf70fdd22015-04-14 18:34:04 -040087
Steve Dower52884772017-02-06 14:11:34 -080088def include_in_embeddable_lib(p):
89 if p.is_dir() and p.name.lower() in EXCLUDE_FROM_EMBEDDABLE_LIBRARY:
90 return False
91
92 return include_in_lib(p)
93
Steve Dower33128c82016-06-27 09:34:18 -070094def include_in_libs(p):
95 if not is_not_debug(p):
96 return False
97
98 return p.stem.lower() not in EXCLUDE_FILE_FROM_LIBS
99
Steve Dowerf70fdd22015-04-14 18:34:04 -0400100def include_in_tools(p):
101 if p.is_dir() and p.name.lower() in {'scripts', 'i18n', 'pynche', 'demo', 'parser'}:
102 return True
103
104 return p.suffix.lower() in {'.py', '.pyw', '.txt'}
105
Steve Dowered51b262016-09-17 12:54:06 -0700106BASE_NAME = 'python{0.major}{0.minor}'.format(sys.version_info)
107
Steve Dowerf70fdd22015-04-14 18:34:04 -0400108FULL_LAYOUT = [
Steve Dower41fca9d2016-09-12 13:29:58 -0700109 ('/', 'PCBuild/$arch', 'python.exe', is_not_debug),
110 ('/', 'PCBuild/$arch', 'pythonw.exe', is_not_debug),
Steve Dowered51b262016-09-17 12:54:06 -0700111 ('/', 'PCBuild/$arch', 'python{}.dll'.format(sys.version_info.major), is_not_debug),
112 ('/', 'PCBuild/$arch', '{}.dll'.format(BASE_NAME), is_not_debug),
Steve Dower41fca9d2016-09-12 13:29:58 -0700113 ('DLLs/', 'PCBuild/$arch', '*.pyd', is_not_debug),
114 ('DLLs/', 'PCBuild/$arch', '*.dll', is_not_debug_or_python),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400115 ('include/', 'include', '*.h', None),
116 ('include/', 'PC', 'pyconfig.h', None),
117 ('Lib/', 'Lib', '**/*', include_in_lib),
Steve Dower41fca9d2016-09-12 13:29:58 -0700118 ('libs/', 'PCBuild/$arch', '*.lib', include_in_libs),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400119 ('Tools/', 'Tools', '**/*', include_in_tools),
120]
121
Steve Dowerf70fdd22015-04-14 18:34:04 -0400122EMBED_LAYOUT = [
Steve Dower41fca9d2016-09-12 13:29:58 -0700123 ('/', 'PCBuild/$arch', 'python*.exe', is_not_debug),
124 ('/', 'PCBuild/$arch', '*.pyd', is_not_debug),
125 ('/', 'PCBuild/$arch', '*.dll', is_not_debug),
Steve Dowerf007b492017-02-06 14:12:19 -0800126 ('{}.zip'.format(BASE_NAME), 'Lib', '**/*', include_in_embeddable_lib),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400127]
128
Steve Dowerfcbe1df2015-09-08 21:39:01 -0700129if os.getenv('DOC_FILENAME'):
130 FULL_LAYOUT.append(('Doc/', 'Doc/build/htmlhelp', os.getenv('DOC_FILENAME'), None))
131if os.getenv('VCREDIST_PATH'):
132 FULL_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
133 EMBED_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
134
Steve Dower8c1cee92015-05-02 21:38:26 -0700135def copy_to_layout(target, rel_sources):
Steve Dowerf70fdd22015-04-14 18:34:04 -0400136 count = 0
137
138 if target.suffix.lower() == '.zip':
139 if target.exists():
140 target.unlink()
141
142 with ZipFile(str(target), 'w', ZIP_DEFLATED) as f:
Steve Dower315b7482015-08-05 11:34:50 -0700143 with tempfile.TemporaryDirectory() as tmpdir:
144 for s, rel in rel_sources:
145 if rel.suffix.lower() == '.py':
146 pyc = Path(tmpdir) / rel.with_suffix('.pyc').name
147 try:
148 py_compile.compile(str(s), str(pyc), str(rel), doraise=True, optimize=2)
149 except py_compile.PyCompileError:
150 f.write(str(s), str(rel))
151 else:
152 f.write(str(pyc), str(rel.with_suffix('.pyc')))
Steve Dower08b18172015-08-04 16:02:40 -0700153 else:
Steve Dower315b7482015-08-05 11:34:50 -0700154 f.write(str(s), str(rel))
155 count += 1
Steve Dowerf70fdd22015-04-14 18:34:04 -0400156
157 else:
158 for s, rel in rel_sources:
Steve Dowerae69de62015-09-09 19:32:45 -0700159 dest = target / rel
Steve Dowerf70fdd22015-04-14 18:34:04 -0400160 try:
Steve Dowerae69de62015-09-09 19:32:45 -0700161 dest.parent.mkdir(parents=True)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400162 except FileExistsError:
163 pass
Steve Dowerae69de62015-09-09 19:32:45 -0700164 if dest.is_file():
165 dest.chmod(stat.S_IWRITE)
166 shutil.copy(str(s), str(dest))
167 if dest.is_file():
168 dest.chmod(stat.S_IWRITE)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400169 count += 1
170
171 return count
172
173def rglob(root, pattern, condition):
174 dirs = [root]
175 recurse = pattern[:3] in {'**/', '**\\'}
176 while dirs:
177 d = dirs.pop(0)
178 for f in d.glob(pattern[3:] if recurse else pattern):
179 if recurse and f.is_dir() and (not condition or condition(f)):
180 dirs.append(f)
181 elif f.is_file() and (not condition or condition(f)):
182 yield f, f.relative_to(root)
183
184def main():
185 parser = argparse.ArgumentParser()
186 parser.add_argument('-s', '--source', metavar='dir', help='The directory containing the repository root', type=Path)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700187 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 -0400188 parser.add_argument('-t', '--temp', metavar='dir', help='A directory to temporarily extract files into', type=Path, default=None)
189 parser.add_argument('-e', '--embed', help='Create an embedding layout', action='store_true', default=False)
Steve Dower41fca9d2016-09-12 13:29:58 -0700190 parser.add_argument('-a', '--arch', help='Specify the architecture to use (win32/amd64)', type=str, default="win32")
Steve Dowerf70fdd22015-04-14 18:34:04 -0400191 ns = parser.parse_args()
192
Steve Dower33f73102016-06-24 10:32:15 -0700193 source = ns.source or (Path(__file__).resolve().parent.parent.parent)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400194 out = ns.out
Steve Dower41fca9d2016-09-12 13:29:58 -0700195 arch = ns.arch
Steve Dowerf70fdd22015-04-14 18:34:04 -0400196 assert isinstance(source, Path)
Steve Dower33f73102016-06-24 10:32:15 -0700197 assert not out or isinstance(out, Path)
Steve Dower41fca9d2016-09-12 13:29:58 -0700198 assert isinstance(arch, str)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400199
200 if ns.temp:
201 temp = ns.temp
202 delete_temp = False
203 else:
204 temp = Path(tempfile.mkdtemp())
205 delete_temp = True
206
Steve Dower33f73102016-06-24 10:32:15 -0700207 if out:
208 try:
209 out.parent.mkdir(parents=True)
210 except FileExistsError:
211 pass
Steve Dowerf70fdd22015-04-14 18:34:04 -0400212 try:
213 temp.mkdir(parents=True)
214 except FileExistsError:
215 pass
216
217 layout = EMBED_LAYOUT if ns.embed else FULL_LAYOUT
218
219 try:
220 for t, s, p, c in layout:
Steve Dower2a943012016-11-23 11:42:35 -0800221 fs = source / s.replace("$arch", arch)
Steve Dowerf0888cd2016-11-23 10:23:47 -0800222 files = rglob(fs, p, c)
223 extra_files = []
224 if s == 'Lib' and p == '**/*':
225 extra_files.append((
Steve Dowere711cc02016-12-11 14:35:07 -0800226 source / 'tools' / 'msi' / 'distutils.command.bdist_wininst.py',
227 Path('distutils') / 'command' / 'bdist_wininst.py'
Steve Dowerf0888cd2016-11-23 10:23:47 -0800228 ))
229 copied = copy_to_layout(temp / t.rstrip('/'), chain(files, extra_files))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400230 print('Copied {} files'.format(copied))
231
Steve Dower41fca9d2016-09-12 13:29:58 -0700232 if ns.embed:
Steve Dowered51b262016-09-17 12:54:06 -0700233 with open(str(temp / (BASE_NAME + '._pth')), 'w') as f:
234 print(BASE_NAME + '.zip', file=f)
Steve Dower41fca9d2016-09-12 13:29:58 -0700235 print('.', file=f)
Steve Dowered51b262016-09-17 12:54:06 -0700236 print('', file=f)
237 print('# Uncomment to run site.main() automatically', file=f)
238 print('#import site', file=f)
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700239
Steve Dower33f73102016-06-24 10:32:15 -0700240 if out:
241 total = copy_to_layout(out, rglob(temp, '**/*', None))
242 print('Wrote {} files to {}'.format(total, out))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400243 finally:
244 if delete_temp:
245 shutil.rmtree(temp, True)
246
247
248if __name__ == "__main__":
249 sys.exit(int(main() or 0))