linux-omap 2.6.39: sync with meta-texasinstruments again
[openembedded.git] / classes / utils.bbclass
blob936f7fdc76f5c89bdfeac4e0d63aeb643e63a619
1 # For compatibility
2 def uniq(iterable):
3     import oe.utils
4     return oe.utils.uniq(iterable)
6 def base_path_join(a, *p):
7     return oe.path.join(a, *p)
9 def base_path_relative(src, dest):
10     return oe.path.relative(src, dest)
12 def base_path_out(path, d):
13     return oe.path.format_display(path, d)
15 def base_read_file(filename):
16     return oe.utils.read_file(filename)
18 def base_ifelse(condition, iftrue = True, iffalse = False):
19     return oe.utils.ifelse(condition, iftrue, iffalse)
21 def base_conditional(variable, checkvalue, truevalue, falsevalue, d):
22     return oe.utils.conditional(variable, checkvalue, truevalue, falsevalue, d)
24 def base_less_or_equal(variable, checkvalue, truevalue, falsevalue, d):
25     return oe.utils.less_or_equal(variable, checkvalue, truevalue, falsevalue, d)
27 def base_version_less_or_equal(variable, checkvalue, truevalue, falsevalue, d):
28     return oe.utils.version_less_or_equal(variable, checkvalue, truevalue, falsevalue, d)
30 def base_contains(variable, checkvalues, truevalue, falsevalue, d):
31     return oe.utils.contains(variable, checkvalues, truevalue, falsevalue, d)
33 def base_both_contain(variable1, variable2, checkvalue, d):
34     return oe.utils.both_contain(variable1, variable2, checkvalue, d)
36 def base_prune_suffix(var, suffixes, d):
37     return oe.utils.prune_suffix(var, suffixes, d)
39 def oe_filter(f, str, d):
40     return oe.utils.str_filter(f, str, d)
42 def oe_filter_out(f, str, d):
43     return oe.utils.str_filter_out(f, str, d)
45 def machine_paths(d):
46     """List any existing machine specific filespath directories"""
47     machine = d.getVar("MACHINE", True)
48     filespathpkg = d.getVar("FILESPATHPKG", True).split(":")
49     for basepath in d.getVar("FILESPATHBASE", True).split(":"):
50         for pkgpath in filespathpkg:
51             machinepath = os.path.join(basepath, pkgpath, machine)
52             if os.path.isdir(machinepath):
53                 yield machinepath
55 def is_machine_specific(d):
56     """Determine whether the current recipe is machine specific"""
57     machinepaths = set(machine_paths(d))
58     urldatadict = bb.fetch.init(d.getVar("SRC_URI", True).split(), d, True)
59     for urldata in (urldata for urldata in urldatadict.itervalues()
60                     if urldata.type == "file"):
61         if any(urldata.localpath.startswith(mp + "/") for mp in machinepaths):
62             return True
64 def oe_popen_env(d):
65     env = {}
66     for v in d.keys():
67         if d.getVarFlag(v, "export"):
68             env[v] = d.getVar(v, True) or ""
69     return env
71 def oe_run(d, cmd, **kwargs):
72     import oe.process
73     kwargs["env"] = oe_popen_env(d)
74     return oe.process.run(cmd, **kwargs)
76 def oe_popen(d, cmd, **kwargs):
77     import oe.process
78     kwargs["env"] = oe_popen_env(d)
79     return oe.process.Popen(cmd, **kwargs)
81 def oe_system(d, cmd, **kwargs):
82     """ Popen based version of os.system. """
83     if not "shell" in kwargs:
84         kwargs["shell"] = True
85     return oe_popen(d, cmd, **kwargs).wait()
87 # for MD5/SHA handling
88 def base_chk_load_parser(config_paths):
89     import ConfigParser
90     parser = ConfigParser.ConfigParser()
91     if len(parser.read(config_paths)) < 1:
92         raise ValueError("no ini files could be found")
94     return parser
96 def setup_checksum_deps(d):
97     try:
98         import hashlib
99     except ImportError:
100         if d.getVar("PN", True) != "shasum-native":
101             depends = d.getVarFlag("do_fetch", "depends") or ""
102             d.setVarFlag("do_fetch", "depends", "%s %s" %
103                          (depends, "shasum-native:do_populate_sysroot"))
105 def base_get_hash_flags(params):
106     try:
107         name = params["name"]
108     except KeyError:
109         name = ""
110     if name:
111         md5flag = "%s.md5sum" % name
112         sha256flag = "%s.sha256sum" % name
113     else:
114         md5flag = "md5sum"
115         sha256flag = "sha256sum"
117     return (md5flag, sha256flag)
119 def base_chk_file_checksum(localpath, src_uri, expected_md5sum, expected_sha256sum, params, data):
120     strict_checking = True
121     if bb.data.getVar("OE_STRICT_CHECKSUMS", data, True) != "1":
122         strict_checking = False
123     if not os.path.exists(localpath):
124         localpath = base_path_out(localpath, data)
125         bb.note("The localpath does not exist '%s'" % localpath)
126         raise Exception("The path does not exist '%s'" % localpath)
128     md5data = bb.utils.md5_file(localpath)
129     sha256data = bb.utils.sha256_file(localpath)
130     if not sha256data:
131         try:
132             shapipe = os.popen('PATH=%s oe_sha256sum "%s"' % (bb.data.getVar('PATH', data, True), localpath))
133             sha256data = (shapipe.readline().split() or [ "" ])[0]
134             shapipe.close()
135         except OSError, e:
136             if strict_checking:
137                 raise Exception("Executing shasum failed")
138             else:
139                 bb.note("Executing shasum failed")
141     if (expected_md5sum == None or expected_md5sum == None):
142         from string import maketrans
143         trtable = maketrans("", "")
144         uname = src_uri.split("/")[-1].translate(trtable, "-+._")
146         try:
147             ufile = open("%s/%s.sum" % (bb.data.getVar("TMPDIR", data, 1), uname), "wt")
148         except:
149             return False
151         if not ufile:
152             raise Exception("Creating %s.sum failed" % uname)
154         (md5flag, sha256flag) = base_get_hash_flags(params)
155         ufile.write("SRC_URI[%s] = \"%s\"\nSRC_URI[%s] = \"%s\"\n" % (md5flag, md5data, sha256flag, sha256data))
156         ufile.close()
157         bb.note("This package has no checksums, please add to recipe")
158         bb.note("\nSRC_URI[%s] = \"%s\"\nSRC_URI[%s] = \"%s\"\n" % (md5flag, md5data, sha256flag, sha256data))
160         # fail for strict, continue for disabled strict checksums
161         return not strict_checking
163     if (expected_md5sum and expected_md5sum != md5data) or (expected_sha256sum and expected_sha256sum != sha256data):
164         (md5flag, sha256flag) = base_get_hash_flags(params)
165         bb.note("The checksums for '%s' did not match.\nExpected MD5: '%s' and Got: '%s'\nExpected SHA256: '%s' and Got: '%s'" % (localpath, expected_md5sum, md5data, expected_sha256sum, sha256data))
166         bb.note("Your checksums:\nSRC_URI[%s] = \"%s\"\nSRC_URI[%s] = \"%s\"\n" % (md5flag, md5data, sha256flag, sha256data))
167         return False
169     return True
171 def base_get_checksums(pn, pv, src_uri, localpath, params, data):
172     # Try checksum from recipe and then parse checksums.ini
173     # and try PN-PV-SRC_URI first and then try PN-SRC_URI
174     # we rely on the get method to create errors
175     (md5flag, sha256flag) = base_get_hash_flags(params)
176     expected_md5sum = bb.data.getVarFlag("SRC_URI", md5flag, data)
177     expected_sha256sum = bb.data.getVarFlag("SRC_URI", sha256flag, data)
179     return (expected_md5sum, expected_sha256sum)
181 def base_chk_file(pn, pv, src_uri, localpath, params, data):
182     (expected_md5sum, expected_sha256sum) = base_get_checksums(pn, pv, src_uri, localpath, params, data)
183     return base_chk_file_checksum(localpath, src_uri, expected_md5sum, expected_sha256sum, params, data)
185 oedebug() {
186         test $# -ge 2 || {
187                 echo "Usage: oedebug level \"message\""
188                 exit 1
189         }
191         test ${OEDEBUG:-0} -ge $1 && {
192                 shift
193                 echo "DEBUG:" $*
194         }
197 oe_soinstall() {
198         # Purpose: Install shared library file and
199         #          create the necessary links
200         # Example:
201         #
202         # oe_
203         #
204         #oenote installing shared library $1 to $2
205         #
206         libname=`basename $1`
207         install -m 755 $1 $2/$libname
208         sonamelink=`${HOST_PREFIX}readelf -d $1 |grep 'Library soname:' |sed -e 's/.*\[\(.*\)\].*/\1/'`
209         solink=`echo $libname | sed -e 's/\.so\..*/.so/'`
210         ln -sf $libname $2/$sonamelink
211         ln -sf $libname $2/$solink
214 oe_libinstall() {
215         # Purpose: Install a library, in all its forms
216         # Example
217         #
218         # oe_libinstall libltdl ${STAGING_LIBDIR}/
219         # oe_libinstall -C src/libblah libblah ${D}/${libdir}/
220         dir=""
221         libtool=""
222         silent=""
223         require_static=""
224         require_shared=""
225         staging_install=""
226         while [ "$#" -gt 0 ]; do
227                 case "$1" in
228                 -C)
229                         shift
230                         dir="$1"
231                         ;;
232                 -s)
233                         silent=1
234                         ;;
235                 -a)
236                         require_static=1
237                         ;;
238                 -so)
239                         require_shared=1
240                         ;;
241                 -*)
242                         oefatal "oe_libinstall: unknown option: $1"
243                         ;;
244                 *)
245                         break;
246                         ;;
247                 esac
248                 shift
249         done
251         libname="$1"
252         shift
253         destpath="$1"
254         if [ -z "$destpath" ]; then
255                 oefatal "oe_libinstall: no destination path specified"
256         fi
257         if echo "$destpath/" | egrep '^${STAGING_LIBDIR}/' >/dev/null
258         then
259                 staging_install=1
260         fi
262         __runcmd () {
263                 if [ -z "$silent" ]; then
264                         echo >&2 "oe_libinstall: $*"
265                 fi
266                 $*
267         }
269         if [ -z "$dir" ]; then
270                 dir=`pwd`
271         fi
273         dotlai=$libname.lai
275         # Sanity check that the libname.lai is unique
276         number_of_files=`(cd $dir; find . -name "$dotlai") | wc -l`
277         if [ $number_of_files -gt 1 ]; then
278                 oefatal "oe_libinstall: $dotlai is not unique in $dir"
279         fi
282         dir=$dir`(cd $dir;find . -name "$dotlai") | sed "s/^\.//;s/\/$dotlai\$//;q"`
283         olddir=`pwd`
284         __runcmd cd $dir
286         lafile=$libname.la
288         # If such file doesn't exist, try to cut version suffix
289         if [ ! -f "$lafile" ]; then
290                 libname1=`echo "$libname" | sed 's/-[0-9.]*$//'`
291                 lafile1=$libname.la
292                 if [ -f "$lafile1" ]; then
293                         libname=$libname1
294                         lafile=$lafile1
295                 fi
296         fi
298         if [ -f "$lafile" ]; then
299                 # libtool archive
300                 eval `cat $lafile|grep "^library_names="`
301                 libtool=1
302         else
303                 library_names="$libname.so* $libname.dll.a $libname.*.dylib"
304         fi
306         __runcmd install -d $destpath/
307         dota=$libname.a
308         if [ -f "$dota" -o -n "$require_static" ]; then
309                 __runcmd install -m 0644 $dota $destpath/
310         fi
311         if [ -f "$dotlai" -a -n "$libtool" ]; then
312                 if [ -n "$staging_install" -a "${LIBTOOL_HAS_SYSROOT}" = "no" ]
313                 then
314                         # stop libtool using the final directory name for libraries
315                         # in staging:
316                         __runcmd rm -f $destpath/$libname.la
317                         __runcmd sed -e 's/^installed=yes$/installed=no/' \
318                                      -e '/^dependency_libs=/s,${WORKDIR}[[:alnum:]/\._+-]*/\([[:alnum:]\._+-]*\),${STAGING_LIBDIR}/\1,g' \
319                                      -e "/^dependency_libs=/s,\([[:space:]']\)${libdir},\1${STAGING_LIBDIR},g" \
320                                      $dotlai >$destpath/$libname.la
321                 else
322                         __runcmd install -m 0644 $dotlai $destpath/$libname.la
323                 fi
324         fi
326         for name in $library_names; do
327                 files=`eval echo $name`
328                 for f in $files; do
329                         if [ ! -e "$f" ]; then
330                                 if [ -n "$libtool" ]; then
331                                         oefatal "oe_libinstall: $dir/$f not found."
332                                 fi
333                         elif [ -L "$f" ]; then
334                                 __runcmd cp -P "$f" $destpath/
335                         elif [ ! -L "$f" ]; then
336                                 libfile="$f"
337                                 __runcmd install -m 0755 $libfile $destpath/
338                         fi
339                 done
340         done
342         if [ -z "$libfile" ]; then
343                 if  [ -n "$require_shared" ]; then
344                         oefatal "oe_libinstall: unable to locate shared library"
345                 fi
346         elif [ -z "$libtool" ]; then
347                 # special case hack for non-libtool .so.#.#.# links
348                 baselibfile=`basename "$libfile"`
349                 if (echo $baselibfile | grep -qE '^lib.*\.so\.[0-9.]*$'); then
350                         sonamelink=`${HOST_PREFIX}readelf -d $libfile |grep 'Library soname:' |sed -e 's/.*\[\(.*\)\].*/\1/'`
351                         solink=`echo $baselibfile | sed -e 's/\.so\..*/.so/'`
352                         if [ -n "$sonamelink" -a x"$baselibfile" != x"$sonamelink" ]; then
353                                 __runcmd ln -sf $baselibfile $destpath/$sonamelink
354                         fi
355                         __runcmd ln -sf $baselibfile $destpath/$solink
356                 fi
357         fi
359         __runcmd cd "$olddir"
362 oe_machinstall() {
363         # Purpose: Install machine dependent files, if available
364         #          If not available, check if there is a default
365         #          If no default, just touch the destination
366         # Example:
367         #                $1  $2   $3         $4
368         # oe_machinstall -m 0644 fstab ${D}/etc/fstab
369         #
370         # TODO: Check argument number?
371         #
372         filename=`basename $3`
373         dirname=`dirname $3`
375         for o in `echo ${OVERRIDES} | tr ':' ' '`; do
376                 if [ -e $dirname/$o/$filename ]; then
377                         oenote $dirname/$o/$filename present, installing to $4
378                         install $1 $2 $dirname/$o/$filename $4
379                         return
380                 fi
381         done
382 #       oenote overrides specific file NOT present, trying default=$3...
383         if [ -e $3 ]; then
384                 oenote $3 present, installing to $4
385                 install $1 $2 $3 $4
386         else
387                 oenote $3 NOT present, touching empty $4
388                 touch $4
389         fi
392 create_wrapper () {
393    # Create a wrapper script
394    #
395    # These are useful to work around relocation issues, by setting environment
396    # variables which point to paths in the filesystem.
397    #
398    # Usage: create_wrapper FILENAME [[VAR=VALUE]..]
400    cmd=$1
401    shift
403    # run echo via env to test syntactic validity of the variable arguments
404    env $@ echo "Generating wrapper script for $cmd"
406    mv $cmd $cmd.real
407    cmdname=`basename $cmd`.real
408    cat <<END >$cmd
409 #!/bin/sh
410 realpath=\`readlink -fn \$0\`
411 exec env $@ \`dirname \$realpath\`/$cmdname "\$@"
413    chmod +x $cmd
416 def check_app_exists(app, d):
417         from bb import which, data
419         app = data.expand(app, d)
420         path = data.getVar('PATH', d, 1)
421         return bool(which(path, app))
423 def explode_deps(s):
424         r = []
425         l = s.split()
426         flag = False
427         for i in l:
428                 if i[0] == '(':
429                         flag = True
430                         j = []
431                 if flag:
432                         j.append(i)
433                         if i.endswith(')'):
434                                 flag = False
435                                 r[-1] += ' ' + ' '.join(j)
436                 else:
437                         r.append(i)
438         return r
440 def base_set_filespath(path, d):
441         bb.note("base_set_filespath usage is deprecated, %s should be fixed" % d.getVar("P", 1))
442         filespath = []
443         # The ":" ensures we have an 'empty' override
444         overrides = (bb.data.getVar("OVERRIDES", d, 1) or "") + ":"
445         for p in path:
446                 for o in overrides.split(":"):
447                         filespath.append(os.path.join(p, o))
448         return ":".join(filespath)
450 # These directory stack functions are based upon the versions in the Korn
451 # Shell documentation - http://docstore.mik.ua/orelly/unix3/korn/ch04_07.htm.
452 dirs() {
453     echo "$_DIRSTACK"
456 pushd() {
457     dirname=$1
458     cd ${dirname:?"missing directory name."} || return 1
459     _DIRSTACK="$PWD $_DIRSTACK"
460     echo "$_DIRSTACK"
463 popd() {
464     _DIRSTACK=${_DIRSTACK#* }
465     top=${_DIRSTACK%% *}
466     cd $top || return 1
467     echo "$PWD"