upgrade.py 28 KB

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