standard.py 104 KB

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