blob: 0e8a4a69bb85b88ea26bbe0f4dac375f175e8a37 [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 Dowerf70fdd22015-04-14 18:34:04 -040049def is_not_debug(p):
Steve Dower6b4c63d2015-05-02 15:32:14 -070050 if DEBUG_RE.search(p.name):
51 return False
52
53 if TKTCL_RE.search(p.name):
54 return False
55
Steve Dower33128c82016-06-27 09:34:18 -070056 return p.stem.lower() not in DEBUG_FILES
Steve Dowerf70fdd22015-04-14 18:34:04 -040057
58def is_not_debug_or_python(p):
59 return is_not_debug(p) and not PYTHON_DLL_RE.search(p.name)
60
61def include_in_lib(p):
62 name = p.name.lower()
63 if p.is_dir():
Steve Dower2495faf2015-09-22 15:03:54 -070064 if name in EXCLUDE_FROM_LIBRARY:
Steve Dowerf70fdd22015-04-14 18:34:04 -040065 return False
66 if name.startswith('plat-'):
67 return False
68 if name == 'test' and p.parts[-2].lower() == 'lib':
69 return False
Steve Dower2495faf2015-09-22 15:03:54 -070070 if name in {'test', 'tests'} and p.parts[-3].lower() == 'lib':
71 return False
Steve Dowerf70fdd22015-04-14 18:34:04 -040072 return True
73
Steve Dower2495faf2015-09-22 15:03:54 -070074 if name in EXCLUDE_FILE_FROM_LIBRARY:
75 return False
76
Steve Dower777af302015-04-19 19:50:35 -070077 suffix = p.suffix.lower()
Steve Dower2495faf2015-09-22 15:03:54 -070078 return suffix not in {'.pyc', '.pyo', '.exe'}
Steve Dowerf70fdd22015-04-14 18:34:04 -040079
Steve Dower33128c82016-06-27 09:34:18 -070080def include_in_libs(p):
81 if not is_not_debug(p):
82 return False
83
84 return p.stem.lower() not in EXCLUDE_FILE_FROM_LIBS
85
Steve Dowerf70fdd22015-04-14 18:34:04 -040086def include_in_tools(p):
87 if p.is_dir() and p.name.lower() in {'scripts', 'i18n', 'pynche', 'demo', 'parser'}:
88 return True
89
90 return p.suffix.lower() in {'.py', '.pyw', '.txt'}
91
92FULL_LAYOUT = [
Steve Dower6fd76bc2016-07-16 16:13:19 -070093 ('/', '$build', 'python.exe', is_not_debug),
94 ('/', '$build', 'pythonw.exe', is_not_debug),
95 ('/', '$build', 'python{0.major}.dll'.format(sys.version_info), is_not_debug),
96 ('/', '$build', 'python{0.major}{0.minor}.dll'.format(sys.version_info), is_not_debug),
97 ('DLLs/', '$build', '*.pyd', is_not_debug),
98 ('DLLs/', '$build', '*.dll', is_not_debug_or_python),
Steve Dowerf70fdd22015-04-14 18:34:04 -040099 ('include/', 'include', '*.h', None),
100 ('include/', 'PC', 'pyconfig.h', None),
101 ('Lib/', 'Lib', '**/*', include_in_lib),
Steve Dower6fd76bc2016-07-16 16:13:19 -0700102 ('libs/', '$build', '*.lib', include_in_libs),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400103 ('Tools/', 'Tools', '**/*', include_in_tools),
104]
105
Steve Dowerf70fdd22015-04-14 18:34:04 -0400106EMBED_LAYOUT = [
Steve Dower6fd76bc2016-07-16 16:13:19 -0700107 ('/', '$build', 'python*.exe', is_not_debug),
108 ('/', '$build', '*.pyd', is_not_debug),
109 ('/', '$build', '*.dll', is_not_debug),
Steve Dowerd8bf09c2016-05-19 10:47:47 -0700110 ('python{0.major}{0.minor}.zip'.format(sys.version_info), 'Lib', '**/*', include_in_lib),
Steve Dowerf70fdd22015-04-14 18:34:04 -0400111]
112
Steve Dowerfcbe1df2015-09-08 21:39:01 -0700113if os.getenv('DOC_FILENAME'):
114 FULL_LAYOUT.append(('Doc/', 'Doc/build/htmlhelp', os.getenv('DOC_FILENAME'), None))
115if os.getenv('VCREDIST_PATH'):
116 FULL_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
117 EMBED_LAYOUT.append(('/', os.getenv('VCREDIST_PATH'), 'vcruntime*.dll', None))
118
Steve Dower8c1cee92015-05-02 21:38:26 -0700119def copy_to_layout(target, rel_sources):
Steve Dowerf70fdd22015-04-14 18:34:04 -0400120 count = 0
121
122 if target.suffix.lower() == '.zip':
123 if target.exists():
124 target.unlink()
125
126 with ZipFile(str(target), 'w', ZIP_DEFLATED) as f:
Steve Dower315b7482015-08-05 11:34:50 -0700127 with tempfile.TemporaryDirectory() as tmpdir:
128 for s, rel in rel_sources:
129 if rel.suffix.lower() == '.py':
130 pyc = Path(tmpdir) / rel.with_suffix('.pyc').name
131 try:
132 py_compile.compile(str(s), str(pyc), str(rel), doraise=True, optimize=2)
133 except py_compile.PyCompileError:
134 f.write(str(s), str(rel))
135 else:
136 f.write(str(pyc), str(rel.with_suffix('.pyc')))
Steve Dower08b18172015-08-04 16:02:40 -0700137 else:
Steve Dower315b7482015-08-05 11:34:50 -0700138 f.write(str(s), str(rel))
139 count += 1
Steve Dowerf70fdd22015-04-14 18:34:04 -0400140
141 else:
142 for s, rel in rel_sources:
Steve Dowerae69de62015-09-09 19:32:45 -0700143 dest = target / rel
Steve Dowerf70fdd22015-04-14 18:34:04 -0400144 try:
Steve Dowerae69de62015-09-09 19:32:45 -0700145 dest.parent.mkdir(parents=True)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400146 except FileExistsError:
147 pass
Steve Dowerae69de62015-09-09 19:32:45 -0700148 if dest.is_file():
149 dest.chmod(stat.S_IWRITE)
150 shutil.copy(str(s), str(dest))
151 if dest.is_file():
152 dest.chmod(stat.S_IWRITE)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400153 count += 1
154
155 return count
156
157def rglob(root, pattern, condition):
158 dirs = [root]
159 recurse = pattern[:3] in {'**/', '**\\'}
160 while dirs:
161 d = dirs.pop(0)
162 for f in d.glob(pattern[3:] if recurse else pattern):
163 if recurse and f.is_dir() and (not condition or condition(f)):
164 dirs.append(f)
165 elif f.is_file() and (not condition or condition(f)):
166 yield f, f.relative_to(root)
167
168def main():
169 parser = argparse.ArgumentParser()
170 parser.add_argument('-s', '--source', metavar='dir', help='The directory containing the repository root', type=Path)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700171 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 -0400172 parser.add_argument('-t', '--temp', metavar='dir', help='A directory to temporarily extract files into', type=Path, default=None)
173 parser.add_argument('-e', '--embed', help='Create an embedding layout', action='store_true', default=False)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700174 parser.add_argument('-b', '--build', help='Specify the build directory', type=Path)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400175 ns = parser.parse_args()
176
Steve Dower33f73102016-06-24 10:32:15 -0700177 source = ns.source or (Path(__file__).resolve().parent.parent.parent)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400178 out = ns.out
Steve Dower6fd76bc2016-07-16 16:13:19 -0700179 build = ns.build
Steve Dowerf70fdd22015-04-14 18:34:04 -0400180 assert isinstance(source, Path)
Steve Dower33f73102016-06-24 10:32:15 -0700181 assert not out or isinstance(out, Path)
Steve Dower6fd76bc2016-07-16 16:13:19 -0700182 assert isinstance(build, Path)
Steve Dowerf70fdd22015-04-14 18:34:04 -0400183
184 if ns.temp:
185 temp = ns.temp
186 delete_temp = False
187 else:
188 temp = Path(tempfile.mkdtemp())
189 delete_temp = True
190
Steve Dower33f73102016-06-24 10:32:15 -0700191 if out:
192 try:
193 out.parent.mkdir(parents=True)
194 except FileExistsError:
195 pass
Steve Dowerf70fdd22015-04-14 18:34:04 -0400196 try:
197 temp.mkdir(parents=True)
198 except FileExistsError:
199 pass
200
201 layout = EMBED_LAYOUT if ns.embed else FULL_LAYOUT
202
203 try:
204 for t, s, p, c in layout:
Steve Dower6fd76bc2016-07-16 16:13:19 -0700205 if s == '$build':
206 s = build
207 else:
208 s = source / s
Steve Dower8c1cee92015-05-02 21:38:26 -0700209 copied = copy_to_layout(temp / t.rstrip('/'), rglob(s, p, c))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400210 print('Copied {} files'.format(copied))
211
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700212 with open(str(temp / 'pyvenv.cfg'), 'w') as f:
213 print('applocal = true', file=f)
214
Steve Dower33f73102016-06-24 10:32:15 -0700215 if out:
216 total = copy_to_layout(out, rglob(temp, '**/*', None))
217 print('Wrote {} files to {}'.format(total, out))
Steve Dowerf70fdd22015-04-14 18:34:04 -0400218 finally:
219 if delete_temp:
220 shutil.rmtree(temp, True)
221
222
223if __name__ == "__main__":
224 sys.exit(int(main() or 0))