merge of '45fb4fa94d52a65c3a3fa636c6122139173dfa8d'
[vuplus_openembedded] / classes / package.bbclass
1 #
2 # General packaging help functions
3 #
4
5 def legitimize_package_name(s):
6         """
7         Make sure package names are legitimate strings
8         """
9         import re
10
11         def fixutf(m):
12                 cp = m.group(1)
13                 if cp:
14                         return ('\u%s' % cp).decode('unicode_escape').encode('utf-8')
15
16         # Handle unicode codepoints encoded as <U0123>, as in glibc locale files.
17         s = re.sub('<U([0-9A-Fa-f]{1,4})>', fixutf, s)
18
19         # Remaining package name validity fixes
20         return s.lower().replace('_', '-').replace('@', '+').replace(',', '+').replace('/', '-')
21
22 def do_split_packages(d, root, file_regex, output_pattern, description, postinst=None, recursive=False, hook=None, extra_depends=None, aux_files_pattern=None, postrm=None, allow_dirs=False, prepend=False, match_path=False, aux_files_pattern_verbatim=None):
23         """
24         Used in .bb files to split up dynamically generated subpackages of a 
25         given package, usually plugins or modules.
26         """
27         import os, os.path, bb
28
29         dvar = bb.data.getVar('D', d, 1)
30         if not dvar:
31                 bb.error("D not defined")
32                 return
33
34         packages = bb.data.getVar('PACKAGES', d, 1).split()
35         if not packages:
36                 # nothing to do
37                 return
38
39         if postinst:
40                 postinst = '#!/bin/sh\n' + postinst + '\n'
41         if postrm:
42                 postrm = '#!/bin/sh\n' + postrm + '\n'
43         if not recursive:
44                 objs = os.listdir(dvar + root)
45         else:
46                 objs = []
47                 for walkroot, dirs, files in os.walk(dvar + root):
48                         for file in files:
49                                 relpath = os.path.join(walkroot, file).replace(dvar + root + '/', '', 1)
50                                 if relpath:
51                                         objs.append(relpath)
52
53         if extra_depends == None:
54                 # This is *really* broken
55                 mainpkg = packages[0]
56                 # At least try and patch it up I guess...
57                 if mainpkg.find('-dbg'):
58                         mainpkg = mainpkg.replace('-dbg', '')
59                 if mainpkg.find('-dev'):
60                         mainpkg = mainpkg.replace('-dev', '')
61                 extra_depends = mainpkg
62
63         for o in objs:
64                 import re, stat
65                 if match_path:
66                         m = re.match(file_regex, o)
67                 else:
68                         m = re.match(file_regex, os.path.basename(o))
69                 
70                 if not m:
71                         continue
72                 f = os.path.join(dvar + root, o)
73                 mode = os.lstat(f).st_mode
74                 if not (stat.S_ISREG(mode) or (allow_dirs and stat.S_ISDIR(mode))):
75                         continue
76                 on = legitimize_package_name(m.group(1))
77                 pkg = output_pattern % on
78                 if not pkg in packages:
79                         if prepend:
80                                 packages = [pkg] + packages
81                         else:
82                                 packages.append(pkg)
83                         the_files = [os.path.join(root, o)]
84                         if aux_files_pattern:
85                                 if type(aux_files_pattern) is list:
86                                         for fp in aux_files_pattern:
87                                                 the_files.append(fp % on)       
88                                 else:
89                                         the_files.append(aux_files_pattern % on)
90                         if aux_files_pattern_verbatim:
91                                 if type(aux_files_pattern_verbatim) is list:
92                                         for fp in aux_files_pattern_verbatim:
93                                                 the_files.append(fp % m.group(1))       
94                                 else:
95                                         the_files.append(aux_files_pattern_verbatim % m.group(1))
96                         bb.data.setVar('FILES_' + pkg, " ".join(the_files), d)
97                         if extra_depends != '':
98                                 the_depends = bb.data.getVar('RDEPENDS_' + pkg, d, 1)
99                                 if the_depends:
100                                         the_depends = '%s %s' % (the_depends, extra_depends)
101                                 else:
102                                         the_depends = extra_depends
103                                 bb.data.setVar('RDEPENDS_' + pkg, the_depends, d)
104                         bb.data.setVar('DESCRIPTION_' + pkg, description % on, d)
105                         if postinst:
106                                 bb.data.setVar('pkg_postinst_' + pkg, postinst, d)
107                         if postrm:
108                                 bb.data.setVar('pkg_postrm_' + pkg, postrm, d)
109                 else:
110                         oldfiles = bb.data.getVar('FILES_' + pkg, d, 1)
111                         if not oldfiles:
112                                 bb.fatal("Package '%s' exists but has no files" % pkg)
113                         bb.data.setVar('FILES_' + pkg, oldfiles + " " + os.path.join(root, o), d)
114                 if callable(hook):
115                         hook(f, pkg, file_regex, output_pattern, m.group(1))
116
117         bb.data.setVar('PACKAGES', ' '.join(packages), d)
118
119 PACKAGE_DEPENDS ?= "file-native"
120 DEPENDS_prepend =+ "${PACKAGE_DEPENDS} "
121 # file(1) output to match to consider a file an unstripped executable
122 FILE_UNSTRIPPED_MATCH ?= "not stripped"
123 #FIXME: this should be "" when any errors are gone!
124 IGNORE_STRIP_ERRORS ?= "1"
125
126 runstrip() {
127         # Function to strip a single file, called from RUNSTRIP in populate_packages below
128         # A working 'file' (one which works on the target architecture)
129         # is necessary for this stuff to work, hence the addition to PACKAGES_DEPENDS
130
131         local ro st
132
133         st=0
134         if {    file "$1" || {
135                         oewarn "file $1: failed (forced strip)" >&2
136                         echo '${FILE_UNSTRIPPED_MATCH}'
137                 }
138            } | grep -q '${FILE_UNSTRIPPED_MATCH}'
139         then
140                 oenote "${STRIP} $1"
141                 ro=
142                 test -w "$1" || {
143                         ro=1
144                         chmod +w "$1"
145                 }
146                 mkdir -p $(dirname "$1")/.debug
147                 debugfile="$(dirname "$1")/.debug/$(basename "$1")"
148                 '${OBJCOPY}' --only-keep-debug "$1" "$debugfile"
149                 '${STRIP}' "$1"
150                 st=$?
151                 '${OBJCOPY}' --add-gnu-debuglink="$debugfile" "$1"
152                 test -n "$ro" && chmod -w "$1"
153                 if test $st -ne 0
154                 then
155                         oewarn "runstrip: ${STRIP} $1: strip failed" >&2
156                         if [ x${IGNORE_STRIP_ERRORS} == x1 ]
157                         then
158                                 #FIXME: remove this, it's for error detection
159                                 if file "$1" 2>/dev/null >&2
160                                 then
161                                         (oefatal "${STRIP} $1: command failed" >/dev/tty)
162                                 else
163                                         (oefatal "file $1: command failed" >/dev/tty)
164                                 fi
165                                 st=0
166                         fi
167                 fi
168         else
169                 oenote "runstrip: skip $1"
170         fi
171         return $st
172 }
173
174
175 #
176 # Package data handling routines
177 #
178
179 STAGING_PKGMAPS_DIR ?= "${STAGING_DIR}/pkgmaps"
180
181 def add_package_mapping (pkg, new_name, d):
182         import bb, os
183
184         def encode(str):
185                 import codecs
186                 c = codecs.getencoder("string_escape")
187                 return c(str)[0]
188
189         pmap_dir = bb.data.getVar('STAGING_PKGMAPS_DIR', d, 1)
190
191         bb.mkdirhier(pmap_dir)
192
193         data_file = os.path.join(pmap_dir, pkg)
194
195         f = open(data_file, 'w')
196         f.write("%s\n" % encode(new_name))
197         f.close()
198
199 def get_package_mapping (pkg, d):
200         import bb, os
201
202         def decode(str):
203                 import codecs
204                 c = codecs.getdecoder("string_escape")
205                 return c(str)[0]
206
207         data_file = bb.data.expand("${STAGING_PKGMAPS_DIR}/%s" % pkg, d)
208
209         if os.access(data_file, os.R_OK):
210                 f = file(data_file, 'r')
211                 lines = f.readlines()
212                 f.close()
213                 for l in lines:
214                         return decode(l).strip()
215         return pkg
216
217 def runtime_mapping_rename (varname, d):
218         import bb, os
219
220         #bb.note("%s before: %s" % (varname, bb.data.getVar(varname, d, 1)))    
221
222         new_depends = []
223         for depend in explode_deps(bb.data.getVar(varname, d, 1) or ""):
224                 # Have to be careful with any version component of the depend
225                 split_depend = depend.split(' (')
226                 new_depend = get_package_mapping(split_depend[0].strip(), d)
227                 if len(split_depend) > 1:
228                         new_depends.append("%s (%s" % (new_depend, split_depend[1]))
229                 else:
230                         new_depends.append(new_depend)
231
232         bb.data.setVar(varname, " ".join(new_depends) or None, d)
233
234         #bb.note("%s after: %s" % (varname, bb.data.getVar(varname, d, 1)))
235
236 #
237 # Package functions suitable for inclusion in PACKAGEFUNCS
238 #
239
240 python package_do_split_locales() {
241         import os
242
243         if (bb.data.getVar('PACKAGE_NO_LOCALE', d, 1) == '1'):
244                 bb.debug(1, "package requested not splitting locales")
245                 return
246
247         packages = (bb.data.getVar('PACKAGES', d, 1) or "").split()
248         if not packages:
249                 bb.debug(1, "no packages to build; not splitting locales")
250                 return
251
252         datadir = bb.data.getVar('datadir', d, 1)
253         if not datadir:
254                 bb.note("datadir not defined")
255                 return
256
257         dvar = bb.data.getVar('D', d, 1)
258         if not dvar:
259                 bb.error("D not defined")
260                 return
261
262         pn = bb.data.getVar('PN', d, 1)
263         if not pn:
264                 bb.error("PN not defined")
265                 return
266
267         if pn + '-locale' in packages:
268                 packages.remove(pn + '-locale')
269
270         localedir = os.path.join(dvar + datadir, 'locale')
271
272         if not os.path.isdir(localedir):
273                 bb.debug(1, "No locale files in this package")
274                 return
275
276         locales = os.listdir(localedir)
277
278         # This is *really* broken
279         mainpkg = packages[0]
280         # At least try and patch it up I guess...
281         if mainpkg.find('-dbg'):
282                 mainpkg = mainpkg.replace('-dbg', '')
283         if mainpkg.find('-dev'):
284                 mainpkg = mainpkg.replace('-dev', '')
285
286         for l in locales:
287                 ln = legitimize_package_name(l)
288                 pkg = pn + '-locale-' + ln
289                 packages.append(pkg)
290                 bb.data.setVar('FILES_' + pkg, os.path.join(datadir, 'locale', l), d)
291                 bb.data.setVar('RDEPENDS_' + pkg, '%s virtual-locale-%s' % (mainpkg, ln), d)
292                 bb.data.setVar('RPROVIDES_' + pkg, '%s-locale %s-translation' % (pn, ln), d)
293                 bb.data.setVar('DESCRIPTION_' + pkg, '%s translation for %s' % (l, pn), d)
294
295         bb.data.setVar('PACKAGES', ' '.join(packages), d)
296
297         rdep = (bb.data.getVar('RDEPENDS_%s' % mainpkg, d, 1) or bb.data.getVar('RDEPENDS', d, 1) or "").split()
298         rdep.append('%s-locale*' % pn)
299         bb.data.setVar('RDEPENDS_%s' % mainpkg, ' '.join(rdep), d)
300 }
301
302 python populate_packages () {
303         import glob, stat, errno, re
304
305         workdir = bb.data.getVar('WORKDIR', d, 1)
306         if not workdir:
307                 bb.error("WORKDIR not defined, unable to package")
308                 return
309
310         import os # path manipulations
311         outdir = bb.data.getVar('DEPLOY_DIR', d, 1)
312         if not outdir:
313                 bb.error("DEPLOY_DIR not defined, unable to package")
314                 return
315         bb.mkdirhier(outdir)
316
317         dvar = bb.data.getVar('D', d, 1)
318         if not dvar:
319                 bb.error("D not defined, unable to package")
320                 return
321         bb.mkdirhier(dvar)
322
323         packages = bb.data.getVar('PACKAGES', d, 1)
324         if not packages:
325                 bb.debug(1, "PACKAGES not defined, nothing to package")
326                 return
327
328         pn = bb.data.getVar('PN', d, 1)
329         if not pn:
330                 bb.error("PN not defined")
331                 return
332
333         os.chdir(dvar)
334
335         def isexec(path):
336                 try:
337                         s = os.stat(path)
338                 except (os.error, AttributeError):
339                         return 0
340                 return (s[stat.ST_MODE] & stat.S_IEXEC)
341
342         # Sanity check PACKAGES for duplicates - should be moved to 
343         # sanity.bbclass once we have the infrastucture
344         package_list = []
345         for pkg in packages.split():
346                 if pkg in package_list:
347                         bb.error("-------------------")
348                         bb.error("%s is listed in PACKAGES mutliple times, this leads to packaging errors." % pkg)
349                         bb.error("Please fix the metadata/report this as bug to OE bugtracker.")
350                         bb.error("-------------------")
351                 else:
352                         package_list.append(pkg)
353
354         if (bb.data.getVar('INHIBIT_PACKAGE_STRIP', d, 1) != '1'):
355                 stripfunc = ""
356                 for root, dirs, files in os.walk(dvar):
357                         for f in files:
358                                 file = os.path.join(root, f)
359                                 if not os.path.islink(file) and not os.path.isdir(file) and isexec(file):
360                                         stripfunc += "\trunstrip %s || st=1\n" % (file)
361                 if not stripfunc == "":
362                         from bb import build
363                         localdata = bb.data.createCopy(d)
364                         # strip
365                         bb.data.setVar('RUNSTRIP', '\tlocal st\n\tst=0\n%s\treturn $st' % stripfunc, localdata)
366                         bb.data.setVarFlag('RUNSTRIP', 'func', 1, localdata)
367                         bb.build.exec_func('RUNSTRIP', localdata)
368
369         for pkg in package_list:
370                 localdata = bb.data.createCopy(d)
371                 root = os.path.join(workdir, "install", pkg)
372
373                 os.system('rm -rf %s' % root)
374
375                 bb.data.setVar('ROOT', '', localdata)
376                 bb.data.setVar('ROOT_%s' % pkg, root, localdata)
377                 bb.data.setVar('PKG', pkg, localdata)
378
379                 overrides = bb.data.getVar('OVERRIDES', localdata, 1)
380                 if not overrides:
381                         raise bb.build.FuncFailed('OVERRIDES not defined')
382                 bb.data.setVar('OVERRIDES', overrides+':'+pkg, localdata)
383
384                 bb.data.update_data(localdata)
385
386                 root = bb.data.getVar('ROOT', localdata, 1)
387                 bb.mkdirhier(root)
388                 filesvar = bb.data.getVar('FILES', localdata, 1) or ""
389                 files = filesvar.split()
390                 for file in files:
391                         if os.path.isabs(file):
392                                 file = '.' + file
393                         if not os.path.islink(file):
394                                 if os.path.isdir(file):
395                                         newfiles =  [ os.path.join(file,x) for x in os.listdir(file) ]
396                                         if newfiles:
397                                                 files += newfiles
398                                                 continue
399                         globbed = glob.glob(file)
400                         if globbed:
401                                 if [ file ] != globbed:
402                                         files += globbed
403                                         continue
404                         if (not os.path.islink(file)) and (not os.path.exists(file)):
405                                 continue
406                         fpath = os.path.join(root,file)
407                         dpath = os.path.dirname(fpath)
408                         bb.mkdirhier(dpath)
409                         ret = bb.movefile(file,fpath)
410                         if ret is None or ret == 0:
411                                 raise bb.build.FuncFailed("File population failed")
412                 del localdata
413         os.chdir(workdir)
414
415         unshipped = []
416         for root, dirs, files in os.walk(dvar):
417                 for f in files:
418                         path = os.path.join(root[len(dvar):], f)
419                         unshipped.append(path)
420
421         if unshipped != []:
422                 bb.note("the following files were installed but not shipped in any package:")
423                 for f in unshipped:
424                         bb.note("  " + f)
425
426         bb.build.exec_func("package_name_hook", d)
427
428         for pkg in package_list:
429                 pkgname = bb.data.getVar('PKG_%s' % pkg, d, 1)
430                 if pkgname is None:
431                         bb.data.setVar('PKG_%s' % pkg, pkg, d)
432                 else:
433                         add_package_mapping(pkg, pkgname, d)
434
435         dangling_links = {}
436         pkg_files = {}
437         for pkg in package_list:
438                 dangling_links[pkg] = []
439                 pkg_files[pkg] = []
440                 inst_root = os.path.join(workdir, "install", pkg)
441                 for root, dirs, files in os.walk(inst_root):
442                         for f in files:
443                                 path = os.path.join(root, f)
444                                 rpath = path[len(inst_root):]
445                                 pkg_files[pkg].append(rpath)
446                                 try:
447                                         s = os.stat(path)
448                                 except OSError, (err, strerror):
449                                         if err != errno.ENOENT:
450                                                 raise
451                                         target = os.readlink(path)
452                                         if target[0] != '/':
453                                                 target = os.path.join(root[len(inst_root):], target)
454                                         dangling_links[pkg].append(os.path.normpath(target))
455
456         for pkg in package_list:
457                 rdepends = explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, 1) or bb.data.getVar('RDEPENDS', d, 1) or "")
458                 for l in dangling_links[pkg]:
459                         found = False
460                         bb.debug(1, "%s contains dangling link %s" % (pkg, l))
461                         for p in package_list:
462                                 for f in pkg_files[p]:
463                                         if f == l:
464                                                 found = True
465                                                 bb.debug(1, "target found in %s" % p)
466                                                 if p == pkg:
467                                                         break
468                                                 if not p in rdepends:
469                                                         rdepends.append(p)
470                                                 break
471                         if found == False:
472                                 bb.note("%s contains dangling symlink to %s" % (pkg, l))
473                 bb.data.setVar('RDEPENDS_' + pkg, " " + " ".join(rdepends), d)
474 }
475 populate_packages[dirs] = "${D}"
476
477 python emit_pkgdata() {
478         def write_if_exists(f, pkg, var):
479                 def encode(str):
480                         import codecs
481                         c = codecs.getencoder("string_escape")
482                         return c(str)[0]
483
484                 val = bb.data.getVar('%s_%s' % (var, pkg), d, 1)
485                 if val:
486                         f.write('%s_%s: %s\n' % (var, pkg, encode(val)))
487
488         packages = bb.data.getVar('PACKAGES', d, 1)
489         if not packages:
490                 return
491
492         data_file = bb.data.expand("${STAGING_DIR}/pkgdata/${PN}", d)
493         f = open(data_file, 'w')
494         f.write("PACKAGES: %s\n" % packages)
495         f.close()
496
497         for pkg in packages.split():
498                 subdata_file = bb.data.expand("${STAGING_DIR}/pkgdata/runtime/%s" % pkg, d)
499                 sf = open(subdata_file, 'w')
500                 write_if_exists(sf, pkg, 'DESCRIPTION')
501                 write_if_exists(sf, pkg, 'RDEPENDS')
502                 write_if_exists(sf, pkg, 'RPROVIDES')
503                 write_if_exists(sf, pkg, 'RRECOMMENDS')
504                 write_if_exists(sf, pkg, 'RSUGGESTS')
505                 write_if_exists(sf, pkg, 'RPROVIDES')
506                 write_if_exists(sf, pkg, 'RREPLACES')
507                 write_if_exists(sf, pkg, 'RCONFLICTS')
508                 write_if_exists(sf, pkg, 'PKG')
509                 write_if_exists(sf, pkg, 'ALLOW_EMPTY')
510                 write_if_exists(sf, pkg, 'FILES')
511                 write_if_exists(sf, pkg, 'pkg_postinst')
512                 write_if_exists(sf, pkg, 'pkg_postrm')
513                 write_if_exists(sf, pkg, 'pkg_preinst')
514                 write_if_exists(sf, pkg, 'pkg_prerm')
515                 sf.close()
516 }
517 emit_pkgdata[dirs] = "${STAGING_DIR}/pkgdata/runtime"
518
519 ldconfig_postinst_fragment() {
520 if [ x"$D" = "x" ]; then
521         ldconfig
522 fi
523 }
524
525 python package_do_shlibs() {
526         import os, re, os.path
527
528         exclude_shlibs = bb.data.getVar('EXCLUDE_FROM_SHLIBS', d, 0)
529         if exclude_shlibs:
530                 bb.note("not generating shlibs")
531                 return
532                 
533         lib_re = re.compile("^lib.*\.so")
534         libdir_re = re.compile(".*/lib$")
535
536         packages = bb.data.getVar('PACKAGES', d, 1)
537         if not packages:
538                 bb.debug(1, "no packages to build; not calculating shlibs")
539                 return
540
541         workdir = bb.data.getVar('WORKDIR', d, 1)
542         if not workdir:
543                 bb.error("WORKDIR not defined")
544                 return
545
546         staging = bb.data.getVar('STAGING_DIR', d, 1)
547         if not staging:
548                 bb.error("STAGING_DIR not defined")
549                 return
550
551         ver = bb.data.getVar('PV', d, 1)
552         if not ver:
553                 bb.error("PV not defined")
554                 return
555
556         target_sys = bb.data.getVar('TARGET_SYS', d, 1)
557         if not target_sys:
558                 bb.error("TARGET_SYS not defined")
559                 return
560
561         shlibs_dir = os.path.join(staging, target_sys, "shlibs")
562         old_shlibs_dir = os.path.join(staging, "shlibs")
563         bb.mkdirhier(shlibs_dir)
564
565         needed = {}
566         for pkg in packages.split():
567                 needs_ldconfig = False
568                 bb.debug(2, "calculating shlib provides for %s" % pkg)
569
570                 needed[pkg] = []
571                 sonames = list()
572                 top = os.path.join(workdir, "install", pkg)
573                 for root, dirs, files in os.walk(top):
574                         for file in files:
575                                 soname = None
576                                 path = os.path.join(root, file)
577                                 if os.access(path, os.X_OK) or lib_re.match(file):
578                                         cmd = bb.data.getVar('OBJDUMP', d, 1) + " -p " + path + " 2>/dev/null"
579                                         cmd = "PATH=\"%s\" %s" % (bb.data.getVar('PATH', d, 1), cmd)
580                                         fd = os.popen(cmd)
581                                         lines = fd.readlines()
582                                         fd.close()
583                                         for l in lines:
584                                                 m = re.match("\s+NEEDED\s+([^\s]*)", l)
585                                                 if m:
586                                                         needed[pkg].append(m.group(1))
587                                                 m = re.match("\s+SONAME\s+([^\s]*)", l)
588                                                 if m and not m.group(1) in sonames:
589                                                         sonames.append(m.group(1))
590                                                 if m and libdir_re.match(root):
591                                                         needs_ldconfig = True
592                 shlibs_file = os.path.join(shlibs_dir, pkg + ".list")
593                 if os.path.exists(shlibs_file):
594                         os.remove(shlibs_file)
595                 shver_file = os.path.join(shlibs_dir, pkg + ".ver")
596                 if os.path.exists(shver_file):
597                         os.remove(shver_file)
598                 if len(sonames):
599                         fd = open(shlibs_file, 'w')
600                         for s in sonames:
601                                 fd.write(s + '\n')
602                         fd.close()
603                         fd = open(shver_file, 'w')
604                         fd.write(ver + '\n')
605                         fd.close()
606                 if needs_ldconfig:
607                         bb.debug(1, 'adding ldconfig call to postinst for %s' % pkg)
608                         postinst = bb.data.getVar('pkg_postinst_%s' % pkg, d, 1) or bb.data.getVar('pkg_postinst', d, 1)
609                         if not postinst:
610                                 postinst = '#!/bin/sh\n'
611                         postinst += bb.data.getVar('ldconfig_postinst_fragment', d, 1)
612                         bb.data.setVar('pkg_postinst_%s' % pkg, postinst, d)
613
614         shlib_provider = {}
615         list_re = re.compile('^(.*)\.list$')
616         for dir in [old_shlibs_dir, shlibs_dir]: 
617                 if not os.path.exists(dir):
618                         continue
619                 for file in os.listdir(dir):
620                         m = list_re.match(file)
621                         if m:
622                                 dep_pkg = m.group(1)
623                                 fd = open(os.path.join(dir, file))
624                                 lines = fd.readlines()
625                                 fd.close()
626                                 ver_file = os.path.join(dir, dep_pkg + '.ver')
627                                 lib_ver = None
628                                 if os.path.exists(ver_file):
629                                         fd = open(ver_file)
630                                         lib_ver = fd.readline().rstrip()
631                                         fd.close()
632                                 for l in lines:
633                                         shlib_provider[l.rstrip()] = (dep_pkg, lib_ver)
634
635
636         for pkg in packages.split():
637                 bb.debug(2, "calculating shlib requirements for %s" % pkg)
638
639                 deps = list()
640                 for n in needed[pkg]:
641                         if n in shlib_provider.keys():
642                                 (dep_pkg, ver_needed) = shlib_provider[n]
643
644                                 if dep_pkg == pkg:
645                                         continue
646
647                                 if ver_needed:
648                                         dep = "%s (>= %s)" % (dep_pkg, ver_needed)
649                                 else:
650                                         dep = dep_pkg
651                                 if not dep in deps:
652                                         deps.append(dep)
653                         else:
654                                 bb.note("Couldn't find shared library provider for %s" % n)
655
656                 deps_file = os.path.join(workdir, "install", pkg + ".shlibdeps")
657                 if os.path.exists(deps_file):
658                         os.remove(deps_file)
659                 if len(deps):
660                         fd = open(deps_file, 'w')
661                         for dep in deps:
662                                 fd.write(dep + '\n')
663                         fd.close()
664 }
665
666 python package_do_pkgconfig () {
667         import re, os
668
669         packages = bb.data.getVar('PACKAGES', d, 1)
670         if not packages:
671                 bb.debug(1, "no packages to build; not calculating pkgconfig dependencies")
672                 return
673
674         workdir = bb.data.getVar('WORKDIR', d, 1)
675         if not workdir:
676                 bb.error("WORKDIR not defined")
677                 return
678
679         staging = bb.data.getVar('STAGING_DIR', d, 1)
680         if not staging:
681                 bb.error("STAGING_DIR not defined")
682                 return
683
684         target_sys = bb.data.getVar('TARGET_SYS', d, 1)
685         if not target_sys:
686                 bb.error("TARGET_SYS not defined")
687                 return
688
689         shlibs_dir = os.path.join(staging, target_sys, "shlibs")
690         old_shlibs_dir = os.path.join(staging, "shlibs")
691         bb.mkdirhier(shlibs_dir)
692
693         pc_re = re.compile('(.*)\.pc$')
694         var_re = re.compile('(.*)=(.*)')
695         field_re = re.compile('(.*): (.*)')
696
697         pkgconfig_provided = {}
698         pkgconfig_needed = {}
699         for pkg in packages.split():
700                 pkgconfig_provided[pkg] = []
701                 pkgconfig_needed[pkg] = []
702                 top = os.path.join(workdir, "install", pkg)
703                 for root, dirs, files in os.walk(top):
704                         for file in files:
705                                 m = pc_re.match(file)
706                                 if m:
707                                         pd = bb.data.init()
708                                         name = m.group(1)
709                                         pkgconfig_provided[pkg].append(name)
710                                         path = os.path.join(root, file)
711                                         if not os.access(path, os.R_OK):
712                                                 continue
713                                         f = open(path, 'r')
714                                         lines = f.readlines()
715                                         f.close()
716                                         for l in lines:
717                                                 m = var_re.match(l)
718                                                 if m:
719                                                         name = m.group(1)
720                                                         val = m.group(2)
721                                                         bb.data.setVar(name, bb.data.expand(val, pd), pd)
722                                                         continue
723                                                 m = field_re.match(l)
724                                                 if m:
725                                                         hdr = m.group(1)
726                                                         exp = bb.data.expand(m.group(2), pd)
727                                                         if hdr == 'Requires':
728                                                                 pkgconfig_needed[pkg] += exp.replace(',', ' ').split()
729
730         for pkg in packages.split():
731                 pkgs_file = os.path.join(shlibs_dir, pkg + ".pclist")
732                 if os.path.exists(pkgs_file):
733                         os.remove(pkgs_file)
734                 if pkgconfig_provided[pkg] != []:
735                         f = open(pkgs_file, 'w')
736                         for p in pkgconfig_provided[pkg]:
737                                 f.write('%s\n' % p)
738                         f.close()
739
740         for dir in [old_shlibs_dir, shlibs_dir]:
741                 if not os.path.exists(dir):
742                         continue
743                 for file in os.listdir(dir):
744                         m = re.match('^(.*)\.pclist$', file)
745                         if m:
746                                 pkg = m.group(1)
747                                 fd = open(os.path.join(dir, file))
748                                 lines = fd.readlines()
749                                 fd.close()
750                                 pkgconfig_provided[pkg] = []
751                                 for l in lines:
752                                         pkgconfig_provided[pkg].append(l.rstrip())
753
754         for pkg in packages.split():
755                 deps = []
756                 for n in pkgconfig_needed[pkg]:
757                         found = False
758                         for k in pkgconfig_provided.keys():
759                                 if n in pkgconfig_provided[k]:
760                                         if k != pkg and not (k in deps):
761                                                 deps.append(k)
762                                         found = True
763                         if found == False:
764                                 bb.note("couldn't find pkgconfig module '%s' in any package" % n)
765                 deps_file = os.path.join(workdir, "install", pkg + ".pcdeps")
766                 if os.path.exists(deps_file):
767                         os.remove(deps_file)
768                 if len(deps):
769                         fd = open(deps_file, 'w')
770                         for dep in deps:
771                                 fd.write(dep + '\n')
772                         fd.close()
773 }
774
775 python read_shlibdeps () {
776         packages = (bb.data.getVar('PACKAGES', d, 1) or "").split()
777         for pkg in packages:
778                 rdepends = explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, 0) or bb.data.getVar('RDEPENDS', d, 0) or "")
779                 shlibsfile = bb.data.expand("${WORKDIR}/install/" + pkg + ".shlibdeps", d)
780                 if os.access(shlibsfile, os.R_OK):
781                         fd = file(shlibsfile)
782                         lines = fd.readlines()
783                         fd.close()
784                         for l in lines:
785                                 rdepends.append(l.rstrip())
786                 pcfile = bb.data.expand("${WORKDIR}/install/" + pkg + ".pcdeps", d)
787                 if os.access(pcfile, os.R_OK):
788                         fd = file(pcfile)
789                         lines = fd.readlines()
790                         fd.close()
791                         for l in lines:
792                                 rdepends.append(l.rstrip())
793                 bb.data.setVar('RDEPENDS_' + pkg, " " + " ".join(rdepends), d)
794 }
795
796 python package_depchains() {
797         """
798         For a given set of prefix and postfix modifiers, make those packages
799         RRECOMMENDS on the corresponding packages for its DEPENDS.
800
801         Example:  If package A depends upon package B, and A's .bb emits an
802         A-dev package, this would make A-dev Recommends: B-dev.
803         """
804
805         packages  = bb.data.getVar('PACKAGES', d, 1)
806         postfixes = (bb.data.getVar('DEPCHAIN_POST', d, 1) or '').split()
807         prefixes  = (bb.data.getVar('DEPCHAIN_PRE', d, 1) or '').split()
808
809         def pkg_addrrecs(pkg, base, func, d):
810                 rdepends = explode_deps(bb.data.getVar('RDEPENDS_' + base, d, 1) or bb.data.getVar('RDEPENDS', d, 1) or "")
811                 # bb.note('rdepends for %s is %s' % (base, rdepends))
812                 rreclist = explode_deps(bb.data.getVar('RRECOMMENDS_' + pkg, d, 1) or bb.data.getVar('RRECOMMENDS', d, 1) or "")
813
814                 for depend in rdepends:
815                         split_depend = depend.split(' (')
816                         name = split_depend[0].strip()
817                         func(rreclist, name)
818
819                 bb.data.setVar('RRECOMMENDS_%s' % pkg, ' '.join(rreclist), d)
820
821         def packaged(pkg, d):
822                 return os.access(bb.data.expand('${STAGING_DIR}/pkgdata/runtime/%s.packaged' % pkg, d), os.R_OK)
823
824         for pkg in packages.split():
825                 for postfix in postfixes:
826                         def func(list, name):
827                                 pkg = '%s%s' % (name, postfix)
828                                 if not pkg in list:
829                                         if packaged(pkg, d):
830                                                 list.append(pkg)
831
832                         base = pkg[:-len(postfix)]
833                         if pkg.endswith(postfix):
834                                 pkg_addrrecs(pkg, base, func, d)
835                                 continue
836
837                 for prefix in prefixes:
838                         def func(list, name):
839                                 pkg = '%s%s' % (prefix, name)
840                                 if not pkg in list:
841                                         if packaged(pkg, d):
842                                                 list.append(pkg)
843
844                         base = pkg[len(prefix):]
845                         if pkg.startswith(prefix):
846                                 pkg_addrrecs(pkg, base, func, d)
847 }
848
849
850 PACKAGEFUNCS ?= "package_do_split_locales \
851                 populate_packages \
852                 package_do_shlibs \
853                 package_do_pkgconfig \
854                 read_shlibdeps \
855                 package_depchains \
856                 emit_pkgdata"
857
858 python package_do_package () {
859         for f in (bb.data.getVar('PACKAGEFUNCS', d, 1) or '').split():
860                 bb.build.exec_func(f, d)
861 }
862 # shlibs requires any DEPENDS to have already packaged for the *.list files
863 do_package[deptask] = "do_package"
864 do_package[dirs] = "${D}"
865 addtask package before do_build after do_install
866
867
868
869 PACKAGE_WRITE_FUNCS ?= "read_subpackage_metadata"
870
871 python package_do_package_write () {
872         for f in (bb.data.getVar('PACKAGE_WRITE_FUNCS', d, 1) or '').split():
873                 bb.build.exec_func(f, d)
874 }
875 do_package_write[dirs] = "${D}"
876 addtask package_write before do_build after do_package
877
878
879 EXPORT_FUNCTIONS do_package do_package_write
880
881
882 #
883 # Helper functions for the package writing classes
884 #
885
886 python package_mapping_rename_hook () {
887         """
888         Rewrite variables to account for package renaming in things
889         like debian.bbclass or manual PKG variable name changes
890         """
891         runtime_mapping_rename("RDEPENDS", d)
892         runtime_mapping_rename("RRECOMMENDS", d)
893         runtime_mapping_rename("RSUGGESTS", d)
894         runtime_mapping_rename("RPROVIDES", d)
895         runtime_mapping_rename("RREPLACES", d)
896         runtime_mapping_rename("RCONFLICTS", d)
897 }
898
899 EXPORT_FUNCTIONS mapping_rename_hook