blob: ebb1766b33be894a6d9fdaf8ad59128e4a9c18f3 [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',
22 '_testimportmultiple',
23 '_testmultiphase',
24 'xxlimited',
25 'python3_dstub',
26}
27
Steve Dower2495faf2015-09-22 15:03:54 -070028EXCLUDE_FROM_LIBRARY = {
29 '__pycache__',
30 'ensurepip',
31 'idlelib',
32 'pydoc_data',
33 'site-packages',
34 'tkinter',
35 'turtledemo',
Steve Dower10cabcb2016-01-16 13:44:43 -080036 'venv',
Steve Dower2495faf2015-09-22 15:03:54 -070037}
38
39EXCLUDE_FILE_FROM_LIBRARY = {
40 'bdist_wininst.py',
41}
42
Steve Dower33128c82016-06-27 09:34:18 -070043EXCLUDE_FILE_FROM_LIBS = {
44 'ssleay',
45 'libeay',
46 'python3stub',
47}
48
Steve Dower4db86bc2016-09-09 09:17:35 -070049EXCLUDED_FILES = {
50 'pyshellext',
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 Dower4db86bc2016-09-09 09:17:35 -070060 return p.stem.lower() not in DEBUG_FILES and p.stem.lower() not in EXCLUDED_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
Steve Dowerf70fdd22015-04-14 18:34:04 -040070 if name == 'test' and p.parts[-2].lower() == 'lib':
71 return False
Steve Dower2495faf2015-09-22 15:03:54 -070072 if name in {'test', 'tests'} and p.parts[-3].lower() == 'lib':
73 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040074 return True
75
Steve Dower2495faf2015-09-22 15:03:54 -070076 if name in EXCLUDE_FILE_FROM_LIBRARY:
77 return False
78
Steve Dower777af302015-04-19 19:50:35 -070079 suffix = p.suffix.lower()
Steve Dower2495faf2015-09-22 15:03:54 -070080 return suffix not in {'.pyc', '.pyo', '.exe'}
Steve Dowerf70fdd22015-04-14 18:34:04 -040081
Steve Dower33128c82016-06-27 09:34:18 -070082def include_in_libs(p):
83 if not is_not_debug(p):
84 return False
85
86 return p.stem.lower() not in EXCLUDE_FILE_FROM_LIBS
87
Steve Dowerf70fdd22015-04-14 18:34:04 -040088def include_in_tools(p):
89 if p.is_dir() and p.name.lower() in {'scripts', 'i18n', 'pynche', 'demo', 'parser'}:
90 return True
91
92 return p.suffix.lower() in {'.py', '.pyw', '.txt'}
93
Steve Dowered51b262016-09-17 12:54:06 -070094BASE_NAME = 'python{0.major}{0.minor}'.format(sys.version_info)
95
Steve Dowerf70fdd22015-04-14 18:34:04 -040096FULL_LAYOUT = [
Steve Dower41fca9d2016-09-12 13:29:58 -070097 ('/', 'PCBuild/$arch', 'python.exe', is_not_debug),
98 ('/', 'PCBuild/$arch', 'pythonw.exe', is_not_debug),
Steve Dowered51b262016-09-17 12:54:06 -070099 ('/', 'PCBuild/$arch', 'python{}.dll'.format(sys.version_info.major), is_not_debug),
100 ('/', 'PCBuild/$arch', '{}.dll'.format(BASE_NAME), is_not_debug),
Steve Dower41fca9d2016-09-12 13:29:58 -0700101 ('DLLs/', 'PCBuild/$arch', '*.pyd', is_not_debug),
102 ('DLLs/', 'PCBuild/$arch', '*.dll', is_not_debug_or_python),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400103 ('include/', 'include', '*.h', None),
104 ('include/', 'PC', 'pyconfig.h', None),
105 ('Lib/', 'Lib', '**/*', include_in_lib),
Steve Dower41fca9d2016-09-12 13:29:58 -0700106 ('libs/', 'PCBuild/$arch', '*.lib', include_in_libs),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400107 ('Tools/', 'Tools', '**/*', include_in_tools),
108]
109
Steve Dowerf70fdd22015-04-14 18:34:04 -0400110EMBED_LAYOUT = [
Steve Dower41fca9d2016-09-12 13:29:58 -0700111 ('/', 'PCBuild/$arch', 'python*.exe', is_not_debug),
112 ('/', 'PCBuild/$arch', '*.pyd', is_not_debug),
113 ('/', 'PCBuild/$arch', '*.dll', is_not_debug),
Steve Dowered51b262016-09-17 12:54:06 -0700114 ('{}.zip'.format(BASE_NAME), 'Lib', '**/*', include_in_lib),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400115]
116
Steve Dowerfcbe1df2015-09-08 21:39:01 -0700117if os.getenv('DOC_FILENAME'):
118 FULL_LAYOUT.append(('Doc/', 'Doc/build/htmlhelp', os.getenv('DOC_FILENAME'), None))
119if os.getenv('VCREDIST_PATH'):
120 FULL_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
121 EMBED_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
122
Steve Dower8c1cee92015-05-02 21:38:26 -0700123def copy_to_layout(target, rel_sources):
Steve Dowerf70fdd22015-04-14 18:34:04 -0400124 count = 0
125
126 if target.suffix.lower() == '.zip':
127 if target.exists():
128 target.unlink()
129
130 with ZipFile(str(target), 'w', ZIP_DEFLATED) as f:
Steve Dower315b7482015-08-05 11:34:50 -0700131 with tempfile.TemporaryDirectory() as tmpdir:
132 for s, rel in rel_sources:
133 if rel.suffix.lower() == '.py':
134 pyc = Path(tmpdir) / rel.with_suffix('.pyc').name
135 try:
136 py_compile.compile(str(s), str(pyc), str(rel), doraise=True, optimize=2)
137 except py_compile.PyCompileError:
138 f.write(str(s), str(rel))
139 else:
140 f.write(str(pyc), str(rel.with_suffix('.pyc')))
Steve Dower08b18172015-08-04 16:02:40 -0700141 else:
Steve Dower315b7482015-08-05 11:34:50 -0700142 f.write(str(s), str(rel))
143 count += 1
Steve Dowerf70fdd22015-04-14 18:34:04 -0400144
145 else:
146 for s, rel in rel_sources:
Steve Dowerae69de62015-09-09 19:32:45 -0700147 dest = target / rel
Steve Dowerf70fdd22015-04-14 18:34:04 -0400148 try:
Steve Dowerae69de62015-09-09 19:32:45 -0700149 dest.parent.mkdir(parents=True)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400150 except FileExistsError:
151 pass
Steve Dowerae69de62015-09-09 19:32:45 -0700152 if dest.is_file():
153 dest.chmod(stat.S_IWRITE)
154 shutil.copy(str(s), str(dest))
155 if dest.is_file():
156 dest.chmod(stat.S_IWRITE)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400157 count += 1
158
159 return count
160
161def rglob(root, pattern, condition):
162 dirs = [root]
163 recurse = pattern[:3] in {'**/', '**\\'}
164 while dirs:
165 d = dirs.pop(0)
166 for f in d.glob(pattern[3:] if recurse else pattern):
167 if recurse and f.is_dir() and (not condition or condition(f)):
168 dirs.append(f)
169 elif f.is_file() and (not condition or condition(f)):
170 yield f, f.relative_to(root)
171
172def main():
173 parser = argparse.ArgumentParser()
174 parser.add_argument('-s', '--source', metavar='dir', help='The directory containing the repository root', type=Path)
Steve Dower41fca9d2016-09-12 13:29:58 -0700175 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 -0400176 parser.add_argument('-t', '--temp', metavar='dir', help='A directory to temporarily extract files into', type=Path, default=None)
177 parser.add_argument('-e', '--embed', help='Create an embedding layout', action='store_true', default=False)
Steve Dower41fca9d2016-09-12 13:29:58 -0700178 parser.add_argument('-a', '--arch', help='Specify the architecture to use (win32/amd64)', type=str, default="win32")
Steve Dowerf70fdd22015-04-14 18:34:04 -0400179 ns = parser.parse_args()
180
Steve Dower33f73102016-06-24 10:32:15 -0700181 source = ns.source or (Path(__file__).resolve().parent.parent.parent)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400182 out = ns.out
Steve Dower41fca9d2016-09-12 13:29:58 -0700183 arch = ns.arch
Steve Dowerf70fdd22015-04-14 18:34:04 -0400184 assert isinstance(source, Path)
Steve Dower33f73102016-06-24 10:32:15 -0700185 assert not out or isinstance(out, Path)
Steve Dower41fca9d2016-09-12 13:29:58 -0700186 assert isinstance(arch, str)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400187
188 if ns.temp:
189 temp = ns.temp
190 delete_temp = False
191 else:
192 temp = Path(tempfile.mkdtemp())
193 delete_temp = True
194
Steve Dower33f73102016-06-24 10:32:15 -0700195 if out:
196 try:
197 out.parent.mkdir(parents=True)
198 except FileExistsError:
199 pass
Steve Dowerf70fdd22015-04-14 18:34:04 -0400200 try:
201 temp.mkdir(parents=True)
202 except FileExistsError:
203 pass
204
205 layout = EMBED_LAYOUT if ns.embed else FULL_LAYOUT
206
207 try:
208 for t, s, p, c in layout:
Steve Dower41fca9d2016-09-12 13:29:58 -0700209 s = source / s.replace("$arch", arch)
Steve Dower8c1cee92015-05-02 21:38:26 -0700210 copied = copy_to_layout(temp / t.rstrip('/'), rglob(s, p, c))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400211 print('Copied {} files'.format(copied))
212
Steve Dower41fca9d2016-09-12 13:29:58 -0700213 if ns.embed:
Steve Dowered51b262016-09-17 12:54:06 -0700214 with open(str(temp / (BASE_NAME + '._pth')), 'w') as f:
215 print(BASE_NAME + '.zip', file=f)
Steve Dower41fca9d2016-09-12 13:29:58 -0700216 print('.', file=f)
Steve Dowered51b262016-09-17 12:54:06 -0700217 print('', file=f)
218 print('# Uncomment to run site.main() automatically', file=f)
219 print('#import site', file=f)
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700220
Steve Dower33f73102016-06-24 10:32:15 -0700221 if out:
222 total = copy_to_layout(out, rglob(temp, '**/*', None))
223 print('Wrote {} files to {}'.format(total, out))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400224 finally:
225 if delete_temp:
226 shutil.rmtree(temp, True)
227
228
229if __name__ == "__main__":
230 sys.exit(int(main() or 0))