standard.py 118 KB

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