1
0

app.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import json
  2. import glob
  3. import os
  4. import platform
  5. import re
  6. import shutil
  7. import stat
  8. import struct
  9. from ...appimage import build_appimage
  10. from ...utils.compat import decode
  11. from ...utils.deps import PREFIX
  12. from ...utils.fs import copy_file, make_tree, remove_file, remove_tree
  13. from ...utils.log import log
  14. from ...utils.system import system
  15. from ...utils.template import copy_template, load_template
  16. from ...utils.tmp import TemporaryDirectory
  17. from ...utils.url import urlopen, urlretrieve
  18. __all__ = ['execute']
  19. def _unpack_args(args):
  20. '''Unpack command line arguments
  21. '''
  22. return args.appdir, args.name, args.python_version, args.linux_tag, \
  23. args.python_tag
  24. _tag_pattern = re.compile('python([^-]+)[-]([^.]+)[.]AppImage')
  25. def execute(appdir, name=None, python_version=None, linux_tag=None,
  26. python_tag=None):
  27. '''Build a Python application using a base AppImage
  28. '''
  29. # Download releases meta data
  30. content = urlopen(
  31. 'https://api.github.com/repos/niess/python-appimage/releases').read()
  32. releases = json.loads(content.decode())
  33. # Fetch the requested Python version or the latest if no specific version
  34. # was requested
  35. release, version = None, '0.0'
  36. for entry in releases:
  37. tag = entry['tag_name']
  38. if not tag.startswith('python'):
  39. continue
  40. v = tag[6:]
  41. if python_version is None:
  42. if v > version:
  43. release, version = entry, v
  44. elif v == python_version:
  45. release = entry
  46. break
  47. if release is None:
  48. raise ValueError('could not find base image for Python ' +
  49. python_version)
  50. elif python_version is None:
  51. python_version = version
  52. # Check for a suitable image
  53. if linux_tag is None:
  54. linux_tag = 'manylinux1_' + platform.machine()
  55. if python_tag is None:
  56. v = ''.join(version.split('.'))
  57. python_tag = 'cp{0:}-cp{0:}'.format(v)
  58. if version < '3.8':
  59. python_tag += 'm'
  60. target_tag = '-'.join((python_tag, linux_tag))
  61. assets = release['assets']
  62. for asset in assets:
  63. match = _tag_pattern.search(asset['name'])
  64. if str(match.group(2)) == target_tag:
  65. python_fullversion = str(match.group(1))
  66. break
  67. else:
  68. raise ValueError('Could not find base image for tag ' + target_tag)
  69. base_image = asset['browser_download_url']
  70. # Set the dictionary for template files
  71. dictionary = {
  72. 'architecture' : platform.machine(),
  73. 'linux-tag' : linux_tag,
  74. 'python-executable' : '${APPDIR}/usr/bin/python' + python_version,
  75. 'python-fullversion' : python_fullversion,
  76. 'python-tag' : python_tag,
  77. 'python-version' : python_version
  78. }
  79. # Get the list of requirements
  80. requirements_list = []
  81. requirements_path = appdir + '/requirements.txt'
  82. if os.path.exists(requirements_path):
  83. with open(requirements_path) as f:
  84. for line in f:
  85. line = line.strip()
  86. if line.startswith('#'):
  87. continue
  88. requirements_list.append(line)
  89. requirements = sorted(requirements_list)
  90. n = len(requirements)
  91. if n == 0:
  92. requirements = ''
  93. elif n == 1:
  94. requirements = requirements[0]
  95. elif n == 2:
  96. requirements = ' and '.join(requirements)
  97. else:
  98. tmp = ', '.join(requirements[:-1])
  99. requirements = tmp + ' and ' + requirements[-1]
  100. dictionary['requirements'] = requirements
  101. # Build the application
  102. appdir = os.path.realpath(appdir)
  103. pwd = os.getcwd()
  104. with TemporaryDirectory() as tmpdir:
  105. application_name = os.path.basename(appdir)
  106. application_icon = application_name
  107. # Extract the base AppImage
  108. log('EXTRACT', '%s', os.path.basename(base_image))
  109. urlretrieve(base_image, 'base.AppImage')
  110. os.chmod('base.AppImage', stat.S_IRWXU)
  111. system(('./base.AppImage', '--appimage-extract'))
  112. system(('mv', 'squashfs-root', 'AppDir'))
  113. # Bundle the desktop file
  114. desktop_path = glob.glob(appdir + '/*.desktop')
  115. if desktop_path:
  116. desktop_path = desktop_path[0]
  117. name = os.path.basename(desktop_path)
  118. log('BUNDLE', name)
  119. python = 'python' + python_fullversion
  120. remove_file('AppDir/{:}.desktop'.format(python))
  121. remove_file('AppDir/usr/share/applications/{:}.desktop'.format(
  122. python))
  123. relpath = 'usr/share/applications/' + name
  124. copy_template(desktop_path, 'AppDir/' + relpath, **dictionary)
  125. os.symlink(relpath, 'AppDir/' + name)
  126. with open('AppDir/' + relpath) as f:
  127. for line in f:
  128. if line.startswith('Name='):
  129. application_name = line[5:].strip()
  130. elif line.startswith('Icon='):
  131. application_icon = line[5:].strip()
  132. # Bundle the application icon
  133. icon_paths = glob.glob('{:}/{:}.*'.format(appdir, application_icon))
  134. if icon_paths:
  135. for icon_path in icon_paths:
  136. ext = os.path.splitext(icon_path)[1]
  137. if ext in ('.png', '.svg'):
  138. break
  139. else:
  140. icon_path = None
  141. else:
  142. icon_path = None
  143. if icon_path is not None:
  144. name = os.path.basename(icon_path)
  145. log('BUNDLE', name)
  146. remove_file('AppDir/python.png')
  147. remove_tree('AppDir/usr/share/icons/hicolor/256x256')
  148. ext = os.path.splitext(name)[1]
  149. if ext == '.svg':
  150. size = 'scalable'
  151. else:
  152. with open(icon_path, 'rb') as f:
  153. head = f.read(24)
  154. width, height = struct.unpack('>ii', head[16:24])
  155. size = '{:}x{:}'.format(width, height)
  156. relpath = 'usr/share/icons/hicolor/{:}/apps/{:}'.format(size, name)
  157. destination = 'AppDir/' + relpath
  158. make_tree(os.path.dirname(destination))
  159. copy_file(icon_path, destination)
  160. os.symlink(relpath, 'AppDir/' + name)
  161. # Bundle any appdata
  162. meta_path = glob.glob(appdir + '/*.appdata.xml')
  163. if meta_path:
  164. meta_path = meta_path[0]
  165. name = os.path.basename(meta_path)
  166. log('BUNDLE', name)
  167. python = 'python' + python_fullversion
  168. remove_file('AppDir/usr/share/metainfo/{:}.appdata.xml'.format(
  169. python))
  170. relpath = 'usr/share/metainfo/' + name
  171. copy_template(meta_path, 'AppDir/' + relpath, **dictionary)
  172. # Bundle the requirements
  173. if requirements_list:
  174. deprecation = 'DEPRECATION: Python 2.7 reached the end of its life'
  175. system(('./AppDir/AppRun', '-m', 'pip', 'install', '-U',
  176. '--no-warn-script-location', 'pip'), exclude=deprecation)
  177. for requirement in requirements_list:
  178. log('BUNDLE', requirement)
  179. system(('./AppDir/AppRun', '-m', 'pip', 'install', '-U',
  180. '--no-warn-script-location', requirement),
  181. exclude=deprecation)
  182. # Bundle the entry point
  183. entrypoint_path = glob.glob(appdir + '/entrypoint.*')
  184. if entrypoint_path:
  185. entrypoint_path = entrypoint_path[0]
  186. log('BUNDLE', os.path.basename(entrypoint_path))
  187. entrypoint = load_template(entrypoint_path, **dictionary)
  188. copy_template(PREFIX + '/data/apprun.sh', 'AppDir/AppRun',
  189. entrypoint=entrypoint)
  190. # Build the new AppImage
  191. destination = '{:}-{:}.AppImage'.format(application_name,
  192. platform.machine())
  193. build_appimage(destination=destination)
  194. shutil.move(destination, os.path.join(pwd, destination))