standard.py 103 KB

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