standard.py 86 KB

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