recipeutils.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  1. # Utility functions for reading and modifying recipes
  2. #
  3. # Some code borrowed from the OE layer index
  4. #
  5. # Copyright (C) 2013-2017 Intel Corporation
  6. #
  7. import sys
  8. import os
  9. import os.path
  10. import tempfile
  11. import textwrap
  12. import difflib
  13. from . import utils
  14. import shutil
  15. import re
  16. import fnmatch
  17. import glob
  18. from collections import OrderedDict, defaultdict
  19. # Help us to find places to insert values
  20. recipe_progression = ['SUMMARY', 'DESCRIPTION', 'HOMEPAGE', 'BUGTRACKER', 'SECTION', 'LICENSE', 'LICENSE_FLAGS', 'LIC_FILES_CHKSUM', 'PROVIDES', 'DEPENDS', 'PR', 'PV', 'SRCREV', 'SRCPV', 'SRC_URI', 'S', 'do_fetch()', 'do_unpack()', 'do_patch()', 'EXTRA_OECONF', 'EXTRA_OECMAKE', 'EXTRA_OESCONS', 'do_configure()', 'EXTRA_OEMAKE', 'do_compile()', 'do_install()', 'do_populate_sysroot()', 'INITSCRIPT', 'USERADD', 'GROUPADD', 'PACKAGES', 'FILES', 'RDEPENDS', 'RRECOMMENDS', 'RSUGGESTS', 'RPROVIDES', 'RREPLACES', 'RCONFLICTS', 'ALLOW_EMPTY', 'populate_packages()', 'do_package()', 'do_deploy()']
  21. # Variables that sometimes are a bit long but shouldn't be wrapped
  22. nowrap_vars = ['SUMMARY', 'HOMEPAGE', 'BUGTRACKER', 'SRC_URI\[(.+\.)?md5sum\]', 'SRC_URI\[(.+\.)?sha256sum\]']
  23. list_vars = ['SRC_URI', 'LIC_FILES_CHKSUM']
  24. meta_vars = ['SUMMARY', 'DESCRIPTION', 'HOMEPAGE', 'BUGTRACKER', 'SECTION']
  25. def simplify_history(history, d):
  26. """
  27. Eliminate any irrelevant events from a variable history
  28. """
  29. ret_history = []
  30. has_set = False
  31. # Go backwards through the history and remove any immediate operations
  32. # before the most recent set
  33. for event in reversed(history):
  34. if 'flag' in event or not 'file' in event:
  35. continue
  36. if event['op'] == 'set':
  37. if has_set:
  38. continue
  39. has_set = True
  40. elif event['op'] in ('append', 'prepend', 'postdot', 'predot'):
  41. # Reminder: "append" and "prepend" mean += and =+ respectively, NOT _append / _prepend
  42. if has_set:
  43. continue
  44. ret_history.insert(0, event)
  45. return ret_history
  46. def get_var_files(fn, varlist, d):
  47. """Find the file in which each of a list of variables is set.
  48. Note: requires variable history to be enabled when parsing.
  49. """
  50. varfiles = {}
  51. for v in varlist:
  52. files = []
  53. if '[' in v:
  54. varsplit = v.split('[')
  55. varflag = varsplit[1].split(']')[0]
  56. history = d.varhistory.variable(varsplit[0])
  57. for event in history:
  58. if 'file' in event and event.get('flag', '') == varflag:
  59. files.append(event['file'])
  60. else:
  61. history = d.varhistory.variable(v)
  62. for event in history:
  63. if 'file' in event and not 'flag' in event:
  64. files.append(event['file'])
  65. if files:
  66. actualfile = files[-1]
  67. else:
  68. actualfile = None
  69. varfiles[v] = actualfile
  70. return varfiles
  71. def split_var_value(value, assignment=True):
  72. """
  73. Split a space-separated variable's value into a list of items,
  74. taking into account that some of the items might be made up of
  75. expressions containing spaces that should not be split.
  76. Parameters:
  77. value:
  78. The string value to split
  79. assignment:
  80. True to assume that the value represents an assignment
  81. statement, False otherwise. If True, and an assignment
  82. statement is passed in the first item in
  83. the returned list will be the part of the assignment
  84. statement up to and including the opening quote character,
  85. and the last item will be the closing quote.
  86. """
  87. inexpr = 0
  88. lastchar = None
  89. out = []
  90. buf = ''
  91. for char in value:
  92. if char == '{':
  93. if lastchar == '$':
  94. inexpr += 1
  95. elif char == '}':
  96. inexpr -= 1
  97. elif assignment and char in '"\'' and inexpr == 0:
  98. if buf:
  99. out.append(buf)
  100. out.append(char)
  101. char = ''
  102. buf = ''
  103. elif char.isspace() and inexpr == 0:
  104. char = ''
  105. if buf:
  106. out.append(buf)
  107. buf = ''
  108. buf += char
  109. lastchar = char
  110. if buf:
  111. out.append(buf)
  112. # Join together assignment statement and opening quote
  113. outlist = out
  114. if assignment:
  115. assigfound = False
  116. for idx, item in enumerate(out):
  117. if '=' in item:
  118. assigfound = True
  119. if assigfound:
  120. if '"' in item or "'" in item:
  121. outlist = [' '.join(out[:idx+1])]
  122. outlist.extend(out[idx+1:])
  123. break
  124. return outlist
  125. def patch_recipe_lines(fromlines, values, trailing_newline=True):
  126. """Update or insert variable values into lines from a recipe.
  127. Note that some manual inspection/intervention may be required
  128. since this cannot handle all situations.
  129. """
  130. import bb.utils
  131. if trailing_newline:
  132. newline = '\n'
  133. else:
  134. newline = ''
  135. nowrap_vars_res = []
  136. for item in nowrap_vars:
  137. nowrap_vars_res.append(re.compile('^%s$' % item))
  138. recipe_progression_res = []
  139. recipe_progression_restrs = []
  140. for item in recipe_progression:
  141. if item.endswith('()'):
  142. key = item[:-2]
  143. else:
  144. key = item
  145. restr = '%s(_[a-zA-Z0-9-_$(){}]+|\[[^\]]*\])?' % key
  146. if item.endswith('()'):
  147. recipe_progression_restrs.append(restr + '()')
  148. else:
  149. recipe_progression_restrs.append(restr)
  150. recipe_progression_res.append(re.compile('^%s$' % restr))
  151. def get_recipe_pos(variable):
  152. for i, p in enumerate(recipe_progression_res):
  153. if p.match(variable):
  154. return i
  155. return -1
  156. remainingnames = {}
  157. for k in values.keys():
  158. remainingnames[k] = get_recipe_pos(k)
  159. remainingnames = OrderedDict(sorted(remainingnames.items(), key=lambda x: x[1]))
  160. modifying = False
  161. def outputvalue(name, lines, rewindcomments=False):
  162. if values[name] is None:
  163. return
  164. if isinstance(values[name], tuple):
  165. op, value = values[name]
  166. if op == '+=' and value.strip() == '':
  167. return
  168. else:
  169. value = values[name]
  170. op = '='
  171. rawtext = '%s %s "%s"%s' % (name, op, value, newline)
  172. addlines = []
  173. nowrap = False
  174. for nowrap_re in nowrap_vars_res:
  175. if nowrap_re.match(name):
  176. nowrap = True
  177. break
  178. if nowrap:
  179. addlines.append(rawtext)
  180. elif name in list_vars:
  181. splitvalue = split_var_value(value, assignment=False)
  182. if len(splitvalue) > 1:
  183. linesplit = ' \\\n' + (' ' * (len(name) + 4))
  184. addlines.append('%s %s "%s%s"%s' % (name, op, linesplit.join(splitvalue), linesplit, newline))
  185. else:
  186. addlines.append(rawtext)
  187. else:
  188. wrapped = textwrap.wrap(rawtext)
  189. for wrapline in wrapped[:-1]:
  190. addlines.append('%s \\%s' % (wrapline, newline))
  191. addlines.append('%s%s' % (wrapped[-1], newline))
  192. # Split on newlines - this isn't strictly necessary if you are only
  193. # going to write the output to disk, but if you want to compare it
  194. # (as patch_recipe_file() will do if patch=True) then it's important.
  195. addlines = [line for l in addlines for line in l.splitlines(True)]
  196. if rewindcomments:
  197. # Ensure we insert the lines before any leading comments
  198. # (that we'd want to ensure remain leading the next value)
  199. for i, ln in reversed(list(enumerate(lines))):
  200. if not ln.startswith('#'):
  201. lines[i+1:i+1] = addlines
  202. break
  203. else:
  204. lines.extend(addlines)
  205. else:
  206. lines.extend(addlines)
  207. existingnames = []
  208. def patch_recipe_varfunc(varname, origvalue, op, newlines):
  209. if modifying:
  210. # Insert anything that should come before this variable
  211. pos = get_recipe_pos(varname)
  212. for k in list(remainingnames):
  213. if remainingnames[k] > -1 and pos >= remainingnames[k] and not k in existingnames:
  214. outputvalue(k, newlines, rewindcomments=True)
  215. del remainingnames[k]
  216. # Now change this variable, if it needs to be changed
  217. if varname in existingnames and op in ['+=', '=', '=+']:
  218. if varname in remainingnames:
  219. outputvalue(varname, newlines)
  220. del remainingnames[varname]
  221. return None, None, 0, True
  222. else:
  223. if varname in values:
  224. existingnames.append(varname)
  225. return origvalue, None, 0, True
  226. # First run - establish which values we want to set are already in the file
  227. varlist = [re.escape(item) for item in values.keys()]
  228. bb.utils.edit_metadata(fromlines, varlist, patch_recipe_varfunc)
  229. # Second run - actually set everything
  230. modifying = True
  231. varlist.extend(recipe_progression_restrs)
  232. changed, tolines = bb.utils.edit_metadata(fromlines, varlist, patch_recipe_varfunc, match_overrides=True)
  233. if remainingnames:
  234. if tolines and tolines[-1].strip() != '':
  235. tolines.append('\n')
  236. for k in remainingnames.keys():
  237. outputvalue(k, tolines)
  238. return changed, tolines
  239. def patch_recipe_file(fn, values, patch=False, relpath='', redirect_output=None):
  240. """Update or insert variable values into a recipe file (assuming you
  241. have already identified the exact file you want to update.)
  242. Note that some manual inspection/intervention may be required
  243. since this cannot handle all situations.
  244. """
  245. with open(fn, 'r') as f:
  246. fromlines = f.readlines()
  247. _, tolines = patch_recipe_lines(fromlines, values)
  248. if redirect_output:
  249. with open(os.path.join(redirect_output, os.path.basename(fn)), 'w') as f:
  250. f.writelines(tolines)
  251. return None
  252. elif patch:
  253. relfn = os.path.relpath(fn, relpath)
  254. diff = difflib.unified_diff(fromlines, tolines, 'a/%s' % relfn, 'b/%s' % relfn)
  255. return diff
  256. else:
  257. with open(fn, 'w') as f:
  258. f.writelines(tolines)
  259. return None
  260. def localise_file_vars(fn, varfiles, varlist):
  261. """Given a list of variables and variable history (fetched with get_var_files())
  262. find where each variable should be set/changed. This handles for example where a
  263. recipe includes an inc file where variables might be changed - in most cases
  264. we want to update the inc file when changing the variable value rather than adding
  265. it to the recipe itself.
  266. """
  267. fndir = os.path.dirname(fn) + os.sep
  268. first_meta_file = None
  269. for v in meta_vars:
  270. f = varfiles.get(v, None)
  271. if f:
  272. actualdir = os.path.dirname(f) + os.sep
  273. if actualdir.startswith(fndir):
  274. first_meta_file = f
  275. break
  276. filevars = defaultdict(list)
  277. for v in varlist:
  278. f = varfiles[v]
  279. # Only return files that are in the same directory as the recipe or in some directory below there
  280. # (this excludes bbclass files and common inc files that wouldn't be appropriate to set the variable
  281. # in if we were going to set a value specific to this recipe)
  282. if f:
  283. actualfile = f
  284. else:
  285. # Variable isn't in a file, if it's one of the "meta" vars, use the first file with a meta var in it
  286. if first_meta_file:
  287. actualfile = first_meta_file
  288. else:
  289. actualfile = fn
  290. actualdir = os.path.dirname(actualfile) + os.sep
  291. if not actualdir.startswith(fndir):
  292. actualfile = fn
  293. filevars[actualfile].append(v)
  294. return filevars
  295. def patch_recipe(d, fn, varvalues, patch=False, relpath='', redirect_output=None):
  296. """Modify a list of variable values in the specified recipe. Handles inc files if
  297. used by the recipe.
  298. """
  299. overrides = d.getVar('OVERRIDES').split(':')
  300. def override_applicable(hevent):
  301. op = hevent['op']
  302. if '[' in op:
  303. opoverrides = op.split('[')[1].split(']')[0].split('_')
  304. for opoverride in opoverrides:
  305. if not opoverride in overrides:
  306. return False
  307. return True
  308. varlist = varvalues.keys()
  309. fn = os.path.abspath(fn)
  310. varfiles = get_var_files(fn, varlist, d)
  311. locs = localise_file_vars(fn, varfiles, varlist)
  312. patches = []
  313. for f,v in locs.items():
  314. vals = {k: varvalues[k] for k in v}
  315. f = os.path.abspath(f)
  316. if f == fn:
  317. extravals = {}
  318. for var, value in vals.items():
  319. if var in list_vars:
  320. history = simplify_history(d.varhistory.variable(var), d)
  321. recipe_set = False
  322. for event in history:
  323. if os.path.abspath(event['file']) == fn:
  324. if event['op'] == 'set':
  325. recipe_set = True
  326. if not recipe_set:
  327. for event in history:
  328. if event['op'].startswith('_remove'):
  329. continue
  330. if not override_applicable(event):
  331. continue
  332. newvalue = value.replace(event['detail'], '')
  333. if newvalue == value and os.path.abspath(event['file']) == fn and event['op'].startswith('_'):
  334. op = event['op'].replace('[', '_').replace(']', '')
  335. extravals[var + op] = None
  336. value = newvalue
  337. vals[var] = ('+=', value)
  338. vals.update(extravals)
  339. patchdata = patch_recipe_file(f, vals, patch, relpath, redirect_output)
  340. if patch:
  341. patches.append(patchdata)
  342. if patch:
  343. return patches
  344. else:
  345. return None
  346. def copy_recipe_files(d, tgt_dir, whole_dir=False, download=True, all_variants=False):
  347. """Copy (local) recipe files, including both files included via include/require,
  348. and files referred to in the SRC_URI variable."""
  349. import bb.fetch2
  350. import oe.path
  351. # FIXME need a warning if the unexpanded SRC_URI value contains variable references
  352. uri_values = []
  353. localpaths = []
  354. def fetch_urls(rdata):
  355. # Collect the local paths from SRC_URI
  356. srcuri = rdata.getVar('SRC_URI') or ""
  357. if srcuri not in uri_values:
  358. fetch = bb.fetch2.Fetch(srcuri.split(), rdata)
  359. if download:
  360. fetch.download()
  361. for pth in fetch.localpaths():
  362. if pth not in localpaths:
  363. localpaths.append(pth)
  364. uri_values.append(srcuri)
  365. fetch_urls(d)
  366. if all_variants:
  367. # Get files for other variants e.g. in the case of a SRC_URI_append
  368. localdata = bb.data.createCopy(d)
  369. variants = (localdata.getVar('BBCLASSEXTEND') or '').split()
  370. if variants:
  371. # Ensure we handle class-target if we're dealing with one of the variants
  372. variants.append('target')
  373. for variant in variants:
  374. localdata.setVar('CLASSOVERRIDE', 'class-%s' % variant)
  375. fetch_urls(localdata)
  376. # Copy local files to target directory and gather any remote files
  377. bb_dir = os.path.abspath(os.path.dirname(d.getVar('FILE'))) + os.sep
  378. remotes = []
  379. copied = []
  380. # Need to do this in two steps since we want to check against the absolute path
  381. includes = [os.path.abspath(path) for path in d.getVar('BBINCLUDED').split() if os.path.exists(path)]
  382. # We also check this below, but we don't want any items in this list being considered remotes
  383. includes = [path for path in includes if path.startswith(bb_dir)]
  384. for path in localpaths + includes:
  385. # Only import files that are under the meta directory
  386. if path.startswith(bb_dir):
  387. if not whole_dir:
  388. relpath = os.path.relpath(path, bb_dir)
  389. subdir = os.path.join(tgt_dir, os.path.dirname(relpath))
  390. if not os.path.exists(subdir):
  391. os.makedirs(subdir)
  392. shutil.copy2(path, os.path.join(tgt_dir, relpath))
  393. copied.append(relpath)
  394. else:
  395. remotes.append(path)
  396. # Simply copy whole meta dir, if requested
  397. if whole_dir:
  398. shutil.copytree(bb_dir, tgt_dir)
  399. return copied, remotes
  400. def get_recipe_local_files(d, patches=False, archives=False):
  401. """Get a list of local files in SRC_URI within a recipe."""
  402. import oe.patch
  403. uris = (d.getVar('SRC_URI') or "").split()
  404. fetch = bb.fetch2.Fetch(uris, d)
  405. # FIXME this list should be factored out somewhere else (such as the
  406. # fetcher) though note that this only encompasses actual container formats
  407. # i.e. that can contain multiple files as opposed to those that only
  408. # contain a compressed stream (i.e. .tar.gz as opposed to just .gz)
  409. archive_exts = ['.tar', '.tgz', '.tar.gz', '.tar.Z', '.tbz', '.tbz2', '.tar.bz2', '.txz', '.tar.xz', '.tar.lz', '.zip', '.jar', '.rpm', '.srpm', '.deb', '.ipk', '.tar.7z', '.7z']
  410. ret = {}
  411. for uri in uris:
  412. if fetch.ud[uri].type == 'file':
  413. if (not patches and
  414. oe.patch.patch_path(uri, fetch, '', expand=False)):
  415. continue
  416. # Skip files that are referenced by absolute path
  417. fname = fetch.ud[uri].basepath
  418. if os.path.isabs(fname):
  419. continue
  420. # Handle subdir=
  421. subdir = fetch.ud[uri].parm.get('subdir', '')
  422. if subdir:
  423. if os.path.isabs(subdir):
  424. continue
  425. fname = os.path.join(subdir, fname)
  426. localpath = fetch.localpath(uri)
  427. if not archives:
  428. # Ignore archives that will be unpacked
  429. if localpath.endswith(tuple(archive_exts)):
  430. unpack = fetch.ud[uri].parm.get('unpack', True)
  431. if unpack:
  432. continue
  433. ret[fname] = localpath
  434. return ret
  435. def get_recipe_patches(d):
  436. """Get a list of the patches included in SRC_URI within a recipe."""
  437. import oe.patch
  438. patches = oe.patch.src_patches(d, expand=False)
  439. patchfiles = []
  440. for patch in patches:
  441. _, _, local, _, _, parm = bb.fetch.decodeurl(patch)
  442. patchfiles.append(local)
  443. return patchfiles
  444. def get_recipe_patched_files(d):
  445. """
  446. Get the list of patches for a recipe along with the files each patch modifies.
  447. Params:
  448. d: the datastore for the recipe
  449. Returns:
  450. a dict mapping patch file path to a list of tuples of changed files and
  451. change mode ('A' for add, 'D' for delete or 'M' for modify)
  452. """
  453. import oe.patch
  454. patches = oe.patch.src_patches(d, expand=False)
  455. patchedfiles = {}
  456. for patch in patches:
  457. _, _, patchfile, _, _, parm = bb.fetch.decodeurl(patch)
  458. striplevel = int(parm['striplevel'])
  459. patchedfiles[patchfile] = oe.patch.PatchSet.getPatchedFiles(patchfile, striplevel, os.path.join(d.getVar('S'), parm.get('patchdir', '')))
  460. return patchedfiles
  461. def validate_pn(pn):
  462. """Perform validation on a recipe name (PN) for a new recipe."""
  463. reserved_names = ['forcevariable', 'append', 'prepend', 'remove']
  464. if not re.match('^[0-9a-z-.+]+$', pn):
  465. return 'Recipe name "%s" is invalid: only characters 0-9, a-z, -, + and . are allowed' % pn
  466. elif pn in reserved_names:
  467. return 'Recipe name "%s" is invalid: is a reserved keyword' % pn
  468. elif pn.startswith('pn-'):
  469. return 'Recipe name "%s" is invalid: names starting with "pn-" are reserved' % pn
  470. elif pn.endswith(('.bb', '.bbappend', '.bbclass', '.inc', '.conf')):
  471. return 'Recipe name "%s" is invalid: should be just a name, not a file name' % pn
  472. return ''
  473. def get_bbfile_path(d, destdir, extrapathhint=None):
  474. """
  475. Determine the correct path for a recipe within a layer
  476. Parameters:
  477. d: Recipe-specific datastore
  478. destdir: destination directory. Can be the path to the base of the layer or a
  479. partial path somewhere within the layer.
  480. extrapathhint: a path relative to the base of the layer to try
  481. """
  482. import bb.cookerdata
  483. destdir = os.path.abspath(destdir)
  484. destlayerdir = find_layerdir(destdir)
  485. # Parse the specified layer's layer.conf file directly, in case the layer isn't in bblayers.conf
  486. confdata = d.createCopy()
  487. confdata.setVar('BBFILES', '')
  488. confdata.setVar('LAYERDIR', destlayerdir)
  489. destlayerconf = os.path.join(destlayerdir, "conf", "layer.conf")
  490. confdata = bb.cookerdata.parse_config_file(destlayerconf, confdata)
  491. pn = d.getVar('PN')
  492. bbfilespecs = (confdata.getVar('BBFILES') or '').split()
  493. if destdir == destlayerdir:
  494. for bbfilespec in bbfilespecs:
  495. if not bbfilespec.endswith('.bbappend'):
  496. for match in glob.glob(bbfilespec):
  497. splitext = os.path.splitext(os.path.basename(match))
  498. if splitext[1] == '.bb':
  499. mpn = splitext[0].split('_')[0]
  500. if mpn == pn:
  501. return os.path.dirname(match)
  502. # Try to make up a path that matches BBFILES
  503. # this is a little crude, but better than nothing
  504. bpn = d.getVar('BPN')
  505. recipefn = os.path.basename(d.getVar('FILE'))
  506. pathoptions = [destdir]
  507. if extrapathhint:
  508. pathoptions.append(os.path.join(destdir, extrapathhint))
  509. if destdir == destlayerdir:
  510. pathoptions.append(os.path.join(destdir, 'recipes-%s' % bpn, bpn))
  511. pathoptions.append(os.path.join(destdir, 'recipes', bpn))
  512. pathoptions.append(os.path.join(destdir, bpn))
  513. elif not destdir.endswith(('/' + pn, '/' + bpn)):
  514. pathoptions.append(os.path.join(destdir, bpn))
  515. closepath = ''
  516. for pathoption in pathoptions:
  517. bbfilepath = os.path.join(pathoption, 'test.bb')
  518. for bbfilespec in bbfilespecs:
  519. if fnmatch.fnmatchcase(bbfilepath, bbfilespec):
  520. return pathoption
  521. return None
  522. def get_bbappend_path(d, destlayerdir, wildcardver=False):
  523. """Determine how a bbappend for a recipe should be named and located within another layer"""
  524. import bb.cookerdata
  525. destlayerdir = os.path.abspath(destlayerdir)
  526. recipefile = d.getVar('FILE')
  527. recipefn = os.path.splitext(os.path.basename(recipefile))[0]
  528. if wildcardver and '_' in recipefn:
  529. recipefn = recipefn.split('_', 1)[0] + '_%'
  530. appendfn = recipefn + '.bbappend'
  531. # Parse the specified layer's layer.conf file directly, in case the layer isn't in bblayers.conf
  532. confdata = d.createCopy()
  533. confdata.setVar('BBFILES', '')
  534. confdata.setVar('LAYERDIR', destlayerdir)
  535. destlayerconf = os.path.join(destlayerdir, "conf", "layer.conf")
  536. confdata = bb.cookerdata.parse_config_file(destlayerconf, confdata)
  537. origlayerdir = find_layerdir(recipefile)
  538. if not origlayerdir:
  539. return (None, False)
  540. # Now join this to the path where the bbappend is going and check if it is covered by BBFILES
  541. appendpath = os.path.join(destlayerdir, os.path.relpath(os.path.dirname(recipefile), origlayerdir), appendfn)
  542. closepath = ''
  543. pathok = True
  544. for bbfilespec in confdata.getVar('BBFILES').split():
  545. if fnmatch.fnmatchcase(appendpath, bbfilespec):
  546. # Our append path works, we're done
  547. break
  548. elif bbfilespec.startswith(destlayerdir) and fnmatch.fnmatchcase('test.bbappend', os.path.basename(bbfilespec)):
  549. # Try to find the longest matching path
  550. if len(bbfilespec) > len(closepath):
  551. closepath = bbfilespec
  552. else:
  553. # Unfortunately the bbappend layer and the original recipe's layer don't have the same structure
  554. if closepath:
  555. # bbappend layer's layer.conf at least has a spec that picks up .bbappend files
  556. # Now we just need to substitute out any wildcards
  557. appendsubdir = os.path.relpath(os.path.dirname(closepath), destlayerdir)
  558. if 'recipes-*' in appendsubdir:
  559. # Try to copy this part from the original recipe path
  560. res = re.search('/recipes-[^/]+/', recipefile)
  561. if res:
  562. appendsubdir = appendsubdir.replace('/recipes-*/', res.group(0))
  563. # This is crude, but we have to do something
  564. appendsubdir = appendsubdir.replace('*', recipefn.split('_')[0])
  565. appendsubdir = appendsubdir.replace('?', 'a')
  566. appendpath = os.path.join(destlayerdir, appendsubdir, appendfn)
  567. else:
  568. pathok = False
  569. return (appendpath, pathok)
  570. def bbappend_recipe(rd, destlayerdir, srcfiles, install=None, wildcardver=False, machine=None, extralines=None, removevalues=None, redirect_output=None):
  571. """
  572. Writes a bbappend file for a recipe
  573. Parameters:
  574. rd: data dictionary for the recipe
  575. destlayerdir: base directory of the layer to place the bbappend in
  576. (subdirectory path from there will be determined automatically)
  577. srcfiles: dict of source files to add to SRC_URI, where the value
  578. is the full path to the file to be added, and the value is the
  579. original filename as it would appear in SRC_URI or None if it
  580. isn't already present. You may pass None for this parameter if
  581. you simply want to specify your own content via the extralines
  582. parameter.
  583. install: dict mapping entries in srcfiles to a tuple of two elements:
  584. install path (*without* ${D} prefix) and permission value (as a
  585. string, e.g. '0644').
  586. wildcardver: True to use a % wildcard in the bbappend filename, or
  587. False to make the bbappend specific to the recipe version.
  588. machine:
  589. If specified, make the changes in the bbappend specific to this
  590. machine. This will also cause PACKAGE_ARCH = "${MACHINE_ARCH}"
  591. to be added to the bbappend.
  592. extralines:
  593. Extra lines to add to the bbappend. This may be a dict of name
  594. value pairs, or simply a list of the lines.
  595. removevalues:
  596. Variable values to remove - a dict of names/values.
  597. redirect_output:
  598. If specified, redirects writing the output file to the
  599. specified directory (for dry-run purposes)
  600. """
  601. if not removevalues:
  602. removevalues = {}
  603. # Determine how the bbappend should be named
  604. appendpath, pathok = get_bbappend_path(rd, destlayerdir, wildcardver)
  605. if not appendpath:
  606. bb.error('Unable to determine layer directory containing %s' % recipefile)
  607. return (None, None)
  608. if not pathok:
  609. bb.warn('Unable to determine correct subdirectory path for bbappend file - check that what %s adds to BBFILES also matches .bbappend files. Using %s for now, but until you fix this the bbappend will not be applied.' % (os.path.join(destlayerdir, 'conf', 'layer.conf'), os.path.dirname(appendpath)))
  610. appenddir = os.path.dirname(appendpath)
  611. if not redirect_output:
  612. bb.utils.mkdirhier(appenddir)
  613. # FIXME check if the bbappend doesn't get overridden by a higher priority layer?
  614. layerdirs = [os.path.abspath(layerdir) for layerdir in rd.getVar('BBLAYERS').split()]
  615. if not os.path.abspath(destlayerdir) in layerdirs:
  616. bb.warn('Specified layer is not currently enabled in bblayers.conf, you will need to add it before this bbappend will be active')
  617. bbappendlines = []
  618. if extralines:
  619. if isinstance(extralines, dict):
  620. for name, value in extralines.items():
  621. bbappendlines.append((name, '=', value))
  622. else:
  623. # Do our best to split it
  624. for line in extralines:
  625. if line[-1] == '\n':
  626. line = line[:-1]
  627. splitline = line.split(None, 2)
  628. if len(splitline) == 3:
  629. bbappendlines.append(tuple(splitline))
  630. else:
  631. raise Exception('Invalid extralines value passed')
  632. def popline(varname):
  633. for i in range(0, len(bbappendlines)):
  634. if bbappendlines[i][0] == varname:
  635. line = bbappendlines.pop(i)
  636. return line
  637. return None
  638. def appendline(varname, op, value):
  639. for i in range(0, len(bbappendlines)):
  640. item = bbappendlines[i]
  641. if item[0] == varname:
  642. bbappendlines[i] = (item[0], item[1], item[2] + ' ' + value)
  643. break
  644. else:
  645. bbappendlines.append((varname, op, value))
  646. destsubdir = rd.getVar('PN')
  647. if srcfiles:
  648. bbappendlines.append(('FILESEXTRAPATHS_prepend', ':=', '${THISDIR}/${PN}:'))
  649. appendoverride = ''
  650. if machine:
  651. bbappendlines.append(('PACKAGE_ARCH', '=', '${MACHINE_ARCH}'))
  652. appendoverride = '_%s' % machine
  653. copyfiles = {}
  654. if srcfiles:
  655. instfunclines = []
  656. for newfile, origsrcfile in srcfiles.items():
  657. srcfile = origsrcfile
  658. srcurientry = None
  659. if not srcfile:
  660. srcfile = os.path.basename(newfile)
  661. srcurientry = 'file://%s' % srcfile
  662. # Double-check it's not there already
  663. # FIXME do we care if the entry is added by another bbappend that might go away?
  664. if not srcurientry in rd.getVar('SRC_URI').split():
  665. if machine:
  666. appendline('SRC_URI_append%s' % appendoverride, '=', ' ' + srcurientry)
  667. else:
  668. appendline('SRC_URI', '+=', srcurientry)
  669. copyfiles[newfile] = srcfile
  670. if install:
  671. institem = install.pop(newfile, None)
  672. if institem:
  673. (destpath, perms) = institem
  674. instdestpath = replace_dir_vars(destpath, rd)
  675. instdirline = 'install -d ${D}%s' % os.path.dirname(instdestpath)
  676. if not instdirline in instfunclines:
  677. instfunclines.append(instdirline)
  678. instfunclines.append('install -m %s ${WORKDIR}/%s ${D}%s' % (perms, os.path.basename(srcfile), instdestpath))
  679. if instfunclines:
  680. bbappendlines.append(('do_install_append%s()' % appendoverride, '', instfunclines))
  681. if redirect_output:
  682. bb.note('Writing append file %s (dry-run)' % appendpath)
  683. outfile = os.path.join(redirect_output, os.path.basename(appendpath))
  684. # Only take a copy if the file isn't already there (this function may be called
  685. # multiple times per operation when we're handling overrides)
  686. if os.path.exists(appendpath) and not os.path.exists(outfile):
  687. shutil.copy2(appendpath, outfile)
  688. else:
  689. bb.note('Writing append file %s' % appendpath)
  690. outfile = appendpath
  691. if os.path.exists(outfile):
  692. # Work around lack of nonlocal in python 2
  693. extvars = {'destsubdir': destsubdir}
  694. def appendfile_varfunc(varname, origvalue, op, newlines):
  695. if varname == 'FILESEXTRAPATHS_prepend':
  696. if origvalue.startswith('${THISDIR}/'):
  697. popline('FILESEXTRAPATHS_prepend')
  698. extvars['destsubdir'] = rd.expand(origvalue.split('${THISDIR}/', 1)[1].rstrip(':'))
  699. elif varname == 'PACKAGE_ARCH':
  700. if machine:
  701. popline('PACKAGE_ARCH')
  702. return (machine, None, 4, False)
  703. elif varname.startswith('do_install_append'):
  704. func = popline(varname)
  705. if func:
  706. instfunclines = [line.strip() for line in origvalue.strip('\n').splitlines()]
  707. for line in func[2]:
  708. if not line in instfunclines:
  709. instfunclines.append(line)
  710. return (instfunclines, None, 4, False)
  711. else:
  712. splitval = split_var_value(origvalue, assignment=False)
  713. changed = False
  714. removevar = varname
  715. if varname in ['SRC_URI', 'SRC_URI_append%s' % appendoverride]:
  716. removevar = 'SRC_URI'
  717. line = popline(varname)
  718. if line:
  719. if line[2] not in splitval:
  720. splitval.append(line[2])
  721. changed = True
  722. else:
  723. line = popline(varname)
  724. if line:
  725. splitval = [line[2]]
  726. changed = True
  727. if removevar in removevalues:
  728. remove = removevalues[removevar]
  729. if isinstance(remove, str):
  730. if remove in splitval:
  731. splitval.remove(remove)
  732. changed = True
  733. else:
  734. for removeitem in remove:
  735. if removeitem in splitval:
  736. splitval.remove(removeitem)
  737. changed = True
  738. if changed:
  739. newvalue = splitval
  740. if len(newvalue) == 1:
  741. # Ensure it's written out as one line
  742. if '_append' in varname:
  743. newvalue = ' ' + newvalue[0]
  744. else:
  745. newvalue = newvalue[0]
  746. if not newvalue and (op in ['+=', '.='] or '_append' in varname):
  747. # There's no point appending nothing
  748. newvalue = None
  749. if varname.endswith('()'):
  750. indent = 4
  751. else:
  752. indent = -1
  753. return (newvalue, None, indent, True)
  754. return (origvalue, None, 4, False)
  755. varnames = [item[0] for item in bbappendlines]
  756. if removevalues:
  757. varnames.extend(list(removevalues.keys()))
  758. with open(outfile, 'r') as f:
  759. (updated, newlines) = bb.utils.edit_metadata(f, varnames, appendfile_varfunc)
  760. destsubdir = extvars['destsubdir']
  761. else:
  762. updated = False
  763. newlines = []
  764. if bbappendlines:
  765. for line in bbappendlines:
  766. if line[0].endswith('()'):
  767. newlines.append('%s {\n %s\n}\n' % (line[0], '\n '.join(line[2])))
  768. else:
  769. newlines.append('%s %s "%s"\n\n' % line)
  770. updated = True
  771. if updated:
  772. with open(outfile, 'w') as f:
  773. f.writelines(newlines)
  774. if copyfiles:
  775. if machine:
  776. destsubdir = os.path.join(destsubdir, machine)
  777. if redirect_output:
  778. outdir = redirect_output
  779. else:
  780. outdir = appenddir
  781. for newfile, srcfile in copyfiles.items():
  782. filedest = os.path.join(outdir, destsubdir, os.path.basename(srcfile))
  783. if os.path.abspath(newfile) != os.path.abspath(filedest):
  784. if newfile.startswith(tempfile.gettempdir()):
  785. newfiledisp = os.path.basename(newfile)
  786. else:
  787. newfiledisp = newfile
  788. if redirect_output:
  789. bb.note('Copying %s to %s (dry-run)' % (newfiledisp, os.path.join(appenddir, destsubdir, os.path.basename(srcfile))))
  790. else:
  791. bb.note('Copying %s to %s' % (newfiledisp, filedest))
  792. bb.utils.mkdirhier(os.path.dirname(filedest))
  793. shutil.copyfile(newfile, filedest)
  794. return (appendpath, os.path.join(appenddir, destsubdir))
  795. def find_layerdir(fn):
  796. """ Figure out the path to the base of the layer containing a file (e.g. a recipe)"""
  797. pth = os.path.abspath(fn)
  798. layerdir = ''
  799. while pth:
  800. if os.path.exists(os.path.join(pth, 'conf', 'layer.conf')):
  801. layerdir = pth
  802. break
  803. pth = os.path.dirname(pth)
  804. if pth == '/':
  805. return None
  806. return layerdir
  807. def replace_dir_vars(path, d):
  808. """Replace common directory paths with appropriate variable references (e.g. /etc becomes ${sysconfdir})"""
  809. dirvars = {}
  810. # Sort by length so we get the variables we're interested in first
  811. for var in sorted(list(d.keys()), key=len):
  812. if var.endswith('dir') and var.lower() == var:
  813. value = d.getVar(var)
  814. if value.startswith('/') and not '\n' in value and value not in dirvars:
  815. dirvars[value] = var
  816. for dirpath in sorted(list(dirvars.keys()), reverse=True):
  817. path = path.replace(dirpath, '${%s}' % dirvars[dirpath])
  818. return path
  819. def get_recipe_pv_without_srcpv(pv, uri_type):
  820. """
  821. Get PV without SRCPV common in SCM's for now only
  822. support git.
  823. Returns tuple with pv, prefix and suffix.
  824. """
  825. pfx = ''
  826. sfx = ''
  827. if uri_type == 'git':
  828. git_regex = re.compile("(?P<pfx>v?)(?P<ver>[^\+]*)((?P<sfx>\+(git)?r?(AUTOINC\+))(?P<rev>.*))?")
  829. m = git_regex.match(pv)
  830. if m:
  831. pv = m.group('ver')
  832. pfx = m.group('pfx')
  833. sfx = m.group('sfx')
  834. else:
  835. regex = re.compile("(?P<pfx>(v|r)?)(?P<ver>.*)")
  836. m = regex.match(pv)
  837. if m:
  838. pv = m.group('ver')
  839. pfx = m.group('pfx')
  840. return (pv, pfx, sfx)
  841. def get_recipe_upstream_version(rd):
  842. """
  843. Get upstream version of recipe using bb.fetch2 methods with support for
  844. http, https, ftp and git.
  845. bb.fetch2 exceptions can be raised,
  846. FetchError when don't have network access or upstream site don't response.
  847. NoMethodError when uri latest_versionstring method isn't implemented.
  848. Returns a dictonary with version, repository revision, current_version, type and datetime.
  849. Type can be A for Automatic, M for Manual and U for Unknown.
  850. """
  851. from bb.fetch2 import decodeurl
  852. from datetime import datetime
  853. ru = {}
  854. ru['current_version'] = rd.getVar('PV')
  855. ru['version'] = ''
  856. ru['type'] = 'U'
  857. ru['datetime'] = ''
  858. ru['revision'] = ''
  859. # XXX: If don't have SRC_URI means that don't have upstream sources so
  860. # returns the current recipe version, so that upstream version check
  861. # declares a match.
  862. src_uris = rd.getVar('SRC_URI')
  863. if not src_uris:
  864. ru['version'] = ru['current_version']
  865. ru['type'] = 'M'
  866. ru['datetime'] = datetime.now()
  867. return ru
  868. # XXX: we suppose that the first entry points to the upstream sources
  869. src_uri = src_uris.split()[0]
  870. uri_type, _, _, _, _, _ = decodeurl(src_uri)
  871. (pv, pfx, sfx) = get_recipe_pv_without_srcpv(rd.getVar('PV'), uri_type)
  872. ru['current_version'] = pv
  873. manual_upstream_version = rd.getVar("RECIPE_UPSTREAM_VERSION")
  874. if manual_upstream_version:
  875. # manual tracking of upstream version.
  876. ru['version'] = manual_upstream_version
  877. ru['type'] = 'M'
  878. manual_upstream_date = rd.getVar("CHECK_DATE")
  879. if manual_upstream_date:
  880. date = datetime.strptime(manual_upstream_date, "%b %d, %Y")
  881. else:
  882. date = datetime.now()
  883. ru['datetime'] = date
  884. elif uri_type == "file":
  885. # files are always up-to-date
  886. ru['version'] = pv
  887. ru['type'] = 'A'
  888. ru['datetime'] = datetime.now()
  889. else:
  890. ud = bb.fetch2.FetchData(src_uri, rd)
  891. if rd.getVar("UPSTREAM_CHECK_COMMITS") == "1":
  892. revision = ud.method.latest_revision(ud, rd, 'default')
  893. upversion = pv
  894. if revision != rd.getVar("SRCREV"):
  895. upversion = upversion + "-new-commits-available"
  896. else:
  897. pupver = ud.method.latest_versionstring(ud, rd)
  898. (upversion, revision) = pupver
  899. if upversion:
  900. ru['version'] = upversion
  901. ru['type'] = 'A'
  902. if revision:
  903. ru['revision'] = revision
  904. ru['datetime'] = datetime.now()
  905. return ru