standard.py 72 KB

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