relocate.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import glob
  2. import os
  3. import re
  4. import shutil
  5. import sys
  6. from ..utils.deps import EXCLUDELIST, PATCHELF, PREFIX, ensure_excludelist, \
  7. ensure_patchelf
  8. from ..utils.fs import make_tree, copy_file, copy_tree, remove_file, remove_tree
  9. from ..utils.log import debug, log
  10. from ..utils.system import ldd, system
  11. __all__ = ["patch_binary", "relocate_python"]
  12. _template_pattern = re.compile('[{][{]([^{}]+)[}][}]')
  13. def _copy_template(name, destination, **kwargs):
  14. '''Copy a template file and substitue keywords
  15. '''
  16. debug('COPY', '%s as %s', name, destination)
  17. source = os.path.join(PREFIX, 'data', name)
  18. with open(source) as f:
  19. template = f.read()
  20. def matcher(m):
  21. return kwargs[m.group(1)]
  22. txt = _template_pattern.sub(matcher, template)
  23. with open(destination, 'w') as f:
  24. f.write(txt)
  25. shutil.copymode(source, destination)
  26. _excluded_libs = None
  27. '''Appimage excluded libraries, i.e. assumed to be installed on the host
  28. '''
  29. def patch_binary(path, libdir, recursive=True):
  30. '''Patch the RPATH of a binary and and fetch its dependencies
  31. '''
  32. global _excluded_libs
  33. if _excluded_libs is None:
  34. ensure_excludelist()
  35. excluded = []
  36. with open(EXCLUDELIST) as f:
  37. for line in f:
  38. line = line.strip()
  39. if (not line) or line.startswith('#'):
  40. continue
  41. excluded.append(line.split(' ', 1)[0])
  42. _excluded_libs = excluded
  43. else:
  44. excluded = _excluded_libs
  45. ensure_patchelf()
  46. rpath = '\'' + system(PATCHELF, '--print-rpath', path) + '\''
  47. relpath = os.path.relpath(libdir, os.path.dirname(path))
  48. relpath = '' if relpath == '.' else '/' + relpath
  49. expected = '\'$ORIGIN' + relpath + '\''
  50. if rpath != expected:
  51. system(PATCHELF, '--set-rpath', expected, path)
  52. deps = ldd(path)
  53. for dep in deps:
  54. name = os.path.basename(dep)
  55. if name in excluded:
  56. continue
  57. target = libdir + '/' + name
  58. if not os.path.exists(target):
  59. libname = os.path.basename(dep)
  60. copy_file(dep, target)
  61. if recursive:
  62. patch_binary(target, libdir, recursive=True)
  63. def relocate_python(python=None, appdir=None):
  64. '''Bundle a Python install inside an AppDir
  65. '''
  66. if python is not None:
  67. if not os.path.exists(python):
  68. raise ValueError('could not access ' + python)
  69. if appdir is None:
  70. appdir = 'AppDir'
  71. # Set some key variables & paths
  72. if python:
  73. FULLVERSION = system(python, '-c',
  74. '"import sys; print(\'{:}.{:}.{:}\'.format(*sys.version_info[:3]))"')
  75. FULLVERSION = FULLVERSION.strip()
  76. else:
  77. FULLVERSION = '{:}.{:}.{:}'.format(*sys.version_info[:3])
  78. VERSION = '.'.join(FULLVERSION.split('.')[:2])
  79. PYTHON_X_Y = 'python' + VERSION
  80. APPDIR = os.path.abspath(appdir)
  81. APPDIR_BIN = APPDIR + '/usr/bin'
  82. APPDIR_LIB = APPDIR + '/usr/lib'
  83. APPDIR_SHARE = APPDIR + '/usr/share'
  84. if python:
  85. HOST_PREFIX = system(
  86. python, '-c', '"import sys; print(sys.prefix)"').strip()
  87. else:
  88. HOST_PREFIX = sys.prefix
  89. HOST_BIN = HOST_PREFIX + '/bin'
  90. HOST_INC = HOST_PREFIX + '/include/' + PYTHON_X_Y
  91. if not os.path.exists(HOST_INC):
  92. HOST_INC += 'm'
  93. HOST_LIB = HOST_PREFIX + '/lib'
  94. HOST_PKG = HOST_LIB + '/' + PYTHON_X_Y
  95. PYTHON_PREFIX = APPDIR + '/opt/' + PYTHON_X_Y
  96. PYTHON_BIN = PYTHON_PREFIX + '/bin'
  97. PYTHON_INC = PYTHON_PREFIX + '/include/' + PYTHON_X_Y
  98. PYTHON_LIB = PYTHON_PREFIX + '/lib'
  99. PYTHON_PKG = PYTHON_LIB + '/' + PYTHON_X_Y
  100. # Copy the running Python's install
  101. log('CLONE', '%s from %s', PYTHON_X_Y, HOST_PREFIX)
  102. source = HOST_BIN + '/' + PYTHON_X_Y
  103. if not os.path.exists(source):
  104. raise ValueError('could not find {0:} executable'.format(PYTHON_X_Y))
  105. make_tree(PYTHON_BIN)
  106. target = PYTHON_BIN + '/' + PYTHON_X_Y
  107. copy_file(source, target, update=True)
  108. copy_tree(HOST_PKG, PYTHON_PKG)
  109. copy_tree(HOST_INC, PYTHON_INC)
  110. # Remove unrelevant files
  111. log('PRUNE', '%s packages', PYTHON_X_Y)
  112. remove_file(PYTHON_LIB + '/lib' + PYTHON_X_Y + '.a')
  113. remove_tree(PYTHON_PKG + '/test')
  114. remove_file(PYTHON_PKG + '/dist-packages')
  115. matches = glob.glob(PYTHON_PKG + '/config-*-linux-*')
  116. for path in matches:
  117. remove_tree(path)
  118. # Wrap the Python executable
  119. log('WRAP', '%s executable', PYTHON_X_Y)
  120. with open(PREFIX + '/data/python-wrapper.sh') as f:
  121. text = f.read()
  122. text = text.replace('{{PYTHON}}', PYTHON_X_Y)
  123. make_tree(APPDIR_BIN)
  124. target = APPDIR_BIN + '/' + PYTHON_X_Y
  125. with open(target, 'w') as f:
  126. f.write(text)
  127. shutil.copymode(PYTHON_BIN + '/' + PYTHON_X_Y, target)
  128. # Set a hook in Python for cleaning the path detection
  129. log('HOOK', '%s site packages', PYTHON_X_Y)
  130. sitepkgs = PYTHON_PKG + '/site-packages'
  131. make_tree(sitepkgs)
  132. copy_file(PREFIX + '/data/sitecustomize.py', sitepkgs)
  133. # Set RPATHs and bundle external libraries
  134. log('LINK', '%s C-extensions', PYTHON_X_Y)
  135. make_tree(APPDIR_LIB)
  136. patch_binary(PYTHON_BIN + '/' + PYTHON_X_Y, APPDIR_LIB, recursive=False)
  137. for root, dirs, files in os.walk(PYTHON_PKG + '/lib-dynload'):
  138. for file_ in files:
  139. if not file_.endswith('.so'):
  140. continue
  141. patch_binary(os.path.join(root, file_), APPDIR_LIB, recursive=False)
  142. for file_ in glob.iglob(APPDIR_LIB + '/lib*.so*'):
  143. patch_binary(file_, APPDIR_LIB, recursive=True)
  144. # Copy shared data for TCl/Tk
  145. tkinter = glob.glob(PYTHON_PKG + '/lib-dynload/_tkinter*.so')
  146. if tkinter:
  147. tkinter = tkinter[0]
  148. for dep in ldd(tkinter):
  149. name = os.path.basename(dep)
  150. if name.startswith('libtk'):
  151. match = re.search('libtk([0-9]+[.][0-9]+)', name)
  152. tk_version = match.group(1)
  153. break
  154. else:
  155. raise RuntimeError('could not guess Tcl/Tk version')
  156. tcltkdir = APPDIR_SHARE + '/tcltk'
  157. if (not os.path.exists(tcltkdir + '/tcl' + tk_version)) or \
  158. (not os.path.exists(tcltkdir + '/tk' + tk_version)):
  159. hostdir = '/usr/share/tcltk'
  160. if os.path.exists(hostdir):
  161. make_tree(APPDIR_SHARE)
  162. copy_tree(hostdir, tcltkdir)
  163. else:
  164. make_tree(tcltkdir)
  165. tclpath = '/usr/share/tcl' + tk_version
  166. if not tclpath:
  167. raise ValueError('could not find ' + tclpath)
  168. copy_tree(tclpath, tcltkdir + '/tcl' + tk_version)
  169. tkpath = '/usr/share/tk' + tk_version
  170. if not tkpath:
  171. raise ValueError('could not find ' + tkpath)
  172. copy_tree(tkpath, tcltkdir + '/tk' + tk_version)
  173. # Bundle the entry point
  174. apprun = APPDIR + '/AppRun'
  175. if not os.path.exists(apprun):
  176. log('INSTALL', 'AppRun')
  177. _copy_template('apprun.sh', apprun, version=VERSION)
  178. # Bundle the desktop file
  179. desktop_name = 'python{:}.desktop'.format(FULLVERSION)
  180. desktop = os.path.join(APPDIR, desktop_name)
  181. if not os.path.exists(desktop):
  182. log('INSTALL', desktop_name)
  183. apps = 'usr/share/applications'
  184. appfile = '{:}/{:}/python{:}.desktop'.format(APPDIR, apps, FULLVERSION)
  185. if not os.path.exists(appfile):
  186. make_tree(os.path.join(APPDIR, apps))
  187. _copy_template('python.desktop', appfile, version=VERSION,
  188. fullversion=FULLVERSION)
  189. os.symlink(os.path.join(apps, desktop_name), desktop)
  190. # Bundle icons
  191. icons = 'usr/share/icons/hicolor/256x256/apps'
  192. icon = os.path.join(APPDIR, 'python.png')
  193. if not os.path.exists(icon):
  194. log('INSTALL', 'python.png')
  195. make_tree(os.path.join(APPDIR, icons))
  196. copy_file(PREFIX + '/data/python.png',
  197. os.path.join(APPDIR, icons, 'python.png'))
  198. os.symlink(os.path.join(icons, 'python.png'), icon)
  199. diricon = os.path.join(APPDIR, '.DirIcon')
  200. if not os.path.exists(diricon):
  201. os.symlink('python.png', diricon)
  202. # Bundle metadata
  203. meta_name = 'python{:}.appdata.xml'.format(FULLVERSION)
  204. meta_dir = os.path.join(APPDIR, 'usr/share/metainfo')
  205. meta_file = os.path.join(meta_dir, meta_name)
  206. if not os.path.exists(meta_file):
  207. log('INSTALL', meta_name)
  208. make_tree(meta_dir)
  209. _copy_template('python.appdata.xml', meta_file, version=VERSION,
  210. fullversion=FULLVERSION)