blob: 9db96cb27169471c18306fcf01cbd047eb6dc7ac [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',
23 '_testimportmultiple',
24 '_testmultiphase',
25 'xxlimited',
26 'python3_dstub',
27}
28
Steve Dower2495faf2015-09-22 15:03:54 -070029EXCLUDE_FROM_LIBRARY = {
30 '__pycache__',
31 'ensurepip',
32 'idlelib',
33 'pydoc_data',
34 'site-packages',
35 'tkinter',
36 'turtledemo',
Steve Dower10cabcb2016-01-16 13:44:43 -080037 'venv',
Steve Dower2495faf2015-09-22 15:03:54 -070038}
39
40EXCLUDE_FILE_FROM_LIBRARY = {
41 'bdist_wininst.py',
42}
43
Steve Dower33128c82016-06-27 09:34:18 -070044EXCLUDE_FILE_FROM_LIBS = {
45 'ssleay',
46 'libeay',
47 'python3stub',
48}
49
Steve Dowerf70fdd22015-04-14 18:34:04 -040050def is_not_debug(p):
Steve Dower6b4c63d2015-05-02 15:32:14 -070051 if DEBUG_RE.search(p.name):
52 return False
53
54 if TKTCL_RE.search(p.name):
55 return False
56
Steve Dower33128c82016-06-27 09:34:18 -070057 return p.stem.lower() not in DEBUG_FILES
Steve Dowerf70fdd22015-04-14 18:34:04 -040058
59def is_not_debug_or_python(p):
60 return is_not_debug(p) and not PYTHON_DLL_RE.search(p.name)
61
62def include_in_lib(p):
63 name = p.name.lower()
64 if p.is_dir():
Steve Dower2495faf2015-09-22 15:03:54 -070065 if name in EXCLUDE_FROM_LIBRARY:
Steve Dowerf70fdd22015-04-14 18:34:04 -040066 return False
67 if name.startswith('plat-'):
68 return False
69 if name == 'test' and p.parts[-2].lower() == 'lib':
70 return False
Steve Dower2495faf2015-09-22 15:03:54 -070071 if name in {'test', 'tests'} and p.parts[-3].lower() == 'lib':
72 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040073 return True
74
Steve Dower2495faf2015-09-22 15:03:54 -070075 if name in EXCLUDE_FILE_FROM_LIBRARY:
76 return False
77
Steve Dower777af302015-04-19 19:50:35 -070078 suffix = p.suffix.lower()
Steve Dower2495faf2015-09-22 15:03:54 -070079 return suffix not in {'.pyc', '.pyo', '.exe'}
Steve Dowerf70fdd22015-04-14 18:34:04 -040080
Steve Dower33128c82016-06-27 09:34:18 -070081def include_in_libs(p):
82 if not is_not_debug(p):
83 return False
84
85 return p.stem.lower() not in EXCLUDE_FILE_FROM_LIBS
86
Steve Dowerf70fdd22015-04-14 18:34:04 -040087def include_in_tools(p):
88 if p.is_dir() and p.name.lower() in {'scripts', 'i18n', 'pynche', 'demo', 'parser'}:
89 return True
90
91 return p.suffix.lower() in {'.py', '.pyw', '.txt'}
92
93FULL_LAYOUT = [
Steve Dower6fd76bc2016-07-16 16:13:19 -070094 ('/', '$build', 'python.exe', is_not_debug),
95 ('/', '$build', 'pythonw.exe', is_not_debug),
96 ('/', '$build', 'python{0.major}.dll'.format(sys.version_info), is_not_debug),
97 ('/', '$build', 'python{0.major}{0.minor}.dll'.format(sys.version_info), is_not_debug),
98 ('DLLs/', '$build', '*.pyd', is_not_debug),
99 ('DLLs/', '$build', '*.dll', is_not_debug_or_python),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400100 ('include/', 'include', '*.h', None),
101 ('include/', 'PC', 'pyconfig.h', None),
102 ('Lib/', 'Lib', '**/*', include_in_lib),
Steve Dower6fd76bc2016-07-16 16:13:19 -0700103 ('libs/', '$build', '*.lib', include_in_libs),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400104 ('Tools/', 'Tools', '**/*', include_in_tools),
105]
106
Steve Dowerf70fdd22015-04-14 18:34:04 -0400107EMBED_LAYOUT = [
Steve Dower6fd76bc2016-07-16 16:13:19 -0700108 ('/', '$build', 'python*.exe', is_not_debug),
109 ('/', '$build', '*.pyd', is_not_debug),
110 ('/', '$build', '*.dll', is_not_debug),
Steve Dowerd8bf09c2016-05-19 10:47:47 -0700111 ('python{0.major}{0.minor}.zip'.format(sys.version_info), 'Lib', '**/*', include_in_lib),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400112]
113
Steve Dowerfcbe1df2015-09-08 21:39:01 -0700114if os.getenv('DOC_FILENAME'):
115 FULL_LAYOUT.append(('Doc/', 'Doc/build/htmlhelp', os.getenv('DOC_FILENAME'), None))
116if os.getenv('VCREDIST_PATH'):
117 FULL_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
118 EMBED_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
119
Steve Dower8c1cee92015-05-02 21:38:26 -0700120def copy_to_layout(target, rel_sources):
Steve Dowerf70fdd22015-04-14 18:34:04 -0400121 count = 0
122
123 if target.suffix.lower() == '.zip':
124 if target.exists():
125 target.unlink()
126
127 with ZipFile(str(target), 'w', ZIP_DEFLATED) as f:
Steve Dower315b7482015-08-05 11:34:50 -0700128 with tempfile.TemporaryDirectory() as tmpdir:
129 for s, rel in rel_sources:
130 if rel.suffix.lower() == '.py':
131 pyc = Path(tmpdir) / rel.with_suffix('.pyc').name
132 try:
133 py_compile.compile(str(s), str(pyc), str(rel), doraise=True, optimize=2)
134 except py_compile.PyCompileError:
135 f.write(str(s), str(rel))
136 else:
137 f.write(str(pyc), str(rel.with_suffix('.pyc')))
Steve Dower08b18172015-08-04 16:02:40 -0700138 else:
Steve Dower315b7482015-08-05 11:34:50 -0700139 f.write(str(s), str(rel))
140 count += 1
Steve Dowerf70fdd22015-04-14 18:34:04 -0400141
142 else:
143 for s, rel in rel_sources:
Steve Dowerae69de62015-09-09 19:32:45 -0700144 dest = target / rel
Steve Dowerf70fdd22015-04-14 18:34:04 -0400145 try:
Steve Dowerae69de62015-09-09 19:32:45 -0700146 dest.parent.mkdir(parents=True)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400147 except FileExistsError:
148 pass
Steve Dowerae69de62015-09-09 19:32:45 -0700149 if dest.is_file():
150 dest.chmod(stat.S_IWRITE)
151 shutil.copy(str(s), str(dest))
152 if dest.is_file():
153 dest.chmod(stat.S_IWRITE)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400154 count += 1
155
156 return count
157
158def rglob(root, pattern, condition):
159 dirs = [root]
160 recurse = pattern[:3] in {'**/', '**\\'}
161 while dirs:
162 d = dirs.pop(0)
163 for f in d.glob(pattern[3:] if recurse else pattern):
164 if recurse and f.is_dir() and (not condition or condition(f)):
165 dirs.append(f)
166 elif f.is_file() and (not condition or condition(f)):
167 yield f, f.relative_to(root)
168
169def main():
170 parser = argparse.ArgumentParser()
171 parser.add_argument('-s', '--source', metavar='dir', help='The directory containing the repository root', type=Path)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700172 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 -0400173 parser.add_argument('-t', '--temp', metavar='dir', help='A directory to temporarily extract files into', type=Path, default=None)
174 parser.add_argument('-e', '--embed', help='Create an embedding layout', action='store_true', default=False)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700175 parser.add_argument('-b', '--build', help='Specify the build directory', type=Path)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400176 ns = parser.parse_args()
177
Steve Dower33f73102016-06-24 10:32:15 -0700178 source = ns.source or (Path(__file__).resolve().parent.parent.parent)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400179 out = ns.out
Steve Dower6fd76bc2016-07-16 16:13:19 -0700180 build = ns.build
Steve Dowerf70fdd22015-04-14 18:34:04 -0400181 assert isinstance(source, Path)
Steve Dower33f73102016-06-24 10:32:15 -0700182 assert not out or isinstance(out, Path)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700183 assert isinstance(build, Path)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400184
185 if ns.temp:
186 temp = ns.temp
187 delete_temp = False
188 else:
189 temp = Path(tempfile.mkdtemp())
190 delete_temp = True
191
Steve Dower33f73102016-06-24 10:32:15 -0700192 if out:
193 try:
194 out.parent.mkdir(parents=True)
195 except FileExistsError:
196 pass
Steve Dowerf70fdd22015-04-14 18:34:04 -0400197 try:
198 temp.mkdir(parents=True)
199 except FileExistsError:
200 pass
201
202 layout = EMBED_LAYOUT if ns.embed else FULL_LAYOUT
203
204 try:
205 for t, s, p, c in layout:
Steve Dower6fd76bc2016-07-16 16:13:19 -0700206 if s == '$build':
Steve Dowerf0888cd2016-11-23 10:23:47 -0800207 fs = build
Steve Dower6fd76bc2016-07-16 16:13:19 -0700208 else:
Steve Dowerf0888cd2016-11-23 10:23:47 -0800209 fs = source / s
210 files = rglob(fs, p, c)
211 extra_files = []
212 if s == 'Lib' and p == '**/*':
213 extra_files.append((
Steve Dowere711cc02016-12-11 14:35:07 -0800214 source / 'tools' / 'msi' / 'distutils.command.bdist_wininst.py',
215 Path('distutils') / 'command' / 'bdist_wininst.py'
Steve Dowerf0888cd2016-11-23 10:23:47 -0800216 ))
217 copied = copy_to_layout(temp / t.rstrip('/'), chain(files, extra_files))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400218 print('Copied {} files'.format(copied))
219
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700220 with open(str(temp / 'pyvenv.cfg'), 'w') as f:
221 print('applocal = true', file=f)
222
Steve Dower33f73102016-06-24 10:32:15 -0700223 if out:
224 total = copy_to_layout(out, rglob(temp, '**/*', None))
225 print('Wrote {} files to {}'.format(total, out))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400226 finally:
227 if delete_temp:
228 shutil.rmtree(temp, True)
229
230
231if __name__ == "__main__":
232 sys.exit(int(main() or 0))