msubprojects.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import os, subprocess
  2. import argparse
  3. from . import mlog
  4. from .mesonlib import git, Popen_safe
  5. from .wrap.wrap import API_ROOT, PackageDefinition, Resolver, WrapException
  6. from .wrap import wraptool
  7. def update_wrapdb_file(wrap, repo_dir, options):
  8. patch_url = wrap.get('patch_url')
  9. branch, revision = wraptool.parse_patch_url(patch_url)
  10. new_branch, new_revision = wraptool.get_latest_version(wrap.name)
  11. if new_branch == branch and new_revision == revision:
  12. mlog.log(' -> Up to date.')
  13. return
  14. wraptool.update_wrap_file(wrap.filename, wrap.name, new_branch, new_revision)
  15. msg = [' -> New wrap file downloaded.']
  16. # Meson reconfigure won't use the new wrap file as long as the source
  17. # directory exists. We don't delete it ourself to avoid data loss in case
  18. # user has changes in their copy.
  19. if os.path.isdir(repo_dir):
  20. msg += ['To use it, delete', mlog.bold(repo_dir), 'and run', mlog.bold('meson --reconfigure')]
  21. mlog.log(*msg)
  22. def update_file(wrap, repo_dir, options):
  23. patch_url = wrap.values.get('patch_url', '')
  24. if patch_url.startswith(API_ROOT):
  25. update_wrapdb_file(wrap, repo_dir, options)
  26. elif not os.path.isdir(repo_dir):
  27. # The subproject is not needed, or it is a tarball extracted in
  28. # 'libfoo-1.0' directory and the version has been bumped and the new
  29. # directory is 'libfoo-2.0'. In that case forcing a meson
  30. # reconfigure will download and use the new tarball.
  31. mlog.log(' -> Subproject has not been checked out. Run', mlog.bold('meson --reconfigure'), 'to fetch it if needed.')
  32. else:
  33. # The subproject has not changed, or the new source and/or patch
  34. # tarballs should be extracted in the same directory than previous
  35. # version.
  36. mlog.log(' -> Subproject has not changed, or the new source/patch needs to be extracted on the same location.\n' +
  37. ' In that case, delete', mlog.bold(repo_dir), 'and run', mlog.bold('meson --reconfigure'))
  38. def git_output(cmd, workingdir):
  39. return git(cmd, workingdir, check=True, universal_newlines=True,
  40. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout
  41. def git_show(repo_dir):
  42. commit_message = git_output(['show', '--quiet', '--pretty=format:%h%n%d%n%s%n[%an]'], repo_dir)
  43. parts = [s.strip() for s in commit_message.split('\n')]
  44. mlog.log(' ->', mlog.yellow(parts[0]), mlog.red(parts[1]), parts[2], mlog.blue(parts[3]))
  45. def update_git(wrap, repo_dir, options):
  46. if not os.path.isdir(repo_dir):
  47. mlog.log(' -> Not used.')
  48. return
  49. revision = wrap.get('revision')
  50. ret = git_output(['rev-parse', '--abbrev-ref', 'HEAD'], repo_dir).strip()
  51. if ret == 'HEAD':
  52. try:
  53. # We are currently in detached mode, just checkout the new revision
  54. git_output(['fetch'], repo_dir)
  55. git_output(['checkout', revision], repo_dir)
  56. except subprocess.CalledProcessError as e:
  57. out = e.output.strip()
  58. mlog.log(' -> Could not checkout revision', mlog.cyan(revision))
  59. mlog.log(mlog.red(out))
  60. mlog.log(mlog.red(str(e)))
  61. return
  62. elif ret == revision:
  63. try:
  64. # We are in the same branch, pull latest commits
  65. git_output(['-c', 'rebase.autoStash=true', 'pull', '--rebase'], repo_dir)
  66. except subprocess.CalledProcessError as e:
  67. out = e.output.strip()
  68. mlog.log(' -> Could not rebase', mlog.bold(repo_dir), 'please fix and try again.')
  69. mlog.log(mlog.red(out))
  70. mlog.log(mlog.red(str(e)))
  71. return
  72. else:
  73. # We are in another branch, probably user created their own branch and
  74. # we should rebase it on top of wrap's branch.
  75. if options.rebase:
  76. try:
  77. git_output(['fetch'], repo_dir)
  78. git_output(['-c', 'rebase.autoStash=true', 'rebase', revision], repo_dir)
  79. except subprocess.CalledProcessError as e:
  80. out = e.output.strip()
  81. mlog.log(' -> Could not rebase', mlog.bold(repo_dir), 'please fix and try again.')
  82. mlog.log(mlog.red(out))
  83. mlog.log(mlog.red(str(e)))
  84. return
  85. else:
  86. mlog.log(' -> Target revision is', mlog.bold(revision), 'but currently in branch is', mlog.bold(ret), '\n' +
  87. ' To rebase your branch on top of', mlog.bold(revision), 'use', mlog.bold('--rebase'), 'option.')
  88. return
  89. git_output(['submodule', 'update', '--checkout', '--recursive'], repo_dir)
  90. git_show(repo_dir)
  91. def update_hg(wrap, repo_dir, options):
  92. if not os.path.isdir(repo_dir):
  93. mlog.log(' -> Not used.')
  94. return
  95. revno = wrap.get('revision')
  96. if revno.lower() == 'tip':
  97. # Failure to do pull is not a fatal error,
  98. # because otherwise you can't develop without
  99. # a working net connection.
  100. subprocess.call(['hg', 'pull'], cwd=repo_dir)
  101. else:
  102. if subprocess.call(['hg', 'checkout', revno], cwd=repo_dir) != 0:
  103. subprocess.check_call(['hg', 'pull'], cwd=repo_dir)
  104. subprocess.check_call(['hg', 'checkout', revno], cwd=repo_dir)
  105. def update_svn(wrap, repo_dir, options):
  106. if not os.path.isdir(repo_dir):
  107. mlog.log(' -> Not used.')
  108. return
  109. revno = wrap.get('revision')
  110. p, out, _ = Popen_safe(['svn', 'info', '--show-item', 'revision', repo_dir])
  111. current_revno = out
  112. if current_revno == revno:
  113. return
  114. if revno.lower() == 'head':
  115. # Failure to do pull is not a fatal error,
  116. # because otherwise you can't develop without
  117. # a working net connection.
  118. subprocess.call(['svn', 'update'], cwd=repo_dir)
  119. else:
  120. subprocess.check_call(['svn', 'update', '-r', revno], cwd=repo_dir)
  121. def update(wrap, repo_dir, options):
  122. mlog.log('Updating {}...'.format(wrap.name))
  123. if wrap.type == 'file':
  124. update_file(wrap, repo_dir, options)
  125. elif wrap.type == 'git':
  126. update_git(wrap, repo_dir, options)
  127. elif wrap.type == 'hg':
  128. update_hg(wrap, repo_dir, options)
  129. elif wrap.type == 'svn':
  130. update_svn(wrap, repo_dir, options)
  131. else:
  132. mlog.log(' -> Cannot update', wrap.type, 'subproject')
  133. def checkout(wrap, repo_dir, options):
  134. if wrap.type != 'git' or not os.path.isdir(repo_dir):
  135. return
  136. branch_name = options.branch_name if options.branch_name else wrap.get('revision')
  137. cmd = ['checkout', branch_name, '--']
  138. if options.b:
  139. cmd.insert(1, '-b')
  140. mlog.log('Checkout {} in {}...'.format(branch_name, wrap.name))
  141. try:
  142. git_output(cmd, repo_dir)
  143. git_show(repo_dir)
  144. except subprocess.CalledProcessError as e:
  145. out = e.output.strip()
  146. mlog.log(' -> ', mlog.red(out))
  147. def download(wrap, repo_dir, options):
  148. mlog.log('Download {}...'.format(wrap.name))
  149. if os.path.isdir(repo_dir):
  150. mlog.log(' -> Already downloaded')
  151. return
  152. try:
  153. r = Resolver(os.path.dirname(repo_dir))
  154. r.resolve(wrap.name, 'meson')
  155. mlog.log(' -> done')
  156. except WrapException as e:
  157. mlog.log(' ->', mlog.red(str(e)))
  158. def foreach(wrap, repo_dir, options):
  159. mlog.log('Executing command in {}'.format(repo_dir))
  160. if not os.path.isdir(repo_dir):
  161. mlog.log(' -> Not downloaded yet')
  162. return
  163. try:
  164. out = subprocess.check_output([options.command] + options.args,
  165. stderr=subprocess.STDOUT,
  166. cwd=repo_dir).decode()
  167. mlog.log(out, end='')
  168. except subprocess.CalledProcessError as e:
  169. err_message = "Command '{}' returned non-zero exit status {}.".format(" ".join(e.cmd), e.returncode)
  170. out = e.output.decode()
  171. mlog.log(' -> ', mlog.red(err_message))
  172. mlog.log(out, end='')
  173. except Exception as e:
  174. mlog.log(' -> ', mlog.red(str(e)))
  175. def add_common_arguments(p):
  176. p.add_argument('--sourcedir', default='.',
  177. help='Path to source directory')
  178. p.add_argument('subprojects', nargs='*',
  179. help='List of subprojects (default: all)')
  180. def add_arguments(parser):
  181. subparsers = parser.add_subparsers(title='Commands', dest='command')
  182. subparsers.required = True
  183. p = subparsers.add_parser('update', help='Update all subprojects from wrap files')
  184. p.add_argument('--rebase', default=False, action='store_true',
  185. help='Rebase your branch on top of wrap\'s revision (git only)')
  186. add_common_arguments(p)
  187. p.set_defaults(subprojects_func=update)
  188. p = subparsers.add_parser('checkout', help='Checkout a branch (git only)')
  189. p.add_argument('-b', default=False, action='store_true',
  190. help='Create a new branch')
  191. p.add_argument('branch_name', nargs='?',
  192. help='Name of the branch to checkout or create (default: revision set in wrap file)')
  193. add_common_arguments(p)
  194. p.set_defaults(subprojects_func=checkout)
  195. p = subparsers.add_parser('download', help='Ensure subprojects are fetched, even if not in use. ' +
  196. 'Already downloaded subprojects are not modified. ' +
  197. 'This can be used to pre-fetch all subprojects and avoid downloads during configure.')
  198. add_common_arguments(p)
  199. p.set_defaults(subprojects_func=download)
  200. p = subparsers.add_parser('foreach', help='Execute a command in each subproject directory.')
  201. p.add_argument('command', metavar='command ...',
  202. help='Command to execute in each subproject directory')
  203. p.add_argument('args', nargs=argparse.REMAINDER,
  204. help=argparse.SUPPRESS)
  205. p.add_argument('--sourcedir', default='.',
  206. help='Path to source directory')
  207. p.set_defaults(subprojects_func=foreach)
  208. def run(options):
  209. src_dir = os.path.relpath(os.path.realpath(options.sourcedir))
  210. if not os.path.isfile(os.path.join(src_dir, 'meson.build')):
  211. mlog.error('Directory', mlog.bold(src_dir), 'does not seem to be a Meson source directory.')
  212. return 1
  213. subprojects_dir = os.path.join(src_dir, 'subprojects')
  214. if not os.path.isdir(subprojects_dir):
  215. mlog.log('Directory', mlog.bold(src_dir), 'does not seem to have subprojects.')
  216. return 0
  217. files = []
  218. if hasattr(options, 'subprojects'):
  219. for name in options.subprojects:
  220. f = os.path.join(subprojects_dir, name + '.wrap')
  221. if not os.path.isfile(f):
  222. mlog.error('Subproject', mlog.bold(name), 'not found.')
  223. return 1
  224. else:
  225. files.append(f)
  226. if not files:
  227. for f in os.listdir(subprojects_dir):
  228. if f.endswith('.wrap'):
  229. files.append(os.path.join(subprojects_dir, f))
  230. for f in files:
  231. wrap = PackageDefinition(f)
  232. directory = wrap.values.get('directory', wrap.name)
  233. repo_dir = os.path.join(subprojects_dir, directory)
  234. options.subprojects_func(wrap, repo_dir, options)
  235. return 0