blob: 6a03cbef0da53a25576df04ad87f3893228d460d [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__',
Steve Dower2495faf2015-09-22 15:03:54 -070031 'idlelib',
32 'pydoc_data',
33 'site-packages',
34 'tkinter',
35 'turtledemo',
Steve Dower52884772017-02-06 14:11:34 -080036}
37
38EXCLUDE_FROM_EMBEDDABLE_LIBRARY = {
39 'ensurepip',
Steve Dower10cabcb2016-01-16 13:44:43 -080040 'venv',
Steve Dower2495faf2015-09-22 15:03:54 -070041}
42
43EXCLUDE_FILE_FROM_LIBRARY = {
44 'bdist_wininst.py',
45}
46
Steve Dower33128c82016-06-27 09:34:18 -070047EXCLUDE_FILE_FROM_LIBS = {
48 'ssleay',
49 'libeay',
50 'python3stub',
51}
52
Steve Dowerf70fdd22015-04-14 18:34:04 -040053def is_not_debug(p):
Steve Dower6b4c63d2015-05-02 15:32:14 -070054 if DEBUG_RE.search(p.name):
55 return False
56
57 if TKTCL_RE.search(p.name):
58 return False
59
Steve Dower33128c82016-06-27 09:34:18 -070060 return p.stem.lower() not in DEBUG_FILES
Steve Dowerf70fdd22015-04-14 18:34:04 -040061
62def is_not_debug_or_python(p):
63 return is_not_debug(p) and not PYTHON_DLL_RE.search(p.name)
64
65def include_in_lib(p):
66 name = p.name.lower()
67 if p.is_dir():
Steve Dower2495faf2015-09-22 15:03:54 -070068 if name in EXCLUDE_FROM_LIBRARY:
Steve Dowerf70fdd22015-04-14 18:34:04 -040069 return False
70 if name.startswith('plat-'):
71 return False
72 if name == 'test' and p.parts[-2].lower() == 'lib':
73 return False
Steve Dower2495faf2015-09-22 15:03:54 -070074 if name in {'test', 'tests'} and p.parts[-3].lower() == 'lib':
75 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040076 return True
77
Steve Dower2495faf2015-09-22 15:03:54 -070078 if name in EXCLUDE_FILE_FROM_LIBRARY:
79 return False
80
Steve Dower777af302015-04-19 19:50:35 -070081 suffix = p.suffix.lower()
Steve Dower2495faf2015-09-22 15:03:54 -070082 return suffix not in {'.pyc', '.pyo', '.exe'}
Steve Dowerf70fdd22015-04-14 18:34:04 -040083
Steve Dower52884772017-02-06 14:11:34 -080084def include_in_embeddable_lib(p):
85 if p.is_dir() and p.name.lower() in EXCLUDE_FROM_EMBEDDABLE_LIBRARY:
86 return False
87
88 return include_in_lib(p)
89
Steve Dower33128c82016-06-27 09:34:18 -070090def include_in_libs(p):
91 if not is_not_debug(p):
92 return False
93
94 return p.stem.lower() not in EXCLUDE_FILE_FROM_LIBS
95
Steve Dowerf70fdd22015-04-14 18:34:04 -040096def include_in_tools(p):
97 if p.is_dir() and p.name.lower() in {'scripts', 'i18n', 'pynche', 'demo', 'parser'}:
98 return True
99
100 return p.suffix.lower() in {'.py', '.pyw', '.txt'}
101
102FULL_LAYOUT = [
Steve Dower6fd76bc2016-07-16 16:13:19 -0700103 ('/', '$build', 'python.exe', is_not_debug),
104 ('/', '$build', 'pythonw.exe', is_not_debug),
105 ('/', '$build', 'python{0.major}.dll'.format(sys.version_info), is_not_debug),
106 ('/', '$build', 'python{0.major}{0.minor}.dll'.format(sys.version_info), is_not_debug),
107 ('DLLs/', '$build', '*.pyd', is_not_debug),
108 ('DLLs/', '$build', '*.dll', is_not_debug_or_python),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400109 ('include/', 'include', '*.h', None),
110 ('include/', 'PC', 'pyconfig.h', None),
111 ('Lib/', 'Lib', '**/*', include_in_lib),
Steve Dower6fd76bc2016-07-16 16:13:19 -0700112 ('libs/', '$build', '*.lib', include_in_libs),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400113 ('Tools/', 'Tools', '**/*', include_in_tools),
114]
115
Steve Dowerf70fdd22015-04-14 18:34:04 -0400116EMBED_LAYOUT = [
Steve Dower6fd76bc2016-07-16 16:13:19 -0700117 ('/', '$build', 'python*.exe', is_not_debug),
118 ('/', '$build', '*.pyd', is_not_debug),
119 ('/', '$build', '*.dll', is_not_debug),
Steve Dower52884772017-02-06 14:11:34 -0800120 ('python{0.major}{0.minor}.zip'.format(sys.version_info), 'Lib', '**/*', include_in_embeddable_lib),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400121]
122
Steve Dowerfcbe1df2015-09-08 21:39:01 -0700123if os.getenv('DOC_FILENAME'):
124 FULL_LAYOUT.append(('Doc/', 'Doc/build/htmlhelp', os.getenv('DOC_FILENAME'), None))
125if os.getenv('VCREDIST_PATH'):
126 FULL_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
127 EMBED_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
128
Steve Dower8c1cee92015-05-02 21:38:26 -0700129def copy_to_layout(target, rel_sources):
Steve Dowerf70fdd22015-04-14 18:34:04 -0400130 count = 0
131
132 if target.suffix.lower() == '.zip':
133 if target.exists():
134 target.unlink()
135
136 with ZipFile(str(target), 'w', ZIP_DEFLATED) as f:
Steve Dower315b7482015-08-05 11:34:50 -0700137 with tempfile.TemporaryDirectory() as tmpdir:
138 for s, rel in rel_sources:
139 if rel.suffix.lower() == '.py':
140 pyc = Path(tmpdir) / rel.with_suffix('.pyc').name
141 try:
142 py_compile.compile(str(s), str(pyc), str(rel), doraise=True, optimize=2)
143 except py_compile.PyCompileError:
144 f.write(str(s), str(rel))
145 else:
146 f.write(str(pyc), str(rel.with_suffix('.pyc')))
Steve Dower08b18172015-08-04 16:02:40 -0700147 else:
Steve Dower315b7482015-08-05 11:34:50 -0700148 f.write(str(s), str(rel))
149 count += 1
Steve Dowerf70fdd22015-04-14 18:34:04 -0400150
151 else:
152 for s, rel in rel_sources:
Steve Dowerae69de62015-09-09 19:32:45 -0700153 dest = target / rel
Steve Dowerf70fdd22015-04-14 18:34:04 -0400154 try:
Steve Dowerae69de62015-09-09 19:32:45 -0700155 dest.parent.mkdir(parents=True)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400156 except FileExistsError:
157 pass
Steve Dowerae69de62015-09-09 19:32:45 -0700158 if dest.is_file():
159 dest.chmod(stat.S_IWRITE)
160 shutil.copy(str(s), str(dest))
161 if dest.is_file():
162 dest.chmod(stat.S_IWRITE)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400163 count += 1
164
165 return count
166
167def rglob(root, pattern, condition):
168 dirs = [root]
169 recurse = pattern[:3] in {'**/', '**\\'}
170 while dirs:
171 d = dirs.pop(0)
172 for f in d.glob(pattern[3:] if recurse else pattern):
173 if recurse and f.is_dir() and (not condition or condition(f)):
174 dirs.append(f)
175 elif f.is_file() and (not condition or condition(f)):
176 yield f, f.relative_to(root)
177
178def main():
179 parser = argparse.ArgumentParser()
180 parser.add_argument('-s', '--source', metavar='dir', help='The directory containing the repository root', type=Path)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700181 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 -0400182 parser.add_argument('-t', '--temp', metavar='dir', help='A directory to temporarily extract files into', type=Path, default=None)
183 parser.add_argument('-e', '--embed', help='Create an embedding layout', action='store_true', default=False)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700184 parser.add_argument('-b', '--build', help='Specify the build directory', type=Path)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400185 ns = parser.parse_args()
186
Steve Dower33f73102016-06-24 10:32:15 -0700187 source = ns.source or (Path(__file__).resolve().parent.parent.parent)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400188 out = ns.out
Steve Dower6fd76bc2016-07-16 16:13:19 -0700189 build = ns.build
Steve Dowerf70fdd22015-04-14 18:34:04 -0400190 assert isinstance(source, Path)
Steve Dower33f73102016-06-24 10:32:15 -0700191 assert not out or isinstance(out, Path)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700192 assert isinstance(build, Path)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400193
194 if ns.temp:
195 temp = ns.temp
196 delete_temp = False
197 else:
198 temp = Path(tempfile.mkdtemp())
199 delete_temp = True
200
Steve Dower33f73102016-06-24 10:32:15 -0700201 if out:
202 try:
203 out.parent.mkdir(parents=True)
204 except FileExistsError:
205 pass
Steve Dowerf70fdd22015-04-14 18:34:04 -0400206 try:
207 temp.mkdir(parents=True)
208 except FileExistsError:
209 pass
210
211 layout = EMBED_LAYOUT if ns.embed else FULL_LAYOUT
212
213 try:
214 for t, s, p, c in layout:
Steve Dower6fd76bc2016-07-16 16:13:19 -0700215 if s == '$build':
Steve Dowerf0888cd2016-11-23 10:23:47 -0800216 fs = build
Steve Dower6fd76bc2016-07-16 16:13:19 -0700217 else:
Steve Dowerf0888cd2016-11-23 10:23:47 -0800218 fs = source / s
219 files = rglob(fs, p, c)
220 extra_files = []
221 if s == 'Lib' and p == '**/*':
222 extra_files.append((
Steve Dowere711cc02016-12-11 14:35:07 -0800223 source / 'tools' / 'msi' / 'distutils.command.bdist_wininst.py',
224 Path('distutils') / 'command' / 'bdist_wininst.py'
Steve Dowerf0888cd2016-11-23 10:23:47 -0800225 ))
226 copied = copy_to_layout(temp / t.rstrip('/'), chain(files, extra_files))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400227 print('Copied {} files'.format(copied))
228
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700229 with open(str(temp / 'pyvenv.cfg'), 'w') as f:
230 print('applocal = true', file=f)
231
Steve Dower33f73102016-06-24 10:32:15 -0700232 if out:
233 total = copy_to_layout(out, rglob(temp, '**/*', None))
234 print('Wrote {} files to {}'.format(total, out))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400235 finally:
236 if delete_temp:
237 shutil.rmtree(temp, True)
238
239
240if __name__ == "__main__":
241 sys.exit(int(main() or 0))