blob: 58f3b15ef8524e3b3487ec688380a8d5b9de0e2c [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
Victor Stinnerd6debb22017-03-27 16:05:26 +020013
Steve Dowerf70fdd22015-04-14 18:34:04 -040014
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 'python3stub',
51}
52
Steve Dower4db86bc2016-09-09 09:17:35 -070053EXCLUDED_FILES = {
54 'pyshellext',
55}
56
Steve Dowerf70fdd22015-04-14 18:34:04 -040057def is_not_debug(p):
Steve Dower6b4c63d2015-05-02 15:32:14 -070058 if DEBUG_RE.search(p.name):
59 return False
60
61 if TKTCL_RE.search(p.name):
62 return False
63
Steve Dower4db86bc2016-09-09 09:17:35 -070064 return p.stem.lower() not in DEBUG_FILES and p.stem.lower() not in EXCLUDED_FILES
Steve Dowerf70fdd22015-04-14 18:34:04 -040065
66def is_not_debug_or_python(p):
67 return is_not_debug(p) and not PYTHON_DLL_RE.search(p.name)
68
69def include_in_lib(p):
70 name = p.name.lower()
71 if p.is_dir():
Steve Dower2495faf2015-09-22 15:03:54 -070072 if name in EXCLUDE_FROM_LIBRARY:
Steve Dowerf70fdd22015-04-14 18:34:04 -040073 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040074 if name == 'test' and p.parts[-2].lower() == 'lib':
75 return False
Steve Dower2495faf2015-09-22 15:03:54 -070076 if name in {'test', 'tests'} and p.parts[-3].lower() == 'lib':
77 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040078 return True
79
Steve Dower2495faf2015-09-22 15:03:54 -070080 if name in EXCLUDE_FILE_FROM_LIBRARY:
81 return False
82
Steve Dower777af302015-04-19 19:50:35 -070083 suffix = p.suffix.lower()
Steve Dower2495faf2015-09-22 15:03:54 -070084 return suffix not in {'.pyc', '.pyo', '.exe'}
Steve Dowerf70fdd22015-04-14 18:34:04 -040085
Steve Dower52884772017-02-06 14:11:34 -080086def include_in_embeddable_lib(p):
87 if p.is_dir() and p.name.lower() in EXCLUDE_FROM_EMBEDDABLE_LIBRARY:
88 return False
89
90 return include_in_lib(p)
91
Steve Dower33128c82016-06-27 09:34:18 -070092def include_in_libs(p):
93 if not is_not_debug(p):
94 return False
95
96 return p.stem.lower() not in EXCLUDE_FILE_FROM_LIBS
97
Steve Dowerf70fdd22015-04-14 18:34:04 -040098def include_in_tools(p):
99 if p.is_dir() and p.name.lower() in {'scripts', 'i18n', 'pynche', 'demo', 'parser'}:
100 return True
101
102 return p.suffix.lower() in {'.py', '.pyw', '.txt'}
103
Steve Dowered51b262016-09-17 12:54:06 -0700104BASE_NAME = 'python{0.major}{0.minor}'.format(sys.version_info)
105
Steve Dowerf70fdd22015-04-14 18:34:04 -0400106FULL_LAYOUT = [
Steve Dowerf0851912017-07-26 09:09:01 -0700107 ('/', '$build', 'python.exe', is_not_debug),
108 ('/', '$build', 'pythonw.exe', is_not_debug),
109 ('/', '$build', 'python{}.dll'.format(sys.version_info.major), is_not_debug),
110 ('/', '$build', '{}.dll'.format(BASE_NAME), is_not_debug),
111 ('DLLs/', '$build', '*.pyd', is_not_debug),
112 ('DLLs/', '$build', '*.dll', is_not_debug_or_python),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400113 ('include/', 'include', '*.h', None),
114 ('include/', 'PC', 'pyconfig.h', None),
115 ('Lib/', 'Lib', '**/*', include_in_lib),
Steve Dowerf0851912017-07-26 09:09:01 -0700116 ('libs/', '$build', '*.lib', include_in_libs),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400117 ('Tools/', 'Tools', '**/*', include_in_tools),
118]
119
Steve Dowerf70fdd22015-04-14 18:34:04 -0400120EMBED_LAYOUT = [
Steve Dowerf0851912017-07-26 09:09:01 -0700121 ('/', '$build', 'python*.exe', is_not_debug),
122 ('/', '$build', '*.pyd', is_not_debug),
123 ('/', '$build', '*.dll', is_not_debug),
Steve Dowerf007b492017-02-06 14:12:19 -0800124 ('{}.zip'.format(BASE_NAME), 'Lib', '**/*', include_in_embeddable_lib),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400125]
126
Steve Dowerfcbe1df2015-09-08 21:39:01 -0700127if os.getenv('DOC_FILENAME'):
128 FULL_LAYOUT.append(('Doc/', 'Doc/build/htmlhelp', os.getenv('DOC_FILENAME'), None))
129if os.getenv('VCREDIST_PATH'):
130 FULL_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
131 EMBED_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
132
Steve Dower8c1cee92015-05-02 21:38:26 -0700133def copy_to_layout(target, rel_sources):
Steve Dowerf70fdd22015-04-14 18:34:04 -0400134 count = 0
135
136 if target.suffix.lower() == '.zip':
137 if target.exists():
138 target.unlink()
139
140 with ZipFile(str(target), 'w', ZIP_DEFLATED) as f:
Steve Dower315b7482015-08-05 11:34:50 -0700141 with tempfile.TemporaryDirectory() as tmpdir:
142 for s, rel in rel_sources:
143 if rel.suffix.lower() == '.py':
144 pyc = Path(tmpdir) / rel.with_suffix('.pyc').name
145 try:
146 py_compile.compile(str(s), str(pyc), str(rel), doraise=True, optimize=2)
147 except py_compile.PyCompileError:
148 f.write(str(s), str(rel))
149 else:
150 f.write(str(pyc), str(rel.with_suffix('.pyc')))
Steve Dower08b18172015-08-04 16:02:40 -0700151 else:
Steve Dower315b7482015-08-05 11:34:50 -0700152 f.write(str(s), str(rel))
153 count += 1
Steve Dowerf70fdd22015-04-14 18:34:04 -0400154
155 else:
156 for s, rel in rel_sources:
Steve Dowerae69de62015-09-09 19:32:45 -0700157 dest = target / rel
Steve Dowerf70fdd22015-04-14 18:34:04 -0400158 try:
Steve Dowerae69de62015-09-09 19:32:45 -0700159 dest.parent.mkdir(parents=True)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400160 except FileExistsError:
161 pass
Steve Dowerae69de62015-09-09 19:32:45 -0700162 if dest.is_file():
163 dest.chmod(stat.S_IWRITE)
164 shutil.copy(str(s), str(dest))
165 if dest.is_file():
166 dest.chmod(stat.S_IWRITE)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400167 count += 1
168
169 return count
170
171def rglob(root, pattern, condition):
172 dirs = [root]
173 recurse = pattern[:3] in {'**/', '**\\'}
174 while dirs:
175 d = dirs.pop(0)
176 for f in d.glob(pattern[3:] if recurse else pattern):
177 if recurse and f.is_dir() and (not condition or condition(f)):
178 dirs.append(f)
179 elif f.is_file() and (not condition or condition(f)):
180 yield f, f.relative_to(root)
181
182def main():
183 parser = argparse.ArgumentParser()
184 parser.add_argument('-s', '--source', metavar='dir', help='The directory containing the repository root', type=Path)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700185 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 -0400186 parser.add_argument('-t', '--temp', metavar='dir', help='A directory to temporarily extract files into', type=Path, default=None)
187 parser.add_argument('-e', '--embed', help='Create an embedding layout', action='store_true', default=False)
Steve Dowerf0851912017-07-26 09:09:01 -0700188 parser.add_argument('-b', '--build', help='Specify the build directory', type=Path, default=None)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400189 ns = parser.parse_args()
190
Steve Dower33f73102016-06-24 10:32:15 -0700191 source = ns.source or (Path(__file__).resolve().parent.parent.parent)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400192 out = ns.out
Steve Dowerf0851912017-07-26 09:09:01 -0700193 build = ns.build or Path(sys.exec_prefix)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400194 assert isinstance(source, Path)
Steve Dower33f73102016-06-24 10:32:15 -0700195 assert not out or isinstance(out, Path)
Steve Dowerf0851912017-07-26 09:09:01 -0700196 assert isinstance(build, Path)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400197
198 if ns.temp:
199 temp = ns.temp
200 delete_temp = False
201 else:
202 temp = Path(tempfile.mkdtemp())
203 delete_temp = True
204
Steve Dower33f73102016-06-24 10:32:15 -0700205 if out:
206 try:
207 out.parent.mkdir(parents=True)
208 except FileExistsError:
209 pass
Steve Dowerf70fdd22015-04-14 18:34:04 -0400210 try:
211 temp.mkdir(parents=True)
212 except FileExistsError:
213 pass
214
215 layout = EMBED_LAYOUT if ns.embed else FULL_LAYOUT
216
217 try:
218 for t, s, p, c in layout:
Steve Dowerf0851912017-07-26 09:09:01 -0700219 if s == '$build':
220 fs = build
221 else:
222 fs = source / s
Steve Dowerf0888cd2016-11-23 10:23:47 -0800223 files = rglob(fs, p, c)
224 extra_files = []
225 if s == 'Lib' and p == '**/*':
226 extra_files.append((
Steve Dowere711cc02016-12-11 14:35:07 -0800227 source / 'tools' / 'msi' / 'distutils.command.bdist_wininst.py',
228 Path('distutils') / 'command' / 'bdist_wininst.py'
Steve Dowerf0888cd2016-11-23 10:23:47 -0800229 ))
230 copied = copy_to_layout(temp / t.rstrip('/'), chain(files, extra_files))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400231 print('Copied {} files'.format(copied))
232
Steve Dower41fca9d2016-09-12 13:29:58 -0700233 if ns.embed:
Steve Dowered51b262016-09-17 12:54:06 -0700234 with open(str(temp / (BASE_NAME + '._pth')), 'w') as f:
235 print(BASE_NAME + '.zip', file=f)
Steve Dower41fca9d2016-09-12 13:29:58 -0700236 print('.', file=f)
Steve Dowered51b262016-09-17 12:54:06 -0700237 print('', file=f)
238 print('# Uncomment to run site.main() automatically', file=f)
239 print('#import site', file=f)
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700240
Steve Dower33f73102016-06-24 10:32:15 -0700241 if out:
242 total = copy_to_layout(out, rglob(temp, '**/*', None))
243 print('Wrote {} files to {}'.format(total, out))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400244 finally:
245 if delete_temp:
246 shutil.rmtree(temp, True)
247
248
249if __name__ == "__main__":
250 sys.exit(int(main() or 0))