relocate.py 12 KB

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