base: erk, don't remove do_setscene from EXPORT_FUNCTIONS, silly
[openembedded.git] / classes / utils.bbclass
1 # like os.path.join but doesn't treat absolute RHS specially
2 def base_path_join(a, *p):
3     path = a
4     for b in p:
5         if path == '' or path.endswith('/'):
6             path +=  b
7         else:
8             path += '/' + b
9     return path
10
11 def base_path_relative(src, dest):
12     """ Return a relative path from src to dest.
13
14     >>> base_path_relative("/usr/bin", "/tmp/foo/bar")
15     ../../tmp/foo/bar
16
17     >>> base_path_relative("/usr/bin", "/usr/lib")
18     ../lib
19
20     >>> base_path_relative("/tmp", "/tmp/foo/bar")
21     foo/bar
22     """
23     from os.path import sep, pardir, normpath, commonprefix
24
25     destlist = normpath(dest).split(sep)
26     srclist = normpath(src).split(sep)
27
28     # Find common section of the path
29     common = commonprefix([destlist, srclist])
30     commonlen = len(common)
31
32     # Climb back to the point where they differentiate
33     relpath = [ pardir ] * (len(srclist) - commonlen)
34     if commonlen < len(destlist):
35         # Add remaining portion
36         relpath += destlist[commonlen:]
37
38     return sep.join(relpath)
39
40 def base_path_out(path, d):
41     """ Prepare a path for display to the user. """
42     rel = base_path_relative(d.getVar("TOPDIR", 1), path)
43     if len(rel) > len(path):
44         return path
45     else:
46         return rel
47
48 # for MD5/SHA handling
49 def base_chk_load_parser(config_paths):
50     import ConfigParser
51     parser = ConfigParser.ConfigParser()
52     if len(parser.read(config_paths)) < 1:
53         raise ValueError("no ini files could be found")
54
55     return parser
56
57 def base_chk_file_vars(parser, localpath, params, data):
58     try:
59         name = params["name"]
60     except KeyError:
61         return False
62     if name:
63         md5flag = "%s.md5sum" % name
64         sha256flag = "%s.sha256sum" % name
65     else:
66         md5flag = "md5sum"
67         sha256flag = "sha256sum"
68     want_md5sum = bb.data.getVarFlag("SRC_URI", md5flag, data)
69     want_sha256sum = bb.data.getVarFlag("SRC_URI", sha256flag, data)
70
71     if (want_sha256sum == None and want_md5sum == None):
72         # no checksums to check, nothing to do
73         return False
74
75     if not os.path.exists(localpath):
76         localpath = base_path_out(localpath, data)
77         bb.note("The localpath does not exist '%s'" % localpath)
78         raise Exception("The path does not exist '%s'" % localpath)
79
80     if want_md5sum:
81         try:
82             md5pipe = os.popen('PATH=%s md5sum "%s"' % (bb.data.getVar('PATH', data, True), localpath))
83             md5data = (md5pipe.readline().split() or [ "" ])[0]
84             md5pipe.close()
85         except OSError, e:
86             raise Exception("Executing md5sum failed")
87         if want_md5sum != md5data:
88             bb.note("The MD5Sums did not match. Wanted: '%s' and Got: '%s'" % (want_md5sum, md5data))
89             raise Exception("MD5 Sums do not match. Wanted: '%s' Got: '%s'" % (want_md5sum, md5data))
90
91     if want_sha256sum:
92         try:
93             shapipe = os.popen('PATH=%s oe_sha256sum "%s"' % (bb.data.getVar('PATH', data, True), localpath))
94             sha256data = (shapipe.readline().split() or [ "" ])[0]
95             shapipe.close()
96         except OSError, e:
97             raise Exception("Executing shasum failed")
98         if want_sha256sum != sha256data:
99             bb.note("The SHA256Sums did not match. Wanted: '%s' and Got: '%s'" % (want_sha256sum, sha256data))
100             raise Exception("SHA256 Sums do not match. Wanted: '%s' Got: '%s'" % (want_sha256sum, sha256data))
101
102     return True
103
104
105 def base_chk_file(parser, pn, pv, src_uri, localpath, data):
106     no_checksum = False
107     # Try PN-PV-SRC_URI first and then try PN-SRC_URI
108     # we rely on the get method to create errors
109     pn_pv_src = "%s-%s-%s" % (pn,pv,src_uri)
110     pn_src    = "%s-%s" % (pn,src_uri)
111     if parser.has_section(pn_pv_src):
112         md5    = parser.get(pn_pv_src, "md5")
113         sha256 = parser.get(pn_pv_src, "sha256")
114     elif parser.has_section(pn_src):
115         md5    = parser.get(pn_src, "md5")
116         sha256 = parser.get(pn_src, "sha256")
117     elif parser.has_section(src_uri):
118         md5    = parser.get(src_uri, "md5")
119         sha256 = parser.get(src_uri, "sha256")
120     else:
121         no_checksum = True
122
123     # md5 and sha256 should be valid now
124     if not os.path.exists(localpath):
125         localpath = base_path_out(localpath, data)
126         bb.note("The localpath does not exist '%s'" % localpath)
127         raise Exception("The path does not exist '%s'" % localpath)
128
129
130     # call md5(sum) and shasum
131     try:
132         md5pipe = os.popen('PATH=%s md5sum "%s"' % (bb.data.getVar('PATH', data, True), localpath))
133         md5data = (md5pipe.readline().split() or [ "" ])[0]
134         md5pipe.close()
135     except OSError:
136         raise Exception("Executing md5sum failed")
137
138     try:
139         shapipe = os.popen('PATH=%s oe_sha256sum "%s"' % (bb.data.getVar('PATH', data, True), localpath))
140         shadata = (shapipe.readline().split() or [ "" ])[0]
141         shapipe.close()
142     except OSError:
143         raise Exception("Executing shasum failed")
144
145     if no_checksum == True:     # we do not have conf/checksums.ini entry
146         try:
147             file = open("%s/checksums.ini" % bb.data.getVar("TMPDIR", data, 1), "a")
148         except:
149             return False
150
151         if not file:
152             raise Exception("Creating checksums.ini failed")
153         
154         file.write("[%s]\nmd5=%s\nsha256=%s\n\n" % (src_uri, md5data, shadata))
155         file.close()
156
157         from string import maketrans
158         trtable = maketrans("", "")
159         uname = src_uri.split("/")[-1].translate(trtable, "-+._")
160
161         try:
162             ufile = open("%s/%s.sum" % (bb.data.getVar("TMPDIR", data, 1), uname), "wt")
163         except:
164             return False
165
166         if not ufile:
167             raise Exception("Creating %s.sum failed" % uname)
168
169         ufile.write("SRC_URI = \"%s;name=%s\"\nSRC_URI[%s.md5sum] = \"%s\"\nSRC_URI[%s.sha256sum] = \"%s\"\n" % (src_uri, uname, uname, md5data, uname, shadata))
170         ufile.close()
171
172         if not bb.data.getVar("OE_STRICT_CHECKSUMS",data, True):
173             bb.note("This package has no entry in checksums.ini, please add one")
174             bb.note("\n[%s]\nmd5=%s\nsha256=%s" % (src_uri, md5data, shadata))
175             bb.note("This package has no checksums in corresponding recipe, please add")
176             bb.note("SRC_URI = \"%s;name=%s\"\nSRC_URI[%s.md5sum] = \"%s\"\nSRC_URI[%s.sha256sum] = \"%s\"\n" % (src_uri, uname, uname, md5data, uname, shadata))
177             return True
178         else:
179             bb.note("Missing checksum")
180             return False
181
182     if not md5 == md5data:
183         bb.note("The MD5Sums did not match. Wanted: '%s' and Got: '%s'" % (md5,md5data))
184         raise Exception("MD5 Sums do not match. Wanted: '%s' Got: '%s'" % (md5, md5data))
185
186     if not sha256 == shadata:
187         bb.note("The SHA256 Sums do not match. Wanted: '%s' Got: '%s'" % (sha256,shadata))
188         raise Exception("SHA256 Sums do not match. Wanted: '%s' Got: '%s'" % (sha256, shadata))
189
190     return True
191
192 def base_read_file(filename):
193         try:
194                 f = file( filename, "r" )
195         except IOError, reason:
196                 return "" # WARNING: can't raise an error now because of the new RDEPENDS handling. This is a bit ugly. :M:
197         else:
198                 return f.read().strip()
199         return None
200
201 def base_ifelse(condition, iftrue = True, iffalse = False):
202     if condition:
203         return iftrue
204     else:
205         return iffalse
206
207 def base_conditional(variable, checkvalue, truevalue, falsevalue, d):
208         if bb.data.getVar(variable,d,1) == checkvalue:
209                 return truevalue
210         else:
211                 return falsevalue
212
213 def base_less_or_equal(variable, checkvalue, truevalue, falsevalue, d):
214         if float(bb.data.getVar(variable,d,1)) <= float(checkvalue):
215                 return truevalue
216         else:
217                 return falsevalue
218
219 def base_version_less_or_equal(variable, checkvalue, truevalue, falsevalue, d):
220     result = bb.vercmp(bb.data.getVar(variable,d,True), checkvalue)
221     if result <= 0:
222         return truevalue
223     else:
224         return falsevalue
225
226 def base_contains(variable, checkvalues, truevalue, falsevalue, d):
227         val = bb.data.getVar(variable,d,1)
228         if not val:
229                 return falsevalue
230         matches = 0
231         if type(checkvalues).__name__ == "str":
232                 checkvalues = [checkvalues]
233         for value in checkvalues:
234                 if val.find(value) != -1:
235                         matches = matches + 1
236         if matches == len(checkvalues):
237                 return truevalue
238         return falsevalue
239
240 def base_both_contain(variable1, variable2, checkvalue, d):
241        if bb.data.getVar(variable1,d,1).find(checkvalue) != -1 and bb.data.getVar(variable2,d,1).find(checkvalue) != -1:
242                return checkvalue
243        else:
244                return ""
245
246 def base_prune_suffix(var, suffixes, d):
247     # See if var ends with any of the suffixes listed and 
248     # remove it if found
249     for suffix in suffixes:
250         if var.endswith(suffix):
251             return var.replace(suffix, "")
252     return var
253
254 def oe_filter(f, str, d):
255         from re import match
256         return " ".join(filter(lambda x: match(f, x, 0), str.split()))
257
258 def oe_filter_out(f, str, d):
259         from re import match
260         return " ".join(filter(lambda x: not match(f, x, 0), str.split()))
261
262 oedebug() {
263         test $# -ge 2 || {
264                 echo "Usage: oedebug level \"message\""
265                 exit 1
266         }
267
268         test ${OEDEBUG:-0} -ge $1 && {
269                 shift
270                 echo "DEBUG:" $*
271         }
272 }
273
274 oe_soinstall() {
275         # Purpose: Install shared library file and
276         #          create the necessary links
277         # Example:
278         #
279         # oe_
280         #
281         #oenote installing shared library $1 to $2
282         #
283         libname=`basename $1`
284         install -m 755 $1 $2/$libname
285         sonamelink=`${HOST_PREFIX}readelf -d $1 |grep 'Library soname:' |sed -e 's/.*\[\(.*\)\].*/\1/'`
286         solink=`echo $libname | sed -e 's/\.so\..*/.so/'`
287         ln -sf $libname $2/$sonamelink
288         ln -sf $libname $2/$solink
289 }
290
291 oe_libinstall() {
292         # Purpose: Install a library, in all its forms
293         # Example
294         #
295         # oe_libinstall libltdl ${STAGING_LIBDIR}/
296         # oe_libinstall -C src/libblah libblah ${D}/${libdir}/
297         dir=""
298         libtool=""
299         silent=""
300         require_static=""
301         require_shared=""
302         staging_install=""
303         while [ "$#" -gt 0 ]; do
304                 case "$1" in
305                 -C)
306                         shift
307                         dir="$1"
308                         ;;
309                 -s)
310                         silent=1
311                         ;;
312                 -a)
313                         require_static=1
314                         ;;
315                 -so)
316                         require_shared=1
317                         ;;
318                 -*)
319                         oefatal "oe_libinstall: unknown option: $1"
320                         ;;
321                 *)
322                         break;
323                         ;;
324                 esac
325                 shift
326         done
327
328         libname="$1"
329         shift
330         destpath="$1"
331         if [ -z "$destpath" ]; then
332                 oefatal "oe_libinstall: no destination path specified"
333         fi
334         if echo "$destpath/" | egrep '^${STAGING_LIBDIR}/' >/dev/null
335         then
336                 staging_install=1
337         fi
338
339         __runcmd () {
340                 if [ -z "$silent" ]; then
341                         echo >&2 "oe_libinstall: $*"
342                 fi
343                 $*
344         }
345
346         if [ -z "$dir" ]; then
347                 dir=`pwd`
348         fi
349
350         dotlai=$libname.lai
351
352         # Sanity check that the libname.lai is unique
353         number_of_files=`(cd $dir; find . -name "$dotlai") | wc -l`
354         if [ $number_of_files -gt 1 ]; then
355                 oefatal "oe_libinstall: $dotlai is not unique in $dir"
356         fi
357
358
359         dir=$dir`(cd $dir;find . -name "$dotlai") | sed "s/^\.//;s/\/$dotlai\$//;q"`
360         olddir=`pwd`
361         __runcmd cd $dir
362
363         lafile=$libname.la
364
365         # If such file doesn't exist, try to cut version suffix
366         if [ ! -f "$lafile" ]; then
367                 libname1=`echo "$libname" | sed 's/-[0-9.]*$//'`
368                 lafile1=$libname.la
369                 if [ -f "$lafile1" ]; then
370                         libname=$libname1
371                         lafile=$lafile1
372                 fi
373         fi
374
375         if [ -f "$lafile" ]; then
376                 # libtool archive
377                 eval `cat $lafile|grep "^library_names="`
378                 libtool=1
379         else
380                 library_names="$libname.so* $libname.dll.a"
381         fi
382
383         __runcmd install -d $destpath/
384         dota=$libname.a
385         if [ -f "$dota" -o -n "$require_static" ]; then
386                 __runcmd install -m 0644 $dota $destpath/
387         fi
388         if [ -f "$dotlai" -a -n "$libtool" ]; then
389                 if test -n "$staging_install"
390                 then
391                         # stop libtool using the final directory name for libraries
392                         # in staging:
393                         __runcmd rm -f $destpath/$libname.la
394                         __runcmd sed -e 's/^installed=yes$/installed=no/' \
395                                      -e '/^dependency_libs=/s,${WORKDIR}[[:alnum:]/\._+-]*/\([[:alnum:]\._+-]*\),${STAGING_LIBDIR}/\1,g' \
396                                      -e "/^dependency_libs=/s,\([[:space:]']\)${libdir},\1${STAGING_LIBDIR},g" \
397                                      $dotlai >$destpath/$libname.la
398                 else
399                         __runcmd install -m 0644 $dotlai $destpath/$libname.la
400                 fi
401         fi
402
403         for name in $library_names; do
404                 files=`eval echo $name`
405                 for f in $files; do
406                         if [ ! -e "$f" ]; then
407                                 if [ -n "$libtool" ]; then
408                                         oefatal "oe_libinstall: $dir/$f not found."
409                                 fi
410                         elif [ -L "$f" ]; then
411                                 __runcmd cp -P "$f" $destpath/
412                         elif [ ! -L "$f" ]; then
413                                 libfile="$f"
414                                 __runcmd install -m 0755 $libfile $destpath/
415                         fi
416                 done
417         done
418
419         if [ -z "$libfile" ]; then
420                 if  [ -n "$require_shared" ]; then
421                         oefatal "oe_libinstall: unable to locate shared library"
422                 fi
423         elif [ -z "$libtool" ]; then
424                 # special case hack for non-libtool .so.#.#.# links
425                 baselibfile=`basename "$libfile"`
426                 if (echo $baselibfile | grep -qE '^lib.*\.so\.[0-9.]*$'); then
427                         sonamelink=`${HOST_PREFIX}readelf -d $libfile |grep 'Library soname:' |sed -e 's/.*\[\(.*\)\].*/\1/'`
428                         solink=`echo $baselibfile | sed -e 's/\.so\..*/.so/'`
429                         if [ -n "$sonamelink" -a x"$baselibfile" != x"$sonamelink" ]; then
430                                 __runcmd ln -sf $baselibfile $destpath/$sonamelink
431                         fi
432                         __runcmd ln -sf $baselibfile $destpath/$solink
433                 fi
434         fi
435
436         __runcmd cd "$olddir"
437 }
438
439 oe_machinstall() {
440         # Purpose: Install machine dependent files, if available
441         #          If not available, check if there is a default
442         #          If no default, just touch the destination
443         # Example:
444         #                $1  $2   $3         $4
445         # oe_machinstall -m 0644 fstab ${D}/etc/fstab
446         #
447         # TODO: Check argument number?
448         #
449         filename=`basename $3`
450         dirname=`dirname $3`
451
452         for o in `echo ${OVERRIDES} | tr ':' ' '`; do
453                 if [ -e $dirname/$o/$filename ]; then
454                         oenote $dirname/$o/$filename present, installing to $4
455                         install $1 $2 $dirname/$o/$filename $4
456                         return
457                 fi
458         done
459 #       oenote overrides specific file NOT present, trying default=$3...
460         if [ -e $3 ]; then
461                 oenote $3 present, installing to $4
462                 install $1 $2 $3 $4
463         else
464                 oenote $3 NOT present, touching empty $4
465                 touch $4
466         fi
467 }
468
469 def check_app_exists(app, d):
470         from bb import which, data
471
472         app = data.expand(app, d)
473         path = data.getVar('PATH', d, 1)
474         return len(which(path, app)) != 0
475
476 def explode_deps(s):
477         return bb.utils.explode_deps(s)
478
479 def base_set_filespath(path, d):
480         bb.note("base_set_filespath usage is deprecated, %s should be fixed" % d.getVar("P", 1))
481         filespath = []
482         # The ":" ensures we have an 'empty' override
483         overrides = (bb.data.getVar("OVERRIDES", d, 1) or "") + ":"
484         for p in path:
485                 for o in overrides.split(":"):
486                         filespath.append(os.path.join(p, o))
487         return ":".join(filespath)