app.py 7.6 KB

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