__main__.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. #!/usr/bin/env python
  2. # vim:fileencoding=utf-8
  3. # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
  4. import errno
  5. import os
  6. import shutil
  7. import stat
  8. import subprocess
  9. import tarfile
  10. import time
  11. from bypy.constants import OUTPUT_DIR, PREFIX, is64bit, python_major_minor_version
  12. from bypy.freeze import extract_extension_modules, freeze_python, path_to_freeze_dir
  13. from bypy.utils import get_dll_path, mkdtemp, py_compile, walk
  14. j = os.path.join
  15. machine = (os.uname()[4] or '').lower()
  16. if machine.startswith('arm64') or machine.startswith('aarch64'):
  17. arch = 'arm64'
  18. else:
  19. arch = 'x86_64' if is64bit else 'i686'
  20. self_dir = os.path.dirname(os.path.abspath(__file__))
  21. py_ver = '.'.join(map(str, python_major_minor_version()))
  22. iv = globals()['init_env']
  23. kitty_constants = iv['kitty_constants']
  24. def binary_includes():
  25. return tuple(map(get_dll_path, (
  26. 'expat', 'sqlite3', 'ffi', 'z', 'lzma', 'png16', 'lcms2', 'ssl', 'crypto', 'crypt',
  27. 'iconv', 'pcre2-8', 'graphite2', 'glib-2.0', 'freetype', 'xxhash',
  28. 'harfbuzz', 'xkbcommon', 'xkbcommon-x11',
  29. # fontconfig is not bundled because in typical brain dead Linux
  30. # distro fashion, different distros use different default config
  31. # paths for fontconfig.
  32. 'ncursesw', 'readline', 'brotlicommon', 'brotlienc', 'brotlidec',
  33. 'wayland-client', 'wayland-cursor',
  34. ))) + (
  35. get_dll_path('bz2', 2),
  36. get_dll_path(f'python{py_ver}', 2),
  37. )
  38. class Env:
  39. def __init__(self, package_dir):
  40. self.base = package_dir
  41. self.lib_dir = j(self.base, 'lib')
  42. self.py_dir = j(self.lib_dir, f'python{py_ver}')
  43. os.makedirs(self.py_dir)
  44. self.bin_dir = j(self.base, 'bin')
  45. self.obj_dir = mkdtemp('launchers-')
  46. def ignore_in_lib(base, items, ignored_dirs=None):
  47. ans = []
  48. if ignored_dirs is None:
  49. ignored_dirs = {'.svn', '.bzr', '.git', 'test', 'tests', 'testing'}
  50. for name in items:
  51. path = j(base, name)
  52. if os.path.isdir(path):
  53. if name in ignored_dirs or not os.path.exists(j(path, '__init__.py')):
  54. if name != 'plugins':
  55. ans.append(name)
  56. else:
  57. if name.rpartition('.')[-1] not in ('so', 'py'):
  58. ans.append(name)
  59. return ans
  60. def import_site_packages(srcdir, dest):
  61. if not os.path.exists(dest):
  62. os.mkdir(dest)
  63. for x in os.listdir(srcdir):
  64. ext = x.rpartition('.')[-1]
  65. f = j(srcdir, x)
  66. if ext in ('py', 'so'):
  67. shutil.copy2(f, dest)
  68. elif ext == 'pth' and x != 'setuptools.pth':
  69. for line in open(f):
  70. src = os.path.abspath(j(srcdir, line))
  71. if os.path.exists(src) and os.path.isdir(src):
  72. import_site_packages(src, dest)
  73. elif os.path.exists(j(f, '__init__.py')):
  74. shutil.copytree(f, j(dest, x), ignore=ignore_in_lib)
  75. def copy_libs(env):
  76. print('Copying libs...')
  77. for x in binary_includes():
  78. dest = env.bin_dir if '/bin/' in x else env.lib_dir
  79. shutil.copy2(x, dest)
  80. dest = os.path.join(dest, os.path.basename(x))
  81. subprocess.check_call(['chrpath', '-d', dest])
  82. def add_ca_certs(env):
  83. print('Downloading CA certs...')
  84. from urllib.request import urlopen
  85. cdata = urlopen(kitty_constants['cacerts_url']).read()
  86. dest = os.path.join(env.lib_dir, 'cacert.pem')
  87. with open(dest, 'wb') as f:
  88. f.write(cdata)
  89. def copy_python(env):
  90. print('Copying python...')
  91. srcdir = j(PREFIX, f'lib/python{py_ver}')
  92. for x in os.listdir(srcdir):
  93. y = j(srcdir, x)
  94. ext = os.path.splitext(x)[1]
  95. if os.path.isdir(y) and x not in ('test', 'hotshot', 'distutils', 'tkinter', 'turtledemo',
  96. 'site-packages', 'idlelib', 'lib2to3', 'dist-packages'):
  97. shutil.copytree(y, j(env.py_dir, x), ignore=ignore_in_lib)
  98. if os.path.isfile(y) and ext in ('.py', '.so'):
  99. shutil.copy2(y, env.py_dir)
  100. srcdir = j(srcdir, 'site-packages')
  101. import_site_packages(srcdir, env.py_dir)
  102. pdir = os.path.join(env.lib_dir, 'kitty-extensions')
  103. os.makedirs(pdir, exist_ok=True)
  104. kitty_dir = os.path.join(env.lib_dir, 'kitty')
  105. bases = ('kitty', 'kittens', 'kitty_tests')
  106. for x in bases:
  107. dest = os.path.join(env.py_dir, x)
  108. os.rename(os.path.join(kitty_dir, x), dest)
  109. if x == 'kitty':
  110. shutil.rmtree(os.path.join(dest, 'launcher'))
  111. os.rename(os.path.join(kitty_dir, '__main__.py'), os.path.join(env.py_dir, 'kitty_main.py'))
  112. shutil.rmtree(os.path.join(kitty_dir, '__pycache__'))
  113. print('Extracting extension modules from', env.py_dir, 'to', pdir)
  114. ext_map = extract_extension_modules(env.py_dir, pdir)
  115. shutil.copy(os.path.join(os.path.dirname(self_dir), 'site.py'), os.path.join(env.py_dir, 'site.py'))
  116. for x in bases:
  117. iv['sanitize_source_folder'](os.path.join(env.py_dir, x))
  118. py_compile(env.py_dir)
  119. freeze_python(env.py_dir, pdir, env.obj_dir, ext_map, develop_mode_env_var='KITTY_DEVELOP_FROM', remove_pyc_files=True)
  120. shutil.rmtree(env.py_dir)
  121. def build_launcher(env):
  122. iv['build_frozen_launcher']([path_to_freeze_dir(), env.obj_dir])
  123. def is_elf(path):
  124. with open(path, 'rb') as f:
  125. return f.read(4) == b'\x7fELF'
  126. def fix_permissions(files):
  127. for path in files:
  128. os.chmod(path, 0o755)
  129. STRIPCMD = ['strip']
  130. def find_binaries(env):
  131. files = {j(env.bin_dir, x) for x in os.listdir(env.bin_dir)} | {
  132. x for x in {
  133. j(os.path.dirname(env.bin_dir), x) for x in os.listdir(env.bin_dir)} if os.path.exists(x)}
  134. for x in walk(env.lib_dir):
  135. x = os.path.realpath(x)
  136. if x not in files and is_elf(x):
  137. files.add(x)
  138. return files
  139. def strip_files(files, argv_max=(256 * 1024)):
  140. """ Strip a list of files """
  141. while files:
  142. cmd = list(STRIPCMD)
  143. pathlen = sum(len(s) + 1 for s in cmd)
  144. while pathlen < argv_max and files:
  145. f = files.pop()
  146. cmd.append(f)
  147. pathlen += len(f) + 1
  148. if len(cmd) > len(STRIPCMD):
  149. all_files = cmd[len(STRIPCMD):]
  150. unwritable_files = tuple(filter(None, (None if os.access(x, os.W_OK) else (x, os.stat(x).st_mode) for x in all_files)))
  151. [os.chmod(x, stat.S_IWRITE | old_mode) for x, old_mode in unwritable_files]
  152. subprocess.check_call(cmd)
  153. [os.chmod(x, old_mode) for x, old_mode in unwritable_files]
  154. def strip_binaries(files):
  155. print(f'Stripping {len(files)} files...')
  156. before = sum(os.path.getsize(x) for x in files)
  157. strip_files(files)
  158. after = sum(os.path.getsize(x) for x in files)
  159. print('Stripped {:.1f} MB'.format((before - after) / (1024 * 1024.)))
  160. def create_tarfile(env, compression_level='9'):
  161. print('Creating archive...')
  162. base = OUTPUT_DIR
  163. try:
  164. shutil.rmtree(base)
  165. except OSError as err:
  166. if err.errno != errno.ENOENT:
  167. raise
  168. os.mkdir(base)
  169. dist = os.path.join(base, f'{kitty_constants["appname"]}-{kitty_constants["version"]}-{arch}.tar')
  170. with tarfile.open(dist, mode='w', format=tarfile.PAX_FORMAT) as tf:
  171. cwd = os.getcwd()
  172. os.chdir(env.base)
  173. try:
  174. for x in os.listdir('.'):
  175. tf.add(x)
  176. finally:
  177. os.chdir(cwd)
  178. print('Compressing archive...')
  179. ans = f'{dist.rpartition(".")[0]}.txz'
  180. start_time = time.time()
  181. subprocess.check_call(['xz', '--verbose', '--threads=0', '-f', f'-{compression_level}', dist])
  182. secs = time.time() - start_time
  183. print('Compressed in {} minutes {} seconds'.format(secs // 60, secs % 60))
  184. os.rename(f'{dist}.xz', ans)
  185. print('Archive {} created: {:.2f} MB'.format(
  186. os.path.basename(ans), os.stat(ans).st_size / (1024.**2)))
  187. def main():
  188. args = globals()['args']
  189. ext_dir = globals()['ext_dir']
  190. env = Env(os.path.join(ext_dir, kitty_constants['appname']))
  191. copy_libs(env)
  192. copy_python(env)
  193. build_launcher(env)
  194. files = find_binaries(env)
  195. fix_permissions(files)
  196. add_ca_certs(env)
  197. kitty_exe = os.path.join(env.base, 'bin', 'kitty')
  198. iv['build_frozen_tools'](kitty_exe)
  199. if not args.dont_strip:
  200. strip_binaries(files)
  201. if not args.skip_tests:
  202. iv['run_tests'](kitty_exe)
  203. create_tarfile(env, args.compression_level)
  204. if __name__ == '__main__':
  205. main()