app.py 7.9 KB

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