upgrade.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. # Development tool - upgrade command plugin
  2. #
  3. # Copyright (C) 2014-2017 Intel Corporation
  4. #
  5. # SPDX-License-Identifier: GPL-2.0-only
  6. #
  7. """Devtool upgrade plugin"""
  8. import os
  9. import sys
  10. import re
  11. import shutil
  12. import tempfile
  13. import logging
  14. import argparse
  15. import scriptutils
  16. import errno
  17. import bb
  18. devtool_path = os.path.dirname(os.path.realpath(__file__)) + '/../../../meta/lib'
  19. sys.path = sys.path + [devtool_path]
  20. import oe.recipeutils
  21. from devtool import standard
  22. from devtool import exec_build_env_command, setup_tinfoil, DevtoolError, parse_recipe, use_external_build, update_unlockedsigs, check_prerelease_version
  23. logger = logging.getLogger('devtool')
  24. def _run(cmd, cwd=''):
  25. logger.debug("Running command %s> %s" % (cwd,cmd))
  26. return bb.process.run('%s' % cmd, cwd=cwd)
  27. def _get_srctree(tmpdir):
  28. srctree = tmpdir
  29. dirs = scriptutils.filter_src_subdirs(tmpdir)
  30. if len(dirs) == 1:
  31. srctree = os.path.join(tmpdir, dirs[0])
  32. return srctree
  33. def _copy_source_code(orig, dest):
  34. for path in standard._ls_tree(orig):
  35. dest_dir = os.path.join(dest, os.path.dirname(path))
  36. bb.utils.mkdirhier(dest_dir)
  37. dest_path = os.path.join(dest, path)
  38. shutil.move(os.path.join(orig, path), dest_path)
  39. def _remove_patch_dirs(recipefolder):
  40. for root, dirs, files in os.walk(recipefolder):
  41. for d in dirs:
  42. shutil.rmtree(os.path.join(root,d))
  43. def _recipe_contains(rd, var):
  44. rf = rd.getVar('FILE')
  45. varfiles = oe.recipeutils.get_var_files(rf, [var], rd)
  46. for var, fn in varfiles.items():
  47. if fn and fn.startswith(os.path.dirname(rf) + os.sep):
  48. return True
  49. return False
  50. def _rename_recipe_dirs(oldpv, newpv, path):
  51. for root, dirs, files in os.walk(path):
  52. # Rename directories with the version in their name
  53. for olddir in dirs:
  54. if olddir.find(oldpv) != -1:
  55. newdir = olddir.replace(oldpv, newpv)
  56. if olddir != newdir:
  57. shutil.move(os.path.join(path, olddir), os.path.join(path, newdir))
  58. # Rename any inc files with the version in their name (unusual, but possible)
  59. for oldfile in files:
  60. if oldfile.endswith('.inc'):
  61. if oldfile.find(oldpv) != -1:
  62. newfile = oldfile.replace(oldpv, newpv)
  63. if oldfile != newfile:
  64. bb.utils.rename(os.path.join(path, oldfile),
  65. os.path.join(path, newfile))
  66. def _rename_recipe_file(oldrecipe, bpn, oldpv, newpv, path):
  67. oldrecipe = os.path.basename(oldrecipe)
  68. if oldrecipe.endswith('_%s.bb' % oldpv):
  69. newrecipe = '%s_%s.bb' % (bpn, newpv)
  70. if oldrecipe != newrecipe:
  71. shutil.move(os.path.join(path, oldrecipe), os.path.join(path, newrecipe))
  72. else:
  73. newrecipe = oldrecipe
  74. return os.path.join(path, newrecipe)
  75. def _rename_recipe_files(oldrecipe, bpn, oldpv, newpv, path):
  76. _rename_recipe_dirs(oldpv, newpv, path)
  77. return _rename_recipe_file(oldrecipe, bpn, oldpv, newpv, path)
  78. def _write_append(rc, srctree, same_dir, no_same_dir, rev, copied, workspace, d):
  79. """Writes an append file"""
  80. if not os.path.exists(rc):
  81. raise DevtoolError("bbappend not created because %s does not exist" % rc)
  82. appendpath = os.path.join(workspace, 'appends')
  83. if not os.path.exists(appendpath):
  84. bb.utils.mkdirhier(appendpath)
  85. brf = os.path.basename(os.path.splitext(rc)[0]) # rc basename
  86. srctree = os.path.abspath(srctree)
  87. pn = d.getVar('PN')
  88. af = os.path.join(appendpath, '%s.bbappend' % brf)
  89. with open(af, 'w') as f:
  90. f.write('FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"\n\n')
  91. f.write('inherit externalsrc\n')
  92. f.write(('# NOTE: We use pn- overrides here to avoid affecting'
  93. 'multiple variants in the case where the recipe uses BBCLASSEXTEND\n'))
  94. f.write('EXTERNALSRC_pn-%s = "%s"\n' % (pn, srctree))
  95. b_is_s = use_external_build(same_dir, no_same_dir, d)
  96. if b_is_s:
  97. f.write('EXTERNALSRC_BUILD_pn-%s = "%s"\n' % (pn, srctree))
  98. f.write('\n')
  99. if rev:
  100. f.write('# initial_rev: %s\n' % rev)
  101. if copied:
  102. f.write('# original_path: %s\n' % os.path.dirname(d.getVar('FILE')))
  103. f.write('# original_files: %s\n' % ' '.join(copied))
  104. return af
  105. def _cleanup_on_error(rf, srctree):
  106. rfp = os.path.split(rf)[0] # recipe folder
  107. rfpp = os.path.split(rfp)[0] # recipes folder
  108. if os.path.exists(rfp):
  109. shutil.rmtree(rfp)
  110. if not len(os.listdir(rfpp)):
  111. os.rmdir(rfpp)
  112. srctree = os.path.abspath(srctree)
  113. if os.path.exists(srctree):
  114. shutil.rmtree(srctree)
  115. def _upgrade_error(e, rf, srctree, keep_failure=False, extramsg=None):
  116. if rf and not keep_failure:
  117. _cleanup_on_error(rf, srctree)
  118. logger.error(e)
  119. if extramsg:
  120. logger.error(extramsg)
  121. if keep_failure:
  122. logger.info('Preserving failed upgrade files (--keep-failure)')
  123. sys.exit(1)
  124. def _get_uri(rd):
  125. srcuris = rd.getVar('SRC_URI').split()
  126. if not len(srcuris):
  127. raise DevtoolError('SRC_URI not found on recipe')
  128. # Get first non-local entry in SRC_URI - usually by convention it's
  129. # the first entry, but not always!
  130. srcuri = None
  131. for entry in srcuris:
  132. if not entry.startswith('file://'):
  133. srcuri = entry
  134. break
  135. if not srcuri:
  136. raise DevtoolError('Unable to find non-local entry in SRC_URI')
  137. srcrev = '${AUTOREV}'
  138. if '://' in srcuri:
  139. # Fetch a URL
  140. rev_re = re.compile(';rev=([^;]+)')
  141. res = rev_re.search(srcuri)
  142. if res:
  143. srcrev = res.group(1)
  144. srcuri = rev_re.sub('', srcuri)
  145. return srcuri, srcrev
  146. def _extract_new_source(newpv, srctree, no_patch, srcrev, srcbranch, branch, keep_temp, tinfoil, rd):
  147. """Extract sources of a recipe with a new version"""
  148. def __run(cmd):
  149. """Simple wrapper which calls _run with srctree as cwd"""
  150. return _run(cmd, srctree)
  151. crd = rd.createCopy()
  152. pv = crd.getVar('PV')
  153. crd.setVar('PV', newpv)
  154. tmpsrctree = None
  155. uri, rev = _get_uri(crd)
  156. if srcrev:
  157. rev = srcrev
  158. if uri.startswith('git://') or uri.startswith('gitsm://'):
  159. __run('git fetch')
  160. __run('git checkout %s' % rev)
  161. __run('git tag -f devtool-base-new')
  162. md5 = None
  163. sha256 = None
  164. _, _, _, _, _, params = bb.fetch2.decodeurl(uri)
  165. srcsubdir_rel = params.get('destsuffix', 'git')
  166. if not srcbranch:
  167. check_branch, check_branch_err = __run('git branch -r --contains %s' % srcrev)
  168. get_branch = [x.strip() for x in check_branch.splitlines()]
  169. # Remove HEAD reference point and drop remote prefix
  170. get_branch = [x.split('/', 1)[1] for x in get_branch if not x.startswith('origin/HEAD')]
  171. if 'master' in get_branch:
  172. # If it is master, we do not need to append 'branch=master' as this is default.
  173. # Even with the case where get_branch has multiple objects, if 'master' is one
  174. # of them, we should default take from 'master'
  175. srcbranch = ''
  176. elif len(get_branch) == 1:
  177. # If 'master' isn't in get_branch and get_branch contains only ONE object, then store result into 'srcbranch'
  178. srcbranch = get_branch[0]
  179. else:
  180. # If get_branch contains more than one objects, then display error and exit.
  181. mbrch = '\n ' + '\n '.join(get_branch)
  182. raise DevtoolError('Revision %s was found on multiple branches: %s\nPlease provide the correct branch in the devtool command with "--srcbranch" or "-B" option.' % (srcrev, mbrch))
  183. else:
  184. __run('git checkout devtool-base -b devtool-%s' % newpv)
  185. tmpdir = tempfile.mkdtemp(prefix='devtool')
  186. try:
  187. checksums, ftmpdir = scriptutils.fetch_url(tinfoil, uri, rev, tmpdir, logger, preserve_tmp=keep_temp)
  188. except scriptutils.FetchUrlFailure as e:
  189. raise DevtoolError(e)
  190. if ftmpdir and keep_temp:
  191. logger.info('Fetch temp directory is %s' % ftmpdir)
  192. md5 = checksums['md5sum']
  193. sha256 = checksums['sha256sum']
  194. tmpsrctree = _get_srctree(tmpdir)
  195. srctree = os.path.abspath(srctree)
  196. srcsubdir_rel = os.path.relpath(tmpsrctree, tmpdir)
  197. # Delete all sources so we ensure no stray files are left over
  198. for item in os.listdir(srctree):
  199. if item in ['.git', 'oe-local-files']:
  200. continue
  201. itempath = os.path.join(srctree, item)
  202. if os.path.isdir(itempath):
  203. shutil.rmtree(itempath)
  204. else:
  205. os.remove(itempath)
  206. # Copy in new ones
  207. _copy_source_code(tmpsrctree, srctree)
  208. (stdout,_) = __run('git ls-files --modified --others')
  209. filelist = stdout.splitlines()
  210. pbar = bb.ui.knotty.BBProgress('Adding changed files', len(filelist))
  211. pbar.start()
  212. batchsize = 100
  213. for i in range(0, len(filelist), batchsize):
  214. batch = filelist[i:i+batchsize]
  215. __run('git add -f -A %s' % ' '.join(['"%s"' % item for item in batch]))
  216. pbar.update(i)
  217. pbar.finish()
  218. useroptions = []
  219. oe.patch.GitApplyTree.gitCommandUserOptions(useroptions, d=rd)
  220. __run('git %s commit -q -m "Commit of upstream changes at version %s" --allow-empty' % (' '.join(useroptions), newpv))
  221. __run('git tag -f devtool-base-%s' % newpv)
  222. (stdout, _) = __run('git rev-parse HEAD')
  223. rev = stdout.rstrip()
  224. if no_patch:
  225. patches = oe.recipeutils.get_recipe_patches(crd)
  226. if patches:
  227. logger.warning('By user choice, the following patches will NOT be applied to the new source tree:\n %s' % '\n '.join([os.path.basename(patch) for patch in patches]))
  228. else:
  229. __run('git checkout devtool-patched -b %s' % branch)
  230. skiptag = False
  231. try:
  232. __run('git rebase %s' % rev)
  233. except bb.process.ExecutionError as e:
  234. skiptag = True
  235. if 'conflict' in e.stdout:
  236. logger.warning('Command \'%s\' failed:\n%s\n\nYou will need to resolve conflicts in order to complete the upgrade.' % (e.command, e.stdout.rstrip()))
  237. else:
  238. logger.warning('Command \'%s\' failed:\n%s' % (e.command, e.stdout))
  239. if not skiptag:
  240. if uri.startswith('git://') or uri.startswith('gitsm://'):
  241. suffix = 'new'
  242. else:
  243. suffix = newpv
  244. __run('git tag -f devtool-patched-%s' % suffix)
  245. if tmpsrctree:
  246. if keep_temp:
  247. logger.info('Preserving temporary directory %s' % tmpsrctree)
  248. else:
  249. shutil.rmtree(tmpsrctree)
  250. if tmpdir != tmpsrctree:
  251. shutil.rmtree(tmpdir)
  252. return (rev, md5, sha256, srcbranch, srcsubdir_rel)
  253. def _add_license_diff_to_recipe(path, diff):
  254. notice_text = """# FIXME: the LIC_FILES_CHKSUM values have been updated by 'devtool upgrade'.
  255. # The following is the difference between the old and the new license text.
  256. # Please update the LICENSE value if needed, and summarize the changes in
  257. # the commit message via 'License-Update:' tag.
  258. # (example: 'License-Update: copyright years updated.')
  259. #
  260. # The changes:
  261. #
  262. """
  263. commented_diff = "\n".join(["# {}".format(l) for l in diff.split('\n')])
  264. with open(path, 'rb') as f:
  265. orig_content = f.read()
  266. with open(path, 'wb') as f:
  267. f.write(notice_text.encode())
  268. f.write(commented_diff.encode())
  269. f.write("\n#\n\n".encode())
  270. f.write(orig_content)
  271. def _create_new_recipe(newpv, md5, sha256, srcrev, srcbranch, srcsubdir_old, srcsubdir_new, workspace, tinfoil, rd, license_diff, new_licenses, srctree, keep_failure):
  272. """Creates the new recipe under workspace"""
  273. bpn = rd.getVar('BPN')
  274. path = os.path.join(workspace, 'recipes', bpn)
  275. bb.utils.mkdirhier(path)
  276. copied, _ = oe.recipeutils.copy_recipe_files(rd, path, all_variants=True)
  277. if not copied:
  278. raise DevtoolError('Internal error - no files were copied for recipe %s' % bpn)
  279. logger.debug('Copied %s to %s' % (copied, path))
  280. oldpv = rd.getVar('PV')
  281. if not newpv:
  282. newpv = oldpv
  283. origpath = rd.getVar('FILE')
  284. fullpath = _rename_recipe_files(origpath, bpn, oldpv, newpv, path)
  285. logger.debug('Upgraded %s => %s' % (origpath, fullpath))
  286. newvalues = {}
  287. if _recipe_contains(rd, 'PV') and newpv != oldpv:
  288. newvalues['PV'] = newpv
  289. if srcrev:
  290. newvalues['SRCREV'] = srcrev
  291. if srcbranch:
  292. src_uri = oe.recipeutils.split_var_value(rd.getVar('SRC_URI', False) or '')
  293. changed = False
  294. replacing = True
  295. new_src_uri = []
  296. for entry in src_uri:
  297. scheme, network, path, user, passwd, params = bb.fetch2.decodeurl(entry)
  298. if replacing and scheme in ['git', 'gitsm']:
  299. branch = params.get('branch', 'master')
  300. if rd.expand(branch) != srcbranch:
  301. # Handle case where branch is set through a variable
  302. res = re.match(r'\$\{([^}@]+)\}', branch)
  303. if res:
  304. newvalues[res.group(1)] = srcbranch
  305. # We know we won't change SRC_URI now, so break out
  306. break
  307. else:
  308. params['branch'] = srcbranch
  309. entry = bb.fetch2.encodeurl((scheme, network, path, user, passwd, params))
  310. changed = True
  311. replacing = False
  312. new_src_uri.append(entry)
  313. if changed:
  314. newvalues['SRC_URI'] = ' '.join(new_src_uri)
  315. newvalues['PR'] = None
  316. # Work out which SRC_URI entries have changed in case the entry uses a name
  317. crd = rd.createCopy()
  318. crd.setVar('PV', newpv)
  319. for var, value in newvalues.items():
  320. crd.setVar(var, value)
  321. old_src_uri = (rd.getVar('SRC_URI') or '').split()
  322. new_src_uri = (crd.getVar('SRC_URI') or '').split()
  323. newnames = []
  324. addnames = []
  325. for newentry in new_src_uri:
  326. _, _, _, _, _, params = bb.fetch2.decodeurl(newentry)
  327. if 'name' in params:
  328. newnames.append(params['name'])
  329. if newentry not in old_src_uri:
  330. addnames.append(params['name'])
  331. # Find what's been set in the original recipe
  332. oldnames = []
  333. noname = False
  334. for varflag in rd.getVarFlags('SRC_URI'):
  335. if varflag.endswith(('.md5sum', '.sha256sum')):
  336. name = varflag.rsplit('.', 1)[0]
  337. if name not in oldnames:
  338. oldnames.append(name)
  339. elif varflag in ['md5sum', 'sha256sum']:
  340. noname = True
  341. # Even if SRC_URI has named entries it doesn't have to actually use the name
  342. if noname and addnames and addnames[0] not in oldnames:
  343. addnames = []
  344. # Drop any old names (the name actually might include ${PV})
  345. for name in oldnames:
  346. if name not in newnames:
  347. newvalues['SRC_URI[%s.md5sum]' % name] = None
  348. newvalues['SRC_URI[%s.sha256sum]' % name] = None
  349. if sha256:
  350. if addnames:
  351. nameprefix = '%s.' % addnames[0]
  352. else:
  353. nameprefix = ''
  354. newvalues['SRC_URI[%smd5sum]' % nameprefix] = None
  355. newvalues['SRC_URI[%ssha256sum]' % nameprefix] = sha256
  356. if srcsubdir_new != srcsubdir_old:
  357. s_subdir_old = os.path.relpath(os.path.abspath(rd.getVar('S')), rd.getVar('WORKDIR'))
  358. s_subdir_new = os.path.relpath(os.path.abspath(crd.getVar('S')), crd.getVar('WORKDIR'))
  359. if srcsubdir_old == s_subdir_old and srcsubdir_new != s_subdir_new:
  360. # Subdir for old extracted source matches what S points to (it should!)
  361. # but subdir for new extracted source doesn't match what S will be
  362. newvalues['S'] = '${WORKDIR}/%s' % srcsubdir_new.replace(newpv, '${PV}')
  363. if crd.expand(newvalues['S']) == crd.expand('${WORKDIR}/${BP}'):
  364. # It's the default, drop it
  365. # FIXME what if S is being set in a .inc?
  366. newvalues['S'] = None
  367. logger.info('Source subdirectory has changed, dropping S value since it now matches the default ("${WORKDIR}/${BP}")')
  368. else:
  369. logger.info('Source subdirectory has changed, updating S value')
  370. if license_diff:
  371. newlicchksum = " ".join(["file://{}".format(l['path']) +
  372. (";beginline={}".format(l['beginline']) if l['beginline'] else "") +
  373. (";endline={}".format(l['endline']) if l['endline'] else "") +
  374. (";md5={}".format(l['actual_md5'])) for l in new_licenses])
  375. newvalues["LIC_FILES_CHKSUM"] = newlicchksum
  376. _add_license_diff_to_recipe(fullpath, license_diff)
  377. try:
  378. rd = tinfoil.parse_recipe_file(fullpath, False)
  379. except bb.tinfoil.TinfoilCommandFailed as e:
  380. _upgrade_error(e, fullpath, srctree, keep_failure, 'Parsing of upgraded recipe failed')
  381. oe.recipeutils.patch_recipe(rd, fullpath, newvalues)
  382. return fullpath, copied
  383. def _check_git_config():
  384. def getconfig(name):
  385. try:
  386. value = bb.process.run('git config --global %s' % name)[0].strip()
  387. except bb.process.ExecutionError as e:
  388. if e.exitcode == 1:
  389. value = None
  390. else:
  391. raise
  392. return value
  393. username = getconfig('user.name')
  394. useremail = getconfig('user.email')
  395. configerr = []
  396. if not username:
  397. configerr.append('Please set your name using:\n git config --global user.name')
  398. if not useremail:
  399. configerr.append('Please set your email using:\n git config --global user.email')
  400. if configerr:
  401. raise DevtoolError('Your git configuration is incomplete which will prevent rebases from working:\n' + '\n'.join(configerr))
  402. def _extract_licenses(srcpath, recipe_licenses):
  403. licenses = []
  404. for url in recipe_licenses.split():
  405. license = {}
  406. (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(url)
  407. license['path'] = path
  408. license['md5'] = parm.get('md5', '')
  409. license['beginline'], license['endline'] = 0, 0
  410. if 'beginline' in parm:
  411. license['beginline'] = int(parm['beginline'])
  412. if 'endline' in parm:
  413. license['endline'] = int(parm['endline'])
  414. license['text'] = []
  415. with open(os.path.join(srcpath, path), 'rb') as f:
  416. import hashlib
  417. actual_md5 = hashlib.md5()
  418. lineno = 0
  419. for line in f:
  420. lineno += 1
  421. if (lineno >= license['beginline']) and ((lineno <= license['endline']) or not license['endline']):
  422. license['text'].append(line.decode(errors='ignore'))
  423. actual_md5.update(line)
  424. license['actual_md5'] = actual_md5.hexdigest()
  425. licenses.append(license)
  426. return licenses
  427. def _generate_license_diff(old_licenses, new_licenses):
  428. need_diff = False
  429. for l in new_licenses:
  430. if l['md5'] != l['actual_md5']:
  431. need_diff = True
  432. break
  433. if need_diff == False:
  434. return None
  435. import difflib
  436. diff = ''
  437. for old, new in zip(old_licenses, new_licenses):
  438. for line in difflib.unified_diff(old['text'], new['text'], old['path'], new['path']):
  439. diff = diff + line
  440. return diff
  441. def upgrade(args, config, basepath, workspace):
  442. """Entry point for the devtool 'upgrade' subcommand"""
  443. if args.recipename in workspace:
  444. raise DevtoolError("recipe %s is already in your workspace" % args.recipename)
  445. if args.srcbranch and not args.srcrev:
  446. raise DevtoolError("If you specify --srcbranch/-B then you must use --srcrev/-S to specify the revision" % args.recipename)
  447. _check_git_config()
  448. tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
  449. try:
  450. rd = parse_recipe(config, tinfoil, args.recipename, True)
  451. if not rd:
  452. return 1
  453. pn = rd.getVar('PN')
  454. if pn != args.recipename:
  455. logger.info('Mapping %s to %s' % (args.recipename, pn))
  456. if pn in workspace:
  457. raise DevtoolError("recipe %s is already in your workspace" % pn)
  458. if args.srctree:
  459. srctree = os.path.abspath(args.srctree)
  460. else:
  461. srctree = standard.get_default_srctree(config, pn)
  462. # try to automatically discover latest version and revision if not provided on command line
  463. if not args.version and not args.srcrev:
  464. version_info = oe.recipeutils.get_recipe_upstream_version(rd)
  465. if version_info['version'] and not version_info['version'].endswith("new-commits-available"):
  466. args.version = version_info['version']
  467. if version_info['revision']:
  468. args.srcrev = version_info['revision']
  469. if not args.version and not args.srcrev:
  470. raise DevtoolError("Automatic discovery of latest version/revision failed - you must provide a version using the --version/-V option, or for recipes that fetch from an SCM such as git, the --srcrev/-S option.")
  471. standard._check_compatible_recipe(pn, rd)
  472. old_srcrev = rd.getVar('SRCREV')
  473. if old_srcrev == 'INVALID':
  474. old_srcrev = None
  475. if old_srcrev and not args.srcrev:
  476. raise DevtoolError("Recipe specifies a SRCREV value; you must specify a new one when upgrading")
  477. old_ver = rd.getVar('PV')
  478. if old_ver == args.version and old_srcrev == args.srcrev:
  479. raise DevtoolError("Current and upgrade versions are the same version")
  480. if args.version:
  481. if bb.utils.vercmp_string(args.version, old_ver) < 0:
  482. logger.warning('Upgrade version %s compares as less than the current version %s. If you are using a package feed for on-target upgrades or providing this recipe for general consumption, then you should increment PE in the recipe (or if there is no current PE value set, set it to "1")' % (args.version, old_ver))
  483. check_prerelease_version(args.version, 'devtool upgrade')
  484. rf = None
  485. license_diff = None
  486. try:
  487. logger.info('Extracting current version source...')
  488. rev1, srcsubdir1 = standard._extract_source(srctree, False, 'devtool-orig', False, config, basepath, workspace, args.fixed_setup, rd, tinfoil, no_overrides=args.no_overrides)
  489. old_licenses = _extract_licenses(srctree, (rd.getVar('LIC_FILES_CHKSUM') or ""))
  490. logger.info('Extracting upgraded version source...')
  491. rev2, md5, sha256, srcbranch, srcsubdir2 = _extract_new_source(args.version, srctree, args.no_patch,
  492. args.srcrev, args.srcbranch, args.branch, args.keep_temp,
  493. tinfoil, rd)
  494. new_licenses = _extract_licenses(srctree, (rd.getVar('LIC_FILES_CHKSUM') or ""))
  495. license_diff = _generate_license_diff(old_licenses, new_licenses)
  496. rf, copied = _create_new_recipe(args.version, md5, sha256, args.srcrev, srcbranch, srcsubdir1, srcsubdir2, config.workspace_path, tinfoil, rd, license_diff, new_licenses, srctree, args.keep_failure)
  497. except bb.process.CmdError as e:
  498. _upgrade_error(e, rf, srctree, args.keep_failure)
  499. except DevtoolError as e:
  500. _upgrade_error(e, rf, srctree, args.keep_failure)
  501. standard._add_md5(config, pn, os.path.dirname(rf))
  502. af = _write_append(rf, srctree, args.same_dir, args.no_same_dir, rev2,
  503. copied, config.workspace_path, rd)
  504. standard._add_md5(config, pn, af)
  505. update_unlockedsigs(basepath, workspace, args.fixed_setup, [pn])
  506. logger.info('Upgraded source extracted to %s' % srctree)
  507. logger.info('New recipe is %s' % rf)
  508. if license_diff:
  509. logger.info('License checksums have been updated in the new recipe; please refer to it for the difference between the old and the new license texts.')
  510. finally:
  511. tinfoil.shutdown()
  512. return 0
  513. def latest_version(args, config, basepath, workspace):
  514. """Entry point for the devtool 'latest_version' subcommand"""
  515. tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
  516. try:
  517. rd = parse_recipe(config, tinfoil, args.recipename, True)
  518. if not rd:
  519. return 1
  520. version_info = oe.recipeutils.get_recipe_upstream_version(rd)
  521. # "new-commits-available" is an indication that upstream never issues version tags
  522. if not version_info['version'].endswith("new-commits-available"):
  523. logger.info("Current version: {}".format(version_info['current_version']))
  524. logger.info("Latest version: {}".format(version_info['version']))
  525. if version_info['revision']:
  526. logger.info("Latest version's commit: {}".format(version_info['revision']))
  527. else:
  528. logger.info("Latest commit: {}".format(version_info['revision']))
  529. finally:
  530. tinfoil.shutdown()
  531. return 0
  532. def check_upgrade_status(args, config, basepath, workspace):
  533. if not args.recipe:
  534. logger.info("Checking the upstream status for all recipes may take a few minutes")
  535. results = oe.recipeutils.get_recipe_upgrade_status(args.recipe)
  536. for result in results:
  537. # pn, update_status, current, latest, maintainer, latest_commit, no_update_reason
  538. if args.all or result[1] != 'MATCH':
  539. logger.info("{:25} {:15} {:15} {} {} {}".format( result[0],
  540. result[2],
  541. result[1] if result[1] != 'UPDATE' else (result[3] if not result[3].endswith("new-commits-available") else "new commits"),
  542. result[4],
  543. result[5] if result[5] != 'N/A' else "",
  544. "cannot be updated due to: %s" %(result[6]) if result[6] else ""))
  545. def register_commands(subparsers, context):
  546. """Register devtool subcommands from this plugin"""
  547. defsrctree = standard.get_default_srctree(context.config)
  548. parser_upgrade = subparsers.add_parser('upgrade', help='Upgrade an existing recipe',
  549. description='Upgrades an existing recipe to a new upstream version. Puts the upgraded recipe file into the workspace along with any associated files, and extracts the source tree to a specified location (in case patches need rebasing or adding to as a result of the upgrade).',
  550. group='starting')
  551. parser_upgrade.add_argument('recipename', help='Name of recipe to upgrade (just name - no version, path or extension)')
  552. parser_upgrade.add_argument('srctree', nargs='?', help='Path to where to extract the source tree. If not specified, a subdirectory of %s will be used.' % defsrctree)
  553. parser_upgrade.add_argument('--version', '-V', help='Version to upgrade to (PV). If omitted, latest upstream version will be determined and used, if possible.')
  554. parser_upgrade.add_argument('--srcrev', '-S', help='Source revision to upgrade to (useful when fetching from an SCM such as git)')
  555. parser_upgrade.add_argument('--srcbranch', '-B', help='Branch in source repository containing the revision to use (if fetching from an SCM such as git)')
  556. parser_upgrade.add_argument('--branch', '-b', default="devtool", help='Name for new development branch to checkout (default "%(default)s")')
  557. parser_upgrade.add_argument('--no-patch', action="store_true", help='Do not apply patches from the recipe to the new source code')
  558. parser_upgrade.add_argument('--no-overrides', '-O', action="store_true", help='Do not create branches for other override configurations')
  559. group = parser_upgrade.add_mutually_exclusive_group()
  560. group.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
  561. group.add_argument('--no-same-dir', help='Force build in a separate build directory', action="store_true")
  562. parser_upgrade.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
  563. parser_upgrade.add_argument('--keep-failure', action="store_true", help='Keep failed upgrade recipe and associated files (for debugging)')
  564. parser_upgrade.set_defaults(func=upgrade, fixed_setup=context.fixed_setup)
  565. parser_latest_version = subparsers.add_parser('latest-version', help='Report the latest version of an existing recipe',
  566. description='Queries the upstream server for what the latest upstream release is (for git, tags are checked, for tarballs, a list of them is obtained, and one with the highest version number is reported)',
  567. group='info')
  568. parser_latest_version.add_argument('recipename', help='Name of recipe to query (just name - no version, path or extension)')
  569. parser_latest_version.set_defaults(func=latest_version)
  570. parser_check_upgrade_status = subparsers.add_parser('check-upgrade-status', help="Report upgradability for multiple (or all) recipes",
  571. description="Prints a table of recipes together with versions currently provided by recipes, and latest upstream versions, when there is a later version available",
  572. group='info')
  573. parser_check_upgrade_status.add_argument('recipe', help='Name of the recipe to report (omit to report upgrade info for all recipes)', nargs='*')
  574. parser_check_upgrade_status.add_argument('--all', '-a', help='Show all recipes, not just recipes needing upgrade', action="store_true")
  575. parser_check_upgrade_status.set_defaults(func=check_upgrade_status)