standard.py 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396
  1. # Development tool - standard commands plugin
  2. #
  3. # Copyright (C) 2014-2017 Intel Corporation
  4. #
  5. # SPDX-License-Identifier: GPL-2.0-only
  6. #
  7. """Devtool standard plugins"""
  8. import os
  9. import sys
  10. import re
  11. import shutil
  12. import subprocess
  13. import tempfile
  14. import logging
  15. import argparse
  16. import argparse_oe
  17. import scriptutils
  18. import errno
  19. import glob
  20. from collections import OrderedDict
  21. from devtool import exec_build_env_command, setup_tinfoil, check_workspace_recipe, use_external_build, setup_git_repo, recipe_to_append, get_bbclassextend_targets, update_unlockedsigs, check_prerelease_version, check_git_repo_dirty, check_git_repo_op, DevtoolError
  22. from devtool import parse_recipe
  23. import bb.utils
  24. logger = logging.getLogger('devtool')
  25. override_branch_prefix = 'devtool-override-'
  26. def add(args, config, basepath, workspace):
  27. """Entry point for the devtool 'add' subcommand"""
  28. import bb.data
  29. import bb.process
  30. import oe.recipeutils
  31. if not args.recipename and not args.srctree and not args.fetch and not args.fetchuri:
  32. raise argparse_oe.ArgumentUsageError('At least one of recipename, srctree, fetchuri or -f/--fetch must be specified', 'add')
  33. # These are positional arguments, but because we're nice, allow
  34. # specifying e.g. source tree without name, or fetch URI without name or
  35. # source tree (if we can detect that that is what the user meant)
  36. if scriptutils.is_src_url(args.recipename):
  37. if not args.fetchuri:
  38. if args.fetch:
  39. raise DevtoolError('URI specified as positional argument as well as -f/--fetch')
  40. args.fetchuri = args.recipename
  41. args.recipename = ''
  42. elif scriptutils.is_src_url(args.srctree):
  43. if not args.fetchuri:
  44. if args.fetch:
  45. raise DevtoolError('URI specified as positional argument as well as -f/--fetch')
  46. args.fetchuri = args.srctree
  47. args.srctree = ''
  48. elif args.recipename and not args.srctree:
  49. if os.sep in args.recipename:
  50. args.srctree = args.recipename
  51. args.recipename = None
  52. elif os.path.isdir(args.recipename):
  53. logger.warning('Ambiguous argument "%s" - assuming you mean it to be the recipe name' % args.recipename)
  54. if not args.fetchuri:
  55. if args.srcrev:
  56. raise DevtoolError('The -S/--srcrev option is only valid when fetching from an SCM repository')
  57. if args.srcbranch:
  58. raise DevtoolError('The -B/--srcbranch option is only valid when fetching from an SCM repository')
  59. if args.srctree and os.path.isfile(args.srctree):
  60. args.fetchuri = 'file://' + os.path.abspath(args.srctree)
  61. args.srctree = ''
  62. if args.fetch:
  63. if args.fetchuri:
  64. raise DevtoolError('URI specified as positional argument as well as -f/--fetch')
  65. else:
  66. logger.warning('-f/--fetch option is deprecated - you can now simply specify the URL to fetch as a positional argument instead')
  67. args.fetchuri = args.fetch
  68. if args.recipename:
  69. if args.recipename in workspace:
  70. raise DevtoolError("recipe %s is already in your workspace" %
  71. args.recipename)
  72. reason = oe.recipeutils.validate_pn(args.recipename)
  73. if reason:
  74. raise DevtoolError(reason)
  75. if args.srctree:
  76. srctree = os.path.abspath(args.srctree)
  77. srctreeparent = None
  78. tmpsrcdir = None
  79. else:
  80. srctree = None
  81. srctreeparent = get_default_srctree(config)
  82. bb.utils.mkdirhier(srctreeparent)
  83. tmpsrcdir = tempfile.mkdtemp(prefix='devtoolsrc', dir=srctreeparent)
  84. if srctree and os.path.exists(srctree):
  85. if args.fetchuri:
  86. if not os.path.isdir(srctree):
  87. raise DevtoolError("Cannot fetch into source tree path %s as "
  88. "it exists and is not a directory" %
  89. srctree)
  90. elif os.listdir(srctree):
  91. raise DevtoolError("Cannot fetch into source tree path %s as "
  92. "it already exists and is non-empty" %
  93. srctree)
  94. elif not args.fetchuri:
  95. if args.srctree:
  96. raise DevtoolError("Specified source tree %s could not be found" %
  97. args.srctree)
  98. elif srctree:
  99. raise DevtoolError("No source tree exists at default path %s - "
  100. "either create and populate this directory, "
  101. "or specify a path to a source tree, or a "
  102. "URI to fetch source from" % srctree)
  103. else:
  104. raise DevtoolError("You must either specify a source tree "
  105. "or a URI to fetch source from")
  106. if args.version:
  107. if '_' in args.version or ' ' in args.version:
  108. raise DevtoolError('Invalid version string "%s"' % args.version)
  109. if args.color == 'auto' and sys.stdout.isatty():
  110. color = 'always'
  111. else:
  112. color = args.color
  113. extracmdopts = ''
  114. if args.fetchuri:
  115. source = args.fetchuri
  116. if srctree:
  117. extracmdopts += ' -x %s' % srctree
  118. else:
  119. extracmdopts += ' -x %s' % tmpsrcdir
  120. else:
  121. source = srctree
  122. if args.recipename:
  123. extracmdopts += ' -N %s' % args.recipename
  124. if args.version:
  125. extracmdopts += ' -V %s' % args.version
  126. if args.binary:
  127. extracmdopts += ' -b'
  128. if args.also_native:
  129. extracmdopts += ' --also-native'
  130. if args.src_subdir:
  131. extracmdopts += ' --src-subdir "%s"' % args.src_subdir
  132. if args.autorev:
  133. extracmdopts += ' -a'
  134. if args.npm_dev:
  135. extracmdopts += ' --npm-dev'
  136. if args.no_pypi:
  137. extracmdopts += ' --no-pypi'
  138. if args.mirrors:
  139. extracmdopts += ' --mirrors'
  140. if args.srcrev:
  141. extracmdopts += ' --srcrev %s' % args.srcrev
  142. if args.srcbranch:
  143. extracmdopts += ' --srcbranch %s' % args.srcbranch
  144. if args.provides:
  145. extracmdopts += ' --provides %s' % args.provides
  146. tempdir = tempfile.mkdtemp(prefix='devtool')
  147. try:
  148. try:
  149. stdout, _ = exec_build_env_command(config.init_path, basepath, 'recipetool --color=%s create --devtool -o %s \'%s\' %s' % (color, tempdir, source, extracmdopts), watch=True)
  150. except bb.process.ExecutionError as e:
  151. if e.exitcode == 15:
  152. raise DevtoolError('Could not auto-determine recipe name, please specify it on the command line')
  153. else:
  154. raise DevtoolError('Command \'%s\' failed' % e.command)
  155. recipes = glob.glob(os.path.join(tempdir, '*.bb'))
  156. if recipes:
  157. recipename = os.path.splitext(os.path.basename(recipes[0]))[0].split('_')[0]
  158. if recipename in workspace:
  159. raise DevtoolError('A recipe with the same name as the one being created (%s) already exists in your workspace' % recipename)
  160. recipedir = os.path.join(config.workspace_path, 'recipes', recipename)
  161. bb.utils.mkdirhier(recipedir)
  162. recipefile = os.path.join(recipedir, os.path.basename(recipes[0]))
  163. appendfile = recipe_to_append(recipefile, config)
  164. if os.path.exists(appendfile):
  165. # This shouldn't be possible, but just in case
  166. raise DevtoolError('A recipe with the same name as the one being created already exists in your workspace')
  167. if os.path.exists(recipefile):
  168. raise DevtoolError('A recipe file %s already exists in your workspace; this shouldn\'t be there - please delete it before continuing' % recipefile)
  169. if tmpsrcdir:
  170. srctree = os.path.join(srctreeparent, recipename)
  171. if os.path.exists(tmpsrcdir):
  172. if os.path.exists(srctree):
  173. if os.path.isdir(srctree):
  174. try:
  175. os.rmdir(srctree)
  176. except OSError as e:
  177. if e.errno == errno.ENOTEMPTY:
  178. raise DevtoolError('Source tree path %s already exists and is not empty' % srctree)
  179. else:
  180. raise
  181. else:
  182. raise DevtoolError('Source tree path %s already exists and is not a directory' % srctree)
  183. logger.info('Using default source tree path %s' % srctree)
  184. shutil.move(tmpsrcdir, srctree)
  185. else:
  186. raise DevtoolError('Couldn\'t find source tree created by recipetool')
  187. bb.utils.mkdirhier(recipedir)
  188. shutil.move(recipes[0], recipefile)
  189. # Move any additional files created by recipetool
  190. for fn in os.listdir(tempdir):
  191. shutil.move(os.path.join(tempdir, fn), recipedir)
  192. else:
  193. raise DevtoolError(f'Failed to create a recipe file for source {source}')
  194. attic_recipe = os.path.join(config.workspace_path, 'attic', recipename, os.path.basename(recipefile))
  195. if os.path.exists(attic_recipe):
  196. logger.warning('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)
  197. finally:
  198. if tmpsrcdir and os.path.exists(tmpsrcdir):
  199. shutil.rmtree(tmpsrcdir)
  200. shutil.rmtree(tempdir)
  201. for fn in os.listdir(recipedir):
  202. _add_md5(config, recipename, os.path.join(recipedir, fn))
  203. tinfoil = setup_tinfoil(config_only=True, basepath=basepath)
  204. try:
  205. try:
  206. rd = tinfoil.parse_recipe_file(recipefile, False)
  207. except Exception as e:
  208. logger.error(str(e))
  209. rd = None
  210. if not rd:
  211. # Parsing failed. We just created this recipe and we shouldn't
  212. # leave it in the workdir or it'll prevent bitbake from starting
  213. movefn = '%s.parsefailed' % recipefile
  214. 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)
  215. shutil.move(recipefile, movefn)
  216. return 1
  217. if args.fetchuri and not args.no_git:
  218. setup_git_repo(srctree, args.version, 'devtool', d=tinfoil.config_data)
  219. initial_rev = {}
  220. if os.path.exists(os.path.join(srctree, '.git')):
  221. (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=srctree)
  222. initial_rev["."] = stdout.rstrip()
  223. (stdout, _) = bb.process.run('git submodule --quiet foreach --recursive \'echo `git rev-parse HEAD` $PWD\'', cwd=srctree)
  224. for line in stdout.splitlines():
  225. (rev, submodule) = line.split()
  226. initial_rev[os.path.relpath(submodule, srctree)] = rev
  227. if args.src_subdir:
  228. srctree = os.path.join(srctree, args.src_subdir)
  229. bb.utils.mkdirhier(os.path.dirname(appendfile))
  230. with open(appendfile, 'w') as f:
  231. f.write('inherit externalsrc\n')
  232. f.write('EXTERNALSRC = "%s"\n' % srctree)
  233. b_is_s = use_external_build(args.same_dir, args.no_same_dir, rd)
  234. if b_is_s:
  235. f.write('EXTERNALSRC_BUILD = "%s"\n' % srctree)
  236. if initial_rev:
  237. for key, value in initial_rev.items():
  238. f.write('\n# initial_rev %s: %s\n' % (key, value))
  239. if args.binary:
  240. f.write('do_install:append() {\n')
  241. f.write(' rm -rf ${D}/.git\n')
  242. f.write(' rm -f ${D}/singletask.lock\n')
  243. f.write('}\n')
  244. if bb.data.inherits_class('npm', rd):
  245. f.write('python do_configure:append() {\n')
  246. f.write(' pkgdir = d.getVar("NPM_PACKAGE")\n')
  247. f.write(' lockfile = os.path.join(pkgdir, "singletask.lock")\n')
  248. f.write(' bb.utils.remove(lockfile)\n')
  249. f.write('}\n')
  250. # Check if the new layer provides recipes whose priorities have been
  251. # overriden by PREFERRED_PROVIDER.
  252. recipe_name = rd.getVar('PN')
  253. provides = rd.getVar('PROVIDES')
  254. # Search every item defined in PROVIDES
  255. for recipe_provided in provides.split():
  256. preferred_provider = 'PREFERRED_PROVIDER_' + recipe_provided
  257. current_pprovider = rd.getVar(preferred_provider)
  258. if current_pprovider and current_pprovider != recipe_name:
  259. if args.fixed_setup:
  260. #if we are inside the eSDK add the new PREFERRED_PROVIDER in the workspace layer.conf
  261. layerconf_file = os.path.join(config.workspace_path, "conf", "layer.conf")
  262. with open(layerconf_file, 'a') as f:
  263. f.write('%s = "%s"\n' % (preferred_provider, recipe_name))
  264. else:
  265. logger.warning('Set \'%s\' in order to use the recipe' % preferred_provider)
  266. break
  267. _add_md5(config, recipename, appendfile)
  268. check_prerelease_version(rd.getVar('PV'), 'devtool add')
  269. logger.info('Recipe %s has been automatically created; further editing may be required to make it fully functional' % recipefile)
  270. finally:
  271. tinfoil.shutdown()
  272. return 0
  273. def _check_compatible_recipe(pn, d):
  274. """Check if the recipe is supported by devtool"""
  275. import bb.data
  276. if pn == 'perf':
  277. raise DevtoolError("The perf recipe does not actually check out "
  278. "source and thus cannot be supported by this tool",
  279. 4)
  280. if pn in ['kernel-devsrc', 'package-index'] or pn.startswith('gcc-source'):
  281. raise DevtoolError("The %s recipe is not supported by this tool" % pn, 4)
  282. if bb.data.inherits_class('image', d):
  283. raise DevtoolError("The %s recipe is an image, and therefore is not "
  284. "supported by this tool" % pn, 4)
  285. if bb.data.inherits_class('populate_sdk', d):
  286. raise DevtoolError("The %s recipe is an SDK, and therefore is not "
  287. "supported by this tool" % pn, 4)
  288. if bb.data.inherits_class('packagegroup', d):
  289. raise DevtoolError("The %s recipe is a packagegroup, and therefore is "
  290. "not supported by this tool" % pn, 4)
  291. if bb.data.inherits_class('externalsrc', d) and d.getVar('EXTERNALSRC'):
  292. # Not an incompatibility error per se, so we don't pass the error code
  293. raise DevtoolError("externalsrc is currently enabled for the %s "
  294. "recipe. This prevents the normal do_patch task "
  295. "from working. You will need to disable this "
  296. "first." % pn)
  297. def _dry_run_copy(src, dst, dry_run_outdir, base_outdir):
  298. """Common function for copying a file to the dry run output directory"""
  299. relpath = os.path.relpath(dst, base_outdir)
  300. if relpath.startswith('..'):
  301. raise Exception('Incorrect base path %s for path %s' % (base_outdir, dst))
  302. dst = os.path.join(dry_run_outdir, relpath)
  303. dst_d = os.path.dirname(dst)
  304. if dst_d:
  305. bb.utils.mkdirhier(dst_d)
  306. # Don't overwrite existing files, otherwise in the case of an upgrade
  307. # the dry-run written out recipe will be overwritten with an unmodified
  308. # version
  309. if not os.path.exists(dst):
  310. shutil.copy(src, dst)
  311. def _move_file(src, dst, dry_run_outdir=None, base_outdir=None):
  312. """Move a file. Creates all the directory components of destination path."""
  313. dry_run_suffix = ' (dry-run)' if dry_run_outdir else ''
  314. logger.debug('Moving %s to %s%s' % (src, dst, dry_run_suffix))
  315. if dry_run_outdir:
  316. # We want to copy here, not move
  317. _dry_run_copy(src, dst, dry_run_outdir, base_outdir)
  318. else:
  319. dst_d = os.path.dirname(dst)
  320. if dst_d:
  321. bb.utils.mkdirhier(dst_d)
  322. shutil.move(src, dst)
  323. def _copy_file(src, dst, dry_run_outdir=None, base_outdir=None):
  324. """Copy a file. Creates all the directory components of destination path."""
  325. dry_run_suffix = ' (dry-run)' if dry_run_outdir else ''
  326. logger.debug('Copying %s to %s%s' % (src, dst, dry_run_suffix))
  327. if dry_run_outdir:
  328. _dry_run_copy(src, dst, dry_run_outdir, base_outdir)
  329. else:
  330. dst_d = os.path.dirname(dst)
  331. if dst_d:
  332. bb.utils.mkdirhier(dst_d)
  333. shutil.copy(src, dst)
  334. def _git_ls_tree(repodir, treeish='HEAD', recursive=False):
  335. """List contents of a git treeish"""
  336. import bb.process
  337. cmd = ['git', 'ls-tree', '-z', treeish]
  338. if recursive:
  339. cmd.append('-r')
  340. out, _ = bb.process.run(cmd, cwd=repodir)
  341. ret = {}
  342. if out:
  343. for line in out.split('\0'):
  344. if line:
  345. split = line.split(None, 4)
  346. ret[split[3]] = split[0:3]
  347. return ret
  348. def _git_modified(repodir):
  349. """List the difference between HEAD and the index"""
  350. import bb.process
  351. cmd = ['git', 'status', '--porcelain']
  352. out, _ = bb.process.run(cmd, cwd=repodir)
  353. ret = []
  354. if out:
  355. for line in out.split("\n"):
  356. if line and not line.startswith('??'):
  357. ret.append(line[3:])
  358. return ret
  359. def _git_exclude_path(srctree, path):
  360. """Return pathspec (list of paths) that excludes certain path"""
  361. # NOTE: "Filtering out" files/paths in this way is not entirely reliable -
  362. # we don't catch files that are deleted, for example. A more reliable way
  363. # to implement this would be to use "negative pathspecs" which were
  364. # introduced in Git v1.9.0. Revisit this when/if the required Git version
  365. # becomes greater than that.
  366. path = os.path.normpath(path)
  367. recurse = True if len(path.split(os.path.sep)) > 1 else False
  368. git_files = list(_git_ls_tree(srctree, 'HEAD', recurse).keys())
  369. if path in git_files:
  370. git_files.remove(path)
  371. return git_files
  372. else:
  373. return ['.']
  374. def _ls_tree(directory):
  375. """Recursive listing of files in a directory"""
  376. ret = []
  377. for root, dirs, files in os.walk(directory):
  378. ret.extend([os.path.relpath(os.path.join(root, fname), directory) for
  379. fname in files])
  380. return ret
  381. def extract(args, config, basepath, workspace):
  382. """Entry point for the devtool 'extract' subcommand"""
  383. tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
  384. if not tinfoil:
  385. # Error already shown
  386. return 1
  387. try:
  388. rd = parse_recipe(config, tinfoil, args.recipename, True)
  389. if not rd:
  390. return 1
  391. srctree = os.path.abspath(args.srctree)
  392. initial_rev, _ = _extract_source(srctree, args.keep_temp, args.branch, False, config, basepath, workspace, args.fixed_setup, rd, tinfoil, no_overrides=args.no_overrides)
  393. logger.info('Source tree extracted to %s' % srctree)
  394. if initial_rev:
  395. return 0
  396. else:
  397. return 1
  398. finally:
  399. tinfoil.shutdown()
  400. def sync(args, config, basepath, workspace):
  401. """Entry point for the devtool 'sync' subcommand"""
  402. tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
  403. if not tinfoil:
  404. # Error already shown
  405. return 1
  406. try:
  407. rd = parse_recipe(config, tinfoil, args.recipename, True)
  408. if not rd:
  409. return 1
  410. srctree = os.path.abspath(args.srctree)
  411. initial_rev, _ = _extract_source(srctree, args.keep_temp, args.branch, True, config, basepath, workspace, args.fixed_setup, rd, tinfoil, no_overrides=True)
  412. logger.info('Source tree %s synchronized' % srctree)
  413. if initial_rev:
  414. return 0
  415. else:
  416. return 1
  417. finally:
  418. tinfoil.shutdown()
  419. def _extract_source(srctree, keep_temp, devbranch, sync, config, basepath, workspace, fixed_setup, d, tinfoil, no_overrides=False):
  420. """Extract sources of a recipe"""
  421. import oe.path
  422. import bb.data
  423. import bb.process
  424. pn = d.getVar('PN')
  425. _check_compatible_recipe(pn, d)
  426. if sync:
  427. if not os.path.exists(srctree):
  428. raise DevtoolError("output path %s does not exist" % srctree)
  429. else:
  430. if os.path.exists(srctree):
  431. if not os.path.isdir(srctree):
  432. raise DevtoolError("output path %s exists and is not a directory" %
  433. srctree)
  434. elif os.listdir(srctree):
  435. raise DevtoolError("output path %s already exists and is "
  436. "non-empty" % srctree)
  437. if 'noexec' in (d.getVarFlags('do_unpack', False) or []):
  438. raise DevtoolError("The %s recipe has do_unpack disabled, unable to "
  439. "extract source" % pn, 4)
  440. if not sync:
  441. # Prepare for shutil.move later on
  442. bb.utils.mkdirhier(srctree)
  443. os.rmdir(srctree)
  444. extra_overrides = []
  445. if not no_overrides:
  446. history = d.varhistory.variable('SRC_URI')
  447. for event in history:
  448. if not 'flag' in event:
  449. if event['op'].startswith((':append[', ':prepend[')):
  450. override = event['op'].split('[')[1].split(']')[0]
  451. if not override.startswith('pn-'):
  452. extra_overrides.append(override)
  453. # We want to remove duplicate overrides. If a recipe had multiple
  454. # SRC_URI_override += values it would cause mulitple instances of
  455. # overrides. This doesn't play nicely with things like creating a
  456. # branch for every instance of DEVTOOL_EXTRA_OVERRIDES.
  457. extra_overrides = list(set(extra_overrides))
  458. if extra_overrides:
  459. logger.info('SRC_URI contains some conditional appends/prepends - will create branches to represent these')
  460. initial_rev = None
  461. recipefile = d.getVar('FILE')
  462. appendfile = recipe_to_append(recipefile, config)
  463. is_kernel_yocto = bb.data.inherits_class('kernel-yocto', d)
  464. # We need to redirect WORKDIR, STAMPS_DIR etc. under a temporary
  465. # directory so that:
  466. # (a) we pick up all files that get unpacked to the WORKDIR, and
  467. # (b) we don't disturb the existing build
  468. # However, with recipe-specific sysroots the sysroots for the recipe
  469. # will be prepared under WORKDIR, and if we used the system temporary
  470. # directory (i.e. usually /tmp) as used by mkdtemp by default, then
  471. # our attempts to hardlink files into the recipe-specific sysroots
  472. # will fail on systems where /tmp is a different filesystem, and it
  473. # would have to fall back to copying the files which is a waste of
  474. # time. Put the temp directory under the WORKDIR to prevent that from
  475. # being a problem.
  476. tempbasedir = d.getVar('WORKDIR')
  477. bb.utils.mkdirhier(tempbasedir)
  478. tempdir = tempfile.mkdtemp(prefix='devtooltmp-', dir=tempbasedir)
  479. appendbackup = None
  480. try:
  481. tinfoil.logger.setLevel(logging.WARNING)
  482. # FIXME this results in a cache reload under control of tinfoil, which is fine
  483. # except we don't get the knotty progress bar
  484. if os.path.exists(appendfile):
  485. appendbackup = os.path.join(tempdir, os.path.basename(appendfile) + '.bak')
  486. shutil.copyfile(appendfile, appendbackup)
  487. else:
  488. bb.utils.mkdirhier(os.path.dirname(appendfile))
  489. logger.debug('writing append file %s' % appendfile)
  490. with open(appendfile, 'a') as f:
  491. f.write('###--- _extract_source\n')
  492. f.write('deltask do_recipe_qa\n')
  493. f.write('deltask do_recipe_qa_setscene\n')
  494. f.write('ERROR_QA:remove = "patch-fuzz"\n')
  495. f.write('DEVTOOL_TEMPDIR = "%s"\n' % tempdir)
  496. f.write('DEVTOOL_DEVBRANCH = "%s"\n' % devbranch)
  497. if not is_kernel_yocto:
  498. f.write('PATCHTOOL = "git"\n')
  499. f.write('PATCH_COMMIT_FUNCTIONS = "1"\n')
  500. if extra_overrides:
  501. f.write('DEVTOOL_EXTRA_OVERRIDES = "%s"\n' % ':'.join(extra_overrides))
  502. f.write('inherit devtool-source\n')
  503. f.write('###--- _extract_source\n')
  504. update_unlockedsigs(basepath, workspace, fixed_setup, [pn])
  505. sstate_manifests = d.getVar('SSTATE_MANIFESTS')
  506. bb.utils.mkdirhier(sstate_manifests)
  507. preservestampfile = os.path.join(sstate_manifests, 'preserve-stamps')
  508. with open(preservestampfile, 'w') as f:
  509. f.write(d.getVar('STAMP'))
  510. tinfoil.modified_files()
  511. try:
  512. if is_kernel_yocto:
  513. # We need to generate the kernel config
  514. task = 'do_configure'
  515. else:
  516. task = 'do_patch'
  517. if 'noexec' in (d.getVarFlags(task, False) or []) or 'task' not in (d.getVarFlags(task, False) or []):
  518. logger.info('The %s recipe has %s disabled. Running only '
  519. 'do_configure task dependencies' % (pn, task))
  520. if 'depends' in d.getVarFlags('do_configure', False):
  521. pn = d.getVarFlags('do_configure', False)['depends']
  522. pn = pn.replace('${PV}', d.getVar('PV'))
  523. pn = pn.replace('${COMPILERDEP}', d.getVar('COMPILERDEP'))
  524. task = None
  525. # Run the fetch + unpack tasks
  526. res = tinfoil.build_targets(pn,
  527. task,
  528. handle_events=True)
  529. finally:
  530. if os.path.exists(preservestampfile):
  531. os.remove(preservestampfile)
  532. if not res:
  533. raise DevtoolError('Extracting source for %s failed' % pn)
  534. if not is_kernel_yocto and ('noexec' in (d.getVarFlags('do_patch', False) or []) or 'task' not in (d.getVarFlags('do_patch', False) or [])):
  535. workshareddir = d.getVar('S')
  536. if os.path.islink(srctree):
  537. os.unlink(srctree)
  538. os.symlink(workshareddir, srctree)
  539. # The initial_rev file is created in devtool_post_unpack function that will not be executed if
  540. # do_unpack/do_patch tasks are disabled so we have to directly say that source extraction was successful
  541. return True, True
  542. try:
  543. with open(os.path.join(tempdir, 'initial_rev'), 'r') as f:
  544. initial_rev = f.read()
  545. with open(os.path.join(tempdir, 'srcsubdir'), 'r') as f:
  546. srcsubdir = f.read()
  547. except FileNotFoundError as e:
  548. raise DevtoolError('Something went wrong with source extraction - the devtool-source class was not active or did not function correctly:\n%s' % str(e))
  549. srcsubdir_rel = os.path.relpath(srcsubdir, os.path.join(tempdir, 'workdir'))
  550. # Check if work-shared is empty, if yes
  551. # find source and copy to work-shared
  552. if is_kernel_yocto:
  553. workshareddir = d.getVar('STAGING_KERNEL_DIR')
  554. staging_kerVer = get_staging_kver(workshareddir)
  555. kernelVersion = d.getVar('LINUX_VERSION')
  556. # handle dangling symbolic link in work-shared:
  557. if os.path.islink(workshareddir):
  558. os.unlink(workshareddir)
  559. if os.path.exists(workshareddir) and (not os.listdir(workshareddir) or kernelVersion != staging_kerVer):
  560. shutil.rmtree(workshareddir)
  561. oe.path.copyhardlinktree(srcsubdir, workshareddir)
  562. elif not os.path.exists(workshareddir):
  563. oe.path.copyhardlinktree(srcsubdir, workshareddir)
  564. if sync:
  565. try:
  566. logger.info('Backing up current %s branch as branch: %s.bak' % (devbranch, devbranch))
  567. bb.process.run('git branch -f ' + devbranch + '.bak', cwd=srctree)
  568. # Use git fetch to update the source with the current recipe
  569. # To be able to update the currently checked out branch with
  570. # possibly new history (no fast-forward) git needs to be told
  571. # that's ok
  572. logger.info('Syncing source files including patches to git branch: %s' % devbranch)
  573. bb.process.run('git fetch --update-head-ok --force file://' + srcsubdir + ' ' + devbranch + ':' + devbranch, cwd=srctree)
  574. except bb.process.ExecutionError as e:
  575. raise DevtoolError("Error when syncing source files to local checkout: %s" % str(e))
  576. else:
  577. shutil.move(srcsubdir, srctree)
  578. if is_kernel_yocto:
  579. logger.info('Copying kernel config to srctree')
  580. shutil.copy2(os.path.join(tempdir, '.config'), srctree)
  581. finally:
  582. if appendbackup:
  583. shutil.copyfile(appendbackup, appendfile)
  584. elif os.path.exists(appendfile):
  585. os.remove(appendfile)
  586. if keep_temp:
  587. logger.info('Preserving temporary directory %s' % tempdir)
  588. else:
  589. shutil.rmtree(tempdir)
  590. return initial_rev, srcsubdir_rel
  591. def _add_md5(config, recipename, filename):
  592. """Record checksum of a file (or recursively for a directory) to the md5-file of the workspace"""
  593. def addfile(fn):
  594. md5 = bb.utils.md5_file(fn)
  595. with open(os.path.join(config.workspace_path, '.devtool_md5'), 'a+') as f:
  596. md5_str = '%s|%s|%s\n' % (recipename, os.path.relpath(fn, config.workspace_path), md5)
  597. f.seek(0, os.SEEK_SET)
  598. if not md5_str in f.read():
  599. f.write(md5_str)
  600. if os.path.isdir(filename):
  601. for root, _, files in os.walk(filename):
  602. for f in files:
  603. addfile(os.path.join(root, f))
  604. else:
  605. addfile(filename)
  606. def _check_preserve(config, recipename):
  607. """Check if a file was manually changed and needs to be saved in 'attic'
  608. directory"""
  609. origfile = os.path.join(config.workspace_path, '.devtool_md5')
  610. newfile = os.path.join(config.workspace_path, '.devtool_md5_new')
  611. preservepath = os.path.join(config.workspace_path, 'attic', recipename)
  612. with open(origfile, 'r') as f:
  613. with open(newfile, 'w') as tf:
  614. for line in f.readlines():
  615. splitline = line.rstrip().split('|')
  616. if splitline[0] == recipename:
  617. removefile = os.path.join(config.workspace_path, splitline[1])
  618. try:
  619. md5 = bb.utils.md5_file(removefile)
  620. except IOError as err:
  621. if err.errno == 2:
  622. # File no longer exists, skip it
  623. continue
  624. else:
  625. raise
  626. if splitline[2] != md5:
  627. bb.utils.mkdirhier(preservepath)
  628. preservefile = os.path.basename(removefile)
  629. logger.warning('File %s modified since it was written, preserving in %s' % (preservefile, preservepath))
  630. shutil.move(removefile, os.path.join(preservepath, preservefile))
  631. else:
  632. os.remove(removefile)
  633. else:
  634. tf.write(line)
  635. bb.utils.rename(newfile, origfile)
  636. def get_staging_kver(srcdir):
  637. # Kernel version from work-shared
  638. import itertools
  639. try:
  640. with open(os.path.join(srcdir, "Makefile")) as f:
  641. # Take VERSION, PATCHLEVEL, SUBLEVEL from lines 1, 2, 3
  642. return ".".join(line.rstrip().split('= ')[1] for line in itertools.islice(f, 1, 4))
  643. except FileNotFoundError:
  644. return ""
  645. def get_staging_kbranch(srcdir):
  646. import bb.process
  647. staging_kbranch = ""
  648. if os.path.exists(srcdir) and os.listdir(srcdir):
  649. (branch, _) = bb.process.run('git branch | grep \\* | cut -d \' \' -f2', cwd=srcdir)
  650. staging_kbranch = "".join(branch.split('\n')[0])
  651. return staging_kbranch
  652. def get_real_srctree(srctree, s, workdir):
  653. # Check that recipe isn't using a shared workdir
  654. s = os.path.abspath(s)
  655. workdir = os.path.abspath(workdir)
  656. if s.startswith(workdir) and s != workdir and os.path.dirname(s) != workdir:
  657. # Handle if S is set to a subdirectory of the source
  658. srcsubdir = os.path.relpath(s, workdir).split(os.sep, 1)[1]
  659. srctree = os.path.join(srctree, srcsubdir)
  660. return srctree
  661. def modify(args, config, basepath, workspace):
  662. """Entry point for the devtool 'modify' subcommand"""
  663. import bb.data
  664. import bb.process
  665. import oe.recipeutils
  666. import oe.patch
  667. import oe.path
  668. if args.recipename in workspace:
  669. raise DevtoolError("recipe %s is already in your workspace" %
  670. args.recipename)
  671. tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
  672. try:
  673. rd = parse_recipe(config, tinfoil, args.recipename, True)
  674. if not rd:
  675. return 1
  676. pn = rd.getVar('PN')
  677. if pn != args.recipename:
  678. logger.info('Mapping %s to %s' % (args.recipename, pn))
  679. if pn in workspace:
  680. raise DevtoolError("recipe %s is already in your workspace" %
  681. pn)
  682. if args.srctree:
  683. srctree = os.path.abspath(args.srctree)
  684. else:
  685. srctree = get_default_srctree(config, pn)
  686. if args.no_extract and not os.path.isdir(srctree):
  687. raise DevtoolError("--no-extract specified and source path %s does "
  688. "not exist or is not a directory" %
  689. srctree)
  690. recipefile = rd.getVar('FILE')
  691. appendfile = recipe_to_append(recipefile, config, args.wildcard)
  692. if os.path.exists(appendfile):
  693. raise DevtoolError("Another variant of recipe %s is already in your "
  694. "workspace (only one variant of a recipe can "
  695. "currently be worked on at once)"
  696. % pn)
  697. _check_compatible_recipe(pn, rd)
  698. initial_revs = {}
  699. commits = {}
  700. check_commits = False
  701. if bb.data.inherits_class('kernel-yocto', rd):
  702. # Current set kernel version
  703. kernelVersion = rd.getVar('LINUX_VERSION')
  704. srcdir = rd.getVar('STAGING_KERNEL_DIR')
  705. kbranch = rd.getVar('KBRANCH')
  706. staging_kerVer = get_staging_kver(srcdir)
  707. staging_kbranch = get_staging_kbranch(srcdir)
  708. if (os.path.exists(srcdir) and os.listdir(srcdir)) and (kernelVersion in staging_kerVer and staging_kbranch == kbranch):
  709. oe.path.copyhardlinktree(srcdir, srctree)
  710. unpackdir = rd.getVar('UNPACKDIR')
  711. srcsubdir = rd.getVar('S')
  712. # Add locally copied files to gitignore as we add back to the metadata directly
  713. local_files = oe.recipeutils.get_recipe_local_files(rd)
  714. srcabspath = os.path.abspath(srcsubdir)
  715. local_files = [fname for fname in local_files if
  716. os.path.exists(os.path.join(unpackdir, fname)) and
  717. srcabspath == unpackdir]
  718. if local_files:
  719. with open(os.path.join(srctree, '.gitignore'), 'a+') as f:
  720. f.write('# Ignore local files, by default. Remove following lines'
  721. 'if you want to commit the directory to Git\n')
  722. for fname in local_files:
  723. f.write('%s\n' % fname)
  724. task = 'do_configure'
  725. res = tinfoil.build_targets(pn, task, handle_events=True)
  726. # Copy .config to workspace
  727. kconfpath = rd.getVar('B')
  728. logger.info('Copying kernel config to workspace')
  729. shutil.copy2(os.path.join(kconfpath, '.config'), srctree)
  730. # Set this to true, we still need to get initial_rev
  731. # by parsing the git repo
  732. args.no_extract = True
  733. if not args.no_extract:
  734. initial_revs["."], _ = _extract_source(srctree, args.keep_temp, args.branch, False, config, basepath, workspace, args.fixed_setup, rd, tinfoil, no_overrides=args.no_overrides)
  735. if not initial_revs["."]:
  736. return 1
  737. logger.info('Source tree extracted to %s' % srctree)
  738. if os.path.exists(os.path.join(srctree, '.git')):
  739. # Get list of commits since this revision
  740. (stdout, _) = bb.process.run('git rev-list --reverse %s..HEAD' % initial_revs["."], cwd=srctree)
  741. commits["."] = stdout.split()
  742. check_commits = True
  743. try:
  744. (stdout, _) = bb.process.run('git submodule --quiet foreach --recursive \'echo `git rev-parse devtool-base` $PWD\'', cwd=srctree)
  745. except bb.process.ExecutionError:
  746. stdout = ""
  747. for line in stdout.splitlines():
  748. (rev, submodule_path) = line.split()
  749. submodule = os.path.relpath(submodule_path, srctree)
  750. initial_revs[submodule] = rev
  751. (stdout, _) = bb.process.run('git rev-list --reverse devtool-base..HEAD', cwd=submodule_path)
  752. commits[submodule] = stdout.split()
  753. else:
  754. if os.path.exists(os.path.join(srctree, '.git')):
  755. # Check if it's a tree previously extracted by us. This is done
  756. # by ensuring that devtool-base and args.branch (devtool) exist.
  757. # The check_commits logic will cause an exception if either one
  758. # of these doesn't exist
  759. try:
  760. (stdout, _) = bb.process.run('git branch --contains devtool-base', cwd=srctree)
  761. bb.process.run('git rev-parse %s' % args.branch, cwd=srctree)
  762. except bb.process.ExecutionError:
  763. stdout = ''
  764. if stdout:
  765. check_commits = True
  766. for line in stdout.splitlines():
  767. if line.startswith('*'):
  768. (stdout, _) = bb.process.run('git rev-parse devtool-base', cwd=srctree)
  769. initial_revs["."] = stdout.rstrip()
  770. if "." not in initial_revs:
  771. # Otherwise, just grab the head revision
  772. (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=srctree)
  773. initial_revs["."] = stdout.rstrip()
  774. branch_patches = {}
  775. if check_commits:
  776. # Check if there are override branches
  777. (stdout, _) = bb.process.run('git branch', cwd=srctree)
  778. branches = []
  779. for line in stdout.rstrip().splitlines():
  780. branchname = line[2:].rstrip()
  781. if branchname.startswith(override_branch_prefix):
  782. branches.append(branchname)
  783. if branches:
  784. logger.warning('SRC_URI is conditionally overridden in this recipe, thus several %s* branches have been created, one for each override that makes changes to SRC_URI. It is recommended that you make changes to the %s branch first, then checkout and rebase each %s* branch and update any unique patches there (duplicates on those branches will be ignored by devtool finish/update-recipe)' % (override_branch_prefix, args.branch, override_branch_prefix))
  785. branches.insert(0, args.branch)
  786. seen_patches = []
  787. for branch in branches:
  788. branch_patches[branch] = []
  789. (stdout, _) = bb.process.run('git rev-list devtool-base..%s' % branch, cwd=srctree)
  790. for sha1 in stdout.splitlines():
  791. notes = oe.patch.GitApplyTree.getNotes(srctree, sha1.strip())
  792. origpatch = notes.get(oe.patch.GitApplyTree.original_patch)
  793. if origpatch and origpatch not in seen_patches:
  794. seen_patches.append(origpatch)
  795. branch_patches[branch].append(origpatch)
  796. # Need to grab this here in case the source is within a subdirectory
  797. srctreebase = srctree
  798. srctree = get_real_srctree(srctree, rd.getVar('S'), rd.getVar('WORKDIR'))
  799. bb.utils.mkdirhier(os.path.dirname(appendfile))
  800. with open(appendfile, 'w') as f:
  801. # if not present, add type=git-dependency to the secondary sources
  802. # (non local files) so they can be extracted correctly when building a recipe after
  803. # doing a devtool modify on it
  804. src_uri = rd.getVar('SRC_URI').split()
  805. src_uri_append = []
  806. src_uri_remove = []
  807. # Assume first entry is main source extracted in ${S} so skip it
  808. src_uri = src_uri[1::]
  809. # Add "type=git-dependency" to all non local sources
  810. for url in src_uri:
  811. if not url.startswith('file://') and not 'type=' in url:
  812. src_uri_remove.append(url)
  813. src_uri_append.append('%s;type=git-dependency' % url)
  814. if src_uri_remove:
  815. f.write('SRC_URI:remove = "%s"\n' % ' '.join(src_uri_remove))
  816. f.write('SRC_URI:append = " %s"\n\n' % ' '.join(src_uri_append))
  817. f.write('FILESEXTRAPATHS:prepend := "${THISDIR}/${PN}:"\n')
  818. # Local files can be modified/tracked in separate subdir under srctree
  819. # Mostly useful for packages with S != WORKDIR
  820. f.write('FILESPATH:prepend := "%s:"\n' %
  821. os.path.join(srctreebase, 'oe-local-files'))
  822. f.write('# srctreebase: %s\n' % srctreebase)
  823. f.write('\ninherit externalsrc\n')
  824. f.write('# NOTE: We use pn- overrides here to avoid affecting multiple variants in the case where the recipe uses BBCLASSEXTEND\n')
  825. f.write('EXTERNALSRC:pn-%s = "%s"\n' % (pn, srctree))
  826. b_is_s = use_external_build(args.same_dir, args.no_same_dir, rd)
  827. if b_is_s:
  828. f.write('EXTERNALSRC_BUILD:pn-%s = "%s"\n' % (pn, srctree))
  829. if bb.data.inherits_class('kernel', rd):
  830. f.write('\ndo_kernel_configme:prepend() {\n'
  831. ' if [ -e ${S}/.config ]; then\n'
  832. ' mv ${S}/.config ${S}/.config.old\n'
  833. ' fi\n'
  834. '}\n')
  835. if rd.getVarFlag('do_menuconfig', 'task'):
  836. f.write('\ndo_configure:append() {\n'
  837. ' if [ ${@oe.types.boolean(d.getVar("KCONFIG_CONFIG_ENABLE_MENUCONFIG"))} = True ]; then\n'
  838. ' cp ${KCONFIG_CONFIG_ROOTDIR}/.config ${S}/.config.baseline\n'
  839. ' ln -sfT ${KCONFIG_CONFIG_ROOTDIR}/.config ${S}/.config.new\n'
  840. ' fi\n'
  841. '}\n')
  842. if initial_revs:
  843. for name, rev in initial_revs.items():
  844. f.write('\n# initial_rev %s: %s\n' % (name, rev))
  845. if name in commits:
  846. for commit in commits[name]:
  847. f.write('# commit %s: %s\n' % (name, commit))
  848. if branch_patches:
  849. for branch in branch_patches:
  850. if branch == args.branch:
  851. continue
  852. f.write('# patches_%s: %s\n' % (branch, ','.join(branch_patches[branch])))
  853. if args.debug_build:
  854. f.write('\nDEBUG_BUILD = "1"\n')
  855. update_unlockedsigs(basepath, workspace, args.fixed_setup, [pn])
  856. _add_md5(config, pn, appendfile)
  857. logger.info('Recipe %s now set up to build from %s' % (pn, srctree))
  858. finally:
  859. tinfoil.shutdown()
  860. return 0
  861. def rename(args, config, basepath, workspace):
  862. """Entry point for the devtool 'rename' subcommand"""
  863. import bb
  864. import oe.recipeutils
  865. check_workspace_recipe(workspace, args.recipename)
  866. if not (args.newname or args.version):
  867. raise DevtoolError('You must specify a new name, a version with -V/--version, or both')
  868. recipefile = workspace[args.recipename]['recipefile']
  869. if not recipefile:
  870. raise DevtoolError('devtool rename can only be used where the recipe file itself is in the workspace (e.g. after devtool add)')
  871. if args.newname and args.newname != args.recipename:
  872. reason = oe.recipeutils.validate_pn(args.newname)
  873. if reason:
  874. raise DevtoolError(reason)
  875. newname = args.newname
  876. else:
  877. newname = args.recipename
  878. append = workspace[args.recipename]['bbappend']
  879. appendfn = os.path.splitext(os.path.basename(append))[0]
  880. splitfn = appendfn.split('_')
  881. if len(splitfn) > 1:
  882. origfnver = appendfn.split('_')[1]
  883. else:
  884. origfnver = ''
  885. recipefilemd5 = None
  886. newrecipefilemd5 = None
  887. tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
  888. try:
  889. rd = parse_recipe(config, tinfoil, args.recipename, True)
  890. if not rd:
  891. return 1
  892. bp = rd.getVar('BP')
  893. bpn = rd.getVar('BPN')
  894. if newname != args.recipename:
  895. localdata = rd.createCopy()
  896. localdata.setVar('PN', newname)
  897. newbpn = localdata.getVar('BPN')
  898. else:
  899. newbpn = bpn
  900. s = rd.getVar('S', False)
  901. src_uri = rd.getVar('SRC_URI', False)
  902. pv = rd.getVar('PV')
  903. # Correct variable values that refer to the upstream source - these
  904. # values must stay the same, so if the name/version are changing then
  905. # we need to fix them up
  906. new_s = s
  907. new_src_uri = src_uri
  908. if newbpn != bpn:
  909. # ${PN} here is technically almost always incorrect, but people do use it
  910. new_s = new_s.replace('${BPN}', bpn)
  911. new_s = new_s.replace('${PN}', bpn)
  912. new_s = new_s.replace('${BP}', '%s-${PV}' % bpn)
  913. new_src_uri = new_src_uri.replace('${BPN}', bpn)
  914. new_src_uri = new_src_uri.replace('${PN}', bpn)
  915. new_src_uri = new_src_uri.replace('${BP}', '%s-${PV}' % bpn)
  916. if args.version and origfnver == pv:
  917. new_s = new_s.replace('${PV}', pv)
  918. new_s = new_s.replace('${BP}', '${BPN}-%s' % pv)
  919. new_src_uri = new_src_uri.replace('${PV}', pv)
  920. new_src_uri = new_src_uri.replace('${BP}', '${BPN}-%s' % pv)
  921. patchfields = {}
  922. if new_s != s:
  923. patchfields['S'] = new_s
  924. if new_src_uri != src_uri:
  925. patchfields['SRC_URI'] = new_src_uri
  926. if patchfields:
  927. recipefilemd5 = bb.utils.md5_file(recipefile)
  928. oe.recipeutils.patch_recipe(rd, recipefile, patchfields)
  929. newrecipefilemd5 = bb.utils.md5_file(recipefile)
  930. finally:
  931. tinfoil.shutdown()
  932. if args.version:
  933. newver = args.version
  934. else:
  935. newver = origfnver
  936. if newver:
  937. newappend = '%s_%s.bbappend' % (newname, newver)
  938. newfile = '%s_%s.bb' % (newname, newver)
  939. else:
  940. newappend = '%s.bbappend' % newname
  941. newfile = '%s.bb' % newname
  942. oldrecipedir = os.path.dirname(recipefile)
  943. newrecipedir = os.path.join(config.workspace_path, 'recipes', newname)
  944. if oldrecipedir != newrecipedir:
  945. bb.utils.mkdirhier(newrecipedir)
  946. newappend = os.path.join(os.path.dirname(append), newappend)
  947. newfile = os.path.join(newrecipedir, newfile)
  948. # Rename bbappend
  949. logger.info('Renaming %s to %s' % (append, newappend))
  950. bb.utils.rename(append, newappend)
  951. # Rename recipe file
  952. logger.info('Renaming %s to %s' % (recipefile, newfile))
  953. bb.utils.rename(recipefile, newfile)
  954. # Rename source tree if it's the default path
  955. appendmd5 = None
  956. newappendmd5 = None
  957. if not args.no_srctree:
  958. srctree = workspace[args.recipename]['srctree']
  959. if os.path.abspath(srctree) == os.path.join(config.workspace_path, 'sources', args.recipename):
  960. newsrctree = os.path.join(config.workspace_path, 'sources', newname)
  961. logger.info('Renaming %s to %s' % (srctree, newsrctree))
  962. shutil.move(srctree, newsrctree)
  963. # Correct any references (basically EXTERNALSRC*) in the .bbappend
  964. appendmd5 = bb.utils.md5_file(newappend)
  965. appendlines = []
  966. with open(newappend, 'r') as f:
  967. for line in f:
  968. appendlines.append(line)
  969. with open(newappend, 'w') as f:
  970. for line in appendlines:
  971. if srctree in line:
  972. line = line.replace(srctree, newsrctree)
  973. f.write(line)
  974. newappendmd5 = bb.utils.md5_file(newappend)
  975. bpndir = None
  976. newbpndir = None
  977. if newbpn != bpn:
  978. bpndir = os.path.join(oldrecipedir, bpn)
  979. if os.path.exists(bpndir):
  980. newbpndir = os.path.join(newrecipedir, newbpn)
  981. logger.info('Renaming %s to %s' % (bpndir, newbpndir))
  982. shutil.move(bpndir, newbpndir)
  983. bpdir = None
  984. newbpdir = None
  985. if newver != origfnver or newbpn != bpn:
  986. bpdir = os.path.join(oldrecipedir, bp)
  987. if os.path.exists(bpdir):
  988. newbpdir = os.path.join(newrecipedir, '%s-%s' % (newbpn, newver))
  989. logger.info('Renaming %s to %s' % (bpdir, newbpdir))
  990. shutil.move(bpdir, newbpdir)
  991. if oldrecipedir != newrecipedir:
  992. # Move any stray files and delete the old recipe directory
  993. for entry in os.listdir(oldrecipedir):
  994. oldpath = os.path.join(oldrecipedir, entry)
  995. newpath = os.path.join(newrecipedir, entry)
  996. logger.info('Renaming %s to %s' % (oldpath, newpath))
  997. shutil.move(oldpath, newpath)
  998. os.rmdir(oldrecipedir)
  999. # Now take care of entries in .devtool_md5
  1000. md5entries = []
  1001. with open(os.path.join(config.workspace_path, '.devtool_md5'), 'r') as f:
  1002. for line in f:
  1003. md5entries.append(line)
  1004. if bpndir and newbpndir:
  1005. relbpndir = os.path.relpath(bpndir, config.workspace_path) + '/'
  1006. else:
  1007. relbpndir = None
  1008. if bpdir and newbpdir:
  1009. relbpdir = os.path.relpath(bpdir, config.workspace_path) + '/'
  1010. else:
  1011. relbpdir = None
  1012. with open(os.path.join(config.workspace_path, '.devtool_md5'), 'w') as f:
  1013. for entry in md5entries:
  1014. splitentry = entry.rstrip().split('|')
  1015. if len(splitentry) > 2:
  1016. if splitentry[0] == args.recipename:
  1017. splitentry[0] = newname
  1018. if splitentry[1] == os.path.relpath(append, config.workspace_path):
  1019. splitentry[1] = os.path.relpath(newappend, config.workspace_path)
  1020. if appendmd5 and splitentry[2] == appendmd5:
  1021. splitentry[2] = newappendmd5
  1022. elif splitentry[1] == os.path.relpath(recipefile, config.workspace_path):
  1023. splitentry[1] = os.path.relpath(newfile, config.workspace_path)
  1024. if recipefilemd5 and splitentry[2] == recipefilemd5:
  1025. splitentry[2] = newrecipefilemd5
  1026. elif relbpndir and splitentry[1].startswith(relbpndir):
  1027. splitentry[1] = os.path.relpath(os.path.join(newbpndir, splitentry[1][len(relbpndir):]), config.workspace_path)
  1028. elif relbpdir and splitentry[1].startswith(relbpdir):
  1029. splitentry[1] = os.path.relpath(os.path.join(newbpdir, splitentry[1][len(relbpdir):]), config.workspace_path)
  1030. entry = '|'.join(splitentry) + '\n'
  1031. f.write(entry)
  1032. return 0
  1033. def _get_patchset_revs(srctree, recipe_path, initial_rev=None, force_patch_refresh=False):
  1034. """Get initial and update rev of a recipe. These are the start point of the
  1035. whole patchset and start point for the patches to be re-generated/updated.
  1036. """
  1037. import bb.process
  1038. # Get current branch
  1039. stdout, _ = bb.process.run('git rev-parse --abbrev-ref HEAD',
  1040. cwd=srctree)
  1041. branchname = stdout.rstrip()
  1042. # Parse initial rev from recipe if not specified
  1043. commits = {}
  1044. patches = []
  1045. initial_revs = {}
  1046. with open(recipe_path, 'r') as f:
  1047. for line in f:
  1048. pattern = r'^#\s.*\s(.*):\s([0-9a-fA-F]+)$'
  1049. match = re.search(pattern, line)
  1050. if match:
  1051. name = match.group(1)
  1052. rev = match.group(2)
  1053. if line.startswith('# initial_rev'):
  1054. if not (name == "." and initial_rev):
  1055. initial_revs[name] = rev
  1056. elif line.startswith('# commit') and not force_patch_refresh:
  1057. if name not in commits:
  1058. commits[name] = [rev]
  1059. else:
  1060. commits[name].append(rev)
  1061. elif line.startswith('# patches_%s:' % branchname):
  1062. patches = line.split(':')[-1].strip().split(',')
  1063. update_revs = dict(initial_revs)
  1064. changed_revs = {}
  1065. for name, rev in initial_revs.items():
  1066. # Find first actually changed revision
  1067. stdout, _ = bb.process.run('git rev-list --reverse %s..HEAD' %
  1068. rev, cwd=os.path.join(srctree, name))
  1069. newcommits = stdout.split()
  1070. if name in commits:
  1071. for i in range(min(len(commits[name]), len(newcommits))):
  1072. if newcommits[i] == commits[name][i]:
  1073. update_revs[name] = commits[name][i]
  1074. try:
  1075. stdout, _ = bb.process.run('git cherry devtool-patched',
  1076. cwd=os.path.join(srctree, name))
  1077. except bb.process.ExecutionError as err:
  1078. stdout = None
  1079. if stdout is not None and not force_patch_refresh:
  1080. for line in stdout.splitlines():
  1081. if line.startswith('+ '):
  1082. rev = line.split()[1]
  1083. if rev in newcommits:
  1084. if name not in changed_revs:
  1085. changed_revs[name] = [rev]
  1086. else:
  1087. changed_revs[name].append(rev)
  1088. return initial_revs, update_revs, changed_revs, patches
  1089. def _remove_file_entries(srcuri, filelist):
  1090. """Remove file:// entries from SRC_URI"""
  1091. remaining = filelist[:]
  1092. entries = []
  1093. for fname in filelist:
  1094. basename = os.path.basename(fname)
  1095. for i in range(len(srcuri)):
  1096. if (srcuri[i].startswith('file://') and
  1097. os.path.basename(srcuri[i].split(';')[0]) == basename):
  1098. entries.append(srcuri[i])
  1099. remaining.remove(fname)
  1100. srcuri.pop(i)
  1101. break
  1102. return entries, remaining
  1103. def _replace_srcuri_entry(srcuri, filename, newentry):
  1104. """Replace entry corresponding to specified file with a new entry"""
  1105. basename = os.path.basename(filename)
  1106. for i in range(len(srcuri)):
  1107. if os.path.basename(srcuri[i].split(';')[0]) == basename:
  1108. srcuri.pop(i)
  1109. srcuri.insert(i, newentry)
  1110. break
  1111. def _remove_source_files(append, files, destpath, no_report_remove=False, dry_run=False):
  1112. """Unlink existing patch files"""
  1113. dry_run_suffix = ' (dry-run)' if dry_run else ''
  1114. for path in files:
  1115. if append:
  1116. if not destpath:
  1117. raise Exception('destpath should be set here')
  1118. path = os.path.join(destpath, os.path.basename(path))
  1119. if os.path.exists(path):
  1120. if not no_report_remove:
  1121. logger.info('Removing file %s%s' % (path, dry_run_suffix))
  1122. if not dry_run:
  1123. # FIXME "git rm" here would be nice if the file in question is
  1124. # tracked
  1125. # FIXME there's a chance that this file is referred to by
  1126. # another recipe, in which case deleting wouldn't be the
  1127. # right thing to do
  1128. os.remove(path)
  1129. # Remove directory if empty
  1130. try:
  1131. os.rmdir(os.path.dirname(path))
  1132. except OSError as ose:
  1133. if ose.errno != errno.ENOTEMPTY:
  1134. raise
  1135. def _export_patches(srctree, rd, start_revs, destdir, changed_revs=None):
  1136. """Export patches from srctree to given location.
  1137. Returns three-tuple of dicts:
  1138. 1. updated - patches that already exist in SRCURI
  1139. 2. added - new patches that don't exist in SRCURI
  1140. 3 removed - patches that exist in SRCURI but not in exported patches
  1141. In each dict the key is the 'basepath' of the URI and value is:
  1142. - for updated and added dicts, a dict with 2 optionnal keys:
  1143. - 'path': the absolute path to the existing file in recipe space (if any)
  1144. - 'patchdir': the directory in wich the patch should be applied (if any)
  1145. - for removed dict, the absolute path to the existing file in recipe space
  1146. """
  1147. import oe.recipeutils
  1148. from oe.patch import GitApplyTree
  1149. import bb.process
  1150. updated = OrderedDict()
  1151. added = OrderedDict()
  1152. seqpatch_re = re.compile('^([0-9]{4}-)?(.+)')
  1153. existing_patches = dict((os.path.basename(path), path) for path in
  1154. oe.recipeutils.get_recipe_patches(rd))
  1155. logger.debug('Existing patches: %s' % existing_patches)
  1156. # Generate patches from Git, exclude local files directory
  1157. patch_pathspec = _git_exclude_path(srctree, 'oe-local-files')
  1158. GitApplyTree.extractPatches(srctree, start_revs, destdir, patch_pathspec)
  1159. for dirpath, dirnames, filenames in os.walk(destdir):
  1160. new_patches = filenames
  1161. reldirpath = os.path.relpath(dirpath, destdir)
  1162. for new_patch in new_patches:
  1163. # Strip numbering from patch names. If it's a git sequence named patch,
  1164. # the numbers might not match up since we are starting from a different
  1165. # revision This does assume that people are using unique shortlog
  1166. # values, but they ought to be anyway...
  1167. new_basename = seqpatch_re.match(new_patch).group(2)
  1168. match_name = None
  1169. old_patch = None
  1170. for old_patch in existing_patches:
  1171. old_basename = seqpatch_re.match(old_patch).group(2)
  1172. old_basename_splitext = os.path.splitext(old_basename)
  1173. if old_basename.endswith(('.gz', '.bz2', '.Z')) and old_basename_splitext[0] == new_basename:
  1174. old_patch_noext = os.path.splitext(old_patch)[0]
  1175. match_name = old_patch_noext
  1176. break
  1177. elif new_basename == old_basename:
  1178. match_name = old_patch
  1179. break
  1180. if match_name:
  1181. # Rename patch files
  1182. if new_patch != match_name:
  1183. bb.utils.rename(os.path.join(destdir, new_patch),
  1184. os.path.join(destdir, match_name))
  1185. # Need to pop it off the list now before checking changed_revs
  1186. oldpath = existing_patches.pop(old_patch)
  1187. if changed_revs is not None and dirpath in changed_revs:
  1188. # Avoid updating patches that have not actually changed
  1189. with open(os.path.join(dirpath, match_name), 'r') as f:
  1190. firstlineitems = f.readline().split()
  1191. # Looking for "From <hash>" line
  1192. if len(firstlineitems) > 1 and len(firstlineitems[1]) == 40:
  1193. if not firstlineitems[1] in changed_revs[dirpath]:
  1194. continue
  1195. # Recompress if necessary
  1196. if oldpath.endswith(('.gz', '.Z')):
  1197. bb.process.run(['gzip', match_name], cwd=destdir)
  1198. if oldpath.endswith('.gz'):
  1199. match_name += '.gz'
  1200. else:
  1201. match_name += '.Z'
  1202. elif oldpath.endswith('.bz2'):
  1203. bb.process.run(['bzip2', match_name], cwd=destdir)
  1204. match_name += '.bz2'
  1205. updated[match_name] = {'path' : oldpath}
  1206. if reldirpath != ".":
  1207. updated[match_name]['patchdir'] = reldirpath
  1208. else:
  1209. added[new_patch] = {}
  1210. if reldirpath != ".":
  1211. added[new_patch]['patchdir'] = reldirpath
  1212. return (updated, added, existing_patches)
  1213. def _create_kconfig_diff(srctree, rd, outfile):
  1214. """Create a kconfig fragment"""
  1215. import bb.process
  1216. # Only update config fragment if both config files exist
  1217. orig_config = os.path.join(srctree, '.config.baseline')
  1218. new_config = os.path.join(srctree, '.config.new')
  1219. if os.path.exists(orig_config) and os.path.exists(new_config):
  1220. cmd = ['diff', '--new-line-format=%L', '--old-line-format=',
  1221. '--unchanged-line-format=', orig_config, new_config]
  1222. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
  1223. stderr=subprocess.PIPE)
  1224. stdout, stderr = pipe.communicate()
  1225. if pipe.returncode == 1:
  1226. logger.info("Updating config fragment %s" % outfile)
  1227. with open(outfile, 'wb') as fobj:
  1228. fobj.write(stdout)
  1229. elif pipe.returncode == 0:
  1230. logger.info("Would remove config fragment %s" % outfile)
  1231. if os.path.exists(outfile):
  1232. # Remove fragment file in case of empty diff
  1233. logger.info("Removing config fragment %s" % outfile)
  1234. os.unlink(outfile)
  1235. else:
  1236. raise bb.process.ExecutionError(cmd, pipe.returncode, stdout, stderr)
  1237. return True
  1238. return False
  1239. def _export_local_files(srctree, rd, destdir, srctreebase):
  1240. """Copy local files from srctree to given location.
  1241. Returns three-tuple of dicts:
  1242. 1. updated - files that already exist in SRCURI
  1243. 2. added - new files files that don't exist in SRCURI
  1244. 3 removed - files that exist in SRCURI but not in exported files
  1245. In each dict the key is the 'basepath' of the URI and value is:
  1246. - for updated and added dicts, a dict with 1 optionnal key:
  1247. - 'path': the absolute path to the existing file in recipe space (if any)
  1248. - for removed dict, the absolute path to the existing file in recipe space
  1249. """
  1250. import oe.recipeutils
  1251. import bb.data
  1252. import bb.process
  1253. # Find out local files (SRC_URI files that exist in the "recipe space").
  1254. # Local files that reside in srctree are not included in patch generation.
  1255. # Instead they are directly copied over the original source files (in
  1256. # recipe space).
  1257. existing_files = oe.recipeutils.get_recipe_local_files(rd)
  1258. new_set = None
  1259. updated = OrderedDict()
  1260. added = OrderedDict()
  1261. removed = OrderedDict()
  1262. # Get current branch and return early with empty lists
  1263. # if on one of the override branches
  1264. # (local files are provided only for the main branch and processing
  1265. # them against lists from recipe overrides will result in mismatches
  1266. # and broken modifications to recipes).
  1267. stdout, _ = bb.process.run('git rev-parse --abbrev-ref HEAD',
  1268. cwd=srctree)
  1269. branchname = stdout.rstrip()
  1270. if branchname.startswith(override_branch_prefix):
  1271. return (updated, added, removed)
  1272. files = _git_modified(srctree)
  1273. #if not files:
  1274. # files = _ls_tree(srctree)
  1275. for f in files:
  1276. fullfile = os.path.join(srctree, f)
  1277. if os.path.exists(os.path.join(fullfile, ".git")):
  1278. # submodules handled elsewhere
  1279. continue
  1280. if f not in existing_files:
  1281. added[f] = {}
  1282. if os.path.isdir(os.path.join(srctree, f)):
  1283. shutil.copytree(fullfile, os.path.join(destdir, f))
  1284. else:
  1285. shutil.copy2(fullfile, os.path.join(destdir, f))
  1286. elif not os.path.exists(fullfile):
  1287. removed[f] = existing_files[f]
  1288. elif f in existing_files:
  1289. updated[f] = {'path' : existing_files[f]}
  1290. if os.path.isdir(os.path.join(srctree, f)):
  1291. shutil.copytree(fullfile, os.path.join(destdir, f))
  1292. else:
  1293. shutil.copy2(fullfile, os.path.join(destdir, f))
  1294. # Special handling for kernel config
  1295. if bb.data.inherits_class('kernel-yocto', rd):
  1296. fragment_fn = 'devtool-fragment.cfg'
  1297. fragment_path = os.path.join(destdir, fragment_fn)
  1298. if _create_kconfig_diff(srctree, rd, fragment_path):
  1299. if os.path.exists(fragment_path):
  1300. if fragment_fn in removed:
  1301. del removed[fragment_fn]
  1302. if fragment_fn not in updated and fragment_fn not in added:
  1303. added[fragment_fn] = {}
  1304. else:
  1305. if fragment_fn in updated:
  1306. removed[fragment_fn] = updated[fragment_fn]
  1307. del updated[fragment_fn]
  1308. # Special handling for cml1, ccmake, etc bbclasses that generated
  1309. # configuration fragment files that are consumed as source files
  1310. for frag_class, frag_name in [("cml1", "fragment.cfg"), ("ccmake", "site-file.cmake")]:
  1311. if bb.data.inherits_class(frag_class, rd):
  1312. srcpath = os.path.join(rd.getVar('WORKDIR'), frag_name)
  1313. if os.path.exists(srcpath):
  1314. if frag_name in removed:
  1315. del removed[frag_name]
  1316. if frag_name not in updated:
  1317. added[frag_name] = {}
  1318. # copy fragment into destdir
  1319. shutil.copy2(srcpath, destdir)
  1320. return (updated, added, removed)
  1321. def _determine_files_dir(rd):
  1322. """Determine the appropriate files directory for a recipe"""
  1323. recipedir = rd.getVar('FILE_DIRNAME')
  1324. for entry in rd.getVar('FILESPATH').split(':'):
  1325. relpth = os.path.relpath(entry, recipedir)
  1326. if not os.sep in relpth:
  1327. # One (or zero) levels below only, so we don't put anything in machine-specific directories
  1328. if os.path.isdir(entry):
  1329. return entry
  1330. return os.path.join(recipedir, rd.getVar('BPN'))
  1331. def _update_recipe_srcrev(recipename, workspace, srctree, rd, appendlayerdir, wildcard_version, no_remove, no_report_remove, dry_run_outdir=None):
  1332. """Implement the 'srcrev' mode of update-recipe"""
  1333. import bb.process
  1334. import oe.recipeutils
  1335. dry_run_suffix = ' (dry-run)' if dry_run_outdir else ''
  1336. recipefile = rd.getVar('FILE')
  1337. recipedir = os.path.basename(recipefile)
  1338. logger.info('Updating SRCREV in recipe %s%s' % (recipedir, dry_run_suffix))
  1339. # Get original SRCREV
  1340. old_srcrev = rd.getVar('SRCREV') or ''
  1341. if old_srcrev == "INVALID":
  1342. raise DevtoolError('Update mode srcrev is only valid for recipe fetched from an SCM repository')
  1343. old_srcrev = {'.': old_srcrev}
  1344. # Get HEAD revision
  1345. try:
  1346. stdout, _ = bb.process.run('git rev-parse HEAD', cwd=srctree)
  1347. except bb.process.ExecutionError as err:
  1348. raise DevtoolError('Failed to get HEAD revision in %s: %s' %
  1349. (srctree, err))
  1350. srcrev = stdout.strip()
  1351. if len(srcrev) != 40:
  1352. raise DevtoolError('Invalid hash returned by git: %s' % stdout)
  1353. destpath = None
  1354. remove_files = []
  1355. patchfields = {}
  1356. patchfields['SRCREV'] = srcrev
  1357. orig_src_uri = rd.getVar('SRC_URI', False) or ''
  1358. srcuri = orig_src_uri.split()
  1359. tempdir = tempfile.mkdtemp(prefix='devtool')
  1360. update_srcuri = False
  1361. appendfile = None
  1362. try:
  1363. local_files_dir = tempfile.mkdtemp(dir=tempdir)
  1364. srctreebase = workspace[recipename]['srctreebase']
  1365. upd_f, new_f, del_f = _export_local_files(srctree, rd, local_files_dir, srctreebase)
  1366. removedentries = {}
  1367. if not no_remove:
  1368. # Find list of existing patches in recipe file
  1369. patches_dir = tempfile.mkdtemp(dir=tempdir)
  1370. upd_p, new_p, del_p = _export_patches(srctree, rd, old_srcrev,
  1371. patches_dir)
  1372. logger.debug('Patches: update %s, new %s, delete %s' % (dict(upd_p), dict(new_p), dict(del_p)))
  1373. # Remove deleted local files and "overlapping" patches
  1374. remove_files = list(del_f.values()) + [value["path"] for value in upd_p.values() if "path" in value] + [value["path"] for value in del_p.values() if "path" in value]
  1375. if remove_files:
  1376. removedentries = _remove_file_entries(srcuri, remove_files)[0]
  1377. update_srcuri = True
  1378. if appendlayerdir:
  1379. files = dict((os.path.join(local_files_dir, key), val) for
  1380. key, val in list(upd_f.items()) + list(new_f.items()))
  1381. removevalues = {}
  1382. if update_srcuri:
  1383. removevalues = {'SRC_URI': removedentries}
  1384. patchfields['SRC_URI'] = '\\\n '.join(srcuri)
  1385. if dry_run_outdir:
  1386. logger.info('Creating bbappend (dry-run)')
  1387. appendfile, destpath = oe.recipeutils.bbappend_recipe(
  1388. rd, appendlayerdir, files, wildcardver=wildcard_version,
  1389. extralines=patchfields, removevalues=removevalues,
  1390. redirect_output=dry_run_outdir)
  1391. else:
  1392. files_dir = _determine_files_dir(rd)
  1393. for basepath, param in upd_f.items():
  1394. path = param['path']
  1395. logger.info('Updating file %s%s' % (basepath, dry_run_suffix))
  1396. if os.path.isabs(basepath):
  1397. # Original file (probably with subdir pointing inside source tree)
  1398. # so we do not want to move it, just copy
  1399. _copy_file(basepath, path, dry_run_outdir=dry_run_outdir, base_outdir=recipedir)
  1400. else:
  1401. _move_file(os.path.join(local_files_dir, basepath), path,
  1402. dry_run_outdir=dry_run_outdir, base_outdir=recipedir)
  1403. update_srcuri= True
  1404. for basepath, param in new_f.items():
  1405. path = param['path']
  1406. logger.info('Adding new file %s%s' % (basepath, dry_run_suffix))
  1407. _move_file(os.path.join(local_files_dir, basepath),
  1408. os.path.join(files_dir, basepath),
  1409. dry_run_outdir=dry_run_outdir,
  1410. base_outdir=recipedir)
  1411. srcuri.append('file://%s' % basepath)
  1412. update_srcuri = True
  1413. if update_srcuri:
  1414. patchfields['SRC_URI'] = ' '.join(srcuri)
  1415. ret = oe.recipeutils.patch_recipe(rd, recipefile, patchfields, redirect_output=dry_run_outdir)
  1416. finally:
  1417. shutil.rmtree(tempdir)
  1418. if not 'git://' in orig_src_uri:
  1419. logger.info('You will need to update SRC_URI within the recipe to '
  1420. 'point to a git repository where you have pushed your '
  1421. 'changes')
  1422. _remove_source_files(appendlayerdir, remove_files, destpath, no_report_remove, dry_run=dry_run_outdir)
  1423. return True, appendfile, remove_files
  1424. def _update_recipe_patch(recipename, workspace, srctree, rd, appendlayerdir, wildcard_version, no_remove, no_report_remove, initial_rev, dry_run_outdir=None, force_patch_refresh=False):
  1425. """Implement the 'patch' mode of update-recipe"""
  1426. import oe.recipeutils
  1427. recipefile = rd.getVar('FILE')
  1428. recipedir = os.path.dirname(recipefile)
  1429. append = workspace[recipename]['bbappend']
  1430. if not os.path.exists(append):
  1431. raise DevtoolError('unable to find workspace bbappend for recipe %s' %
  1432. recipename)
  1433. srctreebase = workspace[recipename]['srctreebase']
  1434. relpatchdir = os.path.relpath(srctreebase, srctree)
  1435. if relpatchdir == '.':
  1436. patchdir_params = {}
  1437. else:
  1438. patchdir_params = {'patchdir': relpatchdir}
  1439. def srcuri_entry(basepath, patchdir_params):
  1440. if patchdir_params:
  1441. paramstr = ';' + ';'.join('%s=%s' % (k,v) for k,v in patchdir_params.items())
  1442. else:
  1443. paramstr = ''
  1444. return 'file://%s%s' % (basepath, paramstr)
  1445. initial_revs, update_revs, changed_revs, filter_patches = _get_patchset_revs(srctree, append, initial_rev, force_patch_refresh)
  1446. if not initial_revs:
  1447. raise DevtoolError('Unable to find initial revision - please specify '
  1448. 'it with --initial-rev')
  1449. appendfile = None
  1450. dl_dir = rd.getVar('DL_DIR')
  1451. if not dl_dir.endswith('/'):
  1452. dl_dir += '/'
  1453. dry_run_suffix = ' (dry-run)' if dry_run_outdir else ''
  1454. tempdir = tempfile.mkdtemp(prefix='devtool')
  1455. try:
  1456. local_files_dir = tempfile.mkdtemp(dir=tempdir)
  1457. upd_f, new_f, del_f = _export_local_files(srctree, rd, local_files_dir, srctreebase)
  1458. # Get updated patches from source tree
  1459. patches_dir = tempfile.mkdtemp(dir=tempdir)
  1460. upd_p, new_p, _ = _export_patches(srctree, rd, update_revs,
  1461. patches_dir, changed_revs)
  1462. # Get all patches from source tree and check if any should be removed
  1463. all_patches_dir = tempfile.mkdtemp(dir=tempdir)
  1464. _, _, del_p = _export_patches(srctree, rd, initial_revs,
  1465. all_patches_dir)
  1466. logger.debug('Pre-filtering: update: %s, new: %s' % (dict(upd_p), dict(new_p)))
  1467. if filter_patches:
  1468. new_p = OrderedDict()
  1469. upd_p = OrderedDict((k,v) for k,v in upd_p.items() if k in filter_patches)
  1470. del_p = OrderedDict((k,v) for k,v in del_p.items() if k in filter_patches)
  1471. remove_files = []
  1472. if not no_remove:
  1473. # Remove deleted local files and patches
  1474. remove_files = list(del_f.values()) + list(del_p.values())
  1475. updatefiles = False
  1476. updaterecipe = False
  1477. destpath = None
  1478. srcuri = (rd.getVar('SRC_URI', False) or '').split()
  1479. if appendlayerdir:
  1480. files = OrderedDict((os.path.join(local_files_dir, key), val) for
  1481. key, val in list(upd_f.items()) + list(new_f.items()))
  1482. files.update(OrderedDict((os.path.join(patches_dir, key), val) for
  1483. key, val in list(upd_p.items()) + list(new_p.items())))
  1484. params = []
  1485. for file, param in files.items():
  1486. patchdir_param = dict(patchdir_params)
  1487. patchdir = param.get('patchdir', ".")
  1488. if patchdir != "." :
  1489. if patchdir_param:
  1490. patchdir_param['patchdir'] += patchdir
  1491. else:
  1492. patchdir_param['patchdir'] = patchdir
  1493. params.append(patchdir_param)
  1494. if files or remove_files:
  1495. removevalues = None
  1496. if remove_files:
  1497. removedentries, remaining = _remove_file_entries(
  1498. srcuri, remove_files)
  1499. if removedentries or remaining:
  1500. remaining = [srcuri_entry(os.path.basename(item), patchdir_params) for
  1501. item in remaining]
  1502. removevalues = {'SRC_URI': removedentries + remaining}
  1503. appendfile, destpath = oe.recipeutils.bbappend_recipe(
  1504. rd, appendlayerdir, files,
  1505. wildcardver=wildcard_version,
  1506. removevalues=removevalues,
  1507. redirect_output=dry_run_outdir,
  1508. params=params)
  1509. else:
  1510. logger.info('No patches or local source files needed updating')
  1511. else:
  1512. # Update existing files
  1513. files_dir = _determine_files_dir(rd)
  1514. for basepath, param in upd_f.items():
  1515. path = param['path']
  1516. logger.info('Updating file %s' % basepath)
  1517. if os.path.isabs(basepath):
  1518. # Original file (probably with subdir pointing inside source tree)
  1519. # so we do not want to move it, just copy
  1520. _copy_file(basepath, path,
  1521. dry_run_outdir=dry_run_outdir, base_outdir=recipedir)
  1522. else:
  1523. _move_file(os.path.join(local_files_dir, basepath), path,
  1524. dry_run_outdir=dry_run_outdir, base_outdir=recipedir)
  1525. updatefiles = True
  1526. for basepath, param in upd_p.items():
  1527. path = param['path']
  1528. patchdir = param.get('patchdir', ".")
  1529. patchdir_param = {}
  1530. if patchdir != "." :
  1531. patchdir_param = dict(patchdir_params)
  1532. if patchdir_param:
  1533. patchdir_param['patchdir'] += patchdir
  1534. else:
  1535. patchdir_param['patchdir'] = patchdir
  1536. patchfn = os.path.join(patches_dir, patchdir, basepath)
  1537. if os.path.dirname(path) + '/' == dl_dir:
  1538. # This is a a downloaded patch file - we now need to
  1539. # replace the entry in SRC_URI with our local version
  1540. logger.info('Replacing remote patch %s with updated local version' % basepath)
  1541. path = os.path.join(files_dir, basepath)
  1542. _replace_srcuri_entry(srcuri, basepath, srcuri_entry(basepath, patchdir_param))
  1543. updaterecipe = True
  1544. else:
  1545. logger.info('Updating patch %s%s' % (basepath, dry_run_suffix))
  1546. _move_file(patchfn, path,
  1547. dry_run_outdir=dry_run_outdir, base_outdir=recipedir)
  1548. updatefiles = True
  1549. # Add any new files
  1550. for basepath, param in new_f.items():
  1551. logger.info('Adding new file %s%s' % (basepath, dry_run_suffix))
  1552. _move_file(os.path.join(local_files_dir, basepath),
  1553. os.path.join(files_dir, basepath),
  1554. dry_run_outdir=dry_run_outdir,
  1555. base_outdir=recipedir)
  1556. srcuri.append(srcuri_entry(basepath, patchdir_params))
  1557. updaterecipe = True
  1558. for basepath, param in new_p.items():
  1559. patchdir = param.get('patchdir', ".")
  1560. logger.info('Adding new patch %s%s' % (basepath, dry_run_suffix))
  1561. _move_file(os.path.join(patches_dir, patchdir, basepath),
  1562. os.path.join(files_dir, basepath),
  1563. dry_run_outdir=dry_run_outdir,
  1564. base_outdir=recipedir)
  1565. params = dict(patchdir_params)
  1566. if patchdir != "." :
  1567. if params:
  1568. params['patchdir'] += patchdir
  1569. else:
  1570. params['patchdir'] = patchdir
  1571. srcuri.append(srcuri_entry(basepath, params))
  1572. updaterecipe = True
  1573. # Update recipe, if needed
  1574. if _remove_file_entries(srcuri, remove_files)[0]:
  1575. updaterecipe = True
  1576. if updaterecipe:
  1577. if not dry_run_outdir:
  1578. logger.info('Updating recipe %s' % os.path.basename(recipefile))
  1579. ret = oe.recipeutils.patch_recipe(rd, recipefile,
  1580. {'SRC_URI': ' '.join(srcuri)},
  1581. redirect_output=dry_run_outdir)
  1582. elif not updatefiles:
  1583. # Neither patches nor recipe were updated
  1584. logger.info('No patches or files need updating')
  1585. return False, None, []
  1586. finally:
  1587. shutil.rmtree(tempdir)
  1588. _remove_source_files(appendlayerdir, remove_files, destpath, no_report_remove, dry_run=dry_run_outdir)
  1589. return True, appendfile, remove_files
  1590. def _guess_recipe_update_mode(srctree, rdata):
  1591. """Guess the recipe update mode to use"""
  1592. import bb.process
  1593. src_uri = (rdata.getVar('SRC_URI') or '').split()
  1594. git_uris = [uri for uri in src_uri if uri.startswith('git://')]
  1595. if not git_uris:
  1596. return 'patch'
  1597. # Just use the first URI for now
  1598. uri = git_uris[0]
  1599. # Check remote branch
  1600. params = bb.fetch.decodeurl(uri)[5]
  1601. upstr_branch = params['branch'] if 'branch' in params else 'master'
  1602. # Check if current branch HEAD is found in upstream branch
  1603. stdout, _ = bb.process.run('git rev-parse HEAD', cwd=srctree)
  1604. head_rev = stdout.rstrip()
  1605. stdout, _ = bb.process.run('git branch -r --contains %s' % head_rev,
  1606. cwd=srctree)
  1607. remote_brs = [branch.strip() for branch in stdout.splitlines()]
  1608. if 'origin/' + upstr_branch in remote_brs:
  1609. return 'srcrev'
  1610. return 'patch'
  1611. def _update_recipe(recipename, workspace, rd, mode, appendlayerdir, wildcard_version, no_remove, initial_rev, no_report_remove=False, dry_run_outdir=None, no_overrides=False, force_patch_refresh=False):
  1612. import bb.data
  1613. import bb.process
  1614. srctree = workspace[recipename]['srctree']
  1615. if mode == 'auto':
  1616. mode = _guess_recipe_update_mode(srctree, rd)
  1617. override_branches = []
  1618. mainbranch = None
  1619. startbranch = None
  1620. if not no_overrides:
  1621. stdout, _ = bb.process.run('git branch', cwd=srctree)
  1622. other_branches = []
  1623. for line in stdout.splitlines():
  1624. branchname = line[2:]
  1625. if line.startswith('* '):
  1626. if 'HEAD' in line:
  1627. raise DevtoolError('Detached HEAD - please check out a branch, e.g., "devtool"')
  1628. startbranch = branchname
  1629. if branchname.startswith(override_branch_prefix):
  1630. override_branches.append(branchname)
  1631. else:
  1632. other_branches.append(branchname)
  1633. if override_branches:
  1634. logger.debug('_update_recipe: override branches: %s' % override_branches)
  1635. logger.debug('_update_recipe: other branches: %s' % other_branches)
  1636. if startbranch.startswith(override_branch_prefix):
  1637. if len(other_branches) == 1:
  1638. mainbranch = other_branches[1]
  1639. else:
  1640. raise DevtoolError('Unable to determine main branch - please check out the main branch in source tree first')
  1641. else:
  1642. mainbranch = startbranch
  1643. checkedout = None
  1644. anyupdated = False
  1645. appendfile = None
  1646. allremoved = []
  1647. if override_branches:
  1648. logger.info('Handling main branch (%s)...' % mainbranch)
  1649. if startbranch != mainbranch:
  1650. bb.process.run('git checkout %s' % mainbranch, cwd=srctree)
  1651. checkedout = mainbranch
  1652. try:
  1653. branchlist = [mainbranch] + override_branches
  1654. for branch in branchlist:
  1655. crd = bb.data.createCopy(rd)
  1656. if branch != mainbranch:
  1657. logger.info('Handling branch %s...' % branch)
  1658. override = branch[len(override_branch_prefix):]
  1659. crd.appendVar('OVERRIDES', ':%s' % override)
  1660. bb.process.run('git checkout %s' % branch, cwd=srctree)
  1661. checkedout = branch
  1662. if mode == 'srcrev':
  1663. updated, appendf, removed = _update_recipe_srcrev(recipename, workspace, srctree, crd, appendlayerdir, wildcard_version, no_remove, no_report_remove, dry_run_outdir)
  1664. elif mode == 'patch':
  1665. updated, appendf, removed = _update_recipe_patch(recipename, workspace, srctree, crd, appendlayerdir, wildcard_version, no_remove, no_report_remove, initial_rev, dry_run_outdir, force_patch_refresh)
  1666. else:
  1667. raise DevtoolError('update_recipe: invalid mode %s' % mode)
  1668. if updated:
  1669. anyupdated = True
  1670. if appendf:
  1671. appendfile = appendf
  1672. allremoved.extend(removed)
  1673. finally:
  1674. if startbranch and checkedout != startbranch:
  1675. bb.process.run('git checkout %s' % startbranch, cwd=srctree)
  1676. return anyupdated, appendfile, allremoved
  1677. def update_recipe(args, config, basepath, workspace):
  1678. """Entry point for the devtool 'update-recipe' subcommand"""
  1679. check_workspace_recipe(workspace, args.recipename)
  1680. if args.append:
  1681. if not os.path.exists(args.append):
  1682. raise DevtoolError('bbappend destination layer directory "%s" '
  1683. 'does not exist' % args.append)
  1684. if not os.path.exists(os.path.join(args.append, 'conf', 'layer.conf')):
  1685. raise DevtoolError('conf/layer.conf not found in bbappend '
  1686. 'destination layer "%s"' % args.append)
  1687. tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
  1688. try:
  1689. rd = parse_recipe(config, tinfoil, args.recipename, True)
  1690. if not rd:
  1691. return 1
  1692. dry_run_output = None
  1693. dry_run_outdir = None
  1694. if args.dry_run:
  1695. dry_run_output = tempfile.TemporaryDirectory(prefix='devtool')
  1696. dry_run_outdir = dry_run_output.name
  1697. updated, _, _ = _update_recipe(args.recipename, workspace, rd, args.mode, args.append, args.wildcard_version, args.no_remove, args.initial_rev, dry_run_outdir=dry_run_outdir, no_overrides=args.no_overrides, force_patch_refresh=args.force_patch_refresh)
  1698. if updated:
  1699. rf = rd.getVar('FILE')
  1700. if rf.startswith(config.workspace_path):
  1701. logger.warning('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)
  1702. finally:
  1703. tinfoil.shutdown()
  1704. return 0
  1705. def status(args, config, basepath, workspace):
  1706. """Entry point for the devtool 'status' subcommand"""
  1707. if workspace:
  1708. for recipe, value in sorted(workspace.items()):
  1709. recipefile = value['recipefile']
  1710. if recipefile:
  1711. recipestr = ' (%s)' % recipefile
  1712. else:
  1713. recipestr = ''
  1714. print("%s: %s%s" % (recipe, value['srctree'], recipestr))
  1715. else:
  1716. 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')
  1717. return 0
  1718. def _reset(recipes, no_clean, remove_work, config, basepath, workspace):
  1719. """Reset one or more recipes"""
  1720. import bb.process
  1721. import oe.path
  1722. def clean_preferred_provider(pn, layerconf_path):
  1723. """Remove PREFERRED_PROVIDER from layer.conf'"""
  1724. import re
  1725. layerconf_file = os.path.join(layerconf_path, 'conf', 'layer.conf')
  1726. new_layerconf_file = os.path.join(layerconf_path, 'conf', '.layer.conf')
  1727. pprovider_found = False
  1728. with open(layerconf_file, 'r') as f:
  1729. lines = f.readlines()
  1730. with open(new_layerconf_file, 'a') as nf:
  1731. for line in lines:
  1732. pprovider_exp = r'^PREFERRED_PROVIDER_.*? = "' + re.escape(pn) + r'"$'
  1733. if not re.match(pprovider_exp, line):
  1734. nf.write(line)
  1735. else:
  1736. pprovider_found = True
  1737. if pprovider_found:
  1738. shutil.move(new_layerconf_file, layerconf_file)
  1739. else:
  1740. os.remove(new_layerconf_file)
  1741. if recipes and not no_clean:
  1742. if len(recipes) == 1:
  1743. logger.info('Cleaning sysroot for recipe %s...' % recipes[0])
  1744. else:
  1745. logger.info('Cleaning sysroot for recipes %s...' % ', '.join(recipes))
  1746. # If the recipe file itself was created in the workspace, and
  1747. # it uses BBCLASSEXTEND, then we need to also clean the other
  1748. # variants
  1749. targets = []
  1750. for recipe in recipes:
  1751. targets.append(recipe)
  1752. recipefile = workspace[recipe]['recipefile']
  1753. if recipefile and os.path.exists(recipefile):
  1754. targets.extend(get_bbclassextend_targets(recipefile, recipe))
  1755. try:
  1756. exec_build_env_command(config.init_path, basepath, 'bitbake -c clean %s' % ' '.join(targets))
  1757. except bb.process.ExecutionError as e:
  1758. raise DevtoolError('Command \'%s\' failed, output:\n%s\nIf you '
  1759. 'wish, you may specify -n/--no-clean to '
  1760. 'skip running this command when resetting' %
  1761. (e.command, e.stdout))
  1762. for pn in recipes:
  1763. _check_preserve(config, pn)
  1764. appendfile = workspace[pn]['bbappend']
  1765. if os.path.exists(appendfile):
  1766. # This shouldn't happen, but is possible if devtool errored out prior to
  1767. # writing the md5 file. We need to delete this here or the recipe won't
  1768. # actually be reset
  1769. os.remove(appendfile)
  1770. preservepath = os.path.join(config.workspace_path, 'attic', pn, pn)
  1771. def preservedir(origdir):
  1772. if os.path.exists(origdir):
  1773. for root, dirs, files in os.walk(origdir):
  1774. for fn in files:
  1775. logger.warning('Preserving %s in %s' % (fn, preservepath))
  1776. _move_file(os.path.join(origdir, fn),
  1777. os.path.join(preservepath, fn))
  1778. for dn in dirs:
  1779. preservedir(os.path.join(root, dn))
  1780. os.rmdir(origdir)
  1781. recipefile = workspace[pn]['recipefile']
  1782. if recipefile and oe.path.is_path_parent(config.workspace_path, recipefile):
  1783. # This should always be true if recipefile is set, but just in case
  1784. preservedir(os.path.dirname(recipefile))
  1785. # We don't automatically create this dir next to appends, but the user can
  1786. preservedir(os.path.join(config.workspace_path, 'appends', pn))
  1787. srctreebase = workspace[pn]['srctreebase']
  1788. if os.path.isdir(srctreebase):
  1789. if os.listdir(srctreebase):
  1790. if remove_work:
  1791. logger.info('-r argument used on %s, removing source tree.'
  1792. ' You will lose any unsaved work' %pn)
  1793. shutil.rmtree(srctreebase)
  1794. else:
  1795. # We don't want to risk wiping out any work in progress
  1796. if srctreebase.startswith(os.path.join(config.workspace_path, 'sources')):
  1797. from datetime import datetime
  1798. preservesrc = os.path.join(config.workspace_path, 'attic', 'sources', "{}.{}".format(pn, datetime.now().strftime("%Y%m%d%H%M%S")))
  1799. logger.info('Preserving source tree in %s\nIf you no '
  1800. 'longer need it then please delete it manually.\n'
  1801. 'It is also possible to reuse it via devtool source tree argument.'
  1802. % preservesrc)
  1803. bb.utils.mkdirhier(os.path.dirname(preservesrc))
  1804. shutil.move(srctreebase, preservesrc)
  1805. else:
  1806. logger.info('Leaving source tree %s as-is; if you no '
  1807. 'longer need it then please delete it manually'
  1808. % srctreebase)
  1809. else:
  1810. # This is unlikely, but if it's empty we can just remove it
  1811. os.rmdir(srctreebase)
  1812. clean_preferred_provider(pn, config.workspace_path)
  1813. def reset(args, config, basepath, workspace):
  1814. """Entry point for the devtool 'reset' subcommand"""
  1815. recipes = ""
  1816. if args.recipename:
  1817. if args.all:
  1818. raise DevtoolError("Recipe cannot be specified if -a/--all is used")
  1819. else:
  1820. for recipe in args.recipename:
  1821. check_workspace_recipe(workspace, recipe, checksrc=False)
  1822. elif not args.all:
  1823. raise DevtoolError("Recipe must be specified, or specify -a/--all to "
  1824. "reset all recipes")
  1825. if args.all:
  1826. recipes = list(workspace.keys())
  1827. else:
  1828. recipes = args.recipename
  1829. _reset(recipes, args.no_clean, args.remove_work, config, basepath, workspace)
  1830. return 0
  1831. def _get_layer(layername, d):
  1832. """Determine the base layer path for the specified layer name/path"""
  1833. layerdirs = d.getVar('BBLAYERS').split()
  1834. layers = {} # {basename: layer_paths}
  1835. for p in layerdirs:
  1836. bn = os.path.basename(p)
  1837. if bn not in layers:
  1838. layers[bn] = [p]
  1839. else:
  1840. layers[bn].append(p)
  1841. # Provide some shortcuts
  1842. if layername.lower() in ['oe-core', 'openembedded-core']:
  1843. layername = 'meta'
  1844. layer_paths = layers.get(layername, None)
  1845. if not layer_paths:
  1846. return os.path.abspath(layername)
  1847. elif len(layer_paths) == 1:
  1848. return os.path.abspath(layer_paths[0])
  1849. else:
  1850. # multiple layers having the same base name
  1851. logger.warning("Multiple layers have the same base name '%s', use the first one '%s'." % (layername, layer_paths[0]))
  1852. logger.warning("Consider using path instead of base name to specify layer:\n\t\t%s" % '\n\t\t'.join(layer_paths))
  1853. return os.path.abspath(layer_paths[0])
  1854. def finish(args, config, basepath, workspace):
  1855. """Entry point for the devtool 'finish' subcommand"""
  1856. import bb
  1857. import oe.recipeutils
  1858. check_workspace_recipe(workspace, args.recipename)
  1859. dry_run_suffix = ' (dry-run)' if args.dry_run else ''
  1860. # Grab the equivalent of COREBASE without having to initialise tinfoil
  1861. corebasedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
  1862. srctree = workspace[args.recipename]['srctree']
  1863. check_git_repo_op(srctree, [corebasedir])
  1864. dirty = check_git_repo_dirty(srctree)
  1865. if dirty:
  1866. if args.force:
  1867. logger.warning('Source tree is not clean, continuing as requested by -f/--force')
  1868. else:
  1869. raise DevtoolError('Source tree is not clean:\n\n%s\nEnsure you have committed your changes or use -f/--force if you are sure there\'s nothing that needs to be committed' % dirty)
  1870. no_clean = args.no_clean
  1871. remove_work=args.remove_work
  1872. tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
  1873. try:
  1874. rd = parse_recipe(config, tinfoil, args.recipename, True)
  1875. if not rd:
  1876. return 1
  1877. destlayerdir = _get_layer(args.destination, tinfoil.config_data)
  1878. recipefile = rd.getVar('FILE')
  1879. recipedir = os.path.dirname(recipefile)
  1880. origlayerdir = oe.recipeutils.find_layerdir(recipefile)
  1881. if not os.path.isdir(destlayerdir):
  1882. raise DevtoolError('Unable to find layer or directory matching "%s"' % args.destination)
  1883. if os.path.abspath(destlayerdir) == config.workspace_path:
  1884. raise DevtoolError('"%s" specifies the workspace layer - that is not a valid destination' % args.destination)
  1885. # If it's an upgrade, grab the original path
  1886. origpath = None
  1887. origfilelist = None
  1888. append = workspace[args.recipename]['bbappend']
  1889. with open(append, 'r') as f:
  1890. for line in f:
  1891. if line.startswith('# original_path:'):
  1892. origpath = line.split(':')[1].strip()
  1893. elif line.startswith('# original_files:'):
  1894. origfilelist = line.split(':')[1].split()
  1895. destlayerbasedir = oe.recipeutils.find_layerdir(destlayerdir)
  1896. if origlayerdir == config.workspace_path:
  1897. # Recipe file itself is in workspace, update it there first
  1898. appendlayerdir = None
  1899. origrelpath = None
  1900. if origpath:
  1901. origlayerpath = oe.recipeutils.find_layerdir(origpath)
  1902. if origlayerpath:
  1903. origrelpath = os.path.relpath(origpath, origlayerpath)
  1904. destpath = oe.recipeutils.get_bbfile_path(rd, destlayerdir, origrelpath)
  1905. if not destpath:
  1906. 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))
  1907. # Warn if the layer isn't in bblayers.conf (the code to create a bbappend will do this in other cases)
  1908. layerdirs = [os.path.abspath(layerdir) for layerdir in rd.getVar('BBLAYERS').split()]
  1909. if not os.path.abspath(destlayerbasedir) in layerdirs:
  1910. 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)
  1911. elif destlayerdir == origlayerdir:
  1912. # Same layer, update the original recipe
  1913. appendlayerdir = None
  1914. destpath = None
  1915. else:
  1916. # Create/update a bbappend in the specified layer
  1917. appendlayerdir = destlayerdir
  1918. destpath = None
  1919. # Actually update the recipe / bbappend
  1920. removing_original = (origpath and origfilelist and oe.recipeutils.find_layerdir(origpath) == destlayerbasedir)
  1921. dry_run_output = None
  1922. dry_run_outdir = None
  1923. if args.dry_run:
  1924. dry_run_output = tempfile.TemporaryDirectory(prefix='devtool')
  1925. dry_run_outdir = dry_run_output.name
  1926. updated, appendfile, removed = _update_recipe(args.recipename, workspace, rd, args.mode, appendlayerdir, wildcard_version=True, no_remove=False, no_report_remove=removing_original, initial_rev=args.initial_rev, dry_run_outdir=dry_run_outdir, no_overrides=args.no_overrides, force_patch_refresh=args.force_patch_refresh)
  1927. removed = [os.path.relpath(pth, recipedir) for pth in removed]
  1928. # Remove any old files in the case of an upgrade
  1929. if removing_original:
  1930. for fn in origfilelist:
  1931. fnp = os.path.join(origpath, fn)
  1932. if fn in removed or not os.path.exists(os.path.join(recipedir, fn)):
  1933. logger.info('Removing file %s%s' % (fnp, dry_run_suffix))
  1934. if not args.dry_run:
  1935. try:
  1936. os.remove(fnp)
  1937. except FileNotFoundError:
  1938. pass
  1939. if origlayerdir == config.workspace_path and destpath:
  1940. # Recipe file itself is in the workspace - need to move it and any
  1941. # associated files to the specified layer
  1942. no_clean = True
  1943. logger.info('Moving recipe file to %s%s' % (destpath, dry_run_suffix))
  1944. for root, _, files in os.walk(recipedir):
  1945. for fn in files:
  1946. srcpath = os.path.join(root, fn)
  1947. relpth = os.path.relpath(os.path.dirname(srcpath), recipedir)
  1948. destdir = os.path.abspath(os.path.join(destpath, relpth))
  1949. destfp = os.path.join(destdir, fn)
  1950. _move_file(srcpath, destfp, dry_run_outdir=dry_run_outdir, base_outdir=destpath)
  1951. if dry_run_outdir:
  1952. import difflib
  1953. comparelist = []
  1954. for root, _, files in os.walk(dry_run_outdir):
  1955. for fn in files:
  1956. outf = os.path.join(root, fn)
  1957. relf = os.path.relpath(outf, dry_run_outdir)
  1958. logger.debug('dry-run: output file %s' % relf)
  1959. if fn.endswith('.bb'):
  1960. if origfilelist and origpath and destpath:
  1961. # Need to match this up with the pre-upgrade recipe file
  1962. for origf in origfilelist:
  1963. if origf.endswith('.bb'):
  1964. comparelist.append((os.path.abspath(os.path.join(origpath, origf)),
  1965. outf,
  1966. os.path.abspath(os.path.join(destpath, relf))))
  1967. break
  1968. else:
  1969. # Compare to the existing recipe
  1970. comparelist.append((recipefile, outf, recipefile))
  1971. elif fn.endswith('.bbappend'):
  1972. if appendfile:
  1973. if os.path.exists(appendfile):
  1974. comparelist.append((appendfile, outf, appendfile))
  1975. else:
  1976. comparelist.append((None, outf, appendfile))
  1977. else:
  1978. if destpath:
  1979. recipedest = destpath
  1980. elif appendfile:
  1981. recipedest = os.path.dirname(appendfile)
  1982. else:
  1983. recipedest = os.path.dirname(recipefile)
  1984. destfp = os.path.join(recipedest, relf)
  1985. if os.path.exists(destfp):
  1986. comparelist.append((destfp, outf, destfp))
  1987. output = ''
  1988. for oldfile, newfile, newfileshow in comparelist:
  1989. if oldfile:
  1990. with open(oldfile, 'r') as f:
  1991. oldlines = f.readlines()
  1992. else:
  1993. oldfile = '/dev/null'
  1994. oldlines = []
  1995. with open(newfile, 'r') as f:
  1996. newlines = f.readlines()
  1997. if not newfileshow:
  1998. newfileshow = newfile
  1999. diff = difflib.unified_diff(oldlines, newlines, oldfile, newfileshow)
  2000. difflines = list(diff)
  2001. if difflines:
  2002. output += ''.join(difflines)
  2003. if output:
  2004. logger.info('Diff of changed files:\n%s' % output)
  2005. finally:
  2006. tinfoil.shutdown()
  2007. # Everything else has succeeded, we can now reset
  2008. if args.dry_run:
  2009. logger.info('Resetting recipe (dry-run)')
  2010. else:
  2011. _reset([args.recipename], no_clean=no_clean, remove_work=remove_work, config=config, basepath=basepath, workspace=workspace)
  2012. return 0
  2013. def get_default_srctree(config, recipename=''):
  2014. """Get the default srctree path"""
  2015. srctreeparent = config.get('General', 'default_source_parent_dir', config.workspace_path)
  2016. if recipename:
  2017. return os.path.join(srctreeparent, 'sources', recipename)
  2018. else:
  2019. return os.path.join(srctreeparent, 'sources')
  2020. def register_commands(subparsers, context):
  2021. """Register devtool subcommands from this plugin"""
  2022. defsrctree = get_default_srctree(context.config)
  2023. parser_add = subparsers.add_parser('add', help='Add a new recipe',
  2024. 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.',
  2025. group='starting', order=100)
  2026. 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.')
  2027. parser_add.add_argument('srctree', nargs='?', help='Path to external source tree. If not specified, a subdirectory of %s will be used.' % defsrctree)
  2028. parser_add.add_argument('fetchuri', nargs='?', help='Fetch the specified URI and extract it to create the source tree')
  2029. group = parser_add.add_mutually_exclusive_group()
  2030. group.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
  2031. group.add_argument('--no-same-dir', help='Force build in a separate build directory', action="store_true")
  2032. 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')
  2033. parser_add.add_argument('--npm-dev', help='For npm, also fetch devDependencies', action="store_true")
  2034. parser_add.add_argument('--no-pypi', help='Do not inherit pypi class', action="store_true")
  2035. parser_add.add_argument('--version', '-V', help='Version to use within recipe (PV)')
  2036. parser_add.add_argument('--no-git', '-g', help='If fetching source, do not set up source tree as a git repository', action="store_true")
  2037. group = parser_add.add_mutually_exclusive_group()
  2038. group.add_argument('--srcrev', '-S', help='Source revision to fetch if fetching from an SCM such as git (default latest)')
  2039. 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")
  2040. parser_add.add_argument('--srcbranch', '-B', help='Branch in source repository if fetching from an SCM such as git (default master)')
  2041. 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')
  2042. 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')
  2043. parser_add.add_argument('--src-subdir', help='Specify subdirectory within source tree to use', metavar='SUBDIR')
  2044. parser_add.add_argument('--mirrors', help='Enable PREMIRRORS and MIRRORS for source tree fetching (disable by default).', action="store_true")
  2045. parser_add.add_argument('--provides', '-p', help='Specify an alias for the item provided by the recipe. E.g. virtual/libgl')
  2046. parser_add.set_defaults(func=add, fixed_setup=context.fixed_setup)
  2047. parser_modify = subparsers.add_parser('modify', help='Modify the source for an existing recipe',
  2048. 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.',
  2049. group='starting', order=90)
  2050. parser_modify.add_argument('recipename', help='Name of existing recipe to edit (just name - no version, path or extension)')
  2051. parser_modify.add_argument('srctree', nargs='?', help='Path to external source tree. If not specified, a subdirectory of %s will be used.' % defsrctree)
  2052. parser_modify.add_argument('--wildcard', '-w', action="store_true", help='Use wildcard for unversioned bbappend')
  2053. group = parser_modify.add_mutually_exclusive_group()
  2054. group.add_argument('--extract', '-x', action="store_true", help='Extract source for recipe (default)')
  2055. group.add_argument('--no-extract', '-n', action="store_true", help='Do not extract source, expect it to exist')
  2056. group = parser_modify.add_mutually_exclusive_group()
  2057. group.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
  2058. group.add_argument('--no-same-dir', help='Force build in a separate build directory', action="store_true")
  2059. parser_modify.add_argument('--branch', '-b', default="devtool", help='Name for development branch to checkout (when not using -n/--no-extract) (default "%(default)s")')
  2060. parser_modify.add_argument('--no-overrides', '-O', action="store_true", help='Do not create branches for other override configurations')
  2061. parser_modify.add_argument('--keep-temp', help='Keep temporary directory (for debugging)', action="store_true")
  2062. parser_modify.add_argument('--debug-build', action="store_true", help='Add DEBUG_BUILD = "1" to the modified recipe')
  2063. parser_modify.set_defaults(func=modify, fixed_setup=context.fixed_setup)
  2064. parser_extract = subparsers.add_parser('extract', help='Extract the source for an existing recipe',
  2065. description='Extracts the source for an existing recipe',
  2066. group='advanced')
  2067. parser_extract.add_argument('recipename', help='Name of recipe to extract the source for')
  2068. parser_extract.add_argument('srctree', help='Path to where to extract the source tree')
  2069. parser_extract.add_argument('--branch', '-b', default="devtool", help='Name for development branch to checkout (default "%(default)s")')
  2070. parser_extract.add_argument('--no-overrides', '-O', action="store_true", help='Do not create branches for other override configurations')
  2071. parser_extract.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
  2072. parser_extract.set_defaults(func=extract, fixed_setup=context.fixed_setup)
  2073. parser_sync = subparsers.add_parser('sync', help='Synchronize the source tree for an existing recipe',
  2074. description='Synchronize the previously extracted source tree for an existing recipe',
  2075. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  2076. group='advanced')
  2077. parser_sync.add_argument('recipename', help='Name of recipe to sync the source for')
  2078. parser_sync.add_argument('srctree', help='Path to the source tree')
  2079. parser_sync.add_argument('--branch', '-b', default="devtool", help='Name for development branch to checkout')
  2080. parser_sync.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
  2081. parser_sync.set_defaults(func=sync, fixed_setup=context.fixed_setup)
  2082. parser_rename = subparsers.add_parser('rename', help='Rename a recipe file in the workspace',
  2083. 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.',
  2084. group='working', order=10)
  2085. parser_rename.add_argument('recipename', help='Current name of recipe to rename')
  2086. parser_rename.add_argument('newname', nargs='?', help='New name for recipe (optional, not needed if you only want to change the version)')
  2087. 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)')
  2088. 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')
  2089. parser_rename.set_defaults(func=rename)
  2090. parser_update_recipe = subparsers.add_parser('update-recipe', help='Apply changes from external source tree to recipe',
  2091. 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.',
  2092. group='working', order=-90)
  2093. parser_update_recipe.add_argument('recipename', help='Name of recipe to update')
  2094. 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')
  2095. parser_update_recipe.add_argument('--initial-rev', help='Override starting revision for patches')
  2096. parser_update_recipe.add_argument('--append', '-a', help='Write changes to a bbappend in the specified layer instead of the recipe', metavar='LAYERDIR')
  2097. 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')
  2098. parser_update_recipe.add_argument('--no-remove', '-n', action="store_true", help='Don\'t remove patches, only add or update')
  2099. parser_update_recipe.add_argument('--no-overrides', '-O', action="store_true", help='Do not handle other override branches (if they exist)')
  2100. parser_update_recipe.add_argument('--dry-run', '-N', action="store_true", help='Dry-run (just report changes instead of writing them)')
  2101. parser_update_recipe.add_argument('--force-patch-refresh', action="store_true", help='Update patches in the layer even if they have not been modified (useful for refreshing patch context)')
  2102. parser_update_recipe.set_defaults(func=update_recipe)
  2103. parser_status = subparsers.add_parser('status', help='Show workspace status',
  2104. description='Lists recipes currently in your workspace and the paths to their respective external source trees',
  2105. group='info', order=100)
  2106. parser_status.set_defaults(func=status)
  2107. parser_reset = subparsers.add_parser('reset', help='Remove a recipe from your workspace',
  2108. description='Removes the specified recipe(s) from your workspace (resetting its state back to that defined by the metadata).',
  2109. group='working', order=-100)
  2110. parser_reset.add_argument('recipename', nargs='*', help='Recipe to reset')
  2111. parser_reset.add_argument('--all', '-a', action="store_true", help='Reset all recipes (clear workspace)')
  2112. parser_reset.add_argument('--no-clean', '-n', action="store_true", help='Don\'t clean the sysroot to remove recipe output')
  2113. parser_reset.add_argument('--remove-work', '-r', action="store_true", help='Clean the sources directory along with append')
  2114. parser_reset.set_defaults(func=reset)
  2115. parser_finish = subparsers.add_parser('finish', help='Finish working on a recipe in your workspace',
  2116. 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. Note that your changes must have been committed to the git repository in order to be recognised.',
  2117. group='working', order=-100)
  2118. parser_finish.add_argument('recipename', help='Recipe to finish')
  2119. 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.')
  2120. 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')
  2121. parser_finish.add_argument('--initial-rev', help='Override starting revision for patches')
  2122. parser_finish.add_argument('--force', '-f', action="store_true", help='Force continuing even if there are uncommitted changes in the source tree repository')
  2123. parser_finish.add_argument('--remove-work', '-r', action="store_true", help='Clean the sources directory under workspace')
  2124. parser_finish.add_argument('--no-clean', '-n', action="store_true", help='Don\'t clean the sysroot to remove recipe output')
  2125. parser_finish.add_argument('--no-overrides', '-O', action="store_true", help='Do not handle other override branches (if they exist)')
  2126. parser_finish.add_argument('--dry-run', '-N', action="store_true", help='Dry-run (just report changes instead of writing them)')
  2127. parser_finish.add_argument('--force-patch-refresh', action="store_true", help='Update patches in the layer even if they have not been modified (useful for refreshing patch context)')
  2128. parser_finish.set_defaults(func=finish)