blob: 2fb40d1c06f1ad8e454b888c4311039bb13d66a6 [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)
15DEBUG_RE = re.compile(r'_d\.(pyd|dll|exe)$', re.IGNORECASE)
16PYTHON_DLL_RE = re.compile(r'python\d\d?\.dll$', re.IGNORECASE)
17
Steve Dower2495faf2015-09-22 15:03:54 -070018EXCLUDE_FROM_LIBRARY = {
19 '__pycache__',
20 'ensurepip',
21 'idlelib',
22 'pydoc_data',
23 'site-packages',
24 'tkinter',
25 'turtledemo',
Steve Dower10cabcb2016-01-16 13:44:43 -080026 'venv',
Steve Dower2495faf2015-09-22 15:03:54 -070027}
28
29EXCLUDE_FILE_FROM_LIBRARY = {
30 'bdist_wininst.py',
31}
32
Steve Dowerf70fdd22015-04-14 18:34:04 -040033def is_not_debug(p):
Steve Dower6b4c63d2015-05-02 15:32:14 -070034 if DEBUG_RE.search(p.name):
35 return False
36
37 if TKTCL_RE.search(p.name):
38 return False
39
40 return p.name.lower() not in {
41 '_ctypes_test.pyd',
42 '_testbuffer.pyd',
43 '_testcapi.pyd',
44 '_testimportmultiple.pyd',
Steve Dower38050192015-05-23 18:08:55 -070045 '_testmultiphase.pyd',
Steve Dower6b4c63d2015-05-02 15:32:14 -070046 'xxlimited.pyd',
47 }
Steve Dowerf70fdd22015-04-14 18:34:04 -040048
49def is_not_debug_or_python(p):
50 return is_not_debug(p) and not PYTHON_DLL_RE.search(p.name)
51
52def include_in_lib(p):
53 name = p.name.lower()
54 if p.is_dir():
Steve Dower2495faf2015-09-22 15:03:54 -070055 if name in EXCLUDE_FROM_LIBRARY:
Steve Dowerf70fdd22015-04-14 18:34:04 -040056 return False
57 if name.startswith('plat-'):
58 return False
59 if name == 'test' and p.parts[-2].lower() == 'lib':
60 return False
Steve Dower2495faf2015-09-22 15:03:54 -070061 if name in {'test', 'tests'} and p.parts[-3].lower() == 'lib':
62 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040063 return True
64
Steve Dower2495faf2015-09-22 15:03:54 -070065 if name in EXCLUDE_FILE_FROM_LIBRARY:
66 return False
67
Steve Dower777af302015-04-19 19:50:35 -070068 suffix = p.suffix.lower()
Steve Dower2495faf2015-09-22 15:03:54 -070069 return suffix not in {'.pyc', '.pyo', '.exe'}
Steve Dowerf70fdd22015-04-14 18:34:04 -040070
71def include_in_tools(p):
72 if p.is_dir() and p.name.lower() in {'scripts', 'i18n', 'pynche', 'demo', 'parser'}:
73 return True
74
75 return p.suffix.lower() in {'.py', '.pyw', '.txt'}
76
77FULL_LAYOUT = [
Steve Dower33f73102016-06-24 10:32:15 -070078 ('/', 'PCBuild/$arch', 'python.exe', is_not_debug),
79 ('/', 'PCBuild/$arch', 'pythonw.exe', is_not_debug),
80 ('/', 'PCBuild/$arch', 'python{0.major}.dll'.format(sys.version_info), is_not_debug),
81 ('/', 'PCBuild/$arch', 'python{0.major}{0.minor}.dll'.format(sys.version_info), is_not_debug),
Steve Dowerf70fdd22015-04-14 18:34:04 -040082 ('DLLs/', 'PCBuild/$arch', '*.pyd', is_not_debug),
Steve Dower33f73102016-06-24 10:32:15 -070083 ('DLLs/', 'PCBuild/$arch', '*.dll', is_not_debug_or_python),
Steve Dowerf70fdd22015-04-14 18:34:04 -040084 ('include/', 'include', '*.h', None),
85 ('include/', 'PC', 'pyconfig.h', None),
86 ('Lib/', 'Lib', '**/*', include_in_lib),
87 ('Tools/', 'Tools', '**/*', include_in_tools),
88]
89
Steve Dowerf70fdd22015-04-14 18:34:04 -040090EMBED_LAYOUT = [
91 ('/', 'PCBuild/$arch', 'python*.exe', is_not_debug),
92 ('/', 'PCBuild/$arch', '*.pyd', is_not_debug),
93 ('/', 'PCBuild/$arch', '*.dll', is_not_debug),
Steve Dowerd8bf09c2016-05-19 10:47:47 -070094 ('python{0.major}{0.minor}.zip'.format(sys.version_info), 'Lib', '**/*', include_in_lib),
Steve Dowerf70fdd22015-04-14 18:34:04 -040095]
96
Steve Dowerfcbe1df2015-09-08 21:39:01 -070097if os.getenv('DOC_FILENAME'):
98 FULL_LAYOUT.append(('Doc/', 'Doc/build/htmlhelp', os.getenv('DOC_FILENAME'), None))
99if os.getenv('VCREDIST_PATH'):
100 FULL_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
101 EMBED_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
102
Steve Dower8c1cee92015-05-02 21:38:26 -0700103def copy_to_layout(target, rel_sources):
Steve Dowerf70fdd22015-04-14 18:34:04 -0400104 count = 0
105
106 if target.suffix.lower() == '.zip':
107 if target.exists():
108 target.unlink()
109
110 with ZipFile(str(target), 'w', ZIP_DEFLATED) as f:
Steve Dower315b7482015-08-05 11:34:50 -0700111 with tempfile.TemporaryDirectory() as tmpdir:
112 for s, rel in rel_sources:
113 if rel.suffix.lower() == '.py':
114 pyc = Path(tmpdir) / rel.with_suffix('.pyc').name
115 try:
116 py_compile.compile(str(s), str(pyc), str(rel), doraise=True, optimize=2)
117 except py_compile.PyCompileError:
118 f.write(str(s), str(rel))
119 else:
120 f.write(str(pyc), str(rel.with_suffix('.pyc')))
Steve Dower08b18172015-08-04 16:02:40 -0700121 else:
Steve Dower315b7482015-08-05 11:34:50 -0700122 f.write(str(s), str(rel))
123 count += 1
Steve Dowerf70fdd22015-04-14 18:34:04 -0400124
125 else:
126 for s, rel in rel_sources:
Steve Dowerae69de62015-09-09 19:32:45 -0700127 dest = target / rel
Steve Dowerf70fdd22015-04-14 18:34:04 -0400128 try:
Steve Dowerae69de62015-09-09 19:32:45 -0700129 dest.parent.mkdir(parents=True)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400130 except FileExistsError:
131 pass
Steve Dowerae69de62015-09-09 19:32:45 -0700132 if dest.is_file():
133 dest.chmod(stat.S_IWRITE)
134 shutil.copy(str(s), str(dest))
135 if dest.is_file():
136 dest.chmod(stat.S_IWRITE)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400137 count += 1
138
139 return count
140
141def rglob(root, pattern, condition):
142 dirs = [root]
143 recurse = pattern[:3] in {'**/', '**\\'}
144 while dirs:
145 d = dirs.pop(0)
146 for f in d.glob(pattern[3:] if recurse else pattern):
147 if recurse and f.is_dir() and (not condition or condition(f)):
148 dirs.append(f)
149 elif f.is_file() and (not condition or condition(f)):
150 yield f, f.relative_to(root)
151
152def main():
153 parser = argparse.ArgumentParser()
154 parser.add_argument('-s', '--source', metavar='dir', help='The directory containing the repository root', type=Path)
Steve Dower33f73102016-06-24 10:32:15 -0700155 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 -0400156 parser.add_argument('-t', '--temp', metavar='dir', help='A directory to temporarily extract files into', type=Path, default=None)
157 parser.add_argument('-e', '--embed', help='Create an embedding layout', action='store_true', default=False)
158 parser.add_argument('-a', '--arch', help='Specify the architecture to use (win32/amd64)', type=str, default="win32")
Steve Dowerf70fdd22015-04-14 18:34:04 -0400159 ns = parser.parse_args()
160
Steve Dower33f73102016-06-24 10:32:15 -0700161 source = ns.source or (Path(__file__).resolve().parent.parent.parent)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400162 out = ns.out
163 arch = ns.arch
Steve Dowerf70fdd22015-04-14 18:34:04 -0400164 assert isinstance(source, Path)
Steve Dower33f73102016-06-24 10:32:15 -0700165 assert not out or isinstance(out, Path)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400166 assert isinstance(arch, str)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400167
168 if ns.temp:
169 temp = ns.temp
170 delete_temp = False
171 else:
172 temp = Path(tempfile.mkdtemp())
173 delete_temp = True
174
Steve Dower33f73102016-06-24 10:32:15 -0700175 if out:
176 try:
177 out.parent.mkdir(parents=True)
178 except FileExistsError:
179 pass
Steve Dowerf70fdd22015-04-14 18:34:04 -0400180 try:
181 temp.mkdir(parents=True)
182 except FileExistsError:
183 pass
184
185 layout = EMBED_LAYOUT if ns.embed else FULL_LAYOUT
186
187 try:
188 for t, s, p, c in layout:
189 s = source / s.replace("$arch", arch)
Steve Dower8c1cee92015-05-02 21:38:26 -0700190 copied = copy_to_layout(temp / t.rstrip('/'), rglob(s, p, c))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400191 print('Copied {} files'.format(copied))
192
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700193 with open(str(temp / 'pyvenv.cfg'), 'w') as f:
194 print('applocal = true', file=f)
195
Steve Dower33f73102016-06-24 10:32:15 -0700196 if out:
197 total = copy_to_layout(out, rglob(temp, '**/*', None))
198 print('Wrote {} files to {}'.format(total, out))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400199 finally:
200 if delete_temp:
201 shutil.rmtree(temp, True)
202
203
204if __name__ == "__main__":
205 sys.exit(int(main() or 0))