blob: 460cd5bff32b50ee77a9a4cdd984a5cd323544aa [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 Dowerf0888cd2016-11-23 10:23:47 -080078 # Special code is included below to patch this file back in
79 if [d.lower() for d in p.parts[-3:]] == ['distutils', 'command', '__init__.py']:
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
97FULL_LAYOUT = [
Steve Dower6fd76bc2016-07-16 16:13:19 -070098 ('/', '$build', 'python.exe', is_not_debug),
99 ('/', '$build', 'pythonw.exe', is_not_debug),
100 ('/', '$build', 'python{0.major}.dll'.format(sys.version_info), is_not_debug),
101 ('/', '$build', 'python{0.major}{0.minor}.dll'.format(sys.version_info), is_not_debug),
102 ('DLLs/', '$build', '*.pyd', is_not_debug),
103 ('DLLs/', '$build', '*.dll', is_not_debug_or_python),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400104 ('include/', 'include', '*.h', None),
105 ('include/', 'PC', 'pyconfig.h', None),
106 ('Lib/', 'Lib', '**/*', include_in_lib),
Steve Dower6fd76bc2016-07-16 16:13:19 -0700107 ('libs/', '$build', '*.lib', include_in_libs),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400108 ('Tools/', 'Tools', '**/*', include_in_tools),
109]
110
Steve Dowerf70fdd22015-04-14 18:34:04 -0400111EMBED_LAYOUT = [
Steve Dower6fd76bc2016-07-16 16:13:19 -0700112 ('/', '$build', 'python*.exe', is_not_debug),
113 ('/', '$build', '*.pyd', is_not_debug),
114 ('/', '$build', '*.dll', is_not_debug),
Steve Dowerd8bf09c2016-05-19 10:47:47 -0700115 ('python{0.major}{0.minor}.zip'.format(sys.version_info), 'Lib', '**/*', include_in_lib),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400116]
117
Steve Dowerfcbe1df2015-09-08 21:39:01 -0700118if os.getenv('DOC_FILENAME'):
119 FULL_LAYOUT.append(('Doc/', 'Doc/build/htmlhelp', os.getenv('DOC_FILENAME'), None))
120if os.getenv('VCREDIST_PATH'):
121 FULL_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
122 EMBED_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
123
Steve Dower8c1cee92015-05-02 21:38:26 -0700124def copy_to_layout(target, rel_sources):
Steve Dowerf70fdd22015-04-14 18:34:04 -0400125 count = 0
126
127 if target.suffix.lower() == '.zip':
128 if target.exists():
129 target.unlink()
130
131 with ZipFile(str(target), 'w', ZIP_DEFLATED) as f:
Steve Dower315b7482015-08-05 11:34:50 -0700132 with tempfile.TemporaryDirectory() as tmpdir:
133 for s, rel in rel_sources:
134 if rel.suffix.lower() == '.py':
135 pyc = Path(tmpdir) / rel.with_suffix('.pyc').name
136 try:
137 py_compile.compile(str(s), str(pyc), str(rel), doraise=True, optimize=2)
138 except py_compile.PyCompileError:
139 f.write(str(s), str(rel))
140 else:
141 f.write(str(pyc), str(rel.with_suffix('.pyc')))
Steve Dower08b18172015-08-04 16:02:40 -0700142 else:
Steve Dower315b7482015-08-05 11:34:50 -0700143 f.write(str(s), str(rel))
144 count += 1
Steve Dowerf70fdd22015-04-14 18:34:04 -0400145
146 else:
147 for s, rel in rel_sources:
Steve Dowerae69de62015-09-09 19:32:45 -0700148 dest = target / rel
Steve Dowerf70fdd22015-04-14 18:34:04 -0400149 try:
Steve Dowerae69de62015-09-09 19:32:45 -0700150 dest.parent.mkdir(parents=True)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400151 except FileExistsError:
152 pass
Steve Dowerae69de62015-09-09 19:32:45 -0700153 if dest.is_file():
154 dest.chmod(stat.S_IWRITE)
155 shutil.copy(str(s), str(dest))
156 if dest.is_file():
157 dest.chmod(stat.S_IWRITE)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400158 count += 1
159
160 return count
161
162def rglob(root, pattern, condition):
163 dirs = [root]
164 recurse = pattern[:3] in {'**/', '**\\'}
165 while dirs:
166 d = dirs.pop(0)
167 for f in d.glob(pattern[3:] if recurse else pattern):
168 if recurse and f.is_dir() and (not condition or condition(f)):
169 dirs.append(f)
170 elif f.is_file() and (not condition or condition(f)):
171 yield f, f.relative_to(root)
172
173def main():
174 parser = argparse.ArgumentParser()
175 parser.add_argument('-s', '--source', metavar='dir', help='The directory containing the repository root', type=Path)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700176 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 -0400177 parser.add_argument('-t', '--temp', metavar='dir', help='A directory to temporarily extract files into', type=Path, default=None)
178 parser.add_argument('-e', '--embed', help='Create an embedding layout', action='store_true', default=False)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700179 parser.add_argument('-b', '--build', help='Specify the build directory', type=Path)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400180 ns = parser.parse_args()
181
Steve Dower33f73102016-06-24 10:32:15 -0700182 source = ns.source or (Path(__file__).resolve().parent.parent.parent)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400183 out = ns.out
Steve Dower6fd76bc2016-07-16 16:13:19 -0700184 build = ns.build
Steve Dowerf70fdd22015-04-14 18:34:04 -0400185 assert isinstance(source, Path)
Steve Dower33f73102016-06-24 10:32:15 -0700186 assert not out or isinstance(out, Path)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700187 assert isinstance(build, Path)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400188
189 if ns.temp:
190 temp = ns.temp
191 delete_temp = False
192 else:
193 temp = Path(tempfile.mkdtemp())
194 delete_temp = True
195
Steve Dower33f73102016-06-24 10:32:15 -0700196 if out:
197 try:
198 out.parent.mkdir(parents=True)
199 except FileExistsError:
200 pass
Steve Dowerf70fdd22015-04-14 18:34:04 -0400201 try:
202 temp.mkdir(parents=True)
203 except FileExistsError:
204 pass
205
206 layout = EMBED_LAYOUT if ns.embed else FULL_LAYOUT
207
208 try:
209 for t, s, p, c in layout:
Steve Dower6fd76bc2016-07-16 16:13:19 -0700210 if s == '$build':
Steve Dowerf0888cd2016-11-23 10:23:47 -0800211 fs = build
Steve Dower6fd76bc2016-07-16 16:13:19 -0700212 else:
Steve Dowerf0888cd2016-11-23 10:23:47 -0800213 fs = source / s
214 files = rglob(fs, p, c)
215 extra_files = []
216 if s == 'Lib' and p == '**/*':
217 extra_files.append((
218 source / 'tools' / 'msi' / 'distutils.command.__init__.py',
219 Path('distutils') / 'command' / '__init__.py'
220 ))
221 copied = copy_to_layout(temp / t.rstrip('/'), chain(files, extra_files))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400222 print('Copied {} files'.format(copied))
223
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700224 with open(str(temp / 'pyvenv.cfg'), 'w') as f:
225 print('applocal = true', file=f)
226
Steve Dower33f73102016-06-24 10:32:15 -0700227 if out:
228 total = copy_to_layout(out, rglob(temp, '**/*', None))
229 print('Wrote {} files to {}'.format(total, out))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400230 finally:
231 if delete_temp:
232 shutil.rmtree(temp, True)
233
234
235if __name__ == "__main__":
236 sys.exit(int(main() or 0))