standard.py 103 KB

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