create.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  1. # Recipe creation tool - create command plugin
  2. #
  3. # Copyright (C) 2014-2017 Intel Corporation
  4. #
  5. # SPDX-License-Identifier: GPL-2.0-only
  6. #
  7. import sys
  8. import os
  9. import argparse
  10. import glob
  11. import fnmatch
  12. import re
  13. import json
  14. import logging
  15. import scriptutils
  16. from urllib.parse import urlparse, urldefrag, urlsplit
  17. import hashlib
  18. import bb.fetch2
  19. logger = logging.getLogger('recipetool')
  20. tinfoil = None
  21. plugins = None
  22. def log_error_cond(message, debugonly):
  23. if debugonly:
  24. logger.debug(message)
  25. else:
  26. logger.error(message)
  27. def log_info_cond(message, debugonly):
  28. if debugonly:
  29. logger.debug(message)
  30. else:
  31. logger.info(message)
  32. def plugin_init(pluginlist):
  33. # Take a reference to the list so we can use it later
  34. global plugins
  35. plugins = pluginlist
  36. def tinfoil_init(instance):
  37. global tinfoil
  38. tinfoil = instance
  39. class RecipeHandler(object):
  40. recipelibmap = {}
  41. recipeheadermap = {}
  42. recipecmakefilemap = {}
  43. recipebinmap = {}
  44. def __init__(self):
  45. self._devtool = False
  46. @staticmethod
  47. def load_libmap(d):
  48. '''Load library->recipe mapping'''
  49. import oe.package
  50. if RecipeHandler.recipelibmap:
  51. return
  52. # First build up library->package mapping
  53. d2 = bb.data.createCopy(d)
  54. d2.setVar("WORKDIR_PKGDATA", "${PKGDATA_DIR}")
  55. shlib_providers = oe.package.read_shlib_providers(d2)
  56. libdir = d.getVar('libdir')
  57. base_libdir = d.getVar('base_libdir')
  58. libpaths = list(set([base_libdir, libdir]))
  59. libname_re = re.compile(r'^lib(.+)\.so.*$')
  60. pkglibmap = {}
  61. for lib, item in shlib_providers.items():
  62. for path, pkg in item.items():
  63. if path in libpaths:
  64. res = libname_re.match(lib)
  65. if res:
  66. libname = res.group(1)
  67. if not libname in pkglibmap:
  68. pkglibmap[libname] = pkg[0]
  69. else:
  70. logger.debug('unable to extract library name from %s' % lib)
  71. # Now turn it into a library->recipe mapping
  72. pkgdata_dir = d.getVar('PKGDATA_DIR')
  73. for libname, pkg in pkglibmap.items():
  74. try:
  75. with open(os.path.join(pkgdata_dir, 'runtime', pkg)) as f:
  76. for line in f:
  77. if line.startswith('PN:'):
  78. RecipeHandler.recipelibmap[libname] = line.split(':', 1)[-1].strip()
  79. break
  80. except IOError as ioe:
  81. if ioe.errno == 2:
  82. logger.warning('unable to find a pkgdata file for package %s' % pkg)
  83. else:
  84. raise
  85. # Some overrides - these should be mapped to the virtual
  86. RecipeHandler.recipelibmap['GL'] = 'virtual/libgl'
  87. RecipeHandler.recipelibmap['EGL'] = 'virtual/egl'
  88. RecipeHandler.recipelibmap['GLESv2'] = 'virtual/libgles2'
  89. @staticmethod
  90. def load_devel_filemap(d):
  91. '''Build up development file->recipe mapping'''
  92. if RecipeHandler.recipeheadermap:
  93. return
  94. pkgdata_dir = d.getVar('PKGDATA_DIR')
  95. includedir = d.getVar('includedir')
  96. cmakedir = os.path.join(d.getVar('libdir'), 'cmake')
  97. for pkg in glob.glob(os.path.join(pkgdata_dir, 'runtime', '*-dev')):
  98. with open(os.path.join(pkgdata_dir, 'runtime', pkg)) as f:
  99. pn = None
  100. headers = []
  101. cmakefiles = []
  102. for line in f:
  103. if line.startswith('PN:'):
  104. pn = line.split(':', 1)[-1].strip()
  105. elif line.startswith('FILES_INFO:%s:' % pkg):
  106. val = line.split(': ', 1)[1].strip()
  107. dictval = json.loads(val)
  108. for fullpth in sorted(dictval):
  109. if fullpth.startswith(includedir) and fullpth.endswith('.h'):
  110. headers.append(os.path.relpath(fullpth, includedir))
  111. elif fullpth.startswith(cmakedir) and fullpth.endswith('.cmake'):
  112. cmakefiles.append(os.path.relpath(fullpth, cmakedir))
  113. if pn and headers:
  114. for header in headers:
  115. RecipeHandler.recipeheadermap[header] = pn
  116. if pn and cmakefiles:
  117. for fn in cmakefiles:
  118. RecipeHandler.recipecmakefilemap[fn] = pn
  119. @staticmethod
  120. def load_binmap(d):
  121. '''Build up native binary->recipe mapping'''
  122. if RecipeHandler.recipebinmap:
  123. return
  124. sstate_manifests = d.getVar('SSTATE_MANIFESTS')
  125. staging_bindir_native = d.getVar('STAGING_BINDIR_NATIVE')
  126. build_arch = d.getVar('BUILD_ARCH')
  127. fileprefix = 'manifest-%s-' % build_arch
  128. for fn in glob.glob(os.path.join(sstate_manifests, '%s*-native.populate_sysroot' % fileprefix)):
  129. with open(fn, 'r') as f:
  130. pn = os.path.basename(fn).rsplit('.', 1)[0][len(fileprefix):]
  131. for line in f:
  132. if line.startswith(staging_bindir_native):
  133. prog = os.path.basename(line.rstrip())
  134. RecipeHandler.recipebinmap[prog] = pn
  135. @staticmethod
  136. def checkfiles(path, speclist, recursive=False, excludedirs=None):
  137. results = []
  138. if recursive:
  139. for root, dirs, files in os.walk(path, topdown=True):
  140. if excludedirs:
  141. dirs[:] = [d for d in dirs if d not in excludedirs]
  142. for fn in files:
  143. for spec in speclist:
  144. if fnmatch.fnmatch(fn, spec):
  145. results.append(os.path.join(root, fn))
  146. else:
  147. for spec in speclist:
  148. results.extend(glob.glob(os.path.join(path, spec)))
  149. return results
  150. @staticmethod
  151. def handle_depends(libdeps, pcdeps, deps, outlines, values, d):
  152. if pcdeps:
  153. recipemap = read_pkgconfig_provides(d)
  154. if libdeps:
  155. RecipeHandler.load_libmap(d)
  156. ignorelibs = ['socket']
  157. ignoredeps = ['gcc-runtime', 'glibc', 'uclibc', 'musl', 'tar-native', 'binutils-native', 'coreutils-native']
  158. unmappedpc = []
  159. pcdeps = list(set(pcdeps))
  160. for pcdep in pcdeps:
  161. if isinstance(pcdep, str):
  162. recipe = recipemap.get(pcdep, None)
  163. if recipe:
  164. deps.append(recipe)
  165. else:
  166. if not pcdep.startswith('$'):
  167. unmappedpc.append(pcdep)
  168. else:
  169. for item in pcdep:
  170. recipe = recipemap.get(pcdep, None)
  171. if recipe:
  172. deps.append(recipe)
  173. break
  174. else:
  175. unmappedpc.append('(%s)' % ' or '.join(pcdep))
  176. unmappedlibs = []
  177. for libdep in libdeps:
  178. if isinstance(libdep, tuple):
  179. lib, header = libdep
  180. else:
  181. lib = libdep
  182. header = None
  183. if lib in ignorelibs:
  184. logger.debug('Ignoring library dependency %s' % lib)
  185. continue
  186. recipe = RecipeHandler.recipelibmap.get(lib, None)
  187. if recipe:
  188. deps.append(recipe)
  189. elif recipe is None:
  190. if header:
  191. RecipeHandler.load_devel_filemap(d)
  192. recipe = RecipeHandler.recipeheadermap.get(header, None)
  193. if recipe:
  194. deps.append(recipe)
  195. elif recipe is None:
  196. unmappedlibs.append(lib)
  197. else:
  198. unmappedlibs.append(lib)
  199. deps = set(deps).difference(set(ignoredeps))
  200. if unmappedpc:
  201. outlines.append('# NOTE: unable to map the following pkg-config dependencies: %s' % ' '.join(unmappedpc))
  202. outlines.append('# (this is based on recipes that have previously been built and packaged)')
  203. if unmappedlibs:
  204. outlines.append('# NOTE: the following library dependencies are unknown, ignoring: %s' % ' '.join(list(set(unmappedlibs))))
  205. outlines.append('# (this is based on recipes that have previously been built and packaged)')
  206. if deps:
  207. values['DEPENDS'] = ' '.join(deps)
  208. @staticmethod
  209. def genfunction(outlines, funcname, content, python=False, forcespace=False):
  210. if python:
  211. prefix = 'python '
  212. else:
  213. prefix = ''
  214. outlines.append('%s%s () {' % (prefix, funcname))
  215. if python or forcespace:
  216. indent = ' '
  217. else:
  218. indent = '\t'
  219. addnoop = not python
  220. for line in content:
  221. outlines.append('%s%s' % (indent, line))
  222. if addnoop:
  223. strippedline = line.lstrip()
  224. if strippedline and not strippedline.startswith('#'):
  225. addnoop = False
  226. if addnoop:
  227. # Without this there'll be a syntax error
  228. outlines.append('%s:' % indent)
  229. outlines.append('}')
  230. outlines.append('')
  231. def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
  232. return False
  233. def validate_pv(pv):
  234. if not pv or '_version' in pv.lower() or pv[0] not in '0123456789':
  235. return False
  236. return True
  237. def determine_from_filename(srcfile):
  238. """Determine name and version from a filename"""
  239. if is_package(srcfile):
  240. # Force getting the value from the package metadata
  241. return None, None
  242. if '.tar.' in srcfile:
  243. namepart = srcfile.split('.tar.')[0]
  244. else:
  245. namepart = os.path.splitext(srcfile)[0]
  246. namepart = namepart.lower().replace('_', '-')
  247. if namepart.endswith('.src'):
  248. namepart = namepart[:-4]
  249. if namepart.endswith('.orig'):
  250. namepart = namepart[:-5]
  251. splitval = namepart.split('-')
  252. logger.debug('determine_from_filename: split name %s into: %s' % (srcfile, splitval))
  253. ver_re = re.compile('^v?[0-9]')
  254. pv = None
  255. pn = None
  256. if len(splitval) == 1:
  257. # Try to split the version out if there is no separator (or a .)
  258. res = re.match('^([^0-9]+)([0-9.]+.*)$', namepart)
  259. if res:
  260. if len(res.group(1)) > 1 and len(res.group(2)) > 1:
  261. pn = res.group(1).rstrip('.')
  262. pv = res.group(2)
  263. else:
  264. pn = namepart
  265. else:
  266. if splitval[-1] in ['source', 'src']:
  267. splitval.pop()
  268. if len(splitval) > 2 and re.match('^(alpha|beta|stable|release|rc[0-9]|pre[0-9]|p[0-9]|[0-9]{8})', splitval[-1]) and ver_re.match(splitval[-2]):
  269. pv = '-'.join(splitval[-2:])
  270. if pv.endswith('-release'):
  271. pv = pv[:-8]
  272. splitval = splitval[:-2]
  273. elif ver_re.match(splitval[-1]):
  274. pv = splitval.pop()
  275. pn = '-'.join(splitval)
  276. if pv and pv.startswith('v'):
  277. pv = pv[1:]
  278. logger.debug('determine_from_filename: name = "%s" version = "%s"' % (pn, pv))
  279. return (pn, pv)
  280. def determine_from_url(srcuri):
  281. """Determine name and version from a URL"""
  282. pn = None
  283. pv = None
  284. parseres = urlparse(srcuri.lower().split(';', 1)[0])
  285. if parseres.path:
  286. if 'github.com' in parseres.netloc:
  287. res = re.search(r'.*/(.*?)/archive/(.*)-final\.(tar|zip)', parseres.path)
  288. if res:
  289. pn = res.group(1).strip().replace('_', '-')
  290. pv = res.group(2).strip().replace('_', '.')
  291. else:
  292. res = re.search(r'.*/(.*?)/archive/v?(.*)\.(tar|zip)', parseres.path)
  293. if res:
  294. pn = res.group(1).strip().replace('_', '-')
  295. pv = res.group(2).strip().replace('_', '.')
  296. elif 'bitbucket.org' in parseres.netloc:
  297. res = re.search(r'.*/(.*?)/get/[a-zA-Z_-]*([0-9][0-9a-zA-Z_.]*)\.(tar|zip)', parseres.path)
  298. if res:
  299. pn = res.group(1).strip().replace('_', '-')
  300. pv = res.group(2).strip().replace('_', '.')
  301. if not pn and not pv:
  302. if parseres.scheme not in ['git', 'gitsm', 'svn', 'hg']:
  303. srcfile = os.path.basename(parseres.path.rstrip('/'))
  304. pn, pv = determine_from_filename(srcfile)
  305. elif parseres.scheme in ['git', 'gitsm']:
  306. pn = os.path.basename(parseres.path.rstrip('/')).lower().replace('_', '-')
  307. if pn.endswith('.git'):
  308. pn = pn[:-4]
  309. logger.debug('Determined from source URL: name = "%s", version = "%s"' % (pn, pv))
  310. return (pn, pv)
  311. def supports_srcrev(uri):
  312. localdata = bb.data.createCopy(tinfoil.config_data)
  313. # This is a bit sad, but if you don't have this set there can be some
  314. # odd interactions with the urldata cache which lead to errors
  315. localdata.setVar('SRCREV', '${AUTOREV}')
  316. try:
  317. fetcher = bb.fetch2.Fetch([uri], localdata)
  318. urldata = fetcher.ud
  319. for u in urldata:
  320. if urldata[u].method.supports_srcrev():
  321. return True
  322. except bb.fetch2.FetchError as e:
  323. logger.debug('FetchError in supports_srcrev: %s' % str(e))
  324. # Fall back to basic check
  325. if uri.startswith(('git://', 'gitsm://')):
  326. return True
  327. return False
  328. def reformat_git_uri(uri):
  329. '''Convert any http[s]://....git URI into git://...;protocol=http[s]'''
  330. checkuri = uri.split(';', 1)[0]
  331. if checkuri.endswith('.git') or '/git/' in checkuri or re.match('https?://git(hub|lab).com/[^/]+/[^/]+/?$', checkuri):
  332. # Appends scheme if the scheme is missing
  333. if not '://' in uri:
  334. uri = 'git://' + uri
  335. scheme, host, path, user, pswd, parms = bb.fetch2.decodeurl(uri)
  336. # Detection mechanism, this is required due to certain URL are formatter with ":" rather than "/"
  337. # which causes decodeurl to fail getting the right host and path
  338. if len(host.split(':')) > 1:
  339. splitslash = host.split(':')
  340. # Port number should not be split from host
  341. if not re.match('^[0-9]+$', splitslash[1]):
  342. host = splitslash[0]
  343. path = '/' + splitslash[1] + path
  344. #Algorithm:
  345. # if user is defined, append protocol=ssh or if a protocol is defined, then honor the user-defined protocol
  346. # if no user & password is defined, check for scheme type and append the protocol with the scheme type
  347. # finally if protocols or if the url is well-formed, do nothing and rejoin everything back to normal
  348. # Need to repackage the arguments for encodeurl, the format is: (scheme, host, path, user, password, OrderedDict([('key', 'value')]))
  349. if user:
  350. if not 'protocol' in parms:
  351. parms.update({('protocol', 'ssh')})
  352. elif (scheme == "http" or scheme == 'https' or scheme == 'ssh') and not ('protocol' in parms):
  353. parms.update({('protocol', scheme)})
  354. # Always append 'git://'
  355. fUrl = bb.fetch2.encodeurl(('git', host, path, user, pswd, parms))
  356. return fUrl
  357. else:
  358. return uri
  359. def is_package(url):
  360. '''Check if a URL points to a package'''
  361. checkurl = url.split(';', 1)[0]
  362. if checkurl.endswith(('.deb', '.ipk', '.rpm', '.srpm')):
  363. return True
  364. return False
  365. def create_recipe(args):
  366. import bb.process
  367. import tempfile
  368. import shutil
  369. import oe.recipeutils
  370. pkgarch = ""
  371. if args.machine:
  372. pkgarch = "${MACHINE_ARCH}"
  373. extravalues = {}
  374. checksums = {}
  375. tempsrc = ''
  376. source = args.source
  377. srcsubdir = ''
  378. srcrev = '${AUTOREV}'
  379. srcbranch = ''
  380. scheme = ''
  381. storeTagName = ''
  382. pv_srcpv = False
  383. handled = []
  384. classes = []
  385. # Find all plugins that want to register handlers
  386. logger.debug('Loading recipe handlers')
  387. raw_handlers = []
  388. for plugin in plugins:
  389. if hasattr(plugin, 'register_recipe_handlers'):
  390. plugin.register_recipe_handlers(raw_handlers)
  391. # Sort handlers by priority
  392. handlers = []
  393. for i, handler in enumerate(raw_handlers):
  394. if isinstance(handler, tuple):
  395. handlers.append((handler[0], handler[1], i))
  396. else:
  397. handlers.append((handler, 0, i))
  398. handlers.sort(key=lambda item: (item[1], -item[2]), reverse=True)
  399. for handler, priority, _ in handlers:
  400. logger.debug('Handler: %s (priority %d)' % (handler.__class__.__name__, priority))
  401. setattr(handler, '_devtool', args.devtool)
  402. handlers = [item[0] for item in handlers]
  403. fetchuri = None
  404. for handler in handlers:
  405. if hasattr(handler, 'process_url'):
  406. ret = handler.process_url(args, classes, handled, extravalues)
  407. if 'url' in handled and ret:
  408. fetchuri = ret
  409. break
  410. if os.path.isfile(source):
  411. source = 'file://%s' % os.path.abspath(source)
  412. if scriptutils.is_src_url(source):
  413. # Warn about github archive URLs
  414. if re.match(r'https?://github.com/[^/]+/[^/]+/archive/.+(\.tar\..*|\.zip)$', source):
  415. logger.warning('github archive files are not guaranteed to be stable and may be re-generated over time. If the latter occurs, the checksums will likely change and the recipe will fail at do_fetch. It is recommended that you point to an actual commit or tag in the repository instead (using the repository URL in conjunction with the -S/--srcrev option).')
  416. # Fetch a URL
  417. if not fetchuri:
  418. fetchuri = reformat_git_uri(urldefrag(source)[0])
  419. if args.binary:
  420. # Assume the archive contains the directory structure verbatim
  421. # so we need to extract to a subdirectory
  422. fetchuri += ';subdir=${BPN}'
  423. srcuri = fetchuri
  424. rev_re = re.compile(';rev=([^;]+)')
  425. res = rev_re.search(srcuri)
  426. if res:
  427. if args.srcrev:
  428. logger.error('rev= parameter and -S/--srcrev option cannot both be specified - use one or the other')
  429. sys.exit(1)
  430. if args.autorev:
  431. logger.error('rev= parameter and -a/--autorev option cannot both be specified - use one or the other')
  432. sys.exit(1)
  433. srcrev = res.group(1)
  434. srcuri = rev_re.sub('', srcuri)
  435. elif args.srcrev:
  436. srcrev = args.srcrev
  437. # Check whether users provides any branch info in fetchuri.
  438. # If true, we will skip all branch checking process to honor all user's input.
  439. scheme, network, path, user, passwd, params = bb.fetch2.decodeurl(fetchuri)
  440. srcbranch = params.get('branch')
  441. if args.srcbranch:
  442. if srcbranch:
  443. logger.error('branch= parameter and -B/--srcbranch option cannot both be specified - use one or the other')
  444. sys.exit(1)
  445. srcbranch = args.srcbranch
  446. params['branch'] = srcbranch
  447. nobranch = params.get('nobranch')
  448. if nobranch and srcbranch:
  449. logger.error('nobranch= cannot be used if you specify a branch')
  450. sys.exit(1)
  451. tag = params.get('tag')
  452. if not srcbranch and not nobranch and srcrev != '${AUTOREV}':
  453. # Append nobranch=1 in the following conditions:
  454. # 1. User did not set 'branch=' in srcuri, and
  455. # 2. User did not set 'nobranch=1' in srcuri, and
  456. # 3. Source revision is not '${AUTOREV}'
  457. params['nobranch'] = '1'
  458. if tag:
  459. # Keep a copy of tag and append nobranch=1 then remove tag from URL.
  460. # Bitbake fetcher unable to fetch when {AUTOREV} and tag is set at the same time.
  461. storeTagName = params['tag']
  462. params['nobranch'] = '1'
  463. del params['tag']
  464. # Assume 'master' branch if not set
  465. if scheme in ['git', 'gitsm'] and 'branch' not in params and 'nobranch' not in params:
  466. params['branch'] = 'master'
  467. fetchuri = bb.fetch2.encodeurl((scheme, network, path, user, passwd, params))
  468. tmpparent = tinfoil.config_data.getVar('BASE_WORKDIR')
  469. bb.utils.mkdirhier(tmpparent)
  470. tempsrc = tempfile.mkdtemp(prefix='recipetool-', dir=tmpparent)
  471. srctree = os.path.join(tempsrc, 'source')
  472. try:
  473. checksums, ftmpdir = scriptutils.fetch_url(tinfoil, fetchuri, srcrev, srctree, logger, preserve_tmp=args.keep_temp)
  474. except scriptutils.FetchUrlFailure as e:
  475. logger.error(str(e))
  476. sys.exit(1)
  477. if ftmpdir and args.keep_temp:
  478. logger.info('Fetch temp directory is %s' % ftmpdir)
  479. dirlist = scriptutils.filter_src_subdirs(srctree)
  480. logger.debug('Directory listing (excluding filtered out):\n %s' % '\n '.join(dirlist))
  481. if len(dirlist) == 1:
  482. singleitem = os.path.join(srctree, dirlist[0])
  483. if os.path.isdir(singleitem):
  484. # We unpacked a single directory, so we should use that
  485. srcsubdir = dirlist[0]
  486. srctree = os.path.join(srctree, srcsubdir)
  487. else:
  488. check_single_file(dirlist[0], fetchuri)
  489. elif len(dirlist) == 0:
  490. if '/' in fetchuri:
  491. fn = os.path.join(tinfoil.config_data.getVar('DL_DIR'), fetchuri.split('/')[-1])
  492. if os.path.isfile(fn):
  493. check_single_file(fn, fetchuri)
  494. # If we've got to here then there's no source so we might as well give up
  495. logger.error('URL %s resulted in an empty source tree' % fetchuri)
  496. sys.exit(1)
  497. # We need this checking mechanism to improve the recipe created by recipetool and devtool
  498. # is able to parse and build by bitbake.
  499. # If there is no input for branch name, then check for branch name with SRCREV provided.
  500. if not srcbranch and not nobranch and srcrev and (srcrev != '${AUTOREV}') and scheme in ['git', 'gitsm']:
  501. try:
  502. cmd = 'git branch -r --contains'
  503. check_branch, check_branch_err = bb.process.run('%s %s' % (cmd, srcrev), cwd=srctree)
  504. except bb.process.ExecutionError as err:
  505. logger.error(str(err))
  506. sys.exit(1)
  507. get_branch = [x.strip() for x in check_branch.splitlines()]
  508. # Remove HEAD reference point and drop remote prefix
  509. get_branch = [x.split('/', 1)[1] for x in get_branch if not x.startswith('origin/HEAD')]
  510. if 'master' in get_branch:
  511. # Even with the case where get_branch has multiple objects, if 'master' is one
  512. # of them, we should default take from 'master'
  513. srcbranch = 'master'
  514. elif len(get_branch) == 1:
  515. # If 'master' isn't in get_branch and get_branch contains only ONE object, then store result into 'srcbranch'
  516. srcbranch = get_branch[0]
  517. else:
  518. # If get_branch contains more than one objects, then display error and exit.
  519. mbrch = '\n ' + '\n '.join(get_branch)
  520. logger.error('Revision %s was found on multiple branches: %s\nPlease provide the correct branch with -B/--srcbranch' % (srcrev, mbrch))
  521. sys.exit(1)
  522. # Since we might have a value in srcbranch, we need to
  523. # recontruct the srcuri to include 'branch' in params.
  524. scheme, network, path, user, passwd, params = bb.fetch2.decodeurl(srcuri)
  525. if scheme in ['git', 'gitsm']:
  526. params['branch'] = srcbranch or 'master'
  527. if storeTagName and scheme in ['git', 'gitsm']:
  528. # Check srcrev using tag and check validity of the tag
  529. cmd = ('git rev-parse --verify %s' % (storeTagName))
  530. try:
  531. check_tag, check_tag_err = bb.process.run('%s' % cmd, cwd=srctree)
  532. srcrev = check_tag.split()[0]
  533. except bb.process.ExecutionError as err:
  534. logger.error(str(err))
  535. logger.error("Possibly wrong tag name is provided")
  536. sys.exit(1)
  537. # Drop tag from srcuri as it will have conflicts with SRCREV during recipe parse.
  538. del params['tag']
  539. srcuri = bb.fetch2.encodeurl((scheme, network, path, user, passwd, params))
  540. if os.path.exists(os.path.join(srctree, '.gitmodules')) and srcuri.startswith('git://'):
  541. srcuri = 'gitsm://' + srcuri[6:]
  542. logger.info('Fetching submodules...')
  543. bb.process.run('git submodule update --init --recursive', cwd=srctree)
  544. if is_package(fetchuri):
  545. localdata = bb.data.createCopy(tinfoil.config_data)
  546. pkgfile = bb.fetch2.localpath(fetchuri, localdata)
  547. if pkgfile:
  548. tmpfdir = tempfile.mkdtemp(prefix='recipetool-')
  549. try:
  550. if pkgfile.endswith(('.deb', '.ipk')):
  551. stdout, _ = bb.process.run('ar x %s' % pkgfile, cwd=tmpfdir)
  552. stdout, _ = bb.process.run('tar xf control.tar.gz', cwd=tmpfdir)
  553. values = convert_debian(tmpfdir)
  554. extravalues.update(values)
  555. elif pkgfile.endswith(('.rpm', '.srpm')):
  556. stdout, _ = bb.process.run('rpm -qp --xml %s > pkginfo.xml' % pkgfile, cwd=tmpfdir)
  557. values = convert_rpm_xml(os.path.join(tmpfdir, 'pkginfo.xml'))
  558. extravalues.update(values)
  559. finally:
  560. shutil.rmtree(tmpfdir)
  561. else:
  562. # Assume we're pointing to an existing source tree
  563. if args.extract_to:
  564. logger.error('--extract-to cannot be specified if source is a directory')
  565. sys.exit(1)
  566. if not os.path.isdir(source):
  567. logger.error('Invalid source directory %s' % source)
  568. sys.exit(1)
  569. srctree = source
  570. srcuri = ''
  571. if os.path.exists(os.path.join(srctree, '.git')):
  572. # Try to get upstream repo location from origin remote
  573. try:
  574. stdout, _ = bb.process.run('git remote -v', cwd=srctree, shell=True)
  575. except bb.process.ExecutionError as e:
  576. stdout = None
  577. if stdout:
  578. for line in stdout.splitlines():
  579. splitline = line.split()
  580. if len(splitline) > 1:
  581. if splitline[0] == 'origin' and scriptutils.is_src_url(splitline[1]):
  582. srcuri = reformat_git_uri(splitline[1]) + ';branch=master'
  583. srcsubdir = 'git'
  584. break
  585. if args.src_subdir:
  586. srcsubdir = os.path.join(srcsubdir, args.src_subdir)
  587. srctree_use = os.path.abspath(os.path.join(srctree, args.src_subdir))
  588. else:
  589. srctree_use = os.path.abspath(srctree)
  590. if args.outfile and os.path.isdir(args.outfile):
  591. outfile = None
  592. outdir = args.outfile
  593. else:
  594. outfile = args.outfile
  595. outdir = None
  596. if outfile and outfile != '-':
  597. if os.path.exists(outfile):
  598. logger.error('Output file %s already exists' % outfile)
  599. sys.exit(1)
  600. lines_before = []
  601. lines_after = []
  602. lines_before.append('# Recipe created by %s' % os.path.basename(sys.argv[0]))
  603. lines_before.append('# This is the basis of a recipe and may need further editing in order to be fully functional.')
  604. lines_before.append('# (Feel free to remove these comments when editing.)')
  605. # We need a blank line here so that patch_recipe_lines can rewind before the LICENSE comments
  606. lines_before.append('')
  607. # We'll come back and replace this later in handle_license_vars()
  608. lines_before.append('##LICENSE_PLACEHOLDER##')
  609. # FIXME This is kind of a hack, we probably ought to be using bitbake to do this
  610. pn = None
  611. pv = None
  612. if outfile:
  613. recipefn = os.path.splitext(os.path.basename(outfile))[0]
  614. fnsplit = recipefn.split('_')
  615. if len(fnsplit) > 1:
  616. pn = fnsplit[0]
  617. pv = fnsplit[1]
  618. else:
  619. pn = recipefn
  620. if args.version:
  621. pv = args.version
  622. if args.name:
  623. pn = args.name
  624. if args.name.endswith('-native'):
  625. if args.also_native:
  626. logger.error('--also-native cannot be specified for a recipe named *-native (*-native denotes a recipe that is already only for native) - either remove the -native suffix from the name or drop --also-native')
  627. sys.exit(1)
  628. classes.append('native')
  629. elif args.name.startswith('nativesdk-'):
  630. if args.also_native:
  631. logger.error('--also-native cannot be specified for a recipe named nativesdk-* (nativesdk-* denotes a recipe that is already only for nativesdk)')
  632. sys.exit(1)
  633. classes.append('nativesdk')
  634. if pv and pv not in 'git svn hg'.split():
  635. realpv = pv
  636. else:
  637. realpv = None
  638. if not srcuri:
  639. lines_before.append('# No information for SRC_URI yet (only an external source tree was specified)')
  640. lines_before.append('SRC_URI = "%s"' % srcuri)
  641. shown_checksums = ["%ssum" % s for s in bb.fetch2.SHOWN_CHECKSUM_LIST]
  642. for key, value in sorted(checksums.items()):
  643. if key in shown_checksums:
  644. lines_before.append('SRC_URI[%s] = "%s"' % (key, value))
  645. if srcuri and supports_srcrev(srcuri):
  646. lines_before.append('')
  647. lines_before.append('# Modify these as desired')
  648. # Note: we have code to replace realpv further down if it gets set to some other value
  649. scheme, _, _, _, _, _ = bb.fetch2.decodeurl(srcuri)
  650. if scheme in ['git', 'gitsm']:
  651. srcpvprefix = 'git'
  652. elif scheme == 'svn':
  653. srcpvprefix = 'svnr'
  654. else:
  655. srcpvprefix = scheme
  656. lines_before.append('PV = "%s+%s"' % (realpv or '1.0', srcpvprefix))
  657. pv_srcpv = True
  658. if not args.autorev and srcrev == '${AUTOREV}':
  659. if os.path.exists(os.path.join(srctree, '.git')):
  660. (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=srctree)
  661. srcrev = stdout.rstrip()
  662. lines_before.append('SRCREV = "%s"' % srcrev)
  663. if args.provides:
  664. lines_before.append('PROVIDES = "%s"' % args.provides)
  665. lines_before.append('')
  666. if srcsubdir and not args.binary:
  667. # (for binary packages we explicitly specify subdir= when fetching to
  668. # match the default value of S, so we don't need to set it in that case)
  669. lines_before.append('S = "${WORKDIR}/%s"' % srcsubdir)
  670. lines_before.append('')
  671. if pkgarch:
  672. lines_after.append('PACKAGE_ARCH = "%s"' % pkgarch)
  673. lines_after.append('')
  674. if args.binary:
  675. lines_after.append('INSANE_SKIP:${PN} += "already-stripped"')
  676. lines_after.append('')
  677. if args.npm_dev:
  678. extravalues['NPM_INSTALL_DEV'] = 1
  679. # Apply the handlers
  680. if args.binary:
  681. classes.append('bin_package')
  682. handled.append('buildsystem')
  683. for handler in handlers:
  684. handler.process(srctree_use, classes, lines_before, lines_after, handled, extravalues)
  685. # native and nativesdk classes are special and must be inherited last
  686. # If present, put them at the end of the classes list
  687. classes.sort(key=lambda c: c in ("native", "nativesdk"))
  688. extrafiles = extravalues.pop('extrafiles', {})
  689. extra_pn = extravalues.pop('PN', None)
  690. extra_pv = extravalues.pop('PV', None)
  691. if extra_pv and not realpv:
  692. realpv = extra_pv
  693. if not validate_pv(realpv):
  694. realpv = None
  695. else:
  696. realpv = realpv.lower().split()[0]
  697. if '_' in realpv:
  698. realpv = realpv.replace('_', '-')
  699. if extra_pn and not pn:
  700. pn = extra_pn
  701. if pn.startswith('GNU '):
  702. pn = pn[4:]
  703. if ' ' in pn:
  704. # Probably a descriptive identifier rather than a proper name
  705. pn = None
  706. else:
  707. pn = pn.lower()
  708. if '_' in pn:
  709. pn = pn.replace('_', '-')
  710. if srcuri and not realpv or not pn:
  711. name_pn, name_pv = determine_from_url(srcuri)
  712. if name_pn and not pn:
  713. pn = name_pn
  714. if name_pv and not realpv:
  715. realpv = name_pv
  716. licvalues = handle_license_vars(srctree_use, lines_before, handled, extravalues, tinfoil.config_data)
  717. if not outfile:
  718. if not pn:
  719. log_error_cond('Unable to determine short program name from source tree - please specify name with -N/--name or output file name with -o/--outfile', args.devtool)
  720. # devtool looks for this specific exit code, so don't change it
  721. sys.exit(15)
  722. else:
  723. if srcuri and srcuri.startswith(('gitsm://', 'git://', 'hg://', 'svn://')):
  724. suffix = srcuri.split(':', 1)[0]
  725. if suffix == 'gitsm':
  726. suffix = 'git'
  727. outfile = '%s_%s.bb' % (pn, suffix)
  728. elif realpv:
  729. outfile = '%s_%s.bb' % (pn, realpv)
  730. else:
  731. outfile = '%s.bb' % pn
  732. if outdir:
  733. outfile = os.path.join(outdir, outfile)
  734. # We need to check this again
  735. if os.path.exists(outfile):
  736. logger.error('Output file %s already exists' % outfile)
  737. sys.exit(1)
  738. # Move any extra files the plugins created to a directory next to the recipe
  739. if extrafiles:
  740. if outfile == '-':
  741. extraoutdir = pn
  742. else:
  743. extraoutdir = os.path.join(os.path.dirname(outfile), pn)
  744. bb.utils.mkdirhier(extraoutdir)
  745. for destfn, extrafile in extrafiles.items():
  746. shutil.move(extrafile, os.path.join(extraoutdir, destfn))
  747. lines = lines_before
  748. lines_before = []
  749. skipblank = True
  750. for line in lines:
  751. if skipblank:
  752. skipblank = False
  753. if not line:
  754. continue
  755. if line.startswith('S = '):
  756. if realpv and pv not in 'git svn hg'.split():
  757. line = line.replace(realpv, '${PV}')
  758. if pn:
  759. line = line.replace(pn, '${BPN}')
  760. if line == 'S = "${WORKDIR}/${BPN}-${PV}"':
  761. skipblank = True
  762. continue
  763. elif line.startswith('SRC_URI = '):
  764. if realpv and not pv_srcpv:
  765. line = line.replace(realpv, '${PV}')
  766. elif line.startswith('PV = '):
  767. if realpv:
  768. # Replace the first part of the PV value
  769. line = re.sub(r'"[^+]*\+', '"%s+' % realpv, line)
  770. lines_before.append(line)
  771. if args.also_native:
  772. lines = lines_after
  773. lines_after = []
  774. bbclassextend = None
  775. for line in lines:
  776. if line.startswith('BBCLASSEXTEND ='):
  777. splitval = line.split('"')
  778. if len(splitval) > 1:
  779. bbclassextend = splitval[1].split()
  780. if not 'native' in bbclassextend:
  781. bbclassextend.insert(0, 'native')
  782. line = 'BBCLASSEXTEND = "%s"' % ' '.join(bbclassextend)
  783. lines_after.append(line)
  784. if not bbclassextend:
  785. lines_after.append('BBCLASSEXTEND = "native"')
  786. postinst = ("postinst", extravalues.pop('postinst', None))
  787. postrm = ("postrm", extravalues.pop('postrm', None))
  788. preinst = ("preinst", extravalues.pop('preinst', None))
  789. prerm = ("prerm", extravalues.pop('prerm', None))
  790. funcs = [postinst, postrm, preinst, prerm]
  791. for func in funcs:
  792. if func[1]:
  793. RecipeHandler.genfunction(lines_after, 'pkg_%s_${PN}' % func[0], func[1])
  794. outlines = []
  795. outlines.extend(lines_before)
  796. if classes:
  797. if outlines[-1] and not outlines[-1].startswith('#'):
  798. outlines.append('')
  799. outlines.append('inherit %s' % ' '.join(classes))
  800. outlines.append('')
  801. outlines.extend(lines_after)
  802. outlines = [ line.rstrip('\n') +"\n" for line in outlines]
  803. if extravalues:
  804. _, outlines = oe.recipeutils.patch_recipe_lines(outlines, extravalues, trailing_newline=True)
  805. if args.extract_to:
  806. scriptutils.git_convert_standalone_clone(srctree)
  807. if os.path.isdir(args.extract_to):
  808. # If the directory exists we'll move the temp dir into it instead of
  809. # its contents - of course, we could try to always move its contents
  810. # but that is a pain if there are symlinks; the simplest solution is
  811. # to just remove it first
  812. os.rmdir(args.extract_to)
  813. shutil.move(srctree, args.extract_to)
  814. if tempsrc == srctree:
  815. tempsrc = None
  816. log_info_cond('Source extracted to %s' % args.extract_to, args.devtool)
  817. if outfile == '-':
  818. sys.stdout.write(''.join(outlines) + '\n')
  819. else:
  820. with open(outfile, 'w') as f:
  821. lastline = None
  822. for line in outlines:
  823. if not lastline and not line:
  824. # Skip extra blank lines
  825. continue
  826. f.write('%s' % line)
  827. lastline = line
  828. log_info_cond('Recipe %s has been created; further editing may be required to make it fully functional' % outfile, args.devtool)
  829. tinfoil.modified_files()
  830. if tempsrc:
  831. if args.keep_temp:
  832. logger.info('Preserving temporary directory %s' % tempsrc)
  833. else:
  834. shutil.rmtree(tempsrc)
  835. return 0
  836. def check_single_file(fn, fetchuri):
  837. """Determine if a single downloaded file is something we can't handle"""
  838. with open(fn, 'r', errors='surrogateescape') as f:
  839. if '<html' in f.read(100).lower():
  840. logger.error('Fetching "%s" returned a single HTML page - check the URL is correct and functional' % fetchuri)
  841. sys.exit(1)
  842. def split_value(value):
  843. if isinstance(value, str):
  844. return value.split()
  845. else:
  846. return value
  847. def fixup_license(value):
  848. # Ensure licenses with OR starts and ends with brackets
  849. if '|' in value:
  850. return '(' + value + ')'
  851. return value
  852. def tidy_licenses(value):
  853. """Flat, split and sort licenses"""
  854. from oe.license import flattened_licenses
  855. def _choose(a, b):
  856. str_a, str_b = sorted((" & ".join(a), " & ".join(b)), key=str.casefold)
  857. return ["(%s | %s)" % (str_a, str_b)]
  858. if not isinstance(value, str):
  859. value = " & ".join(value)
  860. return sorted(list(set(flattened_licenses(value, _choose))), key=str.casefold)
  861. def handle_license_vars(srctree, lines_before, handled, extravalues, d):
  862. lichandled = [x for x in handled if x[0] == 'license']
  863. if lichandled:
  864. # Someone else has already handled the license vars, just return their value
  865. return lichandled[0][1]
  866. licvalues = guess_license(srctree, d)
  867. licenses = []
  868. lic_files_chksum = []
  869. lic_unknown = []
  870. lines = []
  871. if licvalues:
  872. for licvalue in licvalues:
  873. license = licvalue[0]
  874. lics = tidy_licenses(fixup_license(license))
  875. lics = [lic for lic in lics if lic not in licenses]
  876. if len(lics):
  877. licenses.extend(lics)
  878. lic_files_chksum.append('file://%s;md5=%s' % (licvalue[1], licvalue[2]))
  879. if license == 'Unknown':
  880. lic_unknown.append(licvalue[1])
  881. if lic_unknown:
  882. lines.append('#')
  883. lines.append('# The following license files were not able to be identified and are')
  884. lines.append('# represented as "Unknown" below, you will need to check them yourself:')
  885. for licfile in lic_unknown:
  886. lines.append('# %s' % licfile)
  887. extra_license = tidy_licenses(extravalues.pop('LICENSE', ''))
  888. if extra_license:
  889. if licenses == ['Unknown']:
  890. licenses = extra_license
  891. else:
  892. for item in extra_license:
  893. if item not in licenses:
  894. licenses.append(item)
  895. extra_lic_files_chksum = split_value(extravalues.pop('LIC_FILES_CHKSUM', []))
  896. for item in extra_lic_files_chksum:
  897. if item not in lic_files_chksum:
  898. lic_files_chksum.append(item)
  899. if lic_files_chksum:
  900. # We are going to set the vars, so prepend the standard disclaimer
  901. lines.insert(0, '# WARNING: the following LICENSE and LIC_FILES_CHKSUM values are best guesses - it is')
  902. lines.insert(1, '# your responsibility to verify that the values are complete and correct.')
  903. else:
  904. # Without LIC_FILES_CHKSUM we set LICENSE = "CLOSED" to allow the
  905. # user to get started easily
  906. lines.append('# Unable to find any files that looked like license statements. Check the accompanying')
  907. lines.append('# documentation and source headers and set LICENSE and LIC_FILES_CHKSUM accordingly.')
  908. lines.append('#')
  909. lines.append('# NOTE: LICENSE is being set to "CLOSED" to allow you to at least start building - if')
  910. lines.append('# this is not accurate with respect to the licensing of the software being built (it')
  911. lines.append('# will not be in most cases) you must specify the correct value before using this')
  912. lines.append('# recipe for anything other than initial testing/development!')
  913. licenses = ['CLOSED']
  914. if extra_license and sorted(licenses) != sorted(extra_license):
  915. lines.append('# NOTE: Original package / source metadata indicates license is: %s' % ' & '.join(extra_license))
  916. if len(licenses) > 1:
  917. lines.append('#')
  918. lines.append('# NOTE: multiple licenses have been detected; they have been separated with &')
  919. lines.append('# in the LICENSE value for now since it is a reasonable assumption that all')
  920. lines.append('# of the licenses apply. If instead there is a choice between the multiple')
  921. lines.append('# licenses then you should change the value to separate the licenses with |')
  922. lines.append('# instead of &. If there is any doubt, check the accompanying documentation')
  923. lines.append('# to determine which situation is applicable.')
  924. lines.append('LICENSE = "%s"' % ' & '.join(sorted(licenses, key=str.casefold)))
  925. lines.append('LIC_FILES_CHKSUM = "%s"' % ' \\\n '.join(lic_files_chksum))
  926. lines.append('')
  927. # Replace the placeholder so we get the values in the right place in the recipe file
  928. try:
  929. pos = lines_before.index('##LICENSE_PLACEHOLDER##')
  930. except ValueError:
  931. pos = -1
  932. if pos == -1:
  933. lines_before.extend(lines)
  934. else:
  935. lines_before[pos:pos+1] = lines
  936. handled.append(('license', licvalues))
  937. return licvalues
  938. def get_license_md5sums(d, static_only=False, linenumbers=False):
  939. import bb.utils
  940. import csv
  941. md5sums = {}
  942. if not static_only and not linenumbers:
  943. # Gather md5sums of license files in common license dir
  944. commonlicdir = d.getVar('COMMON_LICENSE_DIR')
  945. for fn in os.listdir(commonlicdir):
  946. md5value = bb.utils.md5_file(os.path.join(commonlicdir, fn))
  947. md5sums[md5value] = fn
  948. # The following were extracted from common values in various recipes
  949. # (double checking the license against the license file itself, not just
  950. # the LICENSE value in the recipe)
  951. # Read license md5sums from csv file
  952. scripts_path = os.path.dirname(os.path.realpath(__file__))
  953. for path in (d.getVar('BBPATH').split(':')
  954. + [os.path.join(scripts_path, '..', '..')]):
  955. csv_path = os.path.join(path, 'lib', 'recipetool', 'licenses.csv')
  956. if os.path.isfile(csv_path):
  957. with open(csv_path, newline='') as csv_file:
  958. fieldnames = ['md5sum', 'license', 'beginline', 'endline', 'md5']
  959. reader = csv.DictReader(csv_file, delimiter=',', fieldnames=fieldnames)
  960. for row in reader:
  961. if linenumbers:
  962. md5sums[row['md5sum']] = (
  963. row['license'], row['beginline'], row['endline'], row['md5'])
  964. else:
  965. md5sums[row['md5sum']] = row['license']
  966. return md5sums
  967. def crunch_known_licenses(d):
  968. '''
  969. Calculate the MD5 checksums for the crunched versions of all common
  970. licenses. Also add additional known checksums.
  971. '''
  972. crunched_md5sums = {}
  973. # common licenses
  974. crunched_md5sums['ad4e9d34a2e966dfe9837f18de03266d'] = 'GFDL-1.1-only'
  975. crunched_md5sums['d014fb11a34eb67dc717fdcfc97e60ed'] = 'GFDL-1.2-only'
  976. crunched_md5sums['e020ca655b06c112def28e597ab844f1'] = 'GFDL-1.3-only'
  977. # The following two were gleaned from the "forever" npm package
  978. crunched_md5sums['0a97f8e4cbaf889d6fa51f84b89a79f6'] = 'ISC'
  979. # https://github.com/waffle-gl/waffle/blob/master/LICENSE.txt
  980. crunched_md5sums['50fab24ce589d69af8964fdbfe414c60'] = 'BSD-2-Clause'
  981. # https://github.com/spigwitmer/fakeds1963s/blob/master/LICENSE
  982. crunched_md5sums['88a4355858a1433fea99fae34a44da88'] = 'GPL-2.0-only'
  983. # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
  984. crunched_md5sums['063b5c3ebb5f3aa4c85a2ed18a31fbe7'] = 'GPL-2.0-only'
  985. # https://github.com/FFmpeg/FFmpeg/blob/master/COPYING.LGPLv2.1
  986. crunched_md5sums['7f5202f4d44ed15dcd4915f5210417d8'] = 'LGPL-2.1-only'
  987. # unixODBC-2.3.4 COPYING
  988. crunched_md5sums['3debde09238a8c8e1f6a847e1ec9055b'] = 'LGPL-2.1-only'
  989. # https://github.com/FFmpeg/FFmpeg/blob/master/COPYING.LGPLv3
  990. crunched_md5sums['f90c613c51aa35da4d79dd55fc724ceb'] = 'LGPL-3.0-only'
  991. # https://raw.githubusercontent.com/eclipse/mosquitto/v1.4.14/epl-v10
  992. crunched_md5sums['efe2cb9a35826992b9df68224e3c2628'] = 'EPL-1.0'
  993. # https://raw.githubusercontent.com/jquery/esprima/3.1.3/LICENSE.BSD
  994. crunched_md5sums['80fa7b56a28e8c902e6af194003220a5'] = 'BSD-2-Clause'
  995. # https://raw.githubusercontent.com/npm/npm-install-checks/master/LICENSE
  996. crunched_md5sums['e659f77bfd9002659e112d0d3d59b2c1'] = 'BSD-2-Clause'
  997. # https://raw.githubusercontent.com/silverwind/default-gateway/4.2.0/LICENSE
  998. crunched_md5sums['4c641f2d995c47f5cb08bdb4b5b6ea05'] = 'BSD-2-Clause'
  999. # https://raw.githubusercontent.com/tad-lispy/node-damerau-levenshtein/v1.0.5/LICENSE
  1000. crunched_md5sums['2b8c039b2b9a25f0feb4410c4542d346'] = 'BSD-2-Clause'
  1001. # https://raw.githubusercontent.com/terser/terser/v3.17.0/LICENSE
  1002. crunched_md5sums['8bd23871802951c9ad63855151204c2c'] = 'BSD-2-Clause'
  1003. # https://raw.githubusercontent.com/alexei/sprintf.js/1.0.3/LICENSE
  1004. crunched_md5sums['008c22318c8ea65928bf730ddd0273e3'] = 'BSD-3-Clause'
  1005. # https://raw.githubusercontent.com/Caligatio/jsSHA/v3.2.0/LICENSE
  1006. crunched_md5sums['0e46634a01bfef056892949acaea85b1'] = 'BSD-3-Clause'
  1007. # https://raw.githubusercontent.com/d3/d3-path/v1.0.9/LICENSE
  1008. crunched_md5sums['b5f72aef53d3b2b432702c30b0215666'] = 'BSD-3-Clause'
  1009. # https://raw.githubusercontent.com/feross/ieee754/v1.1.13/LICENSE
  1010. crunched_md5sums['a39327c997c20da0937955192d86232d'] = 'BSD-3-Clause'
  1011. # https://raw.githubusercontent.com/joyent/node-extsprintf/v1.3.0/LICENSE
  1012. crunched_md5sums['721f23a96ff4161ca3a5f071bbe18108'] = 'MIT'
  1013. # https://raw.githubusercontent.com/pvorb/clone/v0.2.0/LICENSE
  1014. crunched_md5sums['b376d29a53c9573006b9970709231431'] = 'MIT'
  1015. # https://raw.githubusercontent.com/andris9/encoding/v0.1.12/LICENSE
  1016. crunched_md5sums['85d8a977ee9d7c5ab4ac03c9b95431c4'] = 'MIT-0'
  1017. # https://raw.githubusercontent.com/faye/websocket-driver-node/0.7.3/LICENSE.md
  1018. crunched_md5sums['b66384e7137e41a9b1904ef4d39703b6'] = 'Apache-2.0'
  1019. # https://raw.githubusercontent.com/less/less.js/v4.1.1/LICENSE
  1020. crunched_md5sums['b27575459e02221ccef97ec0bfd457ae'] = 'Apache-2.0'
  1021. # https://raw.githubusercontent.com/microsoft/TypeScript/v3.5.3/LICENSE.txt
  1022. crunched_md5sums['a54a1a6a39e7f9dbb4a23a42f5c7fd1c'] = 'Apache-2.0'
  1023. # https://raw.githubusercontent.com/request/request/v2.87.0/LICENSE
  1024. crunched_md5sums['1034431802e57486b393d00c5d262b8a'] = 'Apache-2.0'
  1025. # https://raw.githubusercontent.com/dchest/tweetnacl-js/v0.14.5/LICENSE
  1026. crunched_md5sums['75605e6bdd564791ab698fca65c94a4f'] = 'Unlicense'
  1027. # https://raw.githubusercontent.com/stackgl/gl-mat3/v2.0.0/LICENSE.md
  1028. crunched_md5sums['75512892d6f59dddb6d1c7e191957e9c'] = 'Zlib'
  1029. commonlicdir = d.getVar('COMMON_LICENSE_DIR')
  1030. for fn in sorted(os.listdir(commonlicdir)):
  1031. md5value, lictext = crunch_license(os.path.join(commonlicdir, fn))
  1032. if md5value not in crunched_md5sums:
  1033. crunched_md5sums[md5value] = fn
  1034. elif fn != crunched_md5sums[md5value]:
  1035. bb.debug(2, "crunched_md5sums['%s'] is already set to '%s' rather than '%s'" % (md5value, crunched_md5sums[md5value], fn))
  1036. else:
  1037. bb.debug(2, "crunched_md5sums['%s'] is already set to '%s'" % (md5value, crunched_md5sums[md5value]))
  1038. return crunched_md5sums
  1039. def crunch_license(licfile):
  1040. '''
  1041. Remove non-material text from a license file and then calculate its
  1042. md5sum. This works well for licenses that contain a copyright statement,
  1043. but is also a useful way to handle people's insistence upon reformatting
  1044. the license text slightly (with no material difference to the text of the
  1045. license).
  1046. '''
  1047. import oe.utils
  1048. # Note: these are carefully constructed!
  1049. license_title_re = re.compile(r'^#*\(? *(This is )?([Tt]he )?.{0,15} ?[Ll]icen[sc]e( \(.{1,10}\))?\)?[:\.]? ?#*$')
  1050. license_statement_re = re.compile(r'^((This (project|software)|.{1,10}) is( free software)? (released|licen[sc]ed)|(Released|Licen[cs]ed)) under the .{1,10} [Ll]icen[sc]e:?$')
  1051. copyright_re = re.compile(r'^ *[#\*]* *(Modified work |MIT LICENSED )?Copyright ?(\([cC]\))? .*$')
  1052. disclaimer_re = re.compile(r'^ *\*? ?All [Rr]ights [Rr]eserved\.$')
  1053. email_re = re.compile(r'^.*<[\w\.-]*@[\w\.\-]*>$')
  1054. header_re = re.compile(r'^(\/\**!?)? ?[\-=\*]* ?(\*\/)?$')
  1055. tag_re = re.compile(r'^ *@?\(?([Ll]icense|MIT)\)?$')
  1056. url_re = re.compile(r'^ *[#\*]* *https?:\/\/[\w\.\/\-]+$')
  1057. lictext = []
  1058. with open(licfile, 'r', errors='surrogateescape') as f:
  1059. for line in f:
  1060. # Drop opening statements
  1061. if copyright_re.match(line):
  1062. continue
  1063. elif disclaimer_re.match(line):
  1064. continue
  1065. elif email_re.match(line):
  1066. continue
  1067. elif header_re.match(line):
  1068. continue
  1069. elif tag_re.match(line):
  1070. continue
  1071. elif url_re.match(line):
  1072. continue
  1073. elif license_title_re.match(line):
  1074. continue
  1075. elif license_statement_re.match(line):
  1076. continue
  1077. # Strip comment symbols
  1078. line = line.replace('*', '') \
  1079. .replace('#', '')
  1080. # Unify spelling
  1081. line = line.replace('sub-license', 'sublicense')
  1082. # Squash spaces
  1083. line = oe.utils.squashspaces(line.strip())
  1084. # Replace smart quotes, double quotes and backticks with single quotes
  1085. line = line.replace(u"\u2018", "'").replace(u"\u2019", "'").replace(u"\u201c","'").replace(u"\u201d", "'").replace('"', '\'').replace('`', '\'')
  1086. # Unify brackets
  1087. line = line.replace("{", "[").replace("}", "]")
  1088. if line:
  1089. lictext.append(line)
  1090. m = hashlib.md5()
  1091. try:
  1092. m.update(' '.join(lictext).encode('utf-8'))
  1093. md5val = m.hexdigest()
  1094. except UnicodeEncodeError:
  1095. md5val = None
  1096. lictext = ''
  1097. return md5val, lictext
  1098. def guess_license(srctree, d):
  1099. import bb
  1100. md5sums = get_license_md5sums(d)
  1101. crunched_md5sums = crunch_known_licenses(d)
  1102. licenses = []
  1103. licspecs = ['*LICEN[CS]E*', 'COPYING*', '*[Ll]icense*', 'LEGAL*', '[Ll]egal*', '*GPL*', 'README.lic*', 'COPYRIGHT*', '[Cc]opyright*', 'e[dp]l-v10']
  1104. skip_extensions = (".html", ".js", ".json", ".svg", ".ts", ".go")
  1105. licfiles = []
  1106. for root, dirs, files in os.walk(srctree):
  1107. for fn in files:
  1108. if fn.endswith(skip_extensions):
  1109. continue
  1110. for spec in licspecs:
  1111. if fnmatch.fnmatch(fn, spec):
  1112. fullpath = os.path.join(root, fn)
  1113. if not fullpath in licfiles:
  1114. licfiles.append(fullpath)
  1115. for licfile in sorted(licfiles):
  1116. md5value = bb.utils.md5_file(licfile)
  1117. license = md5sums.get(md5value, None)
  1118. if not license:
  1119. crunched_md5, lictext = crunch_license(licfile)
  1120. license = crunched_md5sums.get(crunched_md5, None)
  1121. if lictext and not license:
  1122. license = 'Unknown'
  1123. logger.info("Please add the following line for '%s' to a 'lib/recipetool/licenses.csv' " \
  1124. "and replace `Unknown` with the license:\n" \
  1125. "%s,Unknown" % (os.path.relpath(licfile, srctree), md5value))
  1126. if license:
  1127. licenses.append((license, os.path.relpath(licfile, srctree), md5value))
  1128. # FIXME should we grab at least one source file with a license header and add that too?
  1129. return licenses
  1130. def split_pkg_licenses(licvalues, packages, outlines, fallback_licenses=None, pn='${PN}'):
  1131. """
  1132. Given a list of (license, path, md5sum) as returned by guess_license(),
  1133. a dict of package name to path mappings, write out a set of
  1134. package-specific LICENSE values.
  1135. """
  1136. pkglicenses = {pn: []}
  1137. for license, licpath, _ in licvalues:
  1138. license = fixup_license(license)
  1139. for pkgname, pkgpath in packages.items():
  1140. if licpath.startswith(pkgpath + '/'):
  1141. if pkgname in pkglicenses:
  1142. pkglicenses[pkgname].append(license)
  1143. else:
  1144. pkglicenses[pkgname] = [license]
  1145. break
  1146. else:
  1147. # Accumulate on the main package
  1148. pkglicenses[pn].append(license)
  1149. outlicenses = {}
  1150. for pkgname in packages:
  1151. # Assume AND operator between license files
  1152. license = ' & '.join(list(set(pkglicenses.get(pkgname, ['Unknown'])))) or 'Unknown'
  1153. if license == 'Unknown' and fallback_licenses and pkgname in fallback_licenses:
  1154. license = fallback_licenses[pkgname]
  1155. licenses = tidy_licenses(license)
  1156. license = ' & '.join(licenses)
  1157. outlines.append('LICENSE:%s = "%s"' % (pkgname, license))
  1158. outlicenses[pkgname] = licenses
  1159. return outlicenses
  1160. def read_pkgconfig_provides(d):
  1161. pkgdatadir = d.getVar('PKGDATA_DIR')
  1162. pkgmap = {}
  1163. for fn in glob.glob(os.path.join(pkgdatadir, 'shlibs2', '*.pclist')):
  1164. with open(fn, 'r') as f:
  1165. for line in f:
  1166. pkgmap[os.path.basename(line.rstrip())] = os.path.splitext(os.path.basename(fn))[0]
  1167. recipemap = {}
  1168. for pc, pkg in pkgmap.items():
  1169. pkgdatafile = os.path.join(pkgdatadir, 'runtime', pkg)
  1170. if os.path.exists(pkgdatafile):
  1171. with open(pkgdatafile, 'r') as f:
  1172. for line in f:
  1173. if line.startswith('PN: '):
  1174. recipemap[pc] = line.split(':', 1)[1].strip()
  1175. return recipemap
  1176. def convert_debian(debpath):
  1177. value_map = {'Package': 'PN',
  1178. 'Version': 'PV',
  1179. 'Section': 'SECTION',
  1180. 'License': 'LICENSE',
  1181. 'Homepage': 'HOMEPAGE'}
  1182. # FIXME extend this mapping - perhaps use distro_alias.inc?
  1183. depmap = {'libz-dev': 'zlib'}
  1184. values = {}
  1185. depends = []
  1186. with open(os.path.join(debpath, 'control'), 'r', errors='surrogateescape') as f:
  1187. indesc = False
  1188. for line in f:
  1189. if indesc:
  1190. if line.startswith(' '):
  1191. if line.startswith(' This package contains'):
  1192. indesc = False
  1193. else:
  1194. if 'DESCRIPTION' in values:
  1195. values['DESCRIPTION'] += ' ' + line.strip()
  1196. else:
  1197. values['DESCRIPTION'] = line.strip()
  1198. else:
  1199. indesc = False
  1200. if not indesc:
  1201. splitline = line.split(':', 1)
  1202. if len(splitline) < 2:
  1203. continue
  1204. key = splitline[0]
  1205. value = splitline[1].strip()
  1206. if key == 'Build-Depends':
  1207. for dep in value.split(','):
  1208. dep = dep.split()[0]
  1209. mapped = depmap.get(dep, '')
  1210. if mapped:
  1211. depends.append(mapped)
  1212. elif key == 'Description':
  1213. values['SUMMARY'] = value
  1214. indesc = True
  1215. else:
  1216. varname = value_map.get(key, None)
  1217. if varname:
  1218. values[varname] = value
  1219. postinst = os.path.join(debpath, 'postinst')
  1220. postrm = os.path.join(debpath, 'postrm')
  1221. preinst = os.path.join(debpath, 'preinst')
  1222. prerm = os.path.join(debpath, 'prerm')
  1223. sfiles = [postinst, postrm, preinst, prerm]
  1224. for sfile in sfiles:
  1225. if os.path.isfile(sfile):
  1226. logger.info("Converting %s file to recipe function..." %
  1227. os.path.basename(sfile).upper())
  1228. content = []
  1229. with open(sfile) as f:
  1230. for line in f:
  1231. if "#!/" in line:
  1232. continue
  1233. line = line.rstrip("\n")
  1234. if line.strip():
  1235. content.append(line)
  1236. if content:
  1237. values[os.path.basename(f.name)] = content
  1238. #if depends:
  1239. # values['DEPENDS'] = ' '.join(depends)
  1240. return values
  1241. def convert_rpm_xml(xmlfile):
  1242. '''Converts the output from rpm -qp --xml to a set of variable values'''
  1243. import xml.etree.ElementTree as ElementTree
  1244. rpmtag_map = {'Name': 'PN',
  1245. 'Version': 'PV',
  1246. 'Summary': 'SUMMARY',
  1247. 'Description': 'DESCRIPTION',
  1248. 'License': 'LICENSE',
  1249. 'Url': 'HOMEPAGE'}
  1250. values = {}
  1251. tree = ElementTree.parse(xmlfile)
  1252. root = tree.getroot()
  1253. for child in root:
  1254. if child.tag == 'rpmTag':
  1255. name = child.attrib.get('name', None)
  1256. if name:
  1257. varname = rpmtag_map.get(name, None)
  1258. if varname:
  1259. values[varname] = child[0].text
  1260. return values
  1261. def register_commands(subparsers):
  1262. parser_create = subparsers.add_parser('create',
  1263. help='Create a new recipe',
  1264. description='Creates a new recipe from a source tree')
  1265. parser_create.add_argument('source', help='Path or URL to source')
  1266. parser_create.add_argument('-o', '--outfile', help='Specify filename for recipe to create')
  1267. parser_create.add_argument('-p', '--provides', help='Specify an alias for the item provided by the recipe')
  1268. parser_create.add_argument('-m', '--machine', help='Make recipe machine-specific as opposed to architecture-specific', action='store_true')
  1269. parser_create.add_argument('-x', '--extract-to', metavar='EXTRACTPATH', help='Assuming source is a URL, fetch it and extract it to the directory specified as %(metavar)s')
  1270. parser_create.add_argument('-N', '--name', help='Name to use within recipe (PN)')
  1271. parser_create.add_argument('-V', '--version', help='Version to use within recipe (PV)')
  1272. parser_create.add_argument('-b', '--binary', help='Treat the source tree as something that should be installed verbatim (no compilation, same directory structure)', action='store_true')
  1273. parser_create.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')
  1274. parser_create.add_argument('--src-subdir', help='Specify subdirectory within source tree to use', metavar='SUBDIR')
  1275. group = parser_create.add_mutually_exclusive_group()
  1276. group.add_argument('-a', '--autorev', help='When fetching from a git repository, set SRCREV in the recipe to a floating revision instead of fixed', action="store_true")
  1277. group.add_argument('-S', '--srcrev', help='Source revision to fetch if fetching from an SCM such as git (default latest)')
  1278. parser_create.add_argument('-B', '--srcbranch', help='Branch in source repository if fetching from an SCM such as git (default master)')
  1279. parser_create.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
  1280. parser_create.add_argument('--npm-dev', action="store_true", help='For npm, also fetch devDependencies')
  1281. parser_create.add_argument('--no-pypi', action="store_true", help='Do not inherit pypi class')
  1282. parser_create.add_argument('--devtool', action="store_true", help=argparse.SUPPRESS)
  1283. parser_create.add_argument('--mirrors', action="store_true", help='Enable PREMIRRORS and MIRRORS for source tree fetching (disabled by default).')
  1284. parser_create.set_defaults(func=create_recipe)