relocate.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 copy_file, copy_tree, make_tree, remove_file, remove_tree
  9. from ..utils.log import debug, log
  10. from ..utils.system import ldd, system
  11. from ..utils.template import copy_template, load_template
  12. __all__ = ["patch_binary", "relocate_python", "tcltk_env_string"]
  13. def _copy_template(name, destination, **kwargs):
  14. path = os.path.join(PREFIX, 'data', name)
  15. copy_template(path, destination, **kwargs)
  16. def _get_tk_version(python_pkg):
  17. tkinter = glob.glob(python_pkg + '/lib-dynload/_tkinter*.so')
  18. if tkinter:
  19. tkinter = tkinter[0]
  20. for dep in ldd(tkinter):
  21. name = os.path.basename(dep)
  22. if name.startswith('libtk'):
  23. match = re.search('libtk([0-9]+[.][0-9]+)', name)
  24. return match.group(1)
  25. else:
  26. raise RuntimeError('could not guess Tcl/Tk version')
  27. def tcltk_env_string(python_pkg):
  28. '''Environment for using AppImage's TCl/Tk
  29. '''
  30. tk_version = _get_tk_version(python_pkg)
  31. if tk_version:
  32. return '''
  33. # Export TCl/Tk
  34. export TCL_LIBRARY="${{APPDIR}}/usr/share/tcltk/tcl{tk_version:}"
  35. export TK_LIBRARY="${{APPDIR}}/usr/share/tcltk/tk{tk_version:}"
  36. export TKPATH="${{TK_LIBRARY}}"'''.format(
  37. tk_version=tk_version)
  38. else:
  39. return ''
  40. def cert_file_env_string(cert_file):
  41. '''Environment for using a bundled certificate
  42. '''
  43. if cert_file:
  44. return '''
  45. # Export SSL certificate
  46. export SSL_CERT_FILE="${{APPDIR}}{cert_file:}"'''.format(
  47. cert_file=cert_file)
  48. else:
  49. return ''
  50. _excluded_libs = None
  51. '''Appimage excluded libraries, i.e. assumed to be installed on the host
  52. '''
  53. def patch_binary(path, libdir, recursive=True):
  54. '''Patch the RPATH of a binary and and fetch its dependencies
  55. '''
  56. global _excluded_libs
  57. if _excluded_libs is None:
  58. ensure_excludelist()
  59. excluded = []
  60. with open(EXCLUDELIST) as f:
  61. for line in f:
  62. line = line.strip()
  63. if (not line) or line.startswith('#'):
  64. continue
  65. excluded.append(line.split(' ', 1)[0])
  66. _excluded_libs = excluded
  67. else:
  68. excluded = _excluded_libs
  69. ensure_patchelf()
  70. rpath = '\'' + system((PATCHELF, '--print-rpath', path)) + '\''
  71. relpath = os.path.relpath(libdir, os.path.dirname(path))
  72. relpath = '' if relpath == '.' else '/' + relpath
  73. expected = '\'$ORIGIN' + relpath + '\''
  74. if rpath != expected:
  75. system((PATCHELF, '--set-rpath', expected, path))
  76. deps = ldd(path)
  77. for dep in deps:
  78. name = os.path.basename(dep)
  79. if name in excluded:
  80. continue
  81. target = libdir + '/' + name
  82. if not os.path.exists(target):
  83. libname = os.path.basename(dep)
  84. copy_file(dep, target)
  85. if recursive:
  86. patch_binary(target, libdir, recursive=True)
  87. def relocate_python(python=None, appdir=None):
  88. '''Bundle a Python install inside an AppDir
  89. '''
  90. if python is not None:
  91. if not os.path.exists(python):
  92. raise ValueError('could not access ' + python)
  93. if appdir is None:
  94. appdir = 'AppDir'
  95. # Set some key variables & paths
  96. if python:
  97. FULLVERSION = system((python, '-c',
  98. '"import sys; print(\'{:}.{:}.{:}\'.format(*sys.version_info[:3]))"'))
  99. FULLVERSION = FULLVERSION.strip()
  100. else:
  101. FULLVERSION = '{:}.{:}.{:}'.format(*sys.version_info[:3])
  102. VERSION = '.'.join(FULLVERSION.split('.')[:2])
  103. PYTHON_X_Y = 'python' + VERSION
  104. PIP_X_Y = 'pip' + VERSION
  105. PIP_X = 'pip' + VERSION[0]
  106. APPDIR = os.path.abspath(appdir)
  107. APPDIR_BIN = APPDIR + '/usr/bin'
  108. APPDIR_LIB = APPDIR + '/usr/lib'
  109. APPDIR_SHARE = APPDIR + '/usr/share'
  110. if python:
  111. HOST_PREFIX = system((
  112. python, '-c', '"import sys; print(sys.prefix)"')).strip()
  113. else:
  114. HOST_PREFIX = sys.prefix
  115. HOST_BIN = HOST_PREFIX + '/bin'
  116. HOST_INC = HOST_PREFIX + '/include/' + PYTHON_X_Y
  117. if not os.path.exists(HOST_INC):
  118. HOST_INC += 'm'
  119. HOST_LIB = HOST_PREFIX + '/lib'
  120. HOST_PKG = HOST_LIB + '/' + PYTHON_X_Y
  121. PYTHON_PREFIX = APPDIR + '/opt/' + PYTHON_X_Y
  122. PYTHON_BIN = PYTHON_PREFIX + '/bin'
  123. PYTHON_INC = PYTHON_PREFIX + '/include/' + PYTHON_X_Y
  124. PYTHON_LIB = PYTHON_PREFIX + '/lib'
  125. PYTHON_PKG = PYTHON_LIB + '/' + PYTHON_X_Y
  126. # Copy the running Python's install
  127. log('CLONE', '%s from %s', PYTHON_X_Y, HOST_PREFIX)
  128. source = HOST_BIN + '/' + PYTHON_X_Y
  129. if not os.path.exists(source):
  130. raise ValueError('could not find {0:} executable'.format(PYTHON_X_Y))
  131. make_tree(PYTHON_BIN)
  132. target = PYTHON_BIN + '/' + PYTHON_X_Y
  133. copy_file(source, target, update=True)
  134. relpath = os.path.relpath(target, APPDIR_BIN)
  135. make_tree(APPDIR_BIN)
  136. os.symlink(relpath, APPDIR_BIN + '/' + PYTHON_X_Y)
  137. copy_tree(HOST_PKG, PYTHON_PKG)
  138. copy_tree(HOST_INC, PYTHON_INC)
  139. pip_source = HOST_BIN + '/' + PIP_X_Y
  140. if not os.path.exists(pip_source):
  141. pip_source = HOST_BIN + '/' + PIP_X
  142. if os.path.exists(pip_source):
  143. with open(pip_source) as f:
  144. f.readline()
  145. body = f.read()
  146. target = PYTHON_BIN + '/' + PIP_X_Y
  147. with open(target, 'w') as f:
  148. f.write('#! /bin/sh\n')
  149. f.write(' '.join((
  150. '"exec"',
  151. '"$(dirname $(readlink -f ${0}))/' + PYTHON_X_Y + '"',
  152. '"$0"',
  153. '"$@"\n'
  154. )))
  155. f.write(body)
  156. shutil.copymode(pip_source, target)
  157. relpath = os.path.relpath(target, APPDIR_BIN)
  158. os.symlink(relpath, APPDIR_BIN + '/' + PIP_X_Y)
  159. # Remove unrelevant files
  160. log('PRUNE', '%s packages', PYTHON_X_Y)
  161. remove_file(PYTHON_LIB + '/lib' + PYTHON_X_Y + '.a')
  162. remove_tree(PYTHON_PKG + '/test')
  163. remove_file(PYTHON_PKG + '/dist-packages')
  164. matches = glob.glob(PYTHON_PKG + '/config-*-linux-*')
  165. for path in matches:
  166. remove_tree(path)
  167. # Set or update symlinks to python
  168. pythons = glob.glob(APPDIR_BIN + '/python?.*')
  169. versions = [os.path.basename(python)[6:] for python in pythons]
  170. latest2, latest3 = '0.0', '0.0'
  171. for version in versions:
  172. if version.startswith('2') and version >= latest2:
  173. latest2 = version
  174. elif version.startswith('3') and version >= latest3:
  175. latest3 = version
  176. if latest2 == VERSION:
  177. python2 = APPDIR_BIN + '/python2'
  178. remove_file(python2)
  179. os.symlink(PYTHON_X_Y, python2)
  180. has_pip = os.path.exists(APPDIR_BIN + '/' + PIP_X_Y)
  181. if has_pip:
  182. pip2 = APPDIR_BIN + '/pip2'
  183. remove_file(pip2)
  184. os.symlink(PIP_X_Y, pip2)
  185. if latest3 == '0.0':
  186. log('SYMLINK', 'python, python2 to ' + PYTHON_X_Y)
  187. python = APPDIR_BIN + '/python'
  188. remove_file(python)
  189. os.symlink('python2', python)
  190. if has_pip:
  191. log('SYMLINK', 'pip, pip2 to ' + PIP_X_Y)
  192. pip = APPDIR_BIN + '/pip'
  193. remove_file(pip)
  194. os.symlink('pip2', pip)
  195. else:
  196. log('SYMLINK', 'python2 to ' + PYTHON_X_Y)
  197. if has_pip:
  198. log('SYMLINK', 'pip2 to ' + PIP_X_Y)
  199. elif latest3 == VERSION:
  200. log('SYMLINK', 'python, python3 to ' + PYTHON_X_Y)
  201. python3 = APPDIR_BIN + '/python3'
  202. remove_file(python3)
  203. os.symlink(PYTHON_X_Y, python3)
  204. python = APPDIR_BIN + '/python'
  205. remove_file(python)
  206. os.symlink('python3', python)
  207. if os.path.exists(APPDIR_BIN + '/' + PIP_X_Y):
  208. log('SYMLINK', 'pip, pip3 to ' + PIP_X_Y)
  209. pip3 = APPDIR_BIN + '/pip3'
  210. remove_file(pip3)
  211. os.symlink(PIP_X_Y, pip3)
  212. pip = APPDIR_BIN + '/pip'
  213. remove_file(pip)
  214. os.symlink('pip3', pip)
  215. # Set a hook in Python for cleaning the path detection
  216. log('HOOK', '%s site packages', PYTHON_X_Y)
  217. sitepkgs = PYTHON_PKG + '/site-packages'
  218. make_tree(sitepkgs)
  219. copy_file(PREFIX + '/data/sitecustomize.py', sitepkgs)
  220. # Set RPATHs and bundle external libraries
  221. log('LINK', '%s C-extensions', PYTHON_X_Y)
  222. make_tree(APPDIR_LIB)
  223. patch_binary(PYTHON_BIN + '/' + PYTHON_X_Y, APPDIR_LIB, recursive=False)
  224. for root, dirs, files in os.walk(PYTHON_PKG + '/lib-dynload'):
  225. for file_ in files:
  226. if not file_.endswith('.so'):
  227. continue
  228. patch_binary(os.path.join(root, file_), APPDIR_LIB, recursive=False)
  229. for file_ in glob.iglob(APPDIR_LIB + '/lib*.so*'):
  230. patch_binary(file_, APPDIR_LIB, recursive=True)
  231. # Copy shared data for TCl/Tk
  232. tk_version = _get_tk_version(PYTHON_PKG)
  233. if tk_version is not None:
  234. tcltkdir = APPDIR_SHARE + '/tcltk'
  235. if (not os.path.exists(tcltkdir + '/tcl' + tk_version)) or \
  236. (not os.path.exists(tcltkdir + '/tk' + tk_version)):
  237. hostdir = '/usr/share/tcltk'
  238. if os.path.exists(hostdir):
  239. make_tree(APPDIR_SHARE)
  240. copy_tree(hostdir, tcltkdir)
  241. else:
  242. make_tree(tcltkdir)
  243. tclpath = '/usr/share/tcl' + tk_version
  244. if not tclpath:
  245. raise ValueError('could not find ' + tclpath)
  246. copy_tree(tclpath, tcltkdir + '/tcl' + tk_version)
  247. tkpath = '/usr/share/tk' + tk_version
  248. if not tkpath:
  249. raise ValueError('could not find ' + tkpath)
  250. copy_tree(tkpath, tcltkdir + '/tk' + tk_version)
  251. # Copy any SSL certificate
  252. cert_file = os.getenv('SSL_CERT_FILE')
  253. if cert_file:
  254. # Package certificates as well for SSL
  255. # (see https://github.com/niess/python-appimage/issues/24)
  256. dirname, basename = os.path.split(cert_file)
  257. make_tree('AppDir' + dirname)
  258. copy_file(cert_file, 'AppDir' + cert_file)
  259. log('INSTALL', basename)
  260. # Bundle the entry point
  261. apprun = APPDIR + '/AppRun'
  262. if not os.path.exists(apprun):
  263. log('INSTALL', 'AppRun')
  264. entrypoint_path = PREFIX + '/data/entrypoint.sh'
  265. entrypoint = load_template(entrypoint_path, python=PYTHON_X_Y)
  266. dictionary = {'entrypoint': entrypoint,
  267. 'shebang': '#! /bin/bash',
  268. 'tcltk-env': tcltk_env_string(PYTHON_PKG),
  269. 'cert-file': cert_file_env_string(cert_file)}
  270. _copy_template('apprun.sh', apprun, **dictionary)
  271. # Bundle the desktop file
  272. desktop_name = 'python{:}.desktop'.format(FULLVERSION)
  273. desktop = os.path.join(APPDIR, desktop_name)
  274. if not os.path.exists(desktop):
  275. log('INSTALL', desktop_name)
  276. apps = 'usr/share/applications'
  277. appfile = '{:}/{:}/python{:}.desktop'.format(APPDIR, apps, FULLVERSION)
  278. if not os.path.exists(appfile):
  279. make_tree(os.path.join(APPDIR, apps))
  280. _copy_template('python.desktop', appfile, version=VERSION,
  281. fullversion=FULLVERSION)
  282. os.symlink(os.path.join(apps, desktop_name), desktop)
  283. # Bundle icons
  284. icons = 'usr/share/icons/hicolor/256x256/apps'
  285. icon = os.path.join(APPDIR, 'python.png')
  286. if not os.path.exists(icon):
  287. log('INSTALL', 'python.png')
  288. make_tree(os.path.join(APPDIR, icons))
  289. copy_file(PREFIX + '/data/python.png',
  290. os.path.join(APPDIR, icons, 'python.png'))
  291. os.symlink(os.path.join(icons, 'python.png'), icon)
  292. diricon = os.path.join(APPDIR, '.DirIcon')
  293. if not os.path.exists(diricon):
  294. os.symlink('python.png', diricon)
  295. # Bundle metadata
  296. meta_name = 'python{:}.appdata.xml'.format(FULLVERSION)
  297. meta_dir = os.path.join(APPDIR, 'usr/share/metainfo')
  298. meta_file = os.path.join(meta_dir, meta_name)
  299. if not os.path.exists(meta_file):
  300. log('INSTALL', meta_name)
  301. make_tree(meta_dir)
  302. _copy_template('python.appdata.xml', meta_file, version=VERSION,
  303. fullversion=FULLVERSION)