create.py 56 KB

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