standard.py 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949
  1. # Development tool - standard commands 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. """Devtool standard plugins"""
  18. import os
  19. import sys
  20. import re
  21. import shutil
  22. import subprocess
  23. import tempfile
  24. import logging
  25. import argparse
  26. import argparse_oe
  27. import scriptutils
  28. import errno
  29. import glob
  30. import filecmp
  31. from collections import OrderedDict
  32. from devtool import exec_build_env_command, setup_tinfoil, check_workspace_recipe, use_external_build, setup_git_repo, recipe_to_append, get_bbclassextend_targets, DevtoolError
  33. from devtool import parse_recipe
  34. logger = logging.getLogger('devtool')
  35. def add(args, config, basepath, workspace):
  36. """Entry point for the devtool 'add' subcommand"""
  37. import bb
  38. import oe.recipeutils
  39. if not args.recipename and not args.srctree and not args.fetch and not args.fetchuri:
  40. raise argparse_oe.ArgumentUsageError('At least one of recipename, srctree, fetchuri or -f/--fetch must be specified', 'add')
  41. # These are positional arguments, but because we're nice, allow
  42. # specifying e.g. source tree without name, or fetch URI without name or
  43. # source tree (if we can detect that that is what the user meant)
  44. if scriptutils.is_src_url(args.recipename):
  45. if not args.fetchuri:
  46. if args.fetch:
  47. raise DevtoolError('URI specified as positional argument as well as -f/--fetch')
  48. args.fetchuri = args.recipename
  49. args.recipename = ''
  50. elif scriptutils.is_src_url(args.srctree):
  51. if not args.fetchuri:
  52. if args.fetch:
  53. raise DevtoolError('URI specified as positional argument as well as -f/--fetch')
  54. args.fetchuri = args.srctree
  55. args.srctree = ''
  56. elif args.recipename and not args.srctree:
  57. if os.sep in args.recipename:
  58. args.srctree = args.recipename
  59. args.recipename = None
  60. elif os.path.isdir(args.recipename):
  61. logger.warn('Ambiguous argument "%s" - assuming you mean it to be the recipe name' % args.recipename)
  62. if not args.fetchuri:
  63. if args.srcrev:
  64. raise DevtoolError('The -S/--srcrev option is only valid when fetching from an SCM repository')
  65. if args.srcbranch:
  66. raise DevtoolError('The -B/--srcbranch option is only valid when fetching from an SCM repository')
  67. if args.srctree and os.path.isfile(args.srctree):
  68. args.fetchuri = 'file://' + os.path.abspath(args.srctree)
  69. args.srctree = ''
  70. if args.fetch:
  71. if args.fetchuri:
  72. raise DevtoolError('URI specified as positional argument as well as -f/--fetch')
  73. else:
  74. logger.warn('-f/--fetch option is deprecated - you can now simply specify the URL to fetch as a positional argument instead')
  75. args.fetchuri = args.fetch
  76. if args.recipename:
  77. if args.recipename in workspace:
  78. raise DevtoolError("recipe %s is already in your workspace" %
  79. args.recipename)
  80. reason = oe.recipeutils.validate_pn(args.recipename)
  81. if reason:
  82. raise DevtoolError(reason)
  83. if args.srctree:
  84. srctree = os.path.abspath(args.srctree)
  85. srctreeparent = None
  86. tmpsrcdir = None
  87. else:
  88. srctree = None
  89. srctreeparent = get_default_srctree(config)
  90. bb.utils.mkdirhier(srctreeparent)
  91. tmpsrcdir = tempfile.mkdtemp(prefix='devtoolsrc', dir=srctreeparent)
  92. if srctree and os.path.exists(srctree):
  93. if args.fetchuri:
  94. if not os.path.isdir(srctree):
  95. raise DevtoolError("Cannot fetch into source tree path %s as "
  96. "it exists and is not a directory" %
  97. srctree)
  98. elif os.listdir(srctree):
  99. raise DevtoolError("Cannot fetch into source tree path %s as "
  100. "it already exists and is non-empty" %
  101. srctree)
  102. elif not args.fetchuri:
  103. if args.srctree:
  104. raise DevtoolError("Specified source tree %s could not be found" %
  105. args.srctree)
  106. elif srctree:
  107. raise DevtoolError("No source tree exists at default path %s - "
  108. "either create and populate this directory, "
  109. "or specify a path to a source tree, or a "
  110. "URI to fetch source from" % srctree)
  111. else:
  112. raise DevtoolError("You must either specify a source tree "
  113. "or a URI to fetch source from")
  114. if args.version:
  115. if '_' in args.version or ' ' in args.version:
  116. raise DevtoolError('Invalid version string "%s"' % args.version)
  117. if args.color == 'auto' and sys.stdout.isatty():
  118. color = 'always'
  119. else:
  120. color = args.color
  121. extracmdopts = ''
  122. if args.fetchuri:
  123. source = args.fetchuri
  124. if srctree:
  125. extracmdopts += ' -x %s' % srctree
  126. else:
  127. extracmdopts += ' -x %s' % tmpsrcdir
  128. else:
  129. source = srctree
  130. if args.recipename:
  131. extracmdopts += ' -N %s' % args.recipename
  132. if args.version:
  133. extracmdopts += ' -V %s' % args.version
  134. if args.binary:
  135. extracmdopts += ' -b'
  136. if args.also_native:
  137. extracmdopts += ' --also-native'
  138. if args.src_subdir:
  139. extracmdopts += ' --src-subdir "%s"' % args.src_subdir
  140. if args.autorev:
  141. extracmdopts += ' -a'
  142. if args.fetch_dev:
  143. extracmdopts += ' --fetch-dev'
  144. if args.mirrors:
  145. extracmdopts += ' --mirrors'
  146. if args.srcrev:
  147. extracmdopts += ' --srcrev %s' % args.srcrev
  148. if args.srcbranch:
  149. extracmdopts += ' --srcbranch %s' % args.srcbranch
  150. if args.provides:
  151. extracmdopts += ' --provides %s' % args.provides
  152. tempdir = tempfile.mkdtemp(prefix='devtool')
  153. try:
  154. try:
  155. stdout, _ = exec_build_env_command(config.init_path, basepath, 'recipetool --color=%s create --devtool -o %s \'%s\' %s' % (color, tempdir, source, extracmdopts), watch=True)
  156. except bb.process.ExecutionError as e:
  157. if e.exitcode == 15:
  158. raise DevtoolError('Could not auto-determine recipe name, please specify it on the command line')
  159. else:
  160. raise DevtoolError('Command \'%s\' failed' % e.command)
  161. recipes = glob.glob(os.path.join(tempdir, '*.bb'))
  162. if recipes:
  163. recipename = os.path.splitext(os.path.basename(recipes[0]))[0].split('_')[0]
  164. if recipename in workspace:
  165. raise DevtoolError('A recipe with the same name as the one being created (%s) already exists in your workspace' % recipename)
  166. recipedir = os.path.join(config.workspace_path, 'recipes', recipename)
  167. bb.utils.mkdirhier(recipedir)
  168. recipefile = os.path.join(recipedir, os.path.basename(recipes[0]))
  169. appendfile = recipe_to_append(recipefile, config)
  170. if os.path.exists(appendfile):
  171. # This shouldn't be possible, but just in case
  172. raise DevtoolError('A recipe with the same name as the one being created already exists in your workspace')
  173. if os.path.exists(recipefile):
  174. raise DevtoolError('A recipe file %s already exists in your workspace; this shouldn\'t be there - please delete it before continuing' % recipefile)
  175. if tmpsrcdir:
  176. srctree = os.path.join(srctreeparent, recipename)
  177. if os.path.exists(tmpsrcdir):
  178. if os.path.exists(srctree):
  179. if os.path.isdir(srctree):
  180. try:
  181. os.rmdir(srctree)
  182. except OSError as e:
  183. if e.errno == errno.ENOTEMPTY:
  184. raise DevtoolError('Source tree path %s already exists and is not empty' % srctree)
  185. else:
  186. raise
  187. else:
  188. raise DevtoolError('Source tree path %s already exists and is not a directory' % srctree)
  189. logger.info('Using default source tree path %s' % srctree)
  190. shutil.move(tmpsrcdir, srctree)
  191. else:
  192. raise DevtoolError('Couldn\'t find source tree created by recipetool')
  193. bb.utils.mkdirhier(recipedir)
  194. shutil.move(recipes[0], recipefile)
  195. # Move any additional files created by recipetool
  196. for fn in os.listdir(tempdir):
  197. shutil.move(os.path.join(tempdir, fn), recipedir)
  198. else:
  199. raise DevtoolError('Command \'%s\' did not create any recipe file:\n%s' % (e.command, e.stdout))
  200. attic_recipe = os.path.join(config.workspace_path, 'attic', recipename, os.path.basename(recipefile))
  201. if os.path.exists(attic_recipe):
  202. logger.warn('A modified recipe from a previous invocation exists in %s - you may wish to move this over the top of the new recipe if you had changes in it that you want to continue with' % attic_recipe)
  203. finally:
  204. if tmpsrcdir and os.path.exists(tmpsrcdir):
  205. shutil.rmtree(tmpsrcdir)
  206. shutil.rmtree(tempdir)
  207. for fn in os.listdir(recipedir):
  208. _add_md5(config, recipename, os.path.join(recipedir, fn))
  209. tinfoil = setup_tinfoil(config_only=True, basepath=basepath)
  210. try:
  211. try:
  212. rd = tinfoil.parse_recipe_file(recipefile, False)
  213. except Exception as e:
  214. logger.error(str(e))
  215. rd = None
  216. if not rd:
  217. # Parsing failed. We just created this recipe and we shouldn't
  218. # leave it in the workdir or it'll prevent bitbake from starting
  219. movefn = '%s.parsefailed' % recipefile
  220. logger.error('Parsing newly created recipe failed, moving recipe to %s for reference. If this looks to be caused by the recipe itself, please report this error.' % movefn)
  221. shutil.move(recipefile, movefn)
  222. return 1
  223. if args.fetchuri and not args.no_git:
  224. setup_git_repo(srctree, args.version, 'devtool', d=tinfoil.config_data)
  225. initial_rev = None
  226. if os.path.exists(os.path.join(srctree, '.git')):
  227. (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=srctree)
  228. initial_rev = stdout.rstrip()
  229. if args.src_subdir:
  230. srctree = os.path.join(srctree, args.src_subdir)
  231. bb.utils.mkdirhier(os.path.dirname(appendfile))
  232. with open(appendfile, 'w') as f:
  233. f.write('inherit externalsrc\n')
  234. f.write('EXTERNALSRC = "%s"\n' % srctree)
  235. b_is_s = use_external_build(args.same_dir, args.no_same_dir, rd)
  236. if b_is_s:
  237. f.write('EXTERNALSRC_BUILD = "%s"\n' % srctree)
  238. if initial_rev:
  239. f.write('\n# initial_rev: %s\n' % initial_rev)
  240. if args.binary:
  241. f.write('do_install_append() {\n')
  242. f.write(' rm -rf ${D}/.git\n')
  243. f.write(' rm -f ${D}/singletask.lock\n')
  244. f.write('}\n')
  245. if bb.data.inherits_class('npm', rd):
  246. f.write('do_install_append() {\n')
  247. f.write(' # Remove files added to source dir by devtool/externalsrc\n')
  248. f.write(' rm -f ${NPM_INSTALLDIR}/singletask.lock\n')
  249. f.write(' rm -rf ${NPM_INSTALLDIR}/.git\n')
  250. f.write(' rm -rf ${NPM_INSTALLDIR}/oe-local-files\n')
  251. f.write(' for symlink in ${EXTERNALSRC_SYMLINKS} ; do\n')
  252. f.write(' rm -f ${NPM_INSTALLDIR}/${symlink%%:*}\n')
  253. f.write(' done\n')
  254. f.write('}\n')
  255. # Check if the new layer provides recipes whose priorities have been
  256. # overriden by PREFERRED_PROVIDER.
  257. recipe_name = rd.getVar('PN')
  258. provides = rd.getVar('PROVIDES')
  259. # Search every item defined in PROVIDES
  260. for recipe_provided in provides.split():
  261. preferred_provider = 'PREFERRED_PROVIDER_' + recipe_provided
  262. current_pprovider = rd.getVar(preferred_provider)
  263. if current_pprovider and current_pprovider != recipe_name:
  264. if args.fixed_setup:
  265. #if we are inside the eSDK add the new PREFERRED_PROVIDER in the workspace layer.conf
  266. layerconf_file = os.path.join(config.workspace_path, "conf", "layer.conf")
  267. with open(layerconf_file, 'a') as f:
  268. f.write('%s = "%s"\n' % (preferred_provider, recipe_name))
  269. else:
  270. logger.warn('Set \'%s\' in order to use the recipe' % preferred_provider)
  271. break
  272. _add_md5(config, recipename, appendfile)
  273. logger.info('Recipe %s has been automatically created; further editing may be required to make it fully functional' % recipefile)
  274. finally:
  275. tinfoil.shutdown()
  276. return 0
  277. def _check_compatible_recipe(pn, d):
  278. """Check if the recipe is supported by devtool"""
  279. if pn == 'perf':
  280. raise DevtoolError("The perf recipe does not actually check out "
  281. "source and thus cannot be supported by this tool",
  282. 4)
  283. if pn in ['kernel-devsrc', 'package-index'] or pn.startswith('gcc-source'):
  284. raise DevtoolError("The %s recipe is not supported by this tool" % pn, 4)
  285. if bb.data.inherits_class('image', d):
  286. raise DevtoolError("The %s recipe is an image, and therefore is not "
  287. "supported by this tool" % pn, 4)
  288. if bb.data.inherits_class('populate_sdk', d):
  289. raise DevtoolError("The %s recipe is an SDK, and therefore is not "
  290. "supported by this tool" % pn, 4)
  291. if bb.data.inherits_class('packagegroup', d):
  292. raise DevtoolError("The %s recipe is a packagegroup, and therefore is "
  293. "not supported by this tool" % pn, 4)
  294. if bb.data.inherits_class('meta', d):
  295. raise DevtoolError("The %s recipe is a meta-recipe, and therefore is "
  296. "not supported by this tool" % pn, 4)
  297. if bb.data.inherits_class('externalsrc', d) and d.getVar('EXTERNALSRC'):
  298. # Not an incompatibility error per se, so we don't pass the error code
  299. raise DevtoolError("externalsrc is currently enabled for the %s "
  300. "recipe. This prevents the normal do_patch task "
  301. "from working. You will need to disable this "
  302. "first." % pn)
  303. def _move_file(src, dst):
  304. """Move a file. Creates all the directory components of destination path."""
  305. dst_d = os.path.dirname(dst)
  306. if dst_d:
  307. bb.utils.mkdirhier(dst_d)
  308. shutil.move(src, dst)
  309. def _copy_file(src, dst):
  310. """Copy a file. Creates all the directory components of destination path."""
  311. dst_d = os.path.dirname(dst)
  312. if dst_d:
  313. bb.utils.mkdirhier(dst_d)
  314. shutil.copy(src, dst)
  315. def _git_ls_tree(repodir, treeish='HEAD', recursive=False):
  316. """List contents of a git treeish"""
  317. import bb
  318. cmd = ['git', 'ls-tree', '-z', treeish]
  319. if recursive:
  320. cmd.append('-r')
  321. out, _ = bb.process.run(cmd, cwd=repodir)
  322. ret = {}
  323. if out:
  324. for line in out.split('\0'):
  325. if line:
  326. split = line.split(None, 4)
  327. ret[split[3]] = split[0:3]
  328. return ret
  329. def _git_exclude_path(srctree, path):
  330. """Return pathspec (list of paths) that excludes certain path"""
  331. # NOTE: "Filtering out" files/paths in this way is not entirely reliable -
  332. # we don't catch files that are deleted, for example. A more reliable way
  333. # to implement this would be to use "negative pathspecs" which were
  334. # introduced in Git v1.9.0. Revisit this when/if the required Git version
  335. # becomes greater than that.
  336. path = os.path.normpath(path)
  337. recurse = True if len(path.split(os.path.sep)) > 1 else False
  338. git_files = list(_git_ls_tree(srctree, 'HEAD', recurse).keys())
  339. if path in git_files:
  340. git_files.remove(path)
  341. return git_files
  342. else:
  343. return ['.']
  344. def _ls_tree(directory):
  345. """Recursive listing of files in a directory"""
  346. ret = []
  347. for root, dirs, files in os.walk(directory):
  348. ret.extend([os.path.relpath(os.path.join(root, fname), directory) for
  349. fname in files])
  350. return ret
  351. def extract(args, config, basepath, workspace):
  352. """Entry point for the devtool 'extract' subcommand"""
  353. import bb
  354. tinfoil = setup_tinfoil(basepath=basepath)
  355. if not tinfoil:
  356. # Error already shown
  357. return 1
  358. try:
  359. rd = parse_recipe(config, tinfoil, args.recipename, True)
  360. if not rd:
  361. return 1
  362. srctree = os.path.abspath(args.srctree)
  363. initial_rev = _extract_source(srctree, args.keep_temp, args.branch, False, rd, tinfoil)
  364. logger.info('Source tree extracted to %s' % srctree)
  365. if initial_rev:
  366. return 0
  367. else:
  368. return 1
  369. finally:
  370. tinfoil.shutdown()
  371. def sync(args, config, basepath, workspace):
  372. """Entry point for the devtool 'sync' subcommand"""
  373. import bb
  374. tinfoil = setup_tinfoil(basepath=basepath)
  375. if not tinfoil:
  376. # Error already shown
  377. return 1
  378. try:
  379. rd = parse_recipe(config, tinfoil, args.recipename, True)
  380. if not rd:
  381. return 1
  382. srctree = os.path.abspath(args.srctree)
  383. initial_rev = _extract_source(srctree, args.keep_temp, args.branch, True, rd, tinfoil)
  384. logger.info('Source tree %s synchronized' % srctree)
  385. if initial_rev:
  386. return 0
  387. else:
  388. return 1
  389. finally:
  390. tinfoil.shutdown()
  391. def _extract_source(srctree, keep_temp, devbranch, sync, d, tinfoil):
  392. """Extract sources of a recipe"""
  393. import oe.recipeutils
  394. pn = d.getVar('PN')
  395. _check_compatible_recipe(pn, d)
  396. if sync:
  397. if not os.path.exists(srctree):
  398. raise DevtoolError("output path %s does not exist" % srctree)
  399. else:
  400. if os.path.exists(srctree):
  401. if not os.path.isdir(srctree):
  402. raise DevtoolError("output path %s exists and is not a directory" %
  403. srctree)
  404. elif os.listdir(srctree):
  405. raise DevtoolError("output path %s already exists and is "
  406. "non-empty" % srctree)
  407. if 'noexec' in (d.getVarFlags('do_unpack', False) or []):
  408. raise DevtoolError("The %s recipe has do_unpack disabled, unable to "
  409. "extract source" % pn, 4)
  410. if bb.data.inherits_class('kernel-yocto', d):
  411. tinfoil.build_targets('kern-tools-native')
  412. if not sync:
  413. # Prepare for shutil.move later on
  414. bb.utils.mkdirhier(srctree)
  415. os.rmdir(srctree)
  416. initial_rev = None
  417. # We need to redirect WORKDIR, STAMPS_DIR etc. under a temporary
  418. # directory so that:
  419. # (a) we pick up all files that get unpacked to the WORKDIR, and
  420. # (b) we don't disturb the existing build
  421. # However, with recipe-specific sysroots the sysroots for the recipe
  422. # will be prepared under WORKDIR, and if we used the system temporary
  423. # directory (i.e. usually /tmp) as used by mkdtemp by default, then
  424. # our attempts to hardlink files into the recipe-specific sysroots
  425. # will fail on systems where /tmp is a different filesystem, and it
  426. # would have to fall back to copying the files which is a waste of
  427. # time. Put the temp directory under the WORKDIR to prevent that from
  428. # being a problem.
  429. tempbasedir = d.getVar('WORKDIR')
  430. bb.utils.mkdirhier(tempbasedir)
  431. tempdir = tempfile.mkdtemp(prefix='devtooltmp-', dir=tempbasedir)
  432. try:
  433. tinfoil.logger.setLevel(logging.WARNING)
  434. crd = d.createCopy()
  435. # Make a subdir so we guard against WORKDIR==S
  436. workdir = os.path.join(tempdir, 'workdir')
  437. crd.setVar('WORKDIR', workdir)
  438. if not crd.getVar('S').startswith(workdir):
  439. # Usually a shared workdir recipe (kernel, gcc)
  440. # Try to set a reasonable default
  441. if bb.data.inherits_class('kernel', d):
  442. crd.setVar('S', '${WORKDIR}/source')
  443. else:
  444. crd.setVar('S', '${WORKDIR}/%s' % os.path.basename(d.getVar('S')))
  445. if bb.data.inherits_class('kernel', d):
  446. # We don't want to move the source to STAGING_KERNEL_DIR here
  447. crd.setVar('STAGING_KERNEL_DIR', '${S}')
  448. is_kernel_yocto = bb.data.inherits_class('kernel-yocto', d)
  449. if not is_kernel_yocto:
  450. crd.setVar('PATCHTOOL', 'git')
  451. crd.setVar('PATCH_COMMIT_FUNCTIONS', '1')
  452. # Apply our changes to the datastore to the server's datastore
  453. for key in crd.localkeys():
  454. tinfoil.config_data.setVar('%s_pn-%s' % (key, pn), crd.getVar(key, False))
  455. tinfoil.config_data.setVar('STAMPS_DIR', os.path.join(tempdir, 'stamps'))
  456. tinfoil.config_data.setVar('T', os.path.join(tempdir, 'temp'))
  457. tinfoil.config_data.setVar('BUILDCFG_FUNCS', '')
  458. tinfoil.config_data.setVar('BUILDCFG_HEADER', '')
  459. tinfoil.config_data.setVar('BB_HASH_IGNORE_MISMATCH', '1')
  460. tinfoil.set_event_mask(['bb.event.BuildStarted',
  461. 'bb.event.BuildCompleted',
  462. 'logging.LogRecord',
  463. 'bb.command.CommandCompleted',
  464. 'bb.command.CommandFailed',
  465. 'bb.cooker.CookerExit',
  466. 'bb.build.TaskStarted',
  467. 'bb.build.TaskSucceeded',
  468. 'bb.build.TaskFailed',
  469. 'bb.build.TaskFailedSilent'])
  470. def runtask(target, task):
  471. error = False
  472. if tinfoil.build_file(target, task):
  473. while True:
  474. event = tinfoil.wait_event(0.25)
  475. if event:
  476. if isinstance(event, bb.command.CommandCompleted):
  477. break
  478. elif isinstance(event, bb.cooker.CookerExit):
  479. # The server is going away, so drop the connection
  480. tinfoil.server_connection = None
  481. break
  482. elif isinstance(event, bb.command.CommandFailed):
  483. raise DevtoolError('Task do_%s failed: %s' % (task, event.error))
  484. elif isinstance(event, bb.build.TaskFailed):
  485. raise DevtoolError('Task do_%s failed' % task)
  486. elif isinstance(event, bb.build.TaskStarted):
  487. logger.info('Executing %s...' % event._task)
  488. elif isinstance(event, logging.LogRecord):
  489. if event.levelno <= logging.INFO:
  490. continue
  491. if event.levelno >= logging.ERROR:
  492. error = True
  493. logger.handle(event)
  494. if error:
  495. raise DevtoolError('An error occurred during do_%s, exiting' % task)
  496. # we need virtual:native:/path/to/recipe if it's a BBCLASSEXTEND
  497. fn = tinfoil.get_recipe_file(pn)
  498. runtask(fn, 'unpack')
  499. if bb.data.inherits_class('kernel-yocto', d):
  500. # Extra step for kernel to populate the source directory
  501. runtask(fn, 'kernel_checkout')
  502. srcsubdir = crd.getVar('S')
  503. # Move local source files into separate subdir
  504. recipe_patches = [os.path.basename(patch) for patch in
  505. oe.recipeutils.get_recipe_patches(crd)]
  506. local_files = oe.recipeutils.get_recipe_local_files(crd)
  507. # Ignore local files with subdir={BP}
  508. srcabspath = os.path.abspath(srcsubdir)
  509. local_files = [fname for fname in local_files if
  510. os.path.exists(os.path.join(workdir, fname)) and
  511. (srcabspath == workdir or not
  512. os.path.join(workdir, fname).startswith(srcabspath +
  513. os.sep))]
  514. if local_files:
  515. for fname in local_files:
  516. _move_file(os.path.join(workdir, fname),
  517. os.path.join(tempdir, 'oe-local-files', fname))
  518. with open(os.path.join(tempdir, 'oe-local-files', '.gitignore'),
  519. 'w') as f:
  520. f.write('# Ignore local files, by default. Remove this file '
  521. 'if you want to commit the directory to Git\n*\n')
  522. if srcsubdir == workdir:
  523. # Find non-patch non-local sources that were "unpacked" to srctree
  524. # directory
  525. src_files = [fname for fname in _ls_tree(workdir) if
  526. os.path.basename(fname) not in recipe_patches]
  527. # Force separate S so that patch files can be left out from srctree
  528. srcsubdir = tempfile.mkdtemp(dir=workdir)
  529. tinfoil.config_data.setVar('S_task-patch', srcsubdir)
  530. # Move source files to S
  531. for path in src_files:
  532. _move_file(os.path.join(workdir, path),
  533. os.path.join(srcsubdir, path))
  534. elif os.path.dirname(srcsubdir) != workdir:
  535. # Handle if S is set to a subdirectory of the source
  536. srcsubdir = os.path.join(workdir, os.path.relpath(srcsubdir, workdir).split(os.sep)[0])
  537. scriptutils.git_convert_standalone_clone(srcsubdir)
  538. # Make sure that srcsubdir exists
  539. bb.utils.mkdirhier(srcsubdir)
  540. if not os.path.exists(srcsubdir) or not os.listdir(srcsubdir):
  541. logger.warning("no source unpacked to S, either the %s recipe "
  542. "doesn't use any source or the correct source "
  543. "directory could not be determined" % pn)
  544. setup_git_repo(srcsubdir, crd.getVar('PV'), devbranch, d=d)
  545. (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=srcsubdir)
  546. initial_rev = stdout.rstrip()
  547. logger.info('Patching...')
  548. runtask(fn, 'patch')
  549. bb.process.run('git tag -f devtool-patched', cwd=srcsubdir)
  550. kconfig = None
  551. if bb.data.inherits_class('kernel-yocto', d):
  552. # Store generate and store kernel config
  553. logger.info('Generating kernel config')
  554. runtask(fn, 'configure')
  555. kconfig = os.path.join(crd.getVar('B'), '.config')
  556. tempdir_localdir = os.path.join(tempdir, 'oe-local-files')
  557. srctree_localdir = os.path.join(srctree, 'oe-local-files')
  558. if sync:
  559. bb.process.run('git fetch file://' + srcsubdir + ' ' + devbranch + ':' + devbranch, cwd=srctree)
  560. # Move oe-local-files directory to srctree
  561. # As the oe-local-files is not part of the constructed git tree,
  562. # remove them directly during the synchrounizating might surprise
  563. # the users. Instead, we move it to oe-local-files.bak and remind
  564. # user in the log message.
  565. if os.path.exists(srctree_localdir + '.bak'):
  566. shutil.rmtree(srctree_localdir, srctree_localdir + '.bak')
  567. if os.path.exists(srctree_localdir):
  568. logger.info('Backing up current local file directory %s' % srctree_localdir)
  569. shutil.move(srctree_localdir, srctree_localdir + '.bak')
  570. if os.path.exists(tempdir_localdir):
  571. logger.info('Syncing local source files to srctree...')
  572. shutil.copytree(tempdir_localdir, srctree_localdir)
  573. else:
  574. # Move oe-local-files directory to srctree
  575. if os.path.exists(tempdir_localdir):
  576. logger.info('Adding local source files to srctree...')
  577. shutil.move(tempdir_localdir, srcsubdir)
  578. shutil.move(srcsubdir, srctree)
  579. if os.path.abspath(d.getVar('S')) == os.path.abspath(d.getVar('WORKDIR')):
  580. # If recipe extracts to ${WORKDIR}, symlink the files into the srctree
  581. # (otherwise the recipe won't build as expected)
  582. local_files_dir = os.path.join(srctree, 'oe-local-files')
  583. addfiles = []
  584. for root, _, files in os.walk(local_files_dir):
  585. relpth = os.path.relpath(root, local_files_dir)
  586. if relpth != '.':
  587. bb.utils.mkdirhier(os.path.join(srctree, relpth))
  588. for fn in files:
  589. if fn == '.gitignore':
  590. continue
  591. destpth = os.path.join(srctree, relpth, fn)
  592. if os.path.exists(destpth):
  593. os.unlink(destpth)
  594. os.symlink('oe-local-files/%s' % fn, destpth)
  595. addfiles.append(os.path.join(relpth, fn))
  596. if addfiles:
  597. bb.process.run('git add %s' % ' '.join(addfiles), cwd=srctree)
  598. useroptions = []
  599. oe.patch.GitApplyTree.gitCommandUserOptions(useroptions, d=d)
  600. bb.process.run('git %s commit -a -m "Committing local file symlinks\n\n%s"' % (' '.join(useroptions), oe.patch.GitApplyTree.ignore_commit_prefix), cwd=srctree)
  601. if kconfig:
  602. logger.info('Copying kernel config to srctree')
  603. shutil.copy2(kconfig, srctree)
  604. finally:
  605. if keep_temp:
  606. logger.info('Preserving temporary directory %s' % tempdir)
  607. else:
  608. shutil.rmtree(tempdir)
  609. return initial_rev
  610. def _add_md5(config, recipename, filename):
  611. """Record checksum of a file (or recursively for a directory) to the md5-file of the workspace"""
  612. import bb.utils
  613. def addfile(fn):
  614. md5 = bb.utils.md5_file(fn)
  615. with open(os.path.join(config.workspace_path, '.devtool_md5'), 'a+') as f:
  616. md5_str = '%s|%s|%s\n' % (recipename, os.path.relpath(fn, config.workspace_path), md5)
  617. f.seek(0, os.SEEK_SET)
  618. if not md5_str in f.read():
  619. f.write(md5_str)
  620. if os.path.isdir(filename):
  621. for root, _, files in os.walk(filename):
  622. for f in files:
  623. addfile(os.path.join(root, f))
  624. else:
  625. addfile(filename)
  626. def _check_preserve(config, recipename):
  627. """Check if a file was manually changed and needs to be saved in 'attic'
  628. directory"""
  629. import bb.utils
  630. origfile = os.path.join(config.workspace_path, '.devtool_md5')
  631. newfile = os.path.join(config.workspace_path, '.devtool_md5_new')
  632. preservepath = os.path.join(config.workspace_path, 'attic', recipename)
  633. with open(origfile, 'r') as f:
  634. with open(newfile, 'w') as tf:
  635. for line in f.readlines():
  636. splitline = line.rstrip().split('|')
  637. if splitline[0] == recipename:
  638. removefile = os.path.join(config.workspace_path, splitline[1])
  639. try:
  640. md5 = bb.utils.md5_file(removefile)
  641. except IOError as err:
  642. if err.errno == 2:
  643. # File no longer exists, skip it
  644. continue
  645. else:
  646. raise
  647. if splitline[2] != md5:
  648. bb.utils.mkdirhier(preservepath)
  649. preservefile = os.path.basename(removefile)
  650. logger.warn('File %s modified since it was written, preserving in %s' % (preservefile, preservepath))
  651. shutil.move(removefile, os.path.join(preservepath, preservefile))
  652. else:
  653. os.remove(removefile)
  654. else:
  655. tf.write(line)
  656. os.rename(newfile, origfile)
  657. def modify(args, config, basepath, workspace):
  658. """Entry point for the devtool 'modify' subcommand"""
  659. import bb
  660. import oe.recipeutils
  661. if args.recipename in workspace:
  662. raise DevtoolError("recipe %s is already in your workspace" %
  663. args.recipename)
  664. tinfoil = setup_tinfoil(basepath=basepath)
  665. try:
  666. rd = parse_recipe(config, tinfoil, args.recipename, True)
  667. if not rd:
  668. return 1
  669. pn = rd.getVar('PN')
  670. if pn != args.recipename:
  671. logger.info('Mapping %s to %s' % (args.recipename, pn))
  672. if pn in workspace:
  673. raise DevtoolError("recipe %s is already in your workspace" %
  674. pn)
  675. if args.srctree:
  676. srctree = os.path.abspath(args.srctree)
  677. else:
  678. srctree = get_default_srctree(config, pn)
  679. if args.no_extract and not os.path.isdir(srctree):
  680. raise DevtoolError("--no-extract specified and source path %s does "
  681. "not exist or is not a directory" %
  682. srctree)
  683. recipefile = rd.getVar('FILE')
  684. appendfile = recipe_to_append(recipefile, config, args.wildcard)
  685. if os.path.exists(appendfile):
  686. raise DevtoolError("Another variant of recipe %s is already in your "
  687. "workspace (only one variant of a recipe can "
  688. "currently be worked on at once)"
  689. % pn)
  690. _check_compatible_recipe(pn, rd)
  691. initial_rev = None
  692. commits = []
  693. if not args.no_extract:
  694. initial_rev = _extract_source(srctree, args.keep_temp, args.branch, False, rd, tinfoil)
  695. if not initial_rev:
  696. return 1
  697. logger.info('Source tree extracted to %s' % srctree)
  698. # Get list of commits since this revision
  699. (stdout, _) = bb.process.run('git rev-list --reverse %s..HEAD' % initial_rev, cwd=srctree)
  700. commits = stdout.split()
  701. else:
  702. if os.path.exists(os.path.join(srctree, '.git')):
  703. # Check if it's a tree previously extracted by us
  704. try:
  705. (stdout, _) = bb.process.run('git branch --contains devtool-base', cwd=srctree)
  706. except bb.process.ExecutionError:
  707. stdout = ''
  708. for line in stdout.splitlines():
  709. if line.startswith('*'):
  710. (stdout, _) = bb.process.run('git rev-parse devtool-base', cwd=srctree)
  711. initial_rev = stdout.rstrip()
  712. if not initial_rev:
  713. # Otherwise, just grab the head revision
  714. (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=srctree)
  715. initial_rev = stdout.rstrip()
  716. # Check that recipe isn't using a shared workdir
  717. s = os.path.abspath(rd.getVar('S'))
  718. workdir = os.path.abspath(rd.getVar('WORKDIR'))
  719. if s.startswith(workdir) and s != workdir and os.path.dirname(s) != workdir:
  720. # Handle if S is set to a subdirectory of the source
  721. srcsubdir = os.path.relpath(s, workdir).split(os.sep, 1)[1]
  722. srctree = os.path.join(srctree, srcsubdir)
  723. bb.utils.mkdirhier(os.path.dirname(appendfile))
  724. with open(appendfile, 'w') as f:
  725. f.write('FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"\n')
  726. # Local files can be modified/tracked in separate subdir under srctree
  727. # Mostly useful for packages with S != WORKDIR
  728. f.write('FILESPATH_prepend := "%s:"\n' %
  729. os.path.join(srctree, 'oe-local-files'))
  730. f.write('\ninherit externalsrc\n')
  731. f.write('# NOTE: We use pn- overrides here to avoid affecting multiple variants in the case where the recipe uses BBCLASSEXTEND\n')
  732. f.write('EXTERNALSRC_pn-%s = "%s"\n' % (pn, srctree))
  733. b_is_s = use_external_build(args.same_dir, args.no_same_dir, rd)
  734. if b_is_s:
  735. f.write('EXTERNALSRC_BUILD_pn-%s = "%s"\n' % (pn, srctree))
  736. if bb.data.inherits_class('kernel', rd):
  737. f.write('SRCTREECOVEREDTASKS = "do_validate_branches do_kernel_checkout '
  738. 'do_fetch do_unpack do_kernel_configme do_kernel_configcheck"\n')
  739. f.write('\ndo_patch() {\n'
  740. ' :\n'
  741. '}\n')
  742. f.write('\ndo_configure_append() {\n'
  743. ' cp ${B}/.config ${S}/.config.baseline\n'
  744. ' ln -sfT ${B}/.config ${S}/.config.new\n'
  745. '}\n')
  746. if initial_rev:
  747. f.write('\n# initial_rev: %s\n' % initial_rev)
  748. for commit in commits:
  749. f.write('# commit: %s\n' % commit)
  750. _add_md5(config, pn, appendfile)
  751. logger.info('Recipe %s now set up to build from %s' % (pn, srctree))
  752. finally:
  753. tinfoil.shutdown()
  754. return 0
  755. def rename(args, config, basepath, workspace):
  756. """Entry point for the devtool 'rename' subcommand"""
  757. import bb
  758. import oe.recipeutils
  759. check_workspace_recipe(workspace, args.recipename)
  760. if not (args.newname or args.version):
  761. raise DevtoolError('You must specify a new name, a version with -V/--version, or both')
  762. recipefile = workspace[args.recipename]['recipefile']
  763. if not recipefile:
  764. raise DevtoolError('devtool rename can only be used where the recipe file itself is in the workspace (e.g. after devtool add)')
  765. if args.newname and args.newname != args.recipename:
  766. reason = oe.recipeutils.validate_pn(args.newname)
  767. if reason:
  768. raise DevtoolError(reason)
  769. newname = args.newname
  770. else:
  771. newname = args.recipename
  772. append = workspace[args.recipename]['bbappend']
  773. appendfn = os.path.splitext(os.path.basename(append))[0]
  774. splitfn = appendfn.split('_')
  775. if len(splitfn) > 1:
  776. origfnver = appendfn.split('_')[1]
  777. else:
  778. origfnver = ''
  779. recipefilemd5 = None
  780. tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
  781. try:
  782. rd = parse_recipe(config, tinfoil, args.recipename, True)
  783. if not rd:
  784. return 1
  785. bp = rd.getVar('BP')
  786. bpn = rd.getVar('BPN')
  787. if newname != args.recipename:
  788. localdata = rd.createCopy()
  789. localdata.setVar('PN', newname)
  790. newbpn = localdata.getVar('BPN')
  791. else:
  792. newbpn = bpn
  793. s = rd.getVar('S', False)
  794. src_uri = rd.getVar('SRC_URI', False)
  795. pv = rd.getVar('PV')
  796. # Correct variable values that refer to the upstream source - these
  797. # values must stay the same, so if the name/version are changing then
  798. # we need to fix them up
  799. new_s = s
  800. new_src_uri = src_uri
  801. if newbpn != bpn:
  802. # ${PN} here is technically almost always incorrect, but people do use it
  803. new_s = new_s.replace('${BPN}', bpn)
  804. new_s = new_s.replace('${PN}', bpn)
  805. new_s = new_s.replace('${BP}', '%s-${PV}' % bpn)
  806. new_src_uri = new_src_uri.replace('${BPN}', bpn)
  807. new_src_uri = new_src_uri.replace('${PN}', bpn)
  808. new_src_uri = new_src_uri.replace('${BP}', '%s-${PV}' % bpn)
  809. if args.version and origfnver == pv:
  810. new_s = new_s.replace('${PV}', pv)
  811. new_s = new_s.replace('${BP}', '${BPN}-%s' % pv)
  812. new_src_uri = new_src_uri.replace('${PV}', pv)
  813. new_src_uri = new_src_uri.replace('${BP}', '${BPN}-%s' % pv)
  814. patchfields = {}
  815. if new_s != s:
  816. patchfields['S'] = new_s
  817. if new_src_uri != src_uri:
  818. patchfields['SRC_URI'] = new_src_uri
  819. if patchfields:
  820. recipefilemd5 = bb.utils.md5_file(recipefile)
  821. oe.recipeutils.patch_recipe(rd, recipefile, patchfields)
  822. newrecipefilemd5 = bb.utils.md5_file(recipefile)
  823. finally:
  824. tinfoil.shutdown()
  825. if args.version:
  826. newver = args.version
  827. else:
  828. newver = origfnver
  829. if newver:
  830. newappend = '%s_%s.bbappend' % (newname, newver)
  831. newfile = '%s_%s.bb' % (newname, newver)
  832. else:
  833. newappend = '%s.bbappend' % newname
  834. newfile = '%s.bb' % newname
  835. oldrecipedir = os.path.dirname(recipefile)
  836. newrecipedir = os.path.join(config.workspace_path, 'recipes', newname)
  837. if oldrecipedir != newrecipedir:
  838. bb.utils.mkdirhier(newrecipedir)
  839. newappend = os.path.join(os.path.dirname(append), newappend)
  840. newfile = os.path.join(newrecipedir, newfile)
  841. # Rename bbappend
  842. logger.info('Renaming %s to %s' % (append, newappend))
  843. os.rename(append, newappend)
  844. # Rename recipe file
  845. logger.info('Renaming %s to %s' % (recipefile, newfile))
  846. os.rename(recipefile, newfile)
  847. # Rename source tree if it's the default path
  848. appendmd5 = None
  849. if not args.no_srctree:
  850. srctree = workspace[args.recipename]['srctree']
  851. if os.path.abspath(srctree) == os.path.join(config.workspace_path, 'sources', args.recipename):
  852. newsrctree = os.path.join(config.workspace_path, 'sources', newname)
  853. logger.info('Renaming %s to %s' % (srctree, newsrctree))
  854. shutil.move(srctree, newsrctree)
  855. # Correct any references (basically EXTERNALSRC*) in the .bbappend
  856. appendmd5 = bb.utils.md5_file(newappend)
  857. appendlines = []
  858. with open(newappend, 'r') as f:
  859. for line in f:
  860. appendlines.append(line)
  861. with open(newappend, 'w') as f:
  862. for line in appendlines:
  863. if srctree in line:
  864. line = line.replace(srctree, newsrctree)
  865. f.write(line)
  866. newappendmd5 = bb.utils.md5_file(newappend)
  867. bpndir = None
  868. newbpndir = None
  869. if newbpn != bpn:
  870. bpndir = os.path.join(oldrecipedir, bpn)
  871. if os.path.exists(bpndir):
  872. newbpndir = os.path.join(newrecipedir, newbpn)
  873. logger.info('Renaming %s to %s' % (bpndir, newbpndir))
  874. shutil.move(bpndir, newbpndir)
  875. bpdir = None
  876. newbpdir = None
  877. if newver != origfnver or newbpn != bpn:
  878. bpdir = os.path.join(oldrecipedir, bp)
  879. if os.path.exists(bpdir):
  880. newbpdir = os.path.join(newrecipedir, '%s-%s' % (newbpn, newver))
  881. logger.info('Renaming %s to %s' % (bpdir, newbpdir))
  882. shutil.move(bpdir, newbpdir)
  883. if oldrecipedir != newrecipedir:
  884. # Move any stray files and delete the old recipe directory
  885. for entry in os.listdir(oldrecipedir):
  886. oldpath = os.path.join(oldrecipedir, entry)
  887. newpath = os.path.join(newrecipedir, entry)
  888. logger.info('Renaming %s to %s' % (oldpath, newpath))
  889. shutil.move(oldpath, newpath)
  890. os.rmdir(oldrecipedir)
  891. # Now take care of entries in .devtool_md5
  892. md5entries = []
  893. with open(os.path.join(config.workspace_path, '.devtool_md5'), 'r') as f:
  894. for line in f:
  895. md5entries.append(line)
  896. if bpndir and newbpndir:
  897. relbpndir = os.path.relpath(bpndir, config.workspace_path) + '/'
  898. else:
  899. relbpndir = None
  900. if bpdir and newbpdir:
  901. relbpdir = os.path.relpath(bpdir, config.workspace_path) + '/'
  902. else:
  903. relbpdir = None
  904. with open(os.path.join(config.workspace_path, '.devtool_md5'), 'w') as f:
  905. for entry in md5entries:
  906. splitentry = entry.rstrip().split('|')
  907. if len(splitentry) > 2:
  908. if splitentry[0] == args.recipename:
  909. splitentry[0] = newname
  910. if splitentry[1] == os.path.relpath(append, config.workspace_path):
  911. splitentry[1] = os.path.relpath(newappend, config.workspace_path)
  912. if appendmd5 and splitentry[2] == appendmd5:
  913. splitentry[2] = newappendmd5
  914. elif splitentry[1] == os.path.relpath(recipefile, config.workspace_path):
  915. splitentry[1] = os.path.relpath(newfile, config.workspace_path)
  916. if recipefilemd5 and splitentry[2] == recipefilemd5:
  917. splitentry[2] = newrecipefilemd5
  918. elif relbpndir and splitentry[1].startswith(relbpndir):
  919. splitentry[1] = os.path.relpath(os.path.join(newbpndir, splitentry[1][len(relbpndir):]), config.workspace_path)
  920. elif relbpdir and splitentry[1].startswith(relbpdir):
  921. splitentry[1] = os.path.relpath(os.path.join(newbpdir, splitentry[1][len(relbpdir):]), config.workspace_path)
  922. entry = '|'.join(splitentry) + '\n'
  923. f.write(entry)
  924. return 0
  925. def _get_patchset_revs(srctree, recipe_path, initial_rev=None):
  926. """Get initial and update rev of a recipe. These are the start point of the
  927. whole patchset and start point for the patches to be re-generated/updated.
  928. """
  929. import bb
  930. # Parse initial rev from recipe if not specified
  931. commits = []
  932. with open(recipe_path, 'r') as f:
  933. for line in f:
  934. if line.startswith('# initial_rev:'):
  935. if not initial_rev:
  936. initial_rev = line.split(':')[-1].strip()
  937. elif line.startswith('# commit:'):
  938. commits.append(line.split(':')[-1].strip())
  939. update_rev = initial_rev
  940. changed_revs = None
  941. if initial_rev:
  942. # Find first actually changed revision
  943. stdout, _ = bb.process.run('git rev-list --reverse %s..HEAD' %
  944. initial_rev, cwd=srctree)
  945. newcommits = stdout.split()
  946. for i in range(min(len(commits), len(newcommits))):
  947. if newcommits[i] == commits[i]:
  948. update_rev = commits[i]
  949. try:
  950. stdout, _ = bb.process.run('git cherry devtool-patched',
  951. cwd=srctree)
  952. except bb.process.ExecutionError as err:
  953. stdout = None
  954. if stdout is not None:
  955. changed_revs = []
  956. for line in stdout.splitlines():
  957. if line.startswith('+ '):
  958. rev = line.split()[1]
  959. if rev in newcommits:
  960. changed_revs.append(rev)
  961. return initial_rev, update_rev, changed_revs
  962. def _remove_file_entries(srcuri, filelist):
  963. """Remove file:// entries from SRC_URI"""
  964. remaining = filelist[:]
  965. entries = []
  966. for fname in filelist:
  967. basename = os.path.basename(fname)
  968. for i in range(len(srcuri)):
  969. if (srcuri[i].startswith('file://') and
  970. os.path.basename(srcuri[i].split(';')[0]) == basename):
  971. entries.append(srcuri[i])
  972. remaining.remove(fname)
  973. srcuri.pop(i)
  974. break
  975. return entries, remaining
  976. def _replace_srcuri_entry(srcuri, filename, newentry):
  977. """Replace entry corresponding to specified file with a new entry"""
  978. basename = os.path.basename(filename)
  979. for i in range(len(srcuri)):
  980. if os.path.basename(srcuri[i].split(';')[0]) == basename:
  981. srcuri.pop(i)
  982. srcuri.insert(i, newentry)
  983. break
  984. def _remove_source_files(append, files, destpath):
  985. """Unlink existing patch files"""
  986. for path in files:
  987. if append:
  988. if not destpath:
  989. raise Exception('destpath should be set here')
  990. path = os.path.join(destpath, os.path.basename(path))
  991. if os.path.exists(path):
  992. logger.info('Removing file %s' % path)
  993. # FIXME "git rm" here would be nice if the file in question is
  994. # tracked
  995. # FIXME there's a chance that this file is referred to by
  996. # another recipe, in which case deleting wouldn't be the
  997. # right thing to do
  998. os.remove(path)
  999. # Remove directory if empty
  1000. try:
  1001. os.rmdir(os.path.dirname(path))
  1002. except OSError as ose:
  1003. if ose.errno != errno.ENOTEMPTY:
  1004. raise
  1005. def _export_patches(srctree, rd, start_rev, destdir, changed_revs=None):
  1006. """Export patches from srctree to given location.
  1007. Returns three-tuple of dicts:
  1008. 1. updated - patches that already exist in SRCURI
  1009. 2. added - new patches that don't exist in SRCURI
  1010. 3 removed - patches that exist in SRCURI but not in exported patches
  1011. In each dict the key is the 'basepath' of the URI and value is the
  1012. absolute path to the existing file in recipe space (if any).
  1013. """
  1014. import oe.recipeutils
  1015. from oe.patch import GitApplyTree
  1016. updated = OrderedDict()
  1017. added = OrderedDict()
  1018. seqpatch_re = re.compile('^([0-9]{4}-)?(.+)')
  1019. existing_patches = dict((os.path.basename(path), path) for path in
  1020. oe.recipeutils.get_recipe_patches(rd))
  1021. # Generate patches from Git, exclude local files directory
  1022. patch_pathspec = _git_exclude_path(srctree, 'oe-local-files')
  1023. GitApplyTree.extractPatches(srctree, start_rev, destdir, patch_pathspec)
  1024. new_patches = sorted(os.listdir(destdir))
  1025. for new_patch in new_patches:
  1026. # Strip numbering from patch names. If it's a git sequence named patch,
  1027. # the numbers might not match up since we are starting from a different
  1028. # revision This does assume that people are using unique shortlog
  1029. # values, but they ought to be anyway...
  1030. new_basename = seqpatch_re.match(new_patch).group(2)
  1031. match_name = None
  1032. for old_patch in existing_patches:
  1033. old_basename = seqpatch_re.match(old_patch).group(2)
  1034. old_basename_splitext = os.path.splitext(old_basename)
  1035. if old_basename.endswith(('.gz', '.bz2', '.Z')) and old_basename_splitext[0] == new_basename:
  1036. old_patch_noext = os.path.splitext(old_patch)[0]
  1037. match_name = old_patch_noext
  1038. break
  1039. elif new_basename == old_basename:
  1040. match_name = old_patch
  1041. break
  1042. if match_name:
  1043. # Rename patch files
  1044. if new_patch != match_name:
  1045. os.rename(os.path.join(destdir, new_patch),
  1046. os.path.join(destdir, match_name))
  1047. # Need to pop it off the list now before checking changed_revs
  1048. oldpath = existing_patches.pop(old_patch)
  1049. if changed_revs is not None:
  1050. # Avoid updating patches that have not actually changed
  1051. with open(os.path.join(destdir, match_name), 'r') as f:
  1052. firstlineitems = f.readline().split()
  1053. # Looking for "From <hash>" line
  1054. if len(firstlineitems) > 1 and len(firstlineitems[1]) == 40:
  1055. if not firstlineitems[1] in changed_revs:
  1056. continue
  1057. # Recompress if necessary
  1058. if oldpath.endswith(('.gz', '.Z')):
  1059. bb.process.run(['gzip', match_name], cwd=destdir)
  1060. if oldpath.endswith('.gz'):
  1061. match_name += '.gz'
  1062. else:
  1063. match_name += '.Z'
  1064. elif oldpath.endswith('.bz2'):
  1065. bb.process.run(['bzip2', match_name], cwd=destdir)
  1066. match_name += '.bz2'
  1067. updated[match_name] = oldpath
  1068. else:
  1069. added[new_patch] = None
  1070. return (updated, added, existing_patches)
  1071. def _create_kconfig_diff(srctree, rd, outfile):
  1072. """Create a kconfig fragment"""
  1073. # Only update config fragment if both config files exist
  1074. orig_config = os.path.join(srctree, '.config.baseline')
  1075. new_config = os.path.join(srctree, '.config.new')
  1076. if os.path.exists(orig_config) and os.path.exists(new_config):
  1077. cmd = ['diff', '--new-line-format=%L', '--old-line-format=',
  1078. '--unchanged-line-format=', orig_config, new_config]
  1079. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
  1080. stderr=subprocess.PIPE)
  1081. stdout, stderr = pipe.communicate()
  1082. if pipe.returncode == 1:
  1083. logger.info("Updating config fragment %s" % outfile)
  1084. with open(outfile, 'wb') as fobj:
  1085. fobj.write(stdout)
  1086. elif pipe.returncode == 0:
  1087. logger.info("Would remove config fragment %s" % outfile)
  1088. if os.path.exists(outfile):
  1089. # Remove fragment file in case of empty diff
  1090. logger.info("Removing config fragment %s" % outfile)
  1091. os.unlink(outfile)
  1092. else:
  1093. raise bb.process.ExecutionError(cmd, pipe.returncode, stdout, stderr)
  1094. return True
  1095. return False
  1096. def _export_local_files(srctree, rd, destdir):
  1097. """Copy local files from srctree to given location.
  1098. Returns three-tuple of dicts:
  1099. 1. updated - files that already exist in SRCURI
  1100. 2. added - new files files that don't exist in SRCURI
  1101. 3 removed - files that exist in SRCURI but not in exported files
  1102. In each dict the key is the 'basepath' of the URI and value is the
  1103. absolute path to the existing file in recipe space (if any).
  1104. """
  1105. import oe.recipeutils
  1106. # Find out local files (SRC_URI files that exist in the "recipe space").
  1107. # Local files that reside in srctree are not included in patch generation.
  1108. # Instead they are directly copied over the original source files (in
  1109. # recipe space).
  1110. existing_files = oe.recipeutils.get_recipe_local_files(rd)
  1111. new_set = None
  1112. updated = OrderedDict()
  1113. added = OrderedDict()
  1114. removed = OrderedDict()
  1115. local_files_dir = os.path.join(srctree, 'oe-local-files')
  1116. git_files = _git_ls_tree(srctree)
  1117. if 'oe-local-files' in git_files:
  1118. # If tracked by Git, take the files from srctree HEAD. First get
  1119. # the tree object of the directory
  1120. tmp_index = os.path.join(srctree, '.git', 'index.tmp.devtool')
  1121. tree = git_files['oe-local-files'][2]
  1122. bb.process.run(['git', 'checkout', tree, '--', '.'], cwd=srctree,
  1123. env=dict(os.environ, GIT_WORK_TREE=destdir,
  1124. GIT_INDEX_FILE=tmp_index))
  1125. new_set = list(_git_ls_tree(srctree, tree, True).keys())
  1126. elif os.path.isdir(local_files_dir):
  1127. # If not tracked by Git, just copy from working copy
  1128. new_set = _ls_tree(os.path.join(srctree, 'oe-local-files'))
  1129. bb.process.run(['cp', '-ax',
  1130. os.path.join(srctree, 'oe-local-files', '.'), destdir])
  1131. else:
  1132. new_set = []
  1133. # Special handling for kernel config
  1134. if bb.data.inherits_class('kernel-yocto', rd):
  1135. fragment_fn = 'devtool-fragment.cfg'
  1136. fragment_path = os.path.join(destdir, fragment_fn)
  1137. if _create_kconfig_diff(srctree, rd, fragment_path):
  1138. if os.path.exists(fragment_path):
  1139. if fragment_fn not in new_set:
  1140. new_set.append(fragment_fn)
  1141. # Copy fragment to local-files
  1142. if os.path.isdir(local_files_dir):
  1143. shutil.copy2(fragment_path, local_files_dir)
  1144. else:
  1145. if fragment_fn in new_set:
  1146. new_set.remove(fragment_fn)
  1147. # Remove fragment from local-files
  1148. if os.path.exists(os.path.join(local_files_dir, fragment_fn)):
  1149. os.unlink(os.path.join(local_files_dir, fragment_fn))
  1150. if new_set is not None:
  1151. for fname in new_set:
  1152. if fname in existing_files:
  1153. origpath = existing_files.pop(fname)
  1154. workpath = os.path.join(local_files_dir, fname)
  1155. if not filecmp.cmp(origpath, workpath):
  1156. updated[fname] = origpath
  1157. elif fname != '.gitignore':
  1158. added[fname] = None
  1159. workdir = rd.getVar('WORKDIR')
  1160. s = rd.getVar('S')
  1161. if not s.endswith(os.sep):
  1162. s += os.sep
  1163. if workdir != s:
  1164. # Handle files where subdir= was specified
  1165. for fname in list(existing_files.keys()):
  1166. # FIXME handle both subdir starting with BP and not?
  1167. fworkpath = os.path.join(workdir, fname)
  1168. if fworkpath.startswith(s):
  1169. fpath = os.path.join(srctree, os.path.relpath(fworkpath, s))
  1170. if os.path.exists(fpath):
  1171. origpath = existing_files.pop(fname)
  1172. if not filecmp.cmp(origpath, fpath):
  1173. updated[fpath] = origpath
  1174. removed = existing_files
  1175. return (updated, added, removed)
  1176. def _determine_files_dir(rd):
  1177. """Determine the appropriate files directory for a recipe"""
  1178. recipedir = rd.getVar('FILE_DIRNAME')
  1179. for entry in rd.getVar('FILESPATH').split(':'):
  1180. relpth = os.path.relpath(entry, recipedir)
  1181. if not os.sep in relpth:
  1182. # One (or zero) levels below only, so we don't put anything in machine-specific directories
  1183. if os.path.isdir(entry):
  1184. return entry
  1185. return os.path.join(recipedir, rd.getVar('BPN'))
  1186. def _update_recipe_srcrev(srctree, rd, appendlayerdir, wildcard_version, no_remove):
  1187. """Implement the 'srcrev' mode of update-recipe"""
  1188. import bb
  1189. import oe.recipeutils
  1190. recipefile = rd.getVar('FILE')
  1191. logger.info('Updating SRCREV in recipe %s' % os.path.basename(recipefile))
  1192. # Get HEAD revision
  1193. try:
  1194. stdout, _ = bb.process.run('git rev-parse HEAD', cwd=srctree)
  1195. except bb.process.ExecutionError as err:
  1196. raise DevtoolError('Failed to get HEAD revision in %s: %s' %
  1197. (srctree, err))
  1198. srcrev = stdout.strip()
  1199. if len(srcrev) != 40:
  1200. raise DevtoolError('Invalid hash returned by git: %s' % stdout)
  1201. destpath = None
  1202. remove_files = []
  1203. patchfields = {}
  1204. patchfields['SRCREV'] = srcrev
  1205. orig_src_uri = rd.getVar('SRC_URI', False) or ''
  1206. srcuri = orig_src_uri.split()
  1207. tempdir = tempfile.mkdtemp(prefix='devtool')
  1208. update_srcuri = False
  1209. try:
  1210. local_files_dir = tempfile.mkdtemp(dir=tempdir)
  1211. upd_f, new_f, del_f = _export_local_files(srctree, rd, local_files_dir)
  1212. if not no_remove:
  1213. # Find list of existing patches in recipe file
  1214. patches_dir = tempfile.mkdtemp(dir=tempdir)
  1215. old_srcrev = (rd.getVar('SRCREV', False) or '')
  1216. upd_p, new_p, del_p = _export_patches(srctree, rd, old_srcrev,
  1217. patches_dir)
  1218. logger.debug('Patches: update %s, new %s, delete %s' % (dict(upd_p), dict(new_p), dict(del_p)))
  1219. # Remove deleted local files and "overlapping" patches
  1220. remove_files = list(del_f.values()) + list(upd_p.values()) + list(del_p.values())
  1221. if remove_files:
  1222. removedentries = _remove_file_entries(srcuri, remove_files)[0]
  1223. update_srcuri = True
  1224. if appendlayerdir:
  1225. files = dict((os.path.join(local_files_dir, key), val) for
  1226. key, val in list(upd_f.items()) + list(new_f.items()))
  1227. removevalues = {}
  1228. if update_srcuri:
  1229. removevalues = {'SRC_URI': removedentries}
  1230. patchfields['SRC_URI'] = '\\\n '.join(srcuri)
  1231. _, destpath = oe.recipeutils.bbappend_recipe(
  1232. rd, appendlayerdir, files, wildcardver=wildcard_version,
  1233. extralines=patchfields, removevalues=removevalues)
  1234. else:
  1235. files_dir = _determine_files_dir(rd)
  1236. for basepath, path in upd_f.items():
  1237. logger.info('Updating file %s' % basepath)
  1238. if os.path.isabs(basepath):
  1239. # Original file (probably with subdir pointing inside source tree)
  1240. # so we do not want to move it, just copy
  1241. _copy_file(basepath, path)
  1242. else:
  1243. _move_file(os.path.join(local_files_dir, basepath), path)
  1244. update_srcuri= True
  1245. for basepath, path in new_f.items():
  1246. logger.info('Adding new file %s' % basepath)
  1247. _move_file(os.path.join(local_files_dir, basepath),
  1248. os.path.join(files_dir, basepath))
  1249. srcuri.append('file://%s' % basepath)
  1250. update_srcuri = True
  1251. if update_srcuri:
  1252. patchfields['SRC_URI'] = ' '.join(srcuri)
  1253. oe.recipeutils.patch_recipe(rd, recipefile, patchfields)
  1254. finally:
  1255. shutil.rmtree(tempdir)
  1256. if not 'git://' in orig_src_uri:
  1257. logger.info('You will need to update SRC_URI within the recipe to '
  1258. 'point to a git repository where you have pushed your '
  1259. 'changes')
  1260. _remove_source_files(appendlayerdir, remove_files, destpath)
  1261. return True
  1262. def _update_recipe_patch(recipename, workspace, srctree, rd, appendlayerdir, wildcard_version, no_remove, initial_rev):
  1263. """Implement the 'patch' mode of update-recipe"""
  1264. import bb
  1265. import oe.recipeutils
  1266. recipefile = rd.getVar('FILE')
  1267. append = workspace[recipename]['bbappend']
  1268. if not os.path.exists(append):
  1269. raise DevtoolError('unable to find workspace bbappend for recipe %s' %
  1270. recipename)
  1271. initial_rev, update_rev, changed_revs = _get_patchset_revs(srctree, append, initial_rev)
  1272. if not initial_rev:
  1273. raise DevtoolError('Unable to find initial revision - please specify '
  1274. 'it with --initial-rev')
  1275. dl_dir = rd.getVar('DL_DIR')
  1276. if not dl_dir.endswith('/'):
  1277. dl_dir += '/'
  1278. tempdir = tempfile.mkdtemp(prefix='devtool')
  1279. try:
  1280. local_files_dir = tempfile.mkdtemp(dir=tempdir)
  1281. upd_f, new_f, del_f = _export_local_files(srctree, rd, local_files_dir)
  1282. remove_files = []
  1283. if not no_remove:
  1284. # Get all patches from source tree and check if any should be removed
  1285. all_patches_dir = tempfile.mkdtemp(dir=tempdir)
  1286. upd_p, new_p, del_p = _export_patches(srctree, rd, initial_rev,
  1287. all_patches_dir)
  1288. # Remove deleted local files and patches
  1289. remove_files = list(del_f.values()) + list(del_p.values())
  1290. # Get updated patches from source tree
  1291. patches_dir = tempfile.mkdtemp(dir=tempdir)
  1292. upd_p, new_p, del_p = _export_patches(srctree, rd, update_rev,
  1293. patches_dir, changed_revs)
  1294. updatefiles = False
  1295. updaterecipe = False
  1296. destpath = None
  1297. srcuri = (rd.getVar('SRC_URI', False) or '').split()
  1298. if appendlayerdir:
  1299. files = dict((os.path.join(local_files_dir, key), val) for
  1300. key, val in list(upd_f.items()) + list(new_f.items()))
  1301. files.update(dict((os.path.join(patches_dir, key), val) for
  1302. key, val in list(upd_p.items()) + list(new_p.items())))
  1303. if files or remove_files:
  1304. removevalues = None
  1305. if remove_files:
  1306. removedentries, remaining = _remove_file_entries(
  1307. srcuri, remove_files)
  1308. if removedentries or remaining:
  1309. remaining = ['file://' + os.path.basename(item) for
  1310. item in remaining]
  1311. removevalues = {'SRC_URI': removedentries + remaining}
  1312. _, destpath = oe.recipeutils.bbappend_recipe(
  1313. rd, appendlayerdir, files,
  1314. wildcardver=wildcard_version,
  1315. removevalues=removevalues)
  1316. else:
  1317. logger.info('No patches or local source files needed updating')
  1318. else:
  1319. # Update existing files
  1320. files_dir = _determine_files_dir(rd)
  1321. for basepath, path in upd_f.items():
  1322. logger.info('Updating file %s' % basepath)
  1323. if os.path.isabs(basepath):
  1324. # Original file (probably with subdir pointing inside source tree)
  1325. # so we do not want to move it, just copy
  1326. _copy_file(basepath, path)
  1327. else:
  1328. _move_file(os.path.join(local_files_dir, basepath), path)
  1329. updatefiles = True
  1330. for basepath, path in upd_p.items():
  1331. patchfn = os.path.join(patches_dir, basepath)
  1332. if os.path.dirname(path) + '/' == dl_dir:
  1333. # This is a a downloaded patch file - we now need to
  1334. # replace the entry in SRC_URI with our local version
  1335. logger.info('Replacing remote patch %s with updated local version' % basepath)
  1336. path = os.path.join(files_dir, basepath)
  1337. _replace_srcuri_entry(srcuri, basepath, 'file://%s' % basepath)
  1338. updaterecipe = True
  1339. else:
  1340. logger.info('Updating patch %s' % basepath)
  1341. logger.debug('Moving new patch %s to %s' % (patchfn, path))
  1342. _move_file(patchfn, path)
  1343. updatefiles = True
  1344. # Add any new files
  1345. for basepath, path in new_f.items():
  1346. logger.info('Adding new file %s' % basepath)
  1347. _move_file(os.path.join(local_files_dir, basepath),
  1348. os.path.join(files_dir, basepath))
  1349. srcuri.append('file://%s' % basepath)
  1350. updaterecipe = True
  1351. for basepath, path in new_p.items():
  1352. logger.info('Adding new patch %s' % basepath)
  1353. _move_file(os.path.join(patches_dir, basepath),
  1354. os.path.join(files_dir, basepath))
  1355. srcuri.append('file://%s' % basepath)
  1356. updaterecipe = True
  1357. # Update recipe, if needed
  1358. if _remove_file_entries(srcuri, remove_files)[0]:
  1359. updaterecipe = True
  1360. if updaterecipe:
  1361. logger.info('Updating recipe %s' % os.path.basename(recipefile))
  1362. oe.recipeutils.patch_recipe(rd, recipefile,
  1363. {'SRC_URI': ' '.join(srcuri)})
  1364. elif not updatefiles:
  1365. # Neither patches nor recipe were updated
  1366. logger.info('No patches or files need updating')
  1367. return False
  1368. finally:
  1369. shutil.rmtree(tempdir)
  1370. _remove_source_files(appendlayerdir, remove_files, destpath)
  1371. return True
  1372. def _guess_recipe_update_mode(srctree, rdata):
  1373. """Guess the recipe update mode to use"""
  1374. src_uri = (rdata.getVar('SRC_URI', False) or '').split()
  1375. git_uris = [uri for uri in src_uri if uri.startswith('git://')]
  1376. if not git_uris:
  1377. return 'patch'
  1378. # Just use the first URI for now
  1379. uri = git_uris[0]
  1380. # Check remote branch
  1381. params = bb.fetch.decodeurl(uri)[5]
  1382. upstr_branch = params['branch'] if 'branch' in params else 'master'
  1383. # Check if current branch HEAD is found in upstream branch
  1384. stdout, _ = bb.process.run('git rev-parse HEAD', cwd=srctree)
  1385. head_rev = stdout.rstrip()
  1386. stdout, _ = bb.process.run('git branch -r --contains %s' % head_rev,
  1387. cwd=srctree)
  1388. remote_brs = [branch.strip() for branch in stdout.splitlines()]
  1389. if 'origin/' + upstr_branch in remote_brs:
  1390. return 'srcrev'
  1391. return 'patch'
  1392. def _update_recipe(recipename, workspace, rd, mode, appendlayerdir, wildcard_version, no_remove, initial_rev):
  1393. srctree = workspace[recipename]['srctree']
  1394. if mode == 'auto':
  1395. mode = _guess_recipe_update_mode(srctree, rd)
  1396. if mode == 'srcrev':
  1397. updated = _update_recipe_srcrev(srctree, rd, appendlayerdir, wildcard_version, no_remove)
  1398. elif mode == 'patch':
  1399. updated = _update_recipe_patch(recipename, workspace, srctree, rd, appendlayerdir, wildcard_version, no_remove, initial_rev)
  1400. else:
  1401. raise DevtoolError('update_recipe: invalid mode %s' % mode)
  1402. return updated
  1403. def update_recipe(args, config, basepath, workspace):
  1404. """Entry point for the devtool 'update-recipe' subcommand"""
  1405. check_workspace_recipe(workspace, args.recipename)
  1406. if args.append:
  1407. if not os.path.exists(args.append):
  1408. raise DevtoolError('bbappend destination layer directory "%s" '
  1409. 'does not exist' % args.append)
  1410. if not os.path.exists(os.path.join(args.append, 'conf', 'layer.conf')):
  1411. raise DevtoolError('conf/layer.conf not found in bbappend '
  1412. 'destination layer "%s"' % args.append)
  1413. tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
  1414. try:
  1415. rd = parse_recipe(config, tinfoil, args.recipename, True)
  1416. if not rd:
  1417. return 1
  1418. updated = _update_recipe(args.recipename, workspace, rd, args.mode, args.append, args.wildcard_version, args.no_remove, args.initial_rev)
  1419. if updated:
  1420. rf = rd.getVar('FILE')
  1421. if rf.startswith(config.workspace_path):
  1422. logger.warn('Recipe file %s has been updated but is inside the workspace - you will need to move it (and any associated files next to it) out to the desired layer before using "devtool reset" in order to keep any changes' % rf)
  1423. finally:
  1424. tinfoil.shutdown()
  1425. return 0
  1426. def status(args, config, basepath, workspace):
  1427. """Entry point for the devtool 'status' subcommand"""
  1428. if workspace:
  1429. for recipe, value in sorted(workspace.items()):
  1430. recipefile = value['recipefile']
  1431. if recipefile:
  1432. recipestr = ' (%s)' % recipefile
  1433. else:
  1434. recipestr = ''
  1435. print("%s: %s%s" % (recipe, value['srctree'], recipestr))
  1436. else:
  1437. logger.info('No recipes currently in your workspace - you can use "devtool modify" to work on an existing recipe or "devtool add" to add a new one')
  1438. return 0
  1439. def _reset(recipes, no_clean, config, basepath, workspace):
  1440. """Reset one or more recipes"""
  1441. def clean_preferred_provider(pn, layerconf_path):
  1442. """Remove PREFERRED_PROVIDER from layer.conf'"""
  1443. import re
  1444. layerconf_file = os.path.join(layerconf_path, 'conf', 'layer.conf')
  1445. new_layerconf_file = os.path.join(layerconf_path, 'conf', '.layer.conf')
  1446. pprovider_found = False
  1447. with open(layerconf_file, 'r') as f:
  1448. lines = f.readlines()
  1449. with open(new_layerconf_file, 'a') as nf:
  1450. for line in lines:
  1451. pprovider_exp = r'^PREFERRED_PROVIDER_.*? = "' + pn + r'"$'
  1452. if not re.match(pprovider_exp, line):
  1453. nf.write(line)
  1454. else:
  1455. pprovider_found = True
  1456. if pprovider_found:
  1457. shutil.move(new_layerconf_file, layerconf_file)
  1458. else:
  1459. os.remove(new_layerconf_file)
  1460. if recipes and not no_clean:
  1461. if len(recipes) == 1:
  1462. logger.info('Cleaning sysroot for recipe %s...' % recipes[0])
  1463. else:
  1464. logger.info('Cleaning sysroot for recipes %s...' % ', '.join(recipes))
  1465. # If the recipe file itself was created in the workspace, and
  1466. # it uses BBCLASSEXTEND, then we need to also clean the other
  1467. # variants
  1468. targets = []
  1469. for recipe in recipes:
  1470. targets.append(recipe)
  1471. recipefile = workspace[recipe]['recipefile']
  1472. if recipefile and os.path.exists(recipefile):
  1473. targets.extend(get_bbclassextend_targets(recipefile, recipe))
  1474. try:
  1475. exec_build_env_command(config.init_path, basepath, 'bitbake -c clean %s' % ' '.join(targets))
  1476. except bb.process.ExecutionError as e:
  1477. raise DevtoolError('Command \'%s\' failed, output:\n%s\nIf you '
  1478. 'wish, you may specify -n/--no-clean to '
  1479. 'skip running this command when resetting' %
  1480. (e.command, e.stdout))
  1481. for pn in recipes:
  1482. _check_preserve(config, pn)
  1483. preservepath = os.path.join(config.workspace_path, 'attic', pn, pn)
  1484. def preservedir(origdir):
  1485. if os.path.exists(origdir):
  1486. for root, dirs, files in os.walk(origdir):
  1487. for fn in files:
  1488. logger.warn('Preserving %s in %s' % (fn, preservepath))
  1489. _move_file(os.path.join(origdir, fn),
  1490. os.path.join(preservepath, fn))
  1491. for dn in dirs:
  1492. preservedir(os.path.join(root, dn))
  1493. os.rmdir(origdir)
  1494. preservedir(os.path.join(config.workspace_path, 'recipes', pn))
  1495. # We don't automatically create this dir next to appends, but the user can
  1496. preservedir(os.path.join(config.workspace_path, 'appends', pn))
  1497. srctree = workspace[pn]['srctree']
  1498. if os.path.isdir(srctree):
  1499. if os.listdir(srctree):
  1500. # We don't want to risk wiping out any work in progress
  1501. logger.info('Leaving source tree %s as-is; if you no '
  1502. 'longer need it then please delete it manually'
  1503. % srctree)
  1504. else:
  1505. # This is unlikely, but if it's empty we can just remove it
  1506. os.rmdir(srctree)
  1507. clean_preferred_provider(pn, config.workspace_path)
  1508. def reset(args, config, basepath, workspace):
  1509. """Entry point for the devtool 'reset' subcommand"""
  1510. import bb
  1511. if args.recipename:
  1512. if args.all:
  1513. raise DevtoolError("Recipe cannot be specified if -a/--all is used")
  1514. else:
  1515. for recipe in args.recipename:
  1516. check_workspace_recipe(workspace, recipe, checksrc=False)
  1517. elif not args.all:
  1518. raise DevtoolError("Recipe must be specified, or specify -a/--all to "
  1519. "reset all recipes")
  1520. if args.all:
  1521. recipes = list(workspace.keys())
  1522. else:
  1523. recipes = args.recipename
  1524. _reset(recipes, args.no_clean, config, basepath, workspace)
  1525. return 0
  1526. def _get_layer(layername, d):
  1527. """Determine the base layer path for the specified layer name/path"""
  1528. layerdirs = d.getVar('BBLAYERS').split()
  1529. layers = {os.path.basename(p): p for p in layerdirs}
  1530. # Provide some shortcuts
  1531. if layername.lower() in ['oe-core', 'openembedded-core']:
  1532. layerdir = layers.get('meta', None)
  1533. else:
  1534. layerdir = layers.get(layername, None)
  1535. if layerdir:
  1536. layerdir = os.path.abspath(layerdir)
  1537. return layerdir or layername
  1538. def finish(args, config, basepath, workspace):
  1539. """Entry point for the devtool 'finish' subcommand"""
  1540. import bb
  1541. import oe.recipeutils
  1542. check_workspace_recipe(workspace, args.recipename)
  1543. no_clean = False
  1544. tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
  1545. try:
  1546. rd = parse_recipe(config, tinfoil, args.recipename, True)
  1547. if not rd:
  1548. return 1
  1549. destlayerdir = _get_layer(args.destination, tinfoil.config_data)
  1550. origlayerdir = oe.recipeutils.find_layerdir(rd.getVar('FILE'))
  1551. if not os.path.isdir(destlayerdir):
  1552. raise DevtoolError('Unable to find layer or directory matching "%s"' % args.destination)
  1553. if os.path.abspath(destlayerdir) == config.workspace_path:
  1554. raise DevtoolError('"%s" specifies the workspace layer - that is not a valid destination' % args.destination)
  1555. # If it's an upgrade, grab the original path
  1556. origpath = None
  1557. origfilelist = None
  1558. append = workspace[args.recipename]['bbappend']
  1559. with open(append, 'r') as f:
  1560. for line in f:
  1561. if line.startswith('# original_path:'):
  1562. origpath = line.split(':')[1].strip()
  1563. elif line.startswith('# original_files:'):
  1564. origfilelist = line.split(':')[1].split()
  1565. if origlayerdir == config.workspace_path:
  1566. # Recipe file itself is in workspace, update it there first
  1567. appendlayerdir = None
  1568. origrelpath = None
  1569. if origpath:
  1570. origlayerpath = oe.recipeutils.find_layerdir(origpath)
  1571. if origlayerpath:
  1572. origrelpath = os.path.relpath(origpath, origlayerpath)
  1573. destpath = oe.recipeutils.get_bbfile_path(rd, destlayerdir, origrelpath)
  1574. if not destpath:
  1575. raise DevtoolError("Unable to determine destination layer path - check that %s specifies an actual layer and %s/conf/layer.conf specifies BBFILES. You may also need to specify a more complete path." % (args.destination, destlayerdir))
  1576. # Warn if the layer isn't in bblayers.conf (the code to create a bbappend will do this in other cases)
  1577. layerdirs = [os.path.abspath(layerdir) for layerdir in rd.getVar('BBLAYERS').split()]
  1578. if not os.path.abspath(destlayerdir) in layerdirs:
  1579. bb.warn('Specified destination layer is not currently enabled in bblayers.conf, so the %s recipe will now be unavailable in your current configuration until you add the layer there' % args.recipename)
  1580. elif destlayerdir == origlayerdir:
  1581. # Same layer, update the original recipe
  1582. appendlayerdir = None
  1583. destpath = None
  1584. else:
  1585. # Create/update a bbappend in the specified layer
  1586. appendlayerdir = destlayerdir
  1587. destpath = None
  1588. # Remove any old files in the case of an upgrade
  1589. if origpath and origfilelist and oe.recipeutils.find_layerdir(origpath) == oe.recipeutils.find_layerdir(destlayerdir):
  1590. for fn in origfilelist:
  1591. fnp = os.path.join(origpath, fn)
  1592. try:
  1593. os.remove(fnp)
  1594. except FileNotFoundError:
  1595. pass
  1596. # Actually update the recipe / bbappend
  1597. _update_recipe(args.recipename, workspace, rd, args.mode, appendlayerdir, wildcard_version=True, no_remove=False, initial_rev=args.initial_rev)
  1598. if origlayerdir == config.workspace_path and destpath:
  1599. # Recipe file itself is in the workspace - need to move it and any
  1600. # associated files to the specified layer
  1601. no_clean = True
  1602. logger.info('Moving recipe file to %s' % destpath)
  1603. recipedir = os.path.dirname(rd.getVar('FILE'))
  1604. for root, _, files in os.walk(recipedir):
  1605. for fn in files:
  1606. srcpath = os.path.join(root, fn)
  1607. relpth = os.path.relpath(os.path.dirname(srcpath), recipedir)
  1608. destdir = os.path.abspath(os.path.join(destpath, relpth))
  1609. bb.utils.mkdirhier(destdir)
  1610. shutil.move(srcpath, os.path.join(destdir, fn))
  1611. finally:
  1612. tinfoil.shutdown()
  1613. # Everything else has succeeded, we can now reset
  1614. _reset([args.recipename], no_clean=no_clean, config=config, basepath=basepath, workspace=workspace)
  1615. return 0
  1616. def get_default_srctree(config, recipename=''):
  1617. """Get the default srctree path"""
  1618. srctreeparent = config.get('General', 'default_source_parent_dir', config.workspace_path)
  1619. if recipename:
  1620. return os.path.join(srctreeparent, 'sources', recipename)
  1621. else:
  1622. return os.path.join(srctreeparent, 'sources')
  1623. def register_commands(subparsers, context):
  1624. """Register devtool subcommands from this plugin"""
  1625. defsrctree = get_default_srctree(context.config)
  1626. parser_add = subparsers.add_parser('add', help='Add a new recipe',
  1627. description='Adds a new recipe to the workspace to build a specified source tree. Can optionally fetch a remote URI and unpack it to create the source tree.',
  1628. group='starting', order=100)
  1629. parser_add.add_argument('recipename', nargs='?', help='Name for new recipe to add (just name - no version, path or extension). If not specified, will attempt to auto-detect it.')
  1630. parser_add.add_argument('srctree', nargs='?', help='Path to external source tree. If not specified, a subdirectory of %s will be used.' % defsrctree)
  1631. parser_add.add_argument('fetchuri', nargs='?', help='Fetch the specified URI and extract it to create the source tree')
  1632. group = parser_add.add_mutually_exclusive_group()
  1633. group.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
  1634. group.add_argument('--no-same-dir', help='Force build in a separate build directory', action="store_true")
  1635. parser_add.add_argument('--fetch', '-f', help='Fetch the specified URI and extract it to create the source tree (deprecated - pass as positional argument instead)', metavar='URI')
  1636. parser_add.add_argument('--fetch-dev', help='For npm, also fetch devDependencies', action="store_true")
  1637. parser_add.add_argument('--version', '-V', help='Version to use within recipe (PV)')
  1638. parser_add.add_argument('--no-git', '-g', help='If fetching source, do not set up source tree as a git repository', action="store_true")
  1639. group = parser_add.add_mutually_exclusive_group()
  1640. group.add_argument('--srcrev', '-S', help='Source revision to fetch if fetching from an SCM such as git (default latest)')
  1641. group.add_argument('--autorev', '-a', help='When fetching from a git repository, set SRCREV in the recipe to a floating revision instead of fixed', action="store_true")
  1642. parser_add.add_argument('--srcbranch', '-B', help='Branch in source repository if fetching from an SCM such as git (default master)')
  1643. parser_add.add_argument('--binary', '-b', help='Treat the source tree as something that should be installed verbatim (no compilation, same directory structure). Useful with binary packages e.g. RPMs.', action='store_true')
  1644. parser_add.add_argument('--also-native', help='Also add native variant (i.e. support building recipe for the build host as well as the target machine)', action='store_true')
  1645. parser_add.add_argument('--src-subdir', help='Specify subdirectory within source tree to use', metavar='SUBDIR')
  1646. parser_add.add_argument('--mirrors', help='Enable PREMIRRORS and MIRRORS for source tree fetching (disable by default).', action="store_true")
  1647. parser_add.add_argument('--provides', '-p', help='Specify an alias for the item provided by the recipe. E.g. virtual/libgl')
  1648. parser_add.set_defaults(func=add, fixed_setup=context.fixed_setup)
  1649. parser_modify = subparsers.add_parser('modify', help='Modify the source for an existing recipe',
  1650. description='Sets up the build environment to modify the source for an existing recipe. The default behaviour is to extract the source being fetched by the recipe into a git tree so you can work on it; alternatively if you already have your own pre-prepared source tree you can specify -n/--no-extract.',
  1651. group='starting', order=90)
  1652. parser_modify.add_argument('recipename', help='Name of existing recipe to edit (just name - no version, path or extension)')
  1653. parser_modify.add_argument('srctree', nargs='?', help='Path to external source tree. If not specified, a subdirectory of %s will be used.' % defsrctree)
  1654. parser_modify.add_argument('--wildcard', '-w', action="store_true", help='Use wildcard for unversioned bbappend')
  1655. group = parser_modify.add_mutually_exclusive_group()
  1656. group.add_argument('--extract', '-x', action="store_true", help='Extract source for recipe (default)')
  1657. group.add_argument('--no-extract', '-n', action="store_true", help='Do not extract source, expect it to exist')
  1658. group = parser_modify.add_mutually_exclusive_group()
  1659. group.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
  1660. group.add_argument('--no-same-dir', help='Force build in a separate build directory', action="store_true")
  1661. parser_modify.add_argument('--branch', '-b', default="devtool", help='Name for development branch to checkout (when not using -n/--no-extract) (default "%(default)s")')
  1662. parser_modify.add_argument('--keep-temp', help='Keep temporary directory (for debugging)', action="store_true")
  1663. parser_modify.set_defaults(func=modify)
  1664. parser_extract = subparsers.add_parser('extract', help='Extract the source for an existing recipe',
  1665. description='Extracts the source for an existing recipe',
  1666. group='advanced')
  1667. parser_extract.add_argument('recipename', help='Name of recipe to extract the source for')
  1668. parser_extract.add_argument('srctree', help='Path to where to extract the source tree')
  1669. parser_extract.add_argument('--branch', '-b', default="devtool", help='Name for development branch to checkout (default "%(default)s")')
  1670. parser_extract.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
  1671. parser_extract.set_defaults(func=extract, no_workspace=True)
  1672. parser_sync = subparsers.add_parser('sync', help='Synchronize the source tree for an existing recipe',
  1673. description='Synchronize the previously extracted source tree for an existing recipe',
  1674. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  1675. group='advanced')
  1676. parser_sync.add_argument('recipename', help='Name of recipe to sync the source for')
  1677. parser_sync.add_argument('srctree', help='Path to the source tree')
  1678. parser_sync.add_argument('--branch', '-b', default="devtool", help='Name for development branch to checkout')
  1679. parser_sync.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
  1680. parser_sync.set_defaults(func=sync)
  1681. parser_rename = subparsers.add_parser('rename', help='Rename a recipe file in the workspace',
  1682. description='Renames the recipe file for a recipe in the workspace, changing the name or version part or both, ensuring that all references within the workspace are updated at the same time. Only works when the recipe file itself is in the workspace, e.g. after devtool add. Particularly useful when devtool add did not automatically determine the correct name.',
  1683. group='working', order=10)
  1684. parser_rename.add_argument('recipename', help='Current name of recipe to rename')
  1685. parser_rename.add_argument('newname', nargs='?', help='New name for recipe (optional, not needed if you only want to change the version)')
  1686. parser_rename.add_argument('--version', '-V', help='Change the version (NOTE: this does not change the version fetched by the recipe, just the version in the recipe file name)')
  1687. parser_rename.add_argument('--no-srctree', '-s', action='store_true', help='Do not rename the source tree directory (if the default source tree path has been used) - keeping the old name may be desirable if there are internal/other external references to this path')
  1688. parser_rename.set_defaults(func=rename)
  1689. parser_update_recipe = subparsers.add_parser('update-recipe', help='Apply changes from external source tree to recipe',
  1690. description='Applies changes from external source tree to a recipe (updating/adding/removing patches as necessary, or by updating SRCREV). Note that these changes need to have been committed to the git repository in order to be recognised.',
  1691. group='working', order=-90)
  1692. parser_update_recipe.add_argument('recipename', help='Name of recipe to update')
  1693. parser_update_recipe.add_argument('--mode', '-m', choices=['patch', 'srcrev', 'auto'], default='auto', help='Update mode (where %(metavar)s is %(choices)s; default is %(default)s)', metavar='MODE')
  1694. parser_update_recipe.add_argument('--initial-rev', help='Override starting revision for patches')
  1695. parser_update_recipe.add_argument('--append', '-a', help='Write changes to a bbappend in the specified layer instead of the recipe', metavar='LAYERDIR')
  1696. parser_update_recipe.add_argument('--wildcard-version', '-w', help='In conjunction with -a/--append, use a wildcard to make the bbappend apply to any recipe version', action='store_true')
  1697. parser_update_recipe.add_argument('--no-remove', '-n', action="store_true", help='Don\'t remove patches, only add or update')
  1698. parser_update_recipe.set_defaults(func=update_recipe)
  1699. parser_status = subparsers.add_parser('status', help='Show workspace status',
  1700. description='Lists recipes currently in your workspace and the paths to their respective external source trees',
  1701. group='info', order=100)
  1702. parser_status.set_defaults(func=status)
  1703. parser_reset = subparsers.add_parser('reset', help='Remove a recipe from your workspace',
  1704. description='Removes the specified recipe(s) from your workspace (resetting its state back to that defined by the metadata).',
  1705. group='working', order=-100)
  1706. parser_reset.add_argument('recipename', nargs='*', help='Recipe to reset')
  1707. parser_reset.add_argument('--all', '-a', action="store_true", help='Reset all recipes (clear workspace)')
  1708. parser_reset.add_argument('--no-clean', '-n', action="store_true", help='Don\'t clean the sysroot to remove recipe output')
  1709. parser_reset.set_defaults(func=reset)
  1710. parser_finish = subparsers.add_parser('finish', help='Finish working on a recipe in your workspace',
  1711. description='Pushes any committed changes to the specified recipe to the specified layer and removes it from your workspace. Roughly equivalent to an update-recipe followed by reset, except the update-recipe step will do the "right thing" depending on the recipe and the destination layer specified.',
  1712. group='working', order=-100)
  1713. parser_finish.add_argument('recipename', help='Recipe to finish')
  1714. parser_finish.add_argument('destination', help='Layer/path to put recipe into. Can be the name of a layer configured in your bblayers.conf, the path to the base of a layer, or a partial path inside a layer. %(prog)s will attempt to complete the path based on the layer\'s structure.')
  1715. parser_finish.add_argument('--mode', '-m', choices=['patch', 'srcrev', 'auto'], default='auto', help='Update mode (where %(metavar)s is %(choices)s; default is %(default)s)', metavar='MODE')
  1716. parser_finish.add_argument('--initial-rev', help='Override starting revision for patches')
  1717. parser_finish.set_defaults(func=finish)