blob: 09f6fe328f3d6472c4b499e4971290a307c7291f [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 Dowerf0888cd2016-11-23 10:23:47 -080082 # Special code is included below to patch this file back in
83 if [d.lower() for d in p.parts[-3:]] == ['distutils', 'command', '__init__.py']:
84 return False
85
Steve Dower777af302015-04-19 19:50:35 -070086 suffix = p.suffix.lower()
Steve Dower2495faf2015-09-22 15:03:54 -070087 return suffix not in {'.pyc', '.pyo', '.exe'}
Steve Dowerf70fdd22015-04-14 18:34:04 -040088
Steve Dower33128c82016-06-27 09:34:18 -070089def include_in_libs(p):
90 if not is_not_debug(p):
91 return False
92
93 return p.stem.lower() not in EXCLUDE_FILE_FROM_LIBS
94
Steve Dowerf70fdd22015-04-14 18:34:04 -040095def include_in_tools(p):
96 if p.is_dir() and p.name.lower() in {'scripts', 'i18n', 'pynche', 'demo', 'parser'}:
97 return True
98
99 return p.suffix.lower() in {'.py', '.pyw', '.txt'}
100
Steve Dowered51b262016-09-17 12:54:06 -0700101BASE_NAME = 'python{0.major}{0.minor}'.format(sys.version_info)
102
Steve Dowerf70fdd22015-04-14 18:34:04 -0400103FULL_LAYOUT = [
Steve Dower41fca9d2016-09-12 13:29:58 -0700104 ('/', 'PCBuild/$arch', 'python.exe', is_not_debug),
105 ('/', 'PCBuild/$arch', 'pythonw.exe', is_not_debug),
Steve Dowered51b262016-09-17 12:54:06 -0700106 ('/', 'PCBuild/$arch', 'python{}.dll'.format(sys.version_info.major), is_not_debug),
107 ('/', 'PCBuild/$arch', '{}.dll'.format(BASE_NAME), is_not_debug),
Steve Dower41fca9d2016-09-12 13:29:58 -0700108 ('DLLs/', 'PCBuild/$arch', '*.pyd', is_not_debug),
109 ('DLLs/', 'PCBuild/$arch', '*.dll', is_not_debug_or_python),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400110 ('include/', 'include', '*.h', None),
111 ('include/', 'PC', 'pyconfig.h', None),
112 ('Lib/', 'Lib', '**/*', include_in_lib),
Steve Dower41fca9d2016-09-12 13:29:58 -0700113 ('libs/', 'PCBuild/$arch', '*.lib', include_in_libs),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400114 ('Tools/', 'Tools', '**/*', include_in_tools),
115]
116
Steve Dowerf70fdd22015-04-14 18:34:04 -0400117EMBED_LAYOUT = [
Steve Dower41fca9d2016-09-12 13:29:58 -0700118 ('/', 'PCBuild/$arch', 'python*.exe', is_not_debug),
119 ('/', 'PCBuild/$arch', '*.pyd', is_not_debug),
120 ('/', 'PCBuild/$arch', '*.dll', is_not_debug),
Steve Dowered51b262016-09-17 12:54:06 -0700121 ('{}.zip'.format(BASE_NAME), 'Lib', '**/*', include_in_lib),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400122]
123
Steve Dowerfcbe1df2015-09-08 21:39:01 -0700124if os.getenv('DOC_FILENAME'):
125 FULL_LAYOUT.append(('Doc/', 'Doc/build/htmlhelp', os.getenv('DOC_FILENAME'), None))
126if os.getenv('VCREDIST_PATH'):
127 FULL_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
128 EMBED_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
129
Steve Dower8c1cee92015-05-02 21:38:26 -0700130def copy_to_layout(target, rel_sources):
Steve Dowerf70fdd22015-04-14 18:34:04 -0400131 count = 0
132
133 if target.suffix.lower() == '.zip':
134 if target.exists():
135 target.unlink()
136
137 with ZipFile(str(target), 'w', ZIP_DEFLATED) as f:
Steve Dower315b7482015-08-05 11:34:50 -0700138 with tempfile.TemporaryDirectory() as tmpdir:
139 for s, rel in rel_sources:
140 if rel.suffix.lower() == '.py':
141 pyc = Path(tmpdir) / rel.with_suffix('.pyc').name
142 try:
143 py_compile.compile(str(s), str(pyc), str(rel), doraise=True, optimize=2)
144 except py_compile.PyCompileError:
145 f.write(str(s), str(rel))
146 else:
147 f.write(str(pyc), str(rel.with_suffix('.pyc')))
Steve Dower08b18172015-08-04 16:02:40 -0700148 else:
Steve Dower315b7482015-08-05 11:34:50 -0700149 f.write(str(s), str(rel))
150 count += 1
Steve Dowerf70fdd22015-04-14 18:34:04 -0400151
152 else:
153 for s, rel in rel_sources:
Steve Dowerae69de62015-09-09 19:32:45 -0700154 dest = target / rel
Steve Dowerf70fdd22015-04-14 18:34:04 -0400155 try:
Steve Dowerae69de62015-09-09 19:32:45 -0700156 dest.parent.mkdir(parents=True)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400157 except FileExistsError:
158 pass
Steve Dowerae69de62015-09-09 19:32:45 -0700159 if dest.is_file():
160 dest.chmod(stat.S_IWRITE)
161 shutil.copy(str(s), str(dest))
162 if dest.is_file():
163 dest.chmod(stat.S_IWRITE)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400164 count += 1
165
166 return count
167
168def rglob(root, pattern, condition):
169 dirs = [root]
170 recurse = pattern[:3] in {'**/', '**\\'}
171 while dirs:
172 d = dirs.pop(0)
173 for f in d.glob(pattern[3:] if recurse else pattern):
174 if recurse and f.is_dir() and (not condition or condition(f)):
175 dirs.append(f)
176 elif f.is_file() and (not condition or condition(f)):
177 yield f, f.relative_to(root)
178
179def main():
180 parser = argparse.ArgumentParser()
181 parser.add_argument('-s', '--source', metavar='dir', help='The directory containing the repository root', type=Path)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700182 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 -0400183 parser.add_argument('-t', '--temp', metavar='dir', help='A directory to temporarily extract files into', type=Path, default=None)
184 parser.add_argument('-e', '--embed', help='Create an embedding layout', action='store_true', default=False)
Steve Dower41fca9d2016-09-12 13:29:58 -0700185 parser.add_argument('-a', '--arch', help='Specify the architecture to use (win32/amd64)', type=str, default="win32")
Steve Dowerf70fdd22015-04-14 18:34:04 -0400186 ns = parser.parse_args()
187
Steve Dower33f73102016-06-24 10:32:15 -0700188 source = ns.source or (Path(__file__).resolve().parent.parent.parent)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400189 out = ns.out
Steve Dower41fca9d2016-09-12 13:29:58 -0700190 arch = ns.arch
Steve Dowerf70fdd22015-04-14 18:34:04 -0400191 assert isinstance(source, Path)
Steve Dower33f73102016-06-24 10:32:15 -0700192 assert not out or isinstance(out, Path)
Steve Dower41fca9d2016-09-12 13:29:58 -0700193 assert isinstance(arch, str)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400194
195 if ns.temp:
196 temp = ns.temp
197 delete_temp = False
198 else:
199 temp = Path(tempfile.mkdtemp())
200 delete_temp = True
201
Steve Dower33f73102016-06-24 10:32:15 -0700202 if out:
203 try:
204 out.parent.mkdir(parents=True)
205 except FileExistsError:
206 pass
Steve Dowerf70fdd22015-04-14 18:34:04 -0400207 try:
208 temp.mkdir(parents=True)
209 except FileExistsError:
210 pass
211
212 layout = EMBED_LAYOUT if ns.embed else FULL_LAYOUT
213
214 try:
215 for t, s, p, c in layout:
Steve Dower2a943012016-11-23 11:42:35 -0800216 fs = source / s.replace("$arch", arch)
Steve Dowerf0888cd2016-11-23 10:23:47 -0800217 files = rglob(fs, p, c)
218 extra_files = []
219 if s == 'Lib' and p == '**/*':
220 extra_files.append((
221 source / 'tools' / 'msi' / 'distutils.command.__init__.py',
222 Path('distutils') / 'command' / '__init__.py'
223 ))
224 copied = copy_to_layout(temp / t.rstrip('/'), chain(files, extra_files))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400225 print('Copied {} files'.format(copied))
226
Steve Dower41fca9d2016-09-12 13:29:58 -0700227 if ns.embed:
Steve Dowered51b262016-09-17 12:54:06 -0700228 with open(str(temp / (BASE_NAME + '._pth')), 'w') as f:
229 print(BASE_NAME + '.zip', file=f)
Steve Dower41fca9d2016-09-12 13:29:58 -0700230 print('.', file=f)
Steve Dowered51b262016-09-17 12:54:06 -0700231 print('', file=f)
232 print('# Uncomment to run site.main() automatically', file=f)
233 print('#import site', file=f)
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700234
Steve Dower33f73102016-06-24 10:32:15 -0700235 if out:
236 total = copy_to_layout(out, rglob(temp, '**/*', None))
237 print('Wrote {} files to {}'.format(total, out))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400238 finally:
239 if delete_temp:
240 shutil.rmtree(temp, True)
241
242
243if __name__ == "__main__":
244 sys.exit(int(main() or 0))