relocate.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. HOST_LIB = HOST_PREFIX + '/lib'
  119. HOST_PKG = HOST_LIB + '/' + PYTHON_X_Y
  120. PYTHON_PREFIX = APPDIR + '/opt/' + PYTHON_X_Y
  121. PYTHON_BIN = PYTHON_PREFIX + '/bin'
  122. PYTHON_INC = PYTHON_PREFIX + '/include/' + PYTHON_X_Y
  123. PYTHON_LIB = PYTHON_PREFIX + '/lib'
  124. PYTHON_PKG = PYTHON_LIB + '/' + PYTHON_X_Y
  125. if not os.path.exists(HOST_INC):
  126. HOST_INC += 'm'
  127. PYTHON_INC += 'm'
  128. # Copy the running Python's install
  129. log('CLONE', '%s from %s', PYTHON_X_Y, HOST_PREFIX)
  130. source = HOST_BIN + '/' + PYTHON_X_Y
  131. if not os.path.exists(source):
  132. raise ValueError('could not find {0:} executable'.format(PYTHON_X_Y))
  133. make_tree(PYTHON_BIN)
  134. target = PYTHON_BIN + '/' + PYTHON_X_Y
  135. copy_file(source, target, update=True)
  136. relpath = os.path.relpath(target, APPDIR_BIN)
  137. make_tree(APPDIR_BIN)
  138. os.symlink(relpath, APPDIR_BIN + '/' + PYTHON_X_Y)
  139. copy_tree(HOST_PKG, PYTHON_PKG)
  140. copy_tree(HOST_INC, PYTHON_INC)
  141. pip_source = HOST_BIN + '/' + PIP_X_Y
  142. if not os.path.exists(pip_source):
  143. pip_source = HOST_BIN + '/' + PIP_X
  144. if os.path.exists(pip_source):
  145. with open(pip_source) as f:
  146. f.readline()
  147. body = f.read()
  148. target = PYTHON_BIN + '/' + PIP_X_Y
  149. with open(target, 'w') as f:
  150. f.write('#! /bin/sh\n')
  151. f.write(' '.join((
  152. '"exec"',
  153. '"$(dirname $(readlink -f ${0}))/' + PYTHON_X_Y + '"',
  154. '"$0"',
  155. '"$@"\n'
  156. )))
  157. f.write(body)
  158. shutil.copymode(pip_source, target)
  159. relpath = os.path.relpath(target, APPDIR_BIN)
  160. os.symlink(relpath, APPDIR_BIN + '/' + PIP_X_Y)
  161. # Remove unrelevant files
  162. log('PRUNE', '%s packages', PYTHON_X_Y)
  163. remove_file(PYTHON_LIB + '/lib' + PYTHON_X_Y + '.a')
  164. remove_tree(PYTHON_PKG + '/test')
  165. remove_file(PYTHON_PKG + '/dist-packages')
  166. matches = glob.glob(PYTHON_PKG + '/config-*-linux-*')
  167. for path in matches:
  168. remove_tree(path)
  169. # Set or update symlinks to python
  170. pythons = glob.glob(APPDIR_BIN + '/python?.*')
  171. versions = [os.path.basename(python)[6:] for python in pythons]
  172. latest2, latest3 = '0.0', '0.0'
  173. for version in versions:
  174. if version.startswith('2') and version >= latest2:
  175. latest2 = version
  176. elif version.startswith('3') and version >= latest3:
  177. latest3 = version
  178. if latest2 == VERSION:
  179. python2 = APPDIR_BIN + '/python2'
  180. remove_file(python2)
  181. os.symlink(PYTHON_X_Y, python2)
  182. has_pip = os.path.exists(APPDIR_BIN + '/' + PIP_X_Y)
  183. if has_pip:
  184. pip2 = APPDIR_BIN + '/pip2'
  185. remove_file(pip2)
  186. os.symlink(PIP_X_Y, pip2)
  187. if latest3 == '0.0':
  188. log('SYMLINK', 'python, python2 to ' + PYTHON_X_Y)
  189. python = APPDIR_BIN + '/python'
  190. remove_file(python)
  191. os.symlink('python2', python)
  192. if has_pip:
  193. log('SYMLINK', 'pip, pip2 to ' + PIP_X_Y)
  194. pip = APPDIR_BIN + '/pip'
  195. remove_file(pip)
  196. os.symlink('pip2', pip)
  197. else:
  198. log('SYMLINK', 'python2 to ' + PYTHON_X_Y)
  199. if has_pip:
  200. log('SYMLINK', 'pip2 to ' + PIP_X_Y)
  201. elif latest3 == VERSION:
  202. log('SYMLINK', 'python, python3 to ' + PYTHON_X_Y)
  203. python3 = APPDIR_BIN + '/python3'
  204. remove_file(python3)
  205. os.symlink(PYTHON_X_Y, python3)
  206. python = APPDIR_BIN + '/python'
  207. remove_file(python)
  208. os.symlink('python3', python)
  209. if os.path.exists(APPDIR_BIN + '/' + PIP_X_Y):
  210. log('SYMLINK', 'pip, pip3 to ' + PIP_X_Y)
  211. pip3 = APPDIR_BIN + '/pip3'
  212. remove_file(pip3)
  213. os.symlink(PIP_X_Y, pip3)
  214. pip = APPDIR_BIN + '/pip'
  215. remove_file(pip)
  216. os.symlink('pip3', pip)
  217. # Set a hook in Python for cleaning the path detection
  218. log('HOOK', '%s site packages', PYTHON_X_Y)
  219. sitepkgs = PYTHON_PKG + '/site-packages'
  220. make_tree(sitepkgs)
  221. copy_file(PREFIX + '/data/sitecustomize.py', sitepkgs)
  222. # Set RPATHs and bundle external libraries
  223. log('LINK', '%s C-extensions', PYTHON_X_Y)
  224. make_tree(APPDIR_LIB)
  225. patch_binary(PYTHON_BIN + '/' + PYTHON_X_Y, APPDIR_LIB, recursive=False)
  226. for root, dirs, files in os.walk(PYTHON_PKG + '/lib-dynload'):
  227. for file_ in files:
  228. if not file_.endswith('.so'):
  229. continue
  230. patch_binary(os.path.join(root, file_), APPDIR_LIB, recursive=False)
  231. for file_ in glob.iglob(APPDIR_LIB + '/lib*.so*'):
  232. patch_binary(file_, APPDIR_LIB, recursive=True)
  233. # Copy shared data for TCl/Tk
  234. tk_version = _get_tk_version(PYTHON_PKG)
  235. if tk_version is not None:
  236. tcltkdir = APPDIR_SHARE + '/tcltk'
  237. if (not os.path.exists(tcltkdir + '/tcl' + tk_version)) or \
  238. (not os.path.exists(tcltkdir + '/tk' + tk_version)):
  239. hostdir = '/usr/share/tcltk'
  240. if os.path.exists(hostdir):
  241. make_tree(APPDIR_SHARE)
  242. copy_tree(hostdir, tcltkdir)
  243. else:
  244. make_tree(tcltkdir)
  245. tclpath = '/usr/share/tcl' + tk_version
  246. if not tclpath:
  247. raise ValueError('could not find ' + tclpath)
  248. copy_tree(tclpath, tcltkdir + '/tcl' + tk_version)
  249. tkpath = '/usr/share/tk' + tk_version
  250. if not tkpath:
  251. raise ValueError('could not find ' + tkpath)
  252. copy_tree(tkpath, tcltkdir + '/tk' + tk_version)
  253. # Copy any SSL certificate
  254. cert_file = os.getenv('SSL_CERT_FILE')
  255. if cert_file:
  256. # Package certificates as well for SSL
  257. # (see https://github.com/niess/python-appimage/issues/24)
  258. dirname, basename = os.path.split(cert_file)
  259. make_tree('AppDir' + dirname)
  260. copy_file(cert_file, 'AppDir' + cert_file)
  261. log('INSTALL', basename)
  262. # Bundle the entry point
  263. apprun = APPDIR + '/AppRun'
  264. if not os.path.exists(apprun):
  265. log('INSTALL', 'AppRun')
  266. entrypoint_path = PREFIX + '/data/entrypoint.sh'
  267. entrypoint = load_template(entrypoint_path, python=PYTHON_X_Y)
  268. dictionary = {'entrypoint': entrypoint,
  269. 'shebang': '#! /bin/bash',
  270. 'tcltk-env': tcltk_env_string(PYTHON_PKG),
  271. 'cert-file': cert_file_env_string(cert_file)}
  272. _copy_template('apprun.sh', apprun, **dictionary)
  273. # Bundle the desktop file
  274. desktop_name = 'python{:}.desktop'.format(FULLVERSION)
  275. desktop = os.path.join(APPDIR, desktop_name)
  276. if not os.path.exists(desktop):
  277. log('INSTALL', desktop_name)
  278. apps = 'usr/share/applications'
  279. appfile = '{:}/{:}/python{:}.desktop'.format(APPDIR, apps, FULLVERSION)
  280. if not os.path.exists(appfile):
  281. make_tree(os.path.join(APPDIR, apps))
  282. _copy_template('python.desktop', appfile, version=VERSION,
  283. fullversion=FULLVERSION)
  284. os.symlink(os.path.join(apps, desktop_name), desktop)
  285. # Bundle icons
  286. icons = 'usr/share/icons/hicolor/256x256/apps'
  287. icon = os.path.join(APPDIR, 'python.png')
  288. if not os.path.exists(icon):
  289. log('INSTALL', 'python.png')
  290. make_tree(os.path.join(APPDIR, icons))
  291. copy_file(PREFIX + '/data/python.png',
  292. os.path.join(APPDIR, icons, 'python.png'))
  293. os.symlink(os.path.join(icons, 'python.png'), icon)
  294. diricon = os.path.join(APPDIR, '.DirIcon')
  295. if not os.path.exists(diricon):
  296. os.symlink('python.png', diricon)
  297. # Bundle metadata
  298. meta_name = 'python{:}.appdata.xml'.format(FULLVERSION)
  299. meta_dir = os.path.join(APPDIR, 'usr/share/metainfo')
  300. meta_file = os.path.join(meta_dir, meta_name)
  301. if not os.path.exists(meta_file):
  302. log('INSTALL', meta_name)
  303. make_tree(meta_dir)
  304. _copy_template('python.appdata.xml', meta_file, version=VERSION,
  305. fullversion=FULLVERSION)