blob: f070cb91a9589f61a7c1c3d2594cd5ff0c7cff56 [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
10from pathlib import Path
11from zipfile import ZipFile, ZIP_DEFLATED
12import subprocess
13
14TKTCL_RE = re.compile(r'^(_?tk|tcl).+\.(pyd|dll)', re.IGNORECASE)
Steve Dower33128c82016-06-27 09:34:18 -070015DEBUG_RE = re.compile(r'_d\.(pyd|dll|exe|pdb|lib)$', re.IGNORECASE)
Steve Dowerf70fdd22015-04-14 18:34:04 -040016PYTHON_DLL_RE = re.compile(r'python\d\d?\.dll$', re.IGNORECASE)
17
Steve Dower33128c82016-06-27 09:34:18 -070018DEBUG_FILES = {
19 '_ctypes_test',
20 '_testbuffer',
21 '_testcapi',
Steve Dower4782ab32016-10-29 09:23:39 -070022 '_testconsole',
Steve Dower33128c82016-06-27 09:34:18 -070023 '_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 Dower4db86bc2016-09-09 09:17:35 -070050EXCLUDED_FILES = {
51 'pyshellext',
52}
53
Steve Dowerf70fdd22015-04-14 18:34:04 -040054def is_not_debug(p):
Steve Dower6b4c63d2015-05-02 15:32:14 -070055 if DEBUG_RE.search(p.name):
56 return False
57
58 if TKTCL_RE.search(p.name):
59 return False
60
Steve Dower4db86bc2016-09-09 09:17:35 -070061 return p.stem.lower() not in DEBUG_FILES and p.stem.lower() not in EXCLUDED_FILES
Steve Dowerf70fdd22015-04-14 18:34:04 -040062
63def is_not_debug_or_python(p):
64 return is_not_debug(p) and not PYTHON_DLL_RE.search(p.name)
65
66def include_in_lib(p):
67 name = p.name.lower()
68 if p.is_dir():
Steve Dower2495faf2015-09-22 15:03:54 -070069 if name in EXCLUDE_FROM_LIBRARY:
Steve Dowerf70fdd22015-04-14 18:34:04 -040070 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040071 if name == 'test' and p.parts[-2].lower() == 'lib':
72 return False
Steve Dower2495faf2015-09-22 15:03:54 -070073 if name in {'test', 'tests'} and p.parts[-3].lower() == 'lib':
74 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040075 return True
76
Steve Dower2495faf2015-09-22 15:03:54 -070077 if name in EXCLUDE_FILE_FROM_LIBRARY:
78 return False
79
Steve Dower777af302015-04-19 19:50:35 -070080 suffix = p.suffix.lower()
Steve Dower2495faf2015-09-22 15:03:54 -070081 return suffix not in {'.pyc', '.pyo', '.exe'}
Steve Dowerf70fdd22015-04-14 18:34:04 -040082
Steve Dower33128c82016-06-27 09:34:18 -070083def include_in_libs(p):
84 if not is_not_debug(p):
85 return False
86
87 return p.stem.lower() not in EXCLUDE_FILE_FROM_LIBS
88
Steve Dowerf70fdd22015-04-14 18:34:04 -040089def include_in_tools(p):
90 if p.is_dir() and p.name.lower() in {'scripts', 'i18n', 'pynche', 'demo', 'parser'}:
91 return True
92
93 return p.suffix.lower() in {'.py', '.pyw', '.txt'}
94
Steve Dowered51b262016-09-17 12:54:06 -070095BASE_NAME = 'python{0.major}{0.minor}'.format(sys.version_info)
96
Steve Dowerf70fdd22015-04-14 18:34:04 -040097FULL_LAYOUT = [
Steve Dower41fca9d2016-09-12 13:29:58 -070098 ('/', 'PCBuild/$arch', 'python.exe', is_not_debug),
99 ('/', 'PCBuild/$arch', 'pythonw.exe', is_not_debug),
Steve Dowered51b262016-09-17 12:54:06 -0700100 ('/', 'PCBuild/$arch', 'python{}.dll'.format(sys.version_info.major), is_not_debug),
101 ('/', 'PCBuild/$arch', '{}.dll'.format(BASE_NAME), is_not_debug),
Steve Dower41fca9d2016-09-12 13:29:58 -0700102 ('DLLs/', 'PCBuild/$arch', '*.pyd', is_not_debug),
103 ('DLLs/', 'PCBuild/$arch', '*.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 Dower41fca9d2016-09-12 13:29:58 -0700107 ('libs/', 'PCBuild/$arch', '*.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 Dower41fca9d2016-09-12 13:29:58 -0700112 ('/', 'PCBuild/$arch', 'python*.exe', is_not_debug),
113 ('/', 'PCBuild/$arch', '*.pyd', is_not_debug),
114 ('/', 'PCBuild/$arch', '*.dll', is_not_debug),
Steve Dowered51b262016-09-17 12:54:06 -0700115 ('{}.zip'.format(BASE_NAME), '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 Dower41fca9d2016-09-12 13:29:58 -0700176 parser.add_argument('-o', '--out', metavar='file', help='The name of the output self-extracting 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 Dower41fca9d2016-09-12 13:29:58 -0700179 parser.add_argument('-a', '--arch', help='Specify the architecture to use (win32/amd64)', type=str, default="win32")
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 Dower41fca9d2016-09-12 13:29:58 -0700184 arch = ns.arch
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 Dower41fca9d2016-09-12 13:29:58 -0700187 assert isinstance(arch, str)
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 Dower41fca9d2016-09-12 13:29:58 -0700210 s = source / s.replace("$arch", arch)
Steve Dower8c1cee92015-05-02 21:38:26 -0700211 copied = copy_to_layout(temp / t.rstrip('/'), rglob(s, p, c))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400212 print('Copied {} files'.format(copied))
213
Steve Dower41fca9d2016-09-12 13:29:58 -0700214 if ns.embed:
Steve Dowered51b262016-09-17 12:54:06 -0700215 with open(str(temp / (BASE_NAME + '._pth')), 'w') as f:
216 print(BASE_NAME + '.zip', file=f)
Steve Dower41fca9d2016-09-12 13:29:58 -0700217 print('.', file=f)
Steve Dowered51b262016-09-17 12:54:06 -0700218 print('', file=f)
219 print('# Uncomment to run site.main() automatically', file=f)
220 print('#import site', file=f)
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700221
Steve Dower33f73102016-06-24 10:32:15 -0700222 if out:
223 total = copy_to_layout(out, rglob(temp, '**/*', None))
224 print('Wrote {} files to {}'.format(total, out))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400225 finally:
226 if delete_temp:
227 shutil.rmtree(temp, True)
228
229
230if __name__ == "__main__":
231 sys.exit(int(main() or 0))