blob: 8305e436487fe238a841e12b3c56168097035e8f [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# Recipe creation tool - create command plugin
2#
3# Copyright (C) 2014-2015 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
18import sys
19import os
20import argparse
21import glob
22import fnmatch
23import re
24import logging
25import scriptutils
Patrick Williamsf1e5d692016-03-30 15:21:19 -050026import urlparse
Patrick Williamsc124f4f2015-09-15 14:41:29 -050027
28logger = logging.getLogger('recipetool')
29
30tinfoil = None
31plugins = None
32
33def plugin_init(pluginlist):
34 # Take a reference to the list so we can use it later
35 global plugins
36 plugins = pluginlist
37
38def tinfoil_init(instance):
39 global tinfoil
40 tinfoil = instance
41
42class RecipeHandler():
43 @staticmethod
44 def checkfiles(path, speclist):
45 results = []
46 for spec in speclist:
47 results.extend(glob.glob(os.path.join(path, spec)))
48 return results
49
Patrick Williamsf1e5d692016-03-30 15:21:19 -050050 def genfunction(self, outlines, funcname, content, python=False, forcespace=False):
51 if python:
52 prefix = 'python '
53 else:
54 prefix = ''
55 outlines.append('%s%s () {' % (prefix, funcname))
56 if python or forcespace:
57 indent = ' '
58 else:
59 indent = '\t'
60 addnoop = not python
Patrick Williamsc124f4f2015-09-15 14:41:29 -050061 for line in content:
Patrick Williamsf1e5d692016-03-30 15:21:19 -050062 outlines.append('%s%s' % (indent, line))
63 if addnoop:
64 strippedline = line.lstrip()
65 if strippedline and not strippedline.startswith('#'):
66 addnoop = False
67 if addnoop:
68 # Without this there'll be a syntax error
69 outlines.append('%s:' % indent)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050070 outlines.append('}')
71 outlines.append('')
72
73 def process(self, srctree, classes, lines_before, lines_after, handled):
74 return False
75
76
77
78def supports_srcrev(uri):
79 localdata = bb.data.createCopy(tinfoil.config_data)
80 # This is a bit sad, but if you don't have this set there can be some
81 # odd interactions with the urldata cache which lead to errors
82 localdata.setVar('SRCREV', '${AUTOREV}')
83 bb.data.update_data(localdata)
84 fetcher = bb.fetch2.Fetch([uri], localdata)
85 urldata = fetcher.ud
86 for u in urldata:
87 if urldata[u].method.supports_srcrev():
88 return True
89 return False
90
91def create_recipe(args):
92 import bb.process
93 import tempfile
94 import shutil
95
96 pkgarch = ""
97 if args.machine:
98 pkgarch = "${MACHINE_ARCH}"
99
100 checksums = (None, None)
101 tempsrc = ''
102 srcsubdir = ''
103 srcrev = '${AUTOREV}'
104 if '://' in args.source:
105 # Fetch a URL
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500106 fetchuri = urlparse.urldefrag(args.source)[0]
107 if args.binary:
108 # Assume the archive contains the directory structure verbatim
109 # so we need to extract to a subdirectory
110 fetchuri += ';subdir=%s' % os.path.splitext(os.path.basename(urlparse.urlsplit(fetchuri).path))[0]
111 git_re = re.compile('(https?)://([^;]+\.git)(;.*)?')
112 res = git_re.match(fetchuri)
113 if res:
114 # Need to switch the URI around so that the git fetcher is used
115 fetchuri = 'git://%s;protocol=%s%s' % (res.group(2), res.group(1), res.group(3) or '')
116 srcuri = fetchuri
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500117 rev_re = re.compile(';rev=([^;]+)')
118 res = rev_re.search(srcuri)
119 if res:
120 srcrev = res.group(1)
121 srcuri = rev_re.sub('', srcuri)
122 tempsrc = tempfile.mkdtemp(prefix='recipetool-')
123 srctree = tempsrc
124 logger.info('Fetching %s...' % srcuri)
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500125 try:
126 checksums = scriptutils.fetch_uri(tinfoil.config_data, fetchuri, srctree, srcrev)
127 except bb.fetch2.FetchError:
128 # Error already printed
129 sys.exit(1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500130 dirlist = os.listdir(srctree)
131 if 'git.indirectionsymlink' in dirlist:
132 dirlist.remove('git.indirectionsymlink')
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500133 if len(dirlist) == 1:
134 singleitem = os.path.join(srctree, dirlist[0])
135 if os.path.isdir(singleitem):
136 # We unpacked a single directory, so we should use that
137 srcsubdir = dirlist[0]
138 srctree = os.path.join(srctree, srcsubdir)
139 else:
140 with open(singleitem, 'r') as f:
141 if '<html' in f.read(100).lower():
142 logger.error('Fetching "%s" returned a single HTML page - check the URL is correct and functional' % fetchuri)
143 sys.exit(1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500144 else:
145 # Assume we're pointing to an existing source tree
146 if args.extract_to:
147 logger.error('--extract-to cannot be specified if source is a directory')
148 sys.exit(1)
149 if not os.path.isdir(args.source):
150 logger.error('Invalid source directory %s' % args.source)
151 sys.exit(1)
152 srcuri = ''
153 srctree = args.source
154
155 outfile = args.outfile
156 if outfile and outfile != '-':
157 if os.path.exists(outfile):
158 logger.error('Output file %s already exists' % outfile)
159 sys.exit(1)
160
161 lines_before = []
162 lines_after = []
163
164 lines_before.append('# Recipe created by %s' % os.path.basename(sys.argv[0]))
165 lines_before.append('# This is the basis of a recipe and may need further editing in order to be fully functional.')
166 lines_before.append('# (Feel free to remove these comments when editing.)')
167 lines_before.append('#')
168
169 licvalues = guess_license(srctree)
170 lic_files_chksum = []
171 if licvalues:
172 licenses = []
173 for licvalue in licvalues:
174 if not licvalue[0] in licenses:
175 licenses.append(licvalue[0])
176 lic_files_chksum.append('file://%s;md5=%s' % (licvalue[1], licvalue[2]))
177 lines_before.append('# WARNING: the following LICENSE and LIC_FILES_CHKSUM values are best guesses - it is')
178 lines_before.append('# your responsibility to verify that the values are complete and correct.')
179 if len(licvalues) > 1:
180 lines_before.append('#')
181 lines_before.append('# NOTE: multiple licenses have been detected; if that is correct you should separate')
182 lines_before.append('# these in the LICENSE value using & if the multiple licenses all apply, or | if there')
183 lines_before.append('# is a choice between the multiple licenses. If in doubt, check the accompanying')
184 lines_before.append('# documentation to determine which situation is applicable.')
185 else:
186 lines_before.append('# Unable to find any files that looked like license statements. Check the accompanying')
187 lines_before.append('# documentation and source headers and set LICENSE and LIC_FILES_CHKSUM accordingly.')
188 lines_before.append('#')
189 lines_before.append('# NOTE: LICENSE is being set to "CLOSED" to allow you to at least start building - if')
190 lines_before.append('# this is not accurate with respect to the licensing of the software being built (it')
191 lines_before.append('# will not be in most cases) you must specify the correct value before using this')
192 lines_before.append('# recipe for anything other than initial testing/development!')
193 licenses = ['CLOSED']
194 lines_before.append('LICENSE = "%s"' % ' '.join(licenses))
195 lines_before.append('LIC_FILES_CHKSUM = "%s"' % ' \\\n '.join(lic_files_chksum))
196 lines_before.append('')
197
198 # FIXME This is kind of a hack, we probably ought to be using bitbake to do this
199 # we'd also want a way to automatically set outfile based upon auto-detecting these values from the source if possible
200 recipefn = os.path.splitext(os.path.basename(outfile))[0]
201 fnsplit = recipefn.split('_')
202 if len(fnsplit) > 1:
203 pn = fnsplit[0]
204 pv = fnsplit[1]
205 else:
206 pn = recipefn
207 pv = None
208
209 if args.version:
210 pv = args.version
211
212 if pv and pv not in 'git svn hg'.split():
213 realpv = pv
214 else:
215 realpv = None
216
217 if srcuri:
218 if realpv:
219 srcuri = srcuri.replace(realpv, '${PV}')
220 else:
221 lines_before.append('# No information for SRC_URI yet (only an external source tree was specified)')
222 lines_before.append('SRC_URI = "%s"' % srcuri)
223 (md5value, sha256value) = checksums
224 if md5value:
225 lines_before.append('SRC_URI[md5sum] = "%s"' % md5value)
226 if sha256value:
227 lines_before.append('SRC_URI[sha256sum] = "%s"' % sha256value)
228 if srcuri and supports_srcrev(srcuri):
229 lines_before.append('')
230 lines_before.append('# Modify these as desired')
231 lines_before.append('PV = "%s+git${SRCPV}"' % (realpv or '1.0'))
232 lines_before.append('SRCREV = "%s"' % srcrev)
233 lines_before.append('')
234
235 if srcsubdir and pv:
236 if srcsubdir == "%s-%s" % (pn, pv):
237 # This would be the default, so we don't need to set S in the recipe
238 srcsubdir = ''
239 if srcsubdir:
240 if pv and pv not in 'git svn hg'.split():
241 srcsubdir = srcsubdir.replace(pv, '${PV}')
242 lines_before.append('S = "${WORKDIR}/%s"' % srcsubdir)
243 lines_before.append('')
244
245 if pkgarch:
246 lines_after.append('PACKAGE_ARCH = "%s"' % pkgarch)
247 lines_after.append('')
248
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500249 if args.binary:
250 lines_after.append('INSANE_SKIP_${PN} += "already-stripped"')
251 lines_after.append('')
252
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500253 # Find all plugins that want to register handlers
254 handlers = []
255 for plugin in plugins:
256 if hasattr(plugin, 'register_recipe_handlers'):
257 plugin.register_recipe_handlers(handlers)
258
259 # Apply the handlers
260 classes = []
261 handled = []
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500262
263 if args.binary:
264 classes.append('bin_package')
265 handled.append('buildsystem')
266
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500267 for handler in handlers:
268 handler.process(srctree, classes, lines_before, lines_after, handled)
269
270 outlines = []
271 outlines.extend(lines_before)
272 if classes:
273 outlines.append('inherit %s' % ' '.join(classes))
274 outlines.append('')
275 outlines.extend(lines_after)
276
277 if args.extract_to:
278 scriptutils.git_convert_standalone_clone(srctree)
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500279 if os.path.isdir(args.extract_to):
280 # If the directory exists we'll move the temp dir into it instead of
281 # its contents - of course, we could try to always move its contents
282 # but that is a pain if there are symlinks; the simplest solution is
283 # to just remove it first
284 os.rmdir(args.extract_to)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500285 shutil.move(srctree, args.extract_to)
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500286 if tempsrc == srctree:
287 tempsrc = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500288 logger.info('Source extracted to %s' % args.extract_to)
289
290 if outfile == '-':
291 sys.stdout.write('\n'.join(outlines) + '\n')
292 else:
293 with open(outfile, 'w') as f:
294 f.write('\n'.join(outlines) + '\n')
295 logger.info('Recipe %s has been created; further editing may be required to make it fully functional' % outfile)
296
297 if tempsrc:
298 shutil.rmtree(tempsrc)
299
300 return 0
301
302def get_license_md5sums(d, static_only=False):
303 import bb.utils
304 md5sums = {}
305 if not static_only:
306 # Gather md5sums of license files in common license dir
307 commonlicdir = d.getVar('COMMON_LICENSE_DIR', True)
308 for fn in os.listdir(commonlicdir):
309 md5value = bb.utils.md5_file(os.path.join(commonlicdir, fn))
310 md5sums[md5value] = fn
311 # The following were extracted from common values in various recipes
312 # (double checking the license against the license file itself, not just
313 # the LICENSE value in the recipe)
314 md5sums['94d55d512a9ba36caa9b7df079bae19f'] = 'GPLv2'
315 md5sums['b234ee4d69f5fce4486a80fdaf4a4263'] = 'GPLv2'
316 md5sums['59530bdf33659b29e73d4adb9f9f6552'] = 'GPLv2'
317 md5sums['0636e73ff0215e8d672dc4c32c317bb3'] = 'GPLv2'
318 md5sums['eb723b61539feef013de476e68b5c50a'] = 'GPLv2'
319 md5sums['751419260aa954499f7abaabaa882bbe'] = 'GPLv2'
320 md5sums['393a5ca445f6965873eca0259a17f833'] = 'GPLv2'
321 md5sums['12f884d2ae1ff87c09e5b7ccc2c4ca7e'] = 'GPLv2'
322 md5sums['8ca43cbc842c2336e835926c2166c28b'] = 'GPLv2'
323 md5sums['ebb5c50ab7cab4baeffba14977030c07'] = 'GPLv2'
324 md5sums['c93c0550bd3173f4504b2cbd8991e50b'] = 'GPLv2'
325 md5sums['9ac2e7cff1ddaf48b6eab6028f23ef88'] = 'GPLv2'
326 md5sums['4325afd396febcb659c36b49533135d4'] = 'GPLv2'
327 md5sums['18810669f13b87348459e611d31ab760'] = 'GPLv2'
328 md5sums['d7810fab7487fb0aad327b76f1be7cd7'] = 'GPLv2' # the Linux kernel's COPYING file
329 md5sums['bbb461211a33b134d42ed5ee802b37ff'] = 'LGPLv2.1'
330 md5sums['7fbc338309ac38fefcd64b04bb903e34'] = 'LGPLv2.1'
331 md5sums['4fbd65380cdd255951079008b364516c'] = 'LGPLv2.1'
332 md5sums['2d5025d4aa3495befef8f17206a5b0a1'] = 'LGPLv2.1'
333 md5sums['fbc093901857fcd118f065f900982c24'] = 'LGPLv2.1'
334 md5sums['a6f89e2100d9b6cdffcea4f398e37343'] = 'LGPLv2.1'
335 md5sums['d8045f3b8f929c1cb29a1e3fd737b499'] = 'LGPLv2.1'
336 md5sums['fad9b3332be894bab9bc501572864b29'] = 'LGPLv2.1'
337 md5sums['3bf50002aefd002f49e7bb854063f7e7'] = 'LGPLv2'
338 md5sums['9f604d8a4f8e74f4f5140845a21b6674'] = 'LGPLv2'
339 md5sums['5f30f0716dfdd0d91eb439ebec522ec2'] = 'LGPLv2'
340 md5sums['55ca817ccb7d5b5b66355690e9abc605'] = 'LGPLv2'
341 md5sums['252890d9eee26aab7b432e8b8a616475'] = 'LGPLv2'
342 md5sums['d32239bcb673463ab874e80d47fae504'] = 'GPLv3'
343 md5sums['f27defe1e96c2e1ecd4e0c9be8967949'] = 'GPLv3'
344 md5sums['6a6a8e020838b23406c81b19c1d46df6'] = 'LGPLv3'
345 md5sums['3b83ef96387f14655fc854ddc3c6bd57'] = 'Apache-2.0'
346 md5sums['385c55653886acac3821999a3ccd17b3'] = 'Artistic-1.0 | GPL-2.0' # some perl modules
347 return md5sums
348
349def guess_license(srctree):
350 import bb
351 md5sums = get_license_md5sums(tinfoil.config_data)
352
353 licenses = []
354 licspecs = ['LICENSE*', 'COPYING*', '*[Ll]icense*', 'LICENCE*', 'LEGAL*', '[Ll]egal*', '*GPL*', 'README.lic*', 'COPYRIGHT*', '[Cc]opyright*']
355 licfiles = []
356 for root, dirs, files in os.walk(srctree):
357 for fn in files:
358 for spec in licspecs:
359 if fnmatch.fnmatch(fn, spec):
360 fullpath = os.path.join(root, fn)
361 if not fullpath in licfiles:
362 licfiles.append(fullpath)
363 for licfile in licfiles:
364 md5value = bb.utils.md5_file(licfile)
365 license = md5sums.get(md5value, 'Unknown')
366 licenses.append((license, os.path.relpath(licfile, srctree), md5value))
367
368 # FIXME should we grab at least one source file with a license header and add that too?
369
370 return licenses
371
372def read_pkgconfig_provides(d):
373 pkgdatadir = d.getVar('PKGDATA_DIR', True)
374 pkgmap = {}
375 for fn in glob.glob(os.path.join(pkgdatadir, 'shlibs2', '*.pclist')):
376 with open(fn, 'r') as f:
377 for line in f:
378 pkgmap[os.path.basename(line.rstrip())] = os.path.splitext(os.path.basename(fn))[0]
379 recipemap = {}
380 for pc, pkg in pkgmap.iteritems():
381 pkgdatafile = os.path.join(pkgdatadir, 'runtime', pkg)
382 if os.path.exists(pkgdatafile):
383 with open(pkgdatafile, 'r') as f:
384 for line in f:
385 if line.startswith('PN: '):
386 recipemap[pc] = line.split(':', 1)[1].strip()
387 return recipemap
388
389def convert_pkginfo(pkginfofile):
390 values = {}
391 with open(pkginfofile, 'r') as f:
392 indesc = False
393 for line in f:
394 if indesc:
395 if line.strip():
396 values['DESCRIPTION'] += ' ' + line.strip()
397 else:
398 indesc = False
399 else:
400 splitline = line.split(': ', 1)
401 key = line[0]
402 value = line[1]
403 if key == 'LICENSE':
404 for dep in value.split(','):
405 dep = dep.split()[0]
406 mapped = depmap.get(dep, '')
407 if mapped:
408 depends.append(mapped)
409 elif key == 'License':
410 values['LICENSE'] = value
411 elif key == 'Summary':
412 values['SUMMARY'] = value
413 elif key == 'Description':
414 values['DESCRIPTION'] = value
415 indesc = True
416 return values
417
418def convert_debian(debpath):
419 # FIXME extend this mapping - perhaps use distro_alias.inc?
420 depmap = {'libz-dev': 'zlib'}
421
422 values = {}
423 depends = []
424 with open(os.path.join(debpath, 'control')) as f:
425 indesc = False
426 for line in f:
427 if indesc:
428 if line.strip():
429 if line.startswith(' This package contains'):
430 indesc = False
431 else:
432 values['DESCRIPTION'] += ' ' + line.strip()
433 else:
434 indesc = False
435 else:
436 splitline = line.split(':', 1)
437 key = line[0]
438 value = line[1]
439 if key == 'Build-Depends':
440 for dep in value.split(','):
441 dep = dep.split()[0]
442 mapped = depmap.get(dep, '')
443 if mapped:
444 depends.append(mapped)
445 elif key == 'Section':
446 values['SECTION'] = value
447 elif key == 'Description':
448 values['SUMMARY'] = value
449 indesc = True
450
451 if depends:
452 values['DEPENDS'] = ' '.join(depends)
453
454 return values
455
456
457def register_command(subparsers):
458 parser_create = subparsers.add_parser('create',
459 help='Create a new recipe',
460 description='Creates a new recipe from a source tree')
461 parser_create.add_argument('source', help='Path or URL to source')
462 parser_create.add_argument('-o', '--outfile', help='Specify filename for recipe to create', required=True)
463 parser_create.add_argument('-m', '--machine', help='Make recipe machine-specific as opposed to architecture-specific', action='store_true')
464 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')
465 parser_create.add_argument('-V', '--version', help='Version to use within recipe (PV)')
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500466 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')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500467 parser_create.set_defaults(func=create_recipe)
468