create.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  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:'):
  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?://github.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. if os.path.isfile(source):
  384. source = 'file://%s' % os.path.abspath(source)
  385. if scriptutils.is_src_url(source):
  386. # Warn about github archive URLs
  387. if re.match(r'https?://github.com/[^/]+/[^/]+/archive/.+(\.tar\..*|\.zip)$', source):
  388. 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).')
  389. # Fetch a URL
  390. fetchuri = reformat_git_uri(urldefrag(source)[0])
  391. if args.binary:
  392. # Assume the archive contains the directory structure verbatim
  393. # so we need to extract to a subdirectory
  394. fetchuri += ';subdir=${BP}'
  395. srcuri = fetchuri
  396. rev_re = re.compile(';rev=([^;]+)')
  397. res = rev_re.search(srcuri)
  398. if res:
  399. if args.srcrev:
  400. logger.error('rev= parameter and -S/--srcrev option cannot both be specified - use one or the other')
  401. sys.exit(1)
  402. if args.autorev:
  403. logger.error('rev= parameter and -a/--autorev option cannot both be specified - use one or the other')
  404. sys.exit(1)
  405. srcrev = res.group(1)
  406. srcuri = rev_re.sub('', srcuri)
  407. elif args.srcrev:
  408. srcrev = args.srcrev
  409. # Check whether users provides any branch info in fetchuri.
  410. # If true, we will skip all branch checking process to honor all user's input.
  411. scheme, network, path, user, passwd, params = bb.fetch2.decodeurl(fetchuri)
  412. srcbranch = params.get('branch')
  413. if args.srcbranch:
  414. if srcbranch:
  415. logger.error('branch= parameter and -B/--srcbranch option cannot both be specified - use one or the other')
  416. sys.exit(1)
  417. srcbranch = args.srcbranch
  418. params['branch'] = 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. storeTagName = params['tag']
  434. params['nobranch'] = '1'
  435. del params['tag']
  436. fetchuri = bb.fetch2.encodeurl((scheme, network, path, user, passwd, params))
  437. tmpparent = tinfoil.config_data.getVar('BASE_WORKDIR')
  438. bb.utils.mkdirhier(tmpparent)
  439. tempsrc = tempfile.mkdtemp(prefix='recipetool-', dir=tmpparent)
  440. srctree = os.path.join(tempsrc, 'source')
  441. try:
  442. checksums, ftmpdir = scriptutils.fetch_url(tinfoil, fetchuri, srcrev, srctree, logger, preserve_tmp=args.keep_temp)
  443. except scriptutils.FetchUrlFailure as e:
  444. logger.error(str(e))
  445. sys.exit(1)
  446. if ftmpdir and args.keep_temp:
  447. logger.info('Fetch temp directory is %s' % ftmpdir)
  448. dirlist = scriptutils.filter_src_subdirs(srctree)
  449. logger.debug('Directory listing (excluding filtered out):\n %s' % '\n '.join(dirlist))
  450. if len(dirlist) == 1:
  451. singleitem = os.path.join(srctree, dirlist[0])
  452. if os.path.isdir(singleitem):
  453. # We unpacked a single directory, so we should use that
  454. srcsubdir = dirlist[0]
  455. srctree = os.path.join(srctree, srcsubdir)
  456. else:
  457. check_single_file(dirlist[0], fetchuri)
  458. elif len(dirlist) == 0:
  459. if '/' in fetchuri:
  460. fn = os.path.join(tinfoil.config_data.getVar('DL_DIR'), fetchuri.split('/')[-1])
  461. if os.path.isfile(fn):
  462. check_single_file(fn, fetchuri)
  463. # If we've got to here then there's no source so we might as well give up
  464. logger.error('URL %s resulted in an empty source tree' % fetchuri)
  465. sys.exit(1)
  466. # We need this checking mechanism to improve the recipe created by recipetool and devtool
  467. # is able to parse and build by bitbake.
  468. # If there is no input for branch name, then check for branch name with SRCREV provided.
  469. if not srcbranch and not nobranch and srcrev and (srcrev != '${AUTOREV}') and scheme in ['git', 'gitsm']:
  470. try:
  471. cmd = 'git branch -r --contains'
  472. check_branch, check_branch_err = bb.process.run('%s %s' % (cmd, srcrev), cwd=srctree)
  473. except bb.process.ExecutionError as err:
  474. logger.error(str(err))
  475. sys.exit(1)
  476. get_branch = [x.strip() for x in check_branch.splitlines()]
  477. # Remove HEAD reference point and drop remote prefix
  478. get_branch = [x.split('/', 1)[1] for x in get_branch if not x.startswith('origin/HEAD')]
  479. if 'master' in get_branch:
  480. # If it is master, we do not need to append 'branch=master' as this is default.
  481. # Even with the case where get_branch has multiple objects, if 'master' is one
  482. # of them, we should default take from 'master'
  483. srcbranch = ''
  484. elif len(get_branch) == 1:
  485. # If 'master' isn't in get_branch and get_branch contains only ONE object, then store result into 'srcbranch'
  486. srcbranch = get_branch[0]
  487. else:
  488. # If get_branch contains more than one objects, then display error and exit.
  489. mbrch = '\n ' + '\n '.join(get_branch)
  490. logger.error('Revision %s was found on multiple branches: %s\nPlease provide the correct branch with -B/--srcbranch' % (srcrev, mbrch))
  491. sys.exit(1)
  492. # Since we might have a value in srcbranch, we need to
  493. # recontruct the srcuri to include 'branch' in params.
  494. scheme, network, path, user, passwd, params = bb.fetch2.decodeurl(srcuri)
  495. if srcbranch:
  496. params['branch'] = srcbranch
  497. if storeTagName and scheme in ['git', 'gitsm']:
  498. # Check srcrev using tag and check validity of the tag
  499. cmd = ('git rev-parse --verify %s' % (storeTagName))
  500. try:
  501. check_tag, check_tag_err = bb.process.run('%s' % cmd, cwd=srctree)
  502. srcrev = check_tag.split()[0]
  503. except bb.process.ExecutionError as err:
  504. logger.error(str(err))
  505. logger.error("Possibly wrong tag name is provided")
  506. sys.exit(1)
  507. # Drop tag from srcuri as it will have conflicts with SRCREV during recipe parse.
  508. del params['tag']
  509. srcuri = bb.fetch2.encodeurl((scheme, network, path, user, passwd, params))
  510. if os.path.exists(os.path.join(srctree, '.gitmodules')) and srcuri.startswith('git://'):
  511. srcuri = 'gitsm://' + srcuri[6:]
  512. logger.info('Fetching submodules...')
  513. bb.process.run('git submodule update --init --recursive', cwd=srctree)
  514. if is_package(fetchuri):
  515. localdata = bb.data.createCopy(tinfoil.config_data)
  516. pkgfile = bb.fetch2.localpath(fetchuri, localdata)
  517. if pkgfile:
  518. tmpfdir = tempfile.mkdtemp(prefix='recipetool-')
  519. try:
  520. if pkgfile.endswith(('.deb', '.ipk')):
  521. stdout, _ = bb.process.run('ar x %s' % pkgfile, cwd=tmpfdir)
  522. stdout, _ = bb.process.run('tar xf control.tar.gz', cwd=tmpfdir)
  523. values = convert_debian(tmpfdir)
  524. extravalues.update(values)
  525. elif pkgfile.endswith(('.rpm', '.srpm')):
  526. stdout, _ = bb.process.run('rpm -qp --xml %s > pkginfo.xml' % pkgfile, cwd=tmpfdir)
  527. values = convert_rpm_xml(os.path.join(tmpfdir, 'pkginfo.xml'))
  528. extravalues.update(values)
  529. finally:
  530. shutil.rmtree(tmpfdir)
  531. else:
  532. # Assume we're pointing to an existing source tree
  533. if args.extract_to:
  534. logger.error('--extract-to cannot be specified if source is a directory')
  535. sys.exit(1)
  536. if not os.path.isdir(source):
  537. logger.error('Invalid source directory %s' % source)
  538. sys.exit(1)
  539. srctree = source
  540. srcuri = ''
  541. if os.path.exists(os.path.join(srctree, '.git')):
  542. # Try to get upstream repo location from origin remote
  543. try:
  544. stdout, _ = bb.process.run('git remote -v', cwd=srctree, shell=True)
  545. except bb.process.ExecutionError as e:
  546. stdout = None
  547. if stdout:
  548. for line in stdout.splitlines():
  549. splitline = line.split()
  550. if len(splitline) > 1:
  551. if splitline[0] == 'origin' and scriptutils.is_src_url(splitline[1]):
  552. srcuri = reformat_git_uri(splitline[1])
  553. srcsubdir = 'git'
  554. break
  555. if args.src_subdir:
  556. srcsubdir = os.path.join(srcsubdir, args.src_subdir)
  557. srctree_use = os.path.abspath(os.path.join(srctree, args.src_subdir))
  558. else:
  559. srctree_use = os.path.abspath(srctree)
  560. if args.outfile and os.path.isdir(args.outfile):
  561. outfile = None
  562. outdir = args.outfile
  563. else:
  564. outfile = args.outfile
  565. outdir = None
  566. if outfile and outfile != '-':
  567. if os.path.exists(outfile):
  568. logger.error('Output file %s already exists' % outfile)
  569. sys.exit(1)
  570. lines_before = []
  571. lines_after = []
  572. lines_before.append('# Recipe created by %s' % os.path.basename(sys.argv[0]))
  573. lines_before.append('# This is the basis of a recipe and may need further editing in order to be fully functional.')
  574. lines_before.append('# (Feel free to remove these comments when editing.)')
  575. # We need a blank line here so that patch_recipe_lines can rewind before the LICENSE comments
  576. lines_before.append('')
  577. # We'll come back and replace this later in handle_license_vars()
  578. lines_before.append('##LICENSE_PLACEHOLDER##')
  579. handled = []
  580. classes = []
  581. # FIXME This is kind of a hack, we probably ought to be using bitbake to do this
  582. pn = None
  583. pv = None
  584. if outfile:
  585. recipefn = os.path.splitext(os.path.basename(outfile))[0]
  586. fnsplit = recipefn.split('_')
  587. if len(fnsplit) > 1:
  588. pn = fnsplit[0]
  589. pv = fnsplit[1]
  590. else:
  591. pn = recipefn
  592. if args.version:
  593. pv = args.version
  594. if args.name:
  595. pn = args.name
  596. if args.name.endswith('-native'):
  597. if args.also_native:
  598. 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')
  599. sys.exit(1)
  600. classes.append('native')
  601. elif args.name.startswith('nativesdk-'):
  602. if args.also_native:
  603. logger.error('--also-native cannot be specified for a recipe named nativesdk-* (nativesdk-* denotes a recipe that is already only for nativesdk)')
  604. sys.exit(1)
  605. classes.append('nativesdk')
  606. if pv and pv not in 'git svn hg'.split():
  607. realpv = pv
  608. else:
  609. realpv = None
  610. if not srcuri:
  611. lines_before.append('# No information for SRC_URI yet (only an external source tree was specified)')
  612. lines_before.append('SRC_URI = "%s"' % srcuri)
  613. for key, value in sorted(checksums.items()):
  614. lines_before.append('SRC_URI[%s] = "%s"' % (key, value))
  615. if srcuri and supports_srcrev(srcuri):
  616. lines_before.append('')
  617. lines_before.append('# Modify these as desired')
  618. # Note: we have code to replace realpv further down if it gets set to some other value
  619. scheme, _, _, _, _, _ = bb.fetch2.decodeurl(srcuri)
  620. if scheme in ['git', 'gitsm']:
  621. srcpvprefix = 'git'
  622. elif scheme == 'svn':
  623. srcpvprefix = 'svnr'
  624. else:
  625. srcpvprefix = scheme
  626. lines_before.append('PV = "%s+%s${SRCPV}"' % (realpv or '1.0', srcpvprefix))
  627. pv_srcpv = True
  628. if not args.autorev and srcrev == '${AUTOREV}':
  629. if os.path.exists(os.path.join(srctree, '.git')):
  630. (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=srctree)
  631. srcrev = stdout.rstrip()
  632. lines_before.append('SRCREV = "%s"' % srcrev)
  633. if args.provides:
  634. lines_before.append('PROVIDES = "%s"' % args.provides)
  635. lines_before.append('')
  636. if srcsubdir and not args.binary:
  637. # (for binary packages we explicitly specify subdir= when fetching to
  638. # match the default value of S, so we don't need to set it in that case)
  639. lines_before.append('S = "${WORKDIR}/%s"' % srcsubdir)
  640. lines_before.append('')
  641. if pkgarch:
  642. lines_after.append('PACKAGE_ARCH = "%s"' % pkgarch)
  643. lines_after.append('')
  644. if args.binary:
  645. lines_after.append('INSANE_SKIP_${PN} += "already-stripped"')
  646. lines_after.append('')
  647. if args.npm_dev:
  648. extravalues['NPM_INSTALL_DEV'] = 1
  649. # Find all plugins that want to register handlers
  650. logger.debug('Loading recipe handlers')
  651. raw_handlers = []
  652. for plugin in plugins:
  653. if hasattr(plugin, 'register_recipe_handlers'):
  654. plugin.register_recipe_handlers(raw_handlers)
  655. # Sort handlers by priority
  656. handlers = []
  657. for i, handler in enumerate(raw_handlers):
  658. if isinstance(handler, tuple):
  659. handlers.append((handler[0], handler[1], i))
  660. else:
  661. handlers.append((handler, 0, i))
  662. handlers.sort(key=lambda item: (item[1], -item[2]), reverse=True)
  663. for handler, priority, _ in handlers:
  664. logger.debug('Handler: %s (priority %d)' % (handler.__class__.__name__, priority))
  665. setattr(handler, '_devtool', args.devtool)
  666. handlers = [item[0] for item in handlers]
  667. # Apply the handlers
  668. if args.binary:
  669. classes.append('bin_package')
  670. handled.append('buildsystem')
  671. for handler in handlers:
  672. handler.process(srctree_use, classes, lines_before, lines_after, handled, extravalues)
  673. extrafiles = extravalues.pop('extrafiles', {})
  674. extra_pn = extravalues.pop('PN', None)
  675. extra_pv = extravalues.pop('PV', None)
  676. if extra_pv and not realpv:
  677. realpv = extra_pv
  678. if not validate_pv(realpv):
  679. realpv = None
  680. else:
  681. realpv = realpv.lower().split()[0]
  682. if '_' in realpv:
  683. realpv = realpv.replace('_', '-')
  684. if extra_pn and not pn:
  685. pn = extra_pn
  686. if pn.startswith('GNU '):
  687. pn = pn[4:]
  688. if ' ' in pn:
  689. # Probably a descriptive identifier rather than a proper name
  690. pn = None
  691. else:
  692. pn = pn.lower()
  693. if '_' in pn:
  694. pn = pn.replace('_', '-')
  695. if srcuri and not realpv or not pn:
  696. name_pn, name_pv = determine_from_url(srcuri)
  697. if name_pn and not pn:
  698. pn = name_pn
  699. if name_pv and not realpv:
  700. realpv = name_pv
  701. licvalues = handle_license_vars(srctree_use, lines_before, handled, extravalues, tinfoil.config_data)
  702. if not outfile:
  703. if not pn:
  704. 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)
  705. # devtool looks for this specific exit code, so don't change it
  706. sys.exit(15)
  707. else:
  708. if srcuri and srcuri.startswith(('gitsm://', 'git://', 'hg://', 'svn://')):
  709. suffix = srcuri.split(':', 1)[0]
  710. if suffix == 'gitsm':
  711. suffix = 'git'
  712. outfile = '%s_%s.bb' % (pn, suffix)
  713. elif realpv:
  714. outfile = '%s_%s.bb' % (pn, realpv)
  715. else:
  716. outfile = '%s.bb' % pn
  717. if outdir:
  718. outfile = os.path.join(outdir, outfile)
  719. # We need to check this again
  720. if os.path.exists(outfile):
  721. logger.error('Output file %s already exists' % outfile)
  722. sys.exit(1)
  723. # Move any extra files the plugins created to a directory next to the recipe
  724. if extrafiles:
  725. if outfile == '-':
  726. extraoutdir = pn
  727. else:
  728. extraoutdir = os.path.join(os.path.dirname(outfile), pn)
  729. bb.utils.mkdirhier(extraoutdir)
  730. for destfn, extrafile in extrafiles.items():
  731. shutil.move(extrafile, os.path.join(extraoutdir, destfn))
  732. lines = lines_before
  733. lines_before = []
  734. skipblank = True
  735. for line in lines:
  736. if skipblank:
  737. skipblank = False
  738. if not line:
  739. continue
  740. if line.startswith('S = '):
  741. if realpv and pv not in 'git svn hg'.split():
  742. line = line.replace(realpv, '${PV}')
  743. if pn:
  744. line = line.replace(pn, '${BPN}')
  745. if line == 'S = "${WORKDIR}/${BPN}-${PV}"':
  746. skipblank = True
  747. continue
  748. elif line.startswith('SRC_URI = '):
  749. if realpv and not pv_srcpv:
  750. line = line.replace(realpv, '${PV}')
  751. elif line.startswith('PV = '):
  752. if realpv:
  753. # Replace the first part of the PV value
  754. line = re.sub(r'"[^+]*\+', '"%s+' % realpv, line)
  755. lines_before.append(line)
  756. if args.also_native:
  757. lines = lines_after
  758. lines_after = []
  759. bbclassextend = None
  760. for line in lines:
  761. if line.startswith('BBCLASSEXTEND ='):
  762. splitval = line.split('"')
  763. if len(splitval) > 1:
  764. bbclassextend = splitval[1].split()
  765. if not 'native' in bbclassextend:
  766. bbclassextend.insert(0, 'native')
  767. line = 'BBCLASSEXTEND = "%s"' % ' '.join(bbclassextend)
  768. lines_after.append(line)
  769. if not bbclassextend:
  770. lines_after.append('BBCLASSEXTEND = "native"')
  771. postinst = ("postinst", extravalues.pop('postinst', None))
  772. postrm = ("postrm", extravalues.pop('postrm', None))
  773. preinst = ("preinst", extravalues.pop('preinst', None))
  774. prerm = ("prerm", extravalues.pop('prerm', None))
  775. funcs = [postinst, postrm, preinst, prerm]
  776. for func in funcs:
  777. if func[1]:
  778. RecipeHandler.genfunction(lines_after, 'pkg_%s_${PN}' % func[0], func[1])
  779. outlines = []
  780. outlines.extend(lines_before)
  781. if classes:
  782. if outlines[-1] and not outlines[-1].startswith('#'):
  783. outlines.append('')
  784. outlines.append('inherit %s' % ' '.join(classes))
  785. outlines.append('')
  786. outlines.extend(lines_after)
  787. if extravalues:
  788. _, outlines = oe.recipeutils.patch_recipe_lines(outlines, extravalues, trailing_newline=False)
  789. if args.extract_to:
  790. scriptutils.git_convert_standalone_clone(srctree)
  791. if os.path.isdir(args.extract_to):
  792. # If the directory exists we'll move the temp dir into it instead of
  793. # its contents - of course, we could try to always move its contents
  794. # but that is a pain if there are symlinks; the simplest solution is
  795. # to just remove it first
  796. os.rmdir(args.extract_to)
  797. shutil.move(srctree, args.extract_to)
  798. if tempsrc == srctree:
  799. tempsrc = None
  800. log_info_cond('Source extracted to %s' % args.extract_to, args.devtool)
  801. if outfile == '-':
  802. sys.stdout.write('\n'.join(outlines) + '\n')
  803. else:
  804. with open(outfile, 'w') as f:
  805. lastline = None
  806. for line in outlines:
  807. if not lastline and not line:
  808. # Skip extra blank lines
  809. continue
  810. f.write('%s\n' % line)
  811. lastline = line
  812. log_info_cond('Recipe %s has been created; further editing may be required to make it fully functional' % outfile, args.devtool)
  813. if tempsrc:
  814. if args.keep_temp:
  815. logger.info('Preserving temporary directory %s' % tempsrc)
  816. else:
  817. shutil.rmtree(tempsrc)
  818. return 0
  819. def check_single_file(fn, fetchuri):
  820. """Determine if a single downloaded file is something we can't handle"""
  821. with open(fn, 'r', errors='surrogateescape') as f:
  822. if '<html' in f.read(100).lower():
  823. logger.error('Fetching "%s" returned a single HTML page - check the URL is correct and functional' % fetchuri)
  824. sys.exit(1)
  825. def split_value(value):
  826. if isinstance(value, str):
  827. return value.split()
  828. else:
  829. return value
  830. def handle_license_vars(srctree, lines_before, handled, extravalues, d):
  831. lichandled = [x for x in handled if x[0] == 'license']
  832. if lichandled:
  833. # Someone else has already handled the license vars, just return their value
  834. return lichandled[0][1]
  835. licvalues = guess_license(srctree, d)
  836. licenses = []
  837. lic_files_chksum = []
  838. lic_unknown = []
  839. lines = []
  840. if licvalues:
  841. for licvalue in licvalues:
  842. if not licvalue[0] in licenses:
  843. licenses.append(licvalue[0])
  844. lic_files_chksum.append('file://%s;md5=%s' % (licvalue[1], licvalue[2]))
  845. if licvalue[0] == 'Unknown':
  846. lic_unknown.append(licvalue[1])
  847. if lic_unknown:
  848. lines.append('#')
  849. lines.append('# The following license files were not able to be identified and are')
  850. lines.append('# represented as "Unknown" below, you will need to check them yourself:')
  851. for licfile in lic_unknown:
  852. lines.append('# %s' % licfile)
  853. extra_license = split_value(extravalues.pop('LICENSE', []))
  854. if '&' in extra_license:
  855. extra_license.remove('&')
  856. if extra_license:
  857. if licenses == ['Unknown']:
  858. licenses = extra_license
  859. else:
  860. for item in extra_license:
  861. if item not in licenses:
  862. licenses.append(item)
  863. extra_lic_files_chksum = split_value(extravalues.pop('LIC_FILES_CHKSUM', []))
  864. for item in extra_lic_files_chksum:
  865. if item not in lic_files_chksum:
  866. lic_files_chksum.append(item)
  867. if lic_files_chksum:
  868. # We are going to set the vars, so prepend the standard disclaimer
  869. lines.insert(0, '# WARNING: the following LICENSE and LIC_FILES_CHKSUM values are best guesses - it is')
  870. lines.insert(1, '# your responsibility to verify that the values are complete and correct.')
  871. else:
  872. # Without LIC_FILES_CHKSUM we set LICENSE = "CLOSED" to allow the
  873. # user to get started easily
  874. lines.append('# Unable to find any files that looked like license statements. Check the accompanying')
  875. lines.append('# documentation and source headers and set LICENSE and LIC_FILES_CHKSUM accordingly.')
  876. lines.append('#')
  877. lines.append('# NOTE: LICENSE is being set to "CLOSED" to allow you to at least start building - if')
  878. lines.append('# this is not accurate with respect to the licensing of the software being built (it')
  879. lines.append('# will not be in most cases) you must specify the correct value before using this')
  880. lines.append('# recipe for anything other than initial testing/development!')
  881. licenses = ['CLOSED']
  882. if extra_license and sorted(licenses) != sorted(extra_license):
  883. lines.append('# NOTE: Original package / source metadata indicates license is: %s' % ' & '.join(extra_license))
  884. if len(licenses) > 1:
  885. lines.append('#')
  886. lines.append('# NOTE: multiple licenses have been detected; they have been separated with &')
  887. lines.append('# in the LICENSE value for now since it is a reasonable assumption that all')
  888. lines.append('# of the licenses apply. If instead there is a choice between the multiple')
  889. lines.append('# licenses then you should change the value to separate the licenses with |')
  890. lines.append('# instead of &. If there is any doubt, check the accompanying documentation')
  891. lines.append('# to determine which situation is applicable.')
  892. lines.append('LICENSE = "%s"' % ' & '.join(licenses))
  893. lines.append('LIC_FILES_CHKSUM = "%s"' % ' \\\n '.join(lic_files_chksum))
  894. lines.append('')
  895. # Replace the placeholder so we get the values in the right place in the recipe file
  896. try:
  897. pos = lines_before.index('##LICENSE_PLACEHOLDER##')
  898. except ValueError:
  899. pos = -1
  900. if pos == -1:
  901. lines_before.extend(lines)
  902. else:
  903. lines_before[pos:pos+1] = lines
  904. handled.append(('license', licvalues))
  905. return licvalues
  906. def get_license_md5sums(d, static_only=False):
  907. import bb.utils
  908. md5sums = {}
  909. if not static_only:
  910. # Gather md5sums of license files in common license dir
  911. commonlicdir = d.getVar('COMMON_LICENSE_DIR')
  912. for fn in os.listdir(commonlicdir):
  913. md5value = bb.utils.md5_file(os.path.join(commonlicdir, fn))
  914. md5sums[md5value] = fn
  915. # The following were extracted from common values in various recipes
  916. # (double checking the license against the license file itself, not just
  917. # the LICENSE value in the recipe)
  918. md5sums['94d55d512a9ba36caa9b7df079bae19f'] = 'GPLv2'
  919. md5sums['b234ee4d69f5fce4486a80fdaf4a4263'] = 'GPLv2'
  920. md5sums['59530bdf33659b29e73d4adb9f9f6552'] = 'GPLv2'
  921. md5sums['0636e73ff0215e8d672dc4c32c317bb3'] = 'GPLv2'
  922. md5sums['eb723b61539feef013de476e68b5c50a'] = 'GPLv2'
  923. md5sums['751419260aa954499f7abaabaa882bbe'] = 'GPLv2'
  924. md5sums['393a5ca445f6965873eca0259a17f833'] = 'GPLv2'
  925. md5sums['12f884d2ae1ff87c09e5b7ccc2c4ca7e'] = 'GPLv2'
  926. md5sums['8ca43cbc842c2336e835926c2166c28b'] = 'GPLv2'
  927. md5sums['ebb5c50ab7cab4baeffba14977030c07'] = 'GPLv2'
  928. md5sums['c93c0550bd3173f4504b2cbd8991e50b'] = 'GPLv2'
  929. md5sums['9ac2e7cff1ddaf48b6eab6028f23ef88'] = 'GPLv2'
  930. md5sums['4325afd396febcb659c36b49533135d4'] = 'GPLv2'
  931. md5sums['18810669f13b87348459e611d31ab760'] = 'GPLv2'
  932. md5sums['d7810fab7487fb0aad327b76f1be7cd7'] = 'GPLv2' # the Linux kernel's COPYING file
  933. md5sums['bbb461211a33b134d42ed5ee802b37ff'] = 'LGPLv2.1'
  934. md5sums['7fbc338309ac38fefcd64b04bb903e34'] = 'LGPLv2.1'
  935. md5sums['4fbd65380cdd255951079008b364516c'] = 'LGPLv2.1'
  936. md5sums['2d5025d4aa3495befef8f17206a5b0a1'] = 'LGPLv2.1'
  937. md5sums['fbc093901857fcd118f065f900982c24'] = 'LGPLv2.1'
  938. md5sums['a6f89e2100d9b6cdffcea4f398e37343'] = 'LGPLv2.1'
  939. md5sums['d8045f3b8f929c1cb29a1e3fd737b499'] = 'LGPLv2.1'
  940. md5sums['fad9b3332be894bab9bc501572864b29'] = 'LGPLv2.1'
  941. md5sums['3bf50002aefd002f49e7bb854063f7e7'] = 'LGPLv2'
  942. md5sums['9f604d8a4f8e74f4f5140845a21b6674'] = 'LGPLv2'
  943. md5sums['5f30f0716dfdd0d91eb439ebec522ec2'] = 'LGPLv2'
  944. md5sums['55ca817ccb7d5b5b66355690e9abc605'] = 'LGPLv2'
  945. md5sums['252890d9eee26aab7b432e8b8a616475'] = 'LGPLv2'
  946. md5sums['3214f080875748938ba060314b4f727d'] = 'LGPLv2'
  947. md5sums['db979804f025cf55aabec7129cb671ed'] = 'LGPLv2'
  948. md5sums['d32239bcb673463ab874e80d47fae504'] = 'GPLv3'
  949. md5sums['f27defe1e96c2e1ecd4e0c9be8967949'] = 'GPLv3'
  950. md5sums['6a6a8e020838b23406c81b19c1d46df6'] = 'LGPLv3'
  951. md5sums['3b83ef96387f14655fc854ddc3c6bd57'] = 'Apache-2.0'
  952. md5sums['385c55653886acac3821999a3ccd17b3'] = 'Artistic-1.0 | GPL-2.0' # some perl modules
  953. md5sums['54c7042be62e169199200bc6477f04d1'] = 'BSD-3-Clause'
  954. md5sums['bfe1f75d606912a4111c90743d6c7325'] = 'MPL-1.1'
  955. return md5sums
  956. def crunch_license(licfile):
  957. '''
  958. Remove non-material text from a license file and then check
  959. its md5sum against a known list. This works well for licenses
  960. which contain a copyright statement, but is also a useful way
  961. to handle people's insistence upon reformatting the license text
  962. slightly (with no material difference to the text of the
  963. license).
  964. '''
  965. import oe.utils
  966. # Note: these are carefully constructed!
  967. license_title_re = re.compile(r'^\(?(#+ *)?(The )?.{1,10} [Ll]icen[sc]e( \(.{1,10}\))?\)?:?$')
  968. license_statement_re = re.compile(r'^(This (project|software) is( free software)? (released|licen[sc]ed)|(Released|Licen[cs]ed)) under the .{1,10} [Ll]icen[sc]e:?$')
  969. copyright_re = re.compile('^(#+)? *Copyright .*$')
  970. crunched_md5sums = {}
  971. # The following two were gleaned from the "forever" npm package
  972. crunched_md5sums['0a97f8e4cbaf889d6fa51f84b89a79f6'] = 'ISC'
  973. crunched_md5sums['eecf6429523cbc9693547cf2db790b5c'] = 'MIT'
  974. # https://github.com/vasi/pixz/blob/master/LICENSE
  975. crunched_md5sums['2f03392b40bbe663597b5bd3cc5ebdb9'] = 'BSD-2-Clause'
  976. # https://github.com/waffle-gl/waffle/blob/master/LICENSE.txt
  977. crunched_md5sums['e72e5dfef0b1a4ca8a3d26a60587db66'] = 'BSD-2-Clause'
  978. # https://github.com/spigwitmer/fakeds1963s/blob/master/LICENSE
  979. crunched_md5sums['8be76ac6d191671f347ee4916baa637e'] = 'GPLv2'
  980. # https://github.com/datto/dattobd/blob/master/COPYING
  981. # http://git.savannah.gnu.org/cgit/freetype/freetype2.git/tree/docs/GPLv2.TXT
  982. crunched_md5sums['1d65c5ad4bf6489f85f4812bf08ae73d'] = 'GPLv2'
  983. # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
  984. # http://git.neil.brown.name/?p=mdadm.git;a=blob;f=COPYING;h=d159169d1050894d3ea3b98e1c965c4058208fe1;hb=HEAD
  985. crunched_md5sums['fb530f66a7a89ce920f0e912b5b66d4b'] = 'GPLv2'
  986. # https://github.com/gkos/nrf24/blob/master/COPYING
  987. crunched_md5sums['7b6aaa4daeafdfa6ed5443fd2684581b'] = 'GPLv2'
  988. # https://github.com/josch09/resetusb/blob/master/COPYING
  989. crunched_md5sums['8b8ac1d631a4d220342e83bcf1a1fbc3'] = 'GPLv3'
  990. # https://github.com/FFmpeg/FFmpeg/blob/master/COPYING.LGPLv2.1
  991. crunched_md5sums['2ea316ed973ae176e502e2297b574bb3'] = 'LGPLv2.1'
  992. # unixODBC-2.3.4 COPYING
  993. crunched_md5sums['1daebd9491d1e8426900b4fa5a422814'] = 'LGPLv2.1'
  994. # https://github.com/FFmpeg/FFmpeg/blob/master/COPYING.LGPLv3
  995. crunched_md5sums['2ebfb3bb49b9a48a075cc1425e7f4129'] = 'LGPLv3'
  996. # https://raw.githubusercontent.com/eclipse/mosquitto/v1.4.14/epl-v10
  997. crunched_md5sums['efe2cb9a35826992b9df68224e3c2628'] = 'EPL-1.0'
  998. # https://raw.githubusercontent.com/eclipse/mosquitto/v1.4.14/edl-v10
  999. crunched_md5sums['0a9c78c0a398d1bbce4a166757d60387'] = 'EDL-1.0'
  1000. lictext = []
  1001. with open(licfile, 'r', errors='surrogateescape') as f:
  1002. for line in f:
  1003. # Drop opening statements
  1004. if copyright_re.match(line):
  1005. continue
  1006. elif license_title_re.match(line):
  1007. continue
  1008. elif license_statement_re.match(line):
  1009. continue
  1010. # Squash spaces, and replace smart quotes, double quotes
  1011. # and backticks with single quotes
  1012. line = oe.utils.squashspaces(line.strip())
  1013. line = line.replace(u"\u2018", "'").replace(u"\u2019", "'").replace(u"\u201c","'").replace(u"\u201d", "'").replace('"', '\'').replace('`', '\'')
  1014. if line:
  1015. lictext.append(line)
  1016. m = hashlib.md5()
  1017. try:
  1018. m.update(' '.join(lictext).encode('utf-8'))
  1019. md5val = m.hexdigest()
  1020. except UnicodeEncodeError:
  1021. md5val = None
  1022. lictext = ''
  1023. license = crunched_md5sums.get(md5val, None)
  1024. return license, md5val, lictext
  1025. def guess_license(srctree, d):
  1026. import bb
  1027. md5sums = get_license_md5sums(d)
  1028. licenses = []
  1029. licspecs = ['*LICEN[CS]E*', 'COPYING*', '*[Ll]icense*', 'LEGAL*', '[Ll]egal*', '*GPL*', 'README.lic*', 'COPYRIGHT*', '[Cc]opyright*', 'e[dp]l-v10']
  1030. licfiles = []
  1031. for root, dirs, files in os.walk(srctree):
  1032. for fn in files:
  1033. for spec in licspecs:
  1034. if fnmatch.fnmatch(fn, spec):
  1035. fullpath = os.path.join(root, fn)
  1036. if not fullpath in licfiles:
  1037. licfiles.append(fullpath)
  1038. for licfile in licfiles:
  1039. md5value = bb.utils.md5_file(licfile)
  1040. license = md5sums.get(md5value, None)
  1041. if not license:
  1042. license, crunched_md5, lictext = crunch_license(licfile)
  1043. if not license:
  1044. license = 'Unknown'
  1045. licenses.append((license, os.path.relpath(licfile, srctree), md5value))
  1046. # FIXME should we grab at least one source file with a license header and add that too?
  1047. return licenses
  1048. def split_pkg_licenses(licvalues, packages, outlines, fallback_licenses=None, pn='${PN}'):
  1049. """
  1050. Given a list of (license, path, md5sum) as returned by guess_license(),
  1051. a dict of package name to path mappings, write out a set of
  1052. package-specific LICENSE values.
  1053. """
  1054. pkglicenses = {pn: []}
  1055. for license, licpath, _ in licvalues:
  1056. for pkgname, pkgpath in packages.items():
  1057. if licpath.startswith(pkgpath + '/'):
  1058. if pkgname in pkglicenses:
  1059. pkglicenses[pkgname].append(license)
  1060. else:
  1061. pkglicenses[pkgname] = [license]
  1062. break
  1063. else:
  1064. # Accumulate on the main package
  1065. pkglicenses[pn].append(license)
  1066. outlicenses = {}
  1067. for pkgname in packages:
  1068. license = ' '.join(list(set(pkglicenses.get(pkgname, ['Unknown'])))) or 'Unknown'
  1069. if license == 'Unknown' and pkgname in fallback_licenses:
  1070. license = fallback_licenses[pkgname]
  1071. outlines.append('LICENSE_%s = "%s"' % (pkgname, license))
  1072. outlicenses[pkgname] = license.split()
  1073. return outlicenses
  1074. def read_pkgconfig_provides(d):
  1075. pkgdatadir = d.getVar('PKGDATA_DIR')
  1076. pkgmap = {}
  1077. for fn in glob.glob(os.path.join(pkgdatadir, 'shlibs2', '*.pclist')):
  1078. with open(fn, 'r') as f:
  1079. for line in f:
  1080. pkgmap[os.path.basename(line.rstrip())] = os.path.splitext(os.path.basename(fn))[0]
  1081. recipemap = {}
  1082. for pc, pkg in pkgmap.items():
  1083. pkgdatafile = os.path.join(pkgdatadir, 'runtime', pkg)
  1084. if os.path.exists(pkgdatafile):
  1085. with open(pkgdatafile, 'r') as f:
  1086. for line in f:
  1087. if line.startswith('PN: '):
  1088. recipemap[pc] = line.split(':', 1)[1].strip()
  1089. return recipemap
  1090. def convert_debian(debpath):
  1091. value_map = {'Package': 'PN',
  1092. 'Version': 'PV',
  1093. 'Section': 'SECTION',
  1094. 'License': 'LICENSE',
  1095. 'Homepage': 'HOMEPAGE'}
  1096. # FIXME extend this mapping - perhaps use distro_alias.inc?
  1097. depmap = {'libz-dev': 'zlib'}
  1098. values = {}
  1099. depends = []
  1100. with open(os.path.join(debpath, 'control'), 'r', errors='surrogateescape') as f:
  1101. indesc = False
  1102. for line in f:
  1103. if indesc:
  1104. if line.startswith(' '):
  1105. if line.startswith(' This package contains'):
  1106. indesc = False
  1107. else:
  1108. if 'DESCRIPTION' in values:
  1109. values['DESCRIPTION'] += ' ' + line.strip()
  1110. else:
  1111. values['DESCRIPTION'] = line.strip()
  1112. else:
  1113. indesc = False
  1114. if not indesc:
  1115. splitline = line.split(':', 1)
  1116. if len(splitline) < 2:
  1117. continue
  1118. key = splitline[0]
  1119. value = splitline[1].strip()
  1120. if key == 'Build-Depends':
  1121. for dep in value.split(','):
  1122. dep = dep.split()[0]
  1123. mapped = depmap.get(dep, '')
  1124. if mapped:
  1125. depends.append(mapped)
  1126. elif key == 'Description':
  1127. values['SUMMARY'] = value
  1128. indesc = True
  1129. else:
  1130. varname = value_map.get(key, None)
  1131. if varname:
  1132. values[varname] = value
  1133. postinst = os.path.join(debpath, 'postinst')
  1134. postrm = os.path.join(debpath, 'postrm')
  1135. preinst = os.path.join(debpath, 'preinst')
  1136. prerm = os.path.join(debpath, 'prerm')
  1137. sfiles = [postinst, postrm, preinst, prerm]
  1138. for sfile in sfiles:
  1139. if os.path.isfile(sfile):
  1140. logger.info("Converting %s file to recipe function..." %
  1141. os.path.basename(sfile).upper())
  1142. content = []
  1143. with open(sfile) as f:
  1144. for line in f:
  1145. if "#!/" in line:
  1146. continue
  1147. line = line.rstrip("\n")
  1148. if line.strip():
  1149. content.append(line)
  1150. if content:
  1151. values[os.path.basename(f.name)] = content
  1152. #if depends:
  1153. # values['DEPENDS'] = ' '.join(depends)
  1154. return values
  1155. def convert_rpm_xml(xmlfile):
  1156. '''Converts the output from rpm -qp --xml to a set of variable values'''
  1157. import xml.etree.ElementTree as ElementTree
  1158. rpmtag_map = {'Name': 'PN',
  1159. 'Version': 'PV',
  1160. 'Summary': 'SUMMARY',
  1161. 'Description': 'DESCRIPTION',
  1162. 'License': 'LICENSE',
  1163. 'Url': 'HOMEPAGE'}
  1164. values = {}
  1165. tree = ElementTree.parse(xmlfile)
  1166. root = tree.getroot()
  1167. for child in root:
  1168. if child.tag == 'rpmTag':
  1169. name = child.attrib.get('name', None)
  1170. if name:
  1171. varname = rpmtag_map.get(name, None)
  1172. if varname:
  1173. values[varname] = child[0].text
  1174. return values
  1175. def register_commands(subparsers):
  1176. parser_create = subparsers.add_parser('create',
  1177. help='Create a new recipe',
  1178. description='Creates a new recipe from a source tree')
  1179. parser_create.add_argument('source', help='Path or URL to source')
  1180. parser_create.add_argument('-o', '--outfile', help='Specify filename for recipe to create')
  1181. parser_create.add_argument('-p', '--provides', help='Specify an alias for the item provided by the recipe')
  1182. parser_create.add_argument('-m', '--machine', help='Make recipe machine-specific as opposed to architecture-specific', action='store_true')
  1183. 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')
  1184. parser_create.add_argument('-N', '--name', help='Name to use within recipe (PN)')
  1185. parser_create.add_argument('-V', '--version', help='Version to use within recipe (PV)')
  1186. 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')
  1187. 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')
  1188. parser_create.add_argument('--src-subdir', help='Specify subdirectory within source tree to use', metavar='SUBDIR')
  1189. group = parser_create.add_mutually_exclusive_group()
  1190. 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")
  1191. group.add_argument('-S', '--srcrev', help='Source revision to fetch if fetching from an SCM such as git (default latest)')
  1192. parser_create.add_argument('-B', '--srcbranch', help='Branch in source repository if fetching from an SCM such as git (default master)')
  1193. parser_create.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
  1194. parser_create.add_argument('--npm-dev', action="store_true", help='For npm, also fetch devDependencies')
  1195. parser_create.add_argument('--devtool', action="store_true", help=argparse.SUPPRESS)
  1196. parser_create.add_argument('--mirrors', action="store_true", help='Enable PREMIRRORS and MIRRORS for source tree fetching (disabled by default).')
  1197. parser_create.set_defaults(func=create_recipe)