dbus-hlid: bump
[openembedded.git] / classes / utils.bbclass
blob2fa6204bfa9e70af12fbf9df5b6502085e323415
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 = d.getVar("__oe_popen_env", False)
66     if env is None:
67         env = {}
68         for v in d.keys():
69             if d.getVarFlag(v, "export"):
70                 env[v] = d.getVar(v, True) or ""
71         d.setVar("__oe_popen_env", env)
72     return env
74 def oe_run(d, cmd, **kwargs):
75     import oe.process
76     kwargs["env"] = oe_popen_env(d)
77     return oe.process.run(cmd, **kwargs)
79 def oe_popen(d, cmd, **kwargs):
80     import oe.process
81     kwargs["env"] = oe_popen_env(d)
82     return oe.process.Popen(cmd, **kwargs)
84 def oe_system(d, cmd, **kwargs):
85     """ Popen based version of os.system. """
86     if not "shell" in kwargs:
87         kwargs["shell"] = True
88     return oe_popen(d, cmd, **kwargs).wait()
90 # for MD5/SHA handling
91 def base_chk_load_parser(config_paths):
92     import ConfigParser
93     parser = ConfigParser.ConfigParser()
94     if len(parser.read(config_paths)) < 1:
95         raise ValueError("no ini files could be found")
97     return parser
99 def setup_checksum_deps(d):
100     try:
101         import hashlib
102     except ImportError:
103         if d.getVar("PN", True) != "shasum-native":
104             depends = d.getVarFlag("do_fetch", "depends") or ""
105             d.setVarFlag("do_fetch", "depends", "%s %s" %
106                          (depends, "shasum-native:do_populate_sysroot"))
108 def base_get_hash_flags(params):
109     try:
110         name = params["name"]
111     except KeyError:
112         name = ""
113     if name:
114         md5flag = "%s.md5sum" % name
115         sha256flag = "%s.sha256sum" % name
116     else:
117         md5flag = "md5sum"
118         sha256flag = "sha256sum"
120     return (md5flag, sha256flag)
122 def base_chk_file_checksum(localpath, src_uri, expected_md5sum, expected_sha256sum, params, data):
123     strict_checking = True
124     if bb.data.getVar("OE_STRICT_CHECKSUMS", data, True) != "1":
125         strict_checking = False
126     if not os.path.exists(localpath):
127         localpath = base_path_out(localpath, data)
128         bb.note("The localpath does not exist '%s'" % localpath)
129         raise Exception("The path does not exist '%s'" % localpath)
131     md5data = bb.utils.md5_file(localpath)
132     sha256data = bb.utils.sha256_file(localpath)
133     if not sha256data:
134         try:
135             shapipe = os.popen('PATH=%s oe_sha256sum "%s"' % (bb.data.getVar('PATH', data, True), localpath))
136             sha256data = (shapipe.readline().split() or [ "" ])[0]
137             shapipe.close()
138         except OSError, e:
139             if strict_checking:
140                 raise Exception("Executing shasum failed")
141             else:
142                 bb.note("Executing shasum failed")
144     if (expected_md5sum == None or expected_md5sum == None):
145         from string import maketrans
146         trtable = maketrans("", "")
147         uname = src_uri.split("/")[-1].translate(trtable, "-+._")
149         try:
150             ufile = open("%s/%s.sum" % (bb.data.getVar("TMPDIR", data, 1), uname), "wt")
151         except:
152             return False
154         if not ufile:
155             raise Exception("Creating %s.sum failed" % uname)
157         (md5flag, sha256flag) = base_get_hash_flags(params)
158         ufile.write("SRC_URI[%s] = \"%s\"\nSRC_URI[%s] = \"%s\"\n" % (md5flag, md5data, sha256flag, sha256data))
159         ufile.close()
160         bb.note("This package has no checksums, please add to recipe")
161         bb.note("\nSRC_URI[%s] = \"%s\"\nSRC_URI[%s] = \"%s\"\n" % (md5flag, md5data, sha256flag, sha256data))
163         # fail for strict, continue for disabled strict checksums
164         return not strict_checking
166     if (expected_md5sum and expected_md5sum != md5data) or (expected_sha256sum and expected_sha256sum != sha256data):
167         (md5flag, sha256flag) = base_get_hash_flags(params)
168         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))
169         bb.note("Your checksums:\nSRC_URI[%s] = \"%s\"\nSRC_URI[%s] = \"%s\"\n" % (md5flag, md5data, sha256flag, sha256data))
170         return False
172     return True
174 def base_get_checksums(pn, pv, src_uri, localpath, params, data):
175     # Try checksum from recipe and then parse checksums.ini
176     # and try PN-PV-SRC_URI first and then try PN-SRC_URI
177     # we rely on the get method to create errors
178     (md5flag, sha256flag) = base_get_hash_flags(params)
179     expected_md5sum = bb.data.getVarFlag("SRC_URI", md5flag, data)
180     expected_sha256sum = bb.data.getVarFlag("SRC_URI", sha256flag, data)
182     return (expected_md5sum, expected_sha256sum)
184 def base_chk_file(pn, pv, src_uri, localpath, params, data):
185     (expected_md5sum, expected_sha256sum) = base_get_checksums(pn, pv, src_uri, localpath, params, data)
186     return base_chk_file_checksum(localpath, src_uri, expected_md5sum, expected_sha256sum, params, data)
188 oedebug() {
189         test $# -ge 2 || {
190                 echo "Usage: oedebug level \"message\""
191                 exit 1
192         }
194         test ${OEDEBUG:-0} -ge $1 && {
195                 shift
196                 echo "DEBUG:" $*
197         }
200 oe_soinstall() {
201         # Purpose: Install shared library file and
202         #          create the necessary links
203         # Example:
204         #
205         # oe_
206         #
207         #oenote installing shared library $1 to $2
208         #
209         libname=`basename $1`
210         install -m 755 $1 $2/$libname
211         sonamelink=`${HOST_PREFIX}readelf -d $1 |grep 'Library soname:' |sed -e 's/.*\[\(.*\)\].*/\1/'`
212         solink=`echo $libname | sed -e 's/\.so\..*/.so/'`
213         ln -sf $libname $2/$sonamelink
214         ln -sf $libname $2/$solink
217 oe_libinstall() {
218         # Purpose: Install a library, in all its forms
219         # Example
220         #
221         # oe_libinstall libltdl ${STAGING_LIBDIR}/
222         # oe_libinstall -C src/libblah libblah ${D}/${libdir}/
223         dir=""
224         libtool=""
225         silent=""
226         require_static=""
227         require_shared=""
228         staging_install=""
229         while [ "$#" -gt 0 ]; do
230                 case "$1" in
231                 -C)
232                         shift
233                         dir="$1"
234                         ;;
235                 -s)
236                         silent=1
237                         ;;
238                 -a)
239                         require_static=1
240                         ;;
241                 -so)
242                         require_shared=1
243                         ;;
244                 -*)
245                         oefatal "oe_libinstall: unknown option: $1"
246                         ;;
247                 *)
248                         break;
249                         ;;
250                 esac
251                 shift
252         done
254         libname="$1"
255         shift
256         destpath="$1"
257         if [ -z "$destpath" ]; then
258                 oefatal "oe_libinstall: no destination path specified"
259         fi
260         if echo "$destpath/" | egrep '^${STAGING_LIBDIR}/' >/dev/null
261         then
262                 staging_install=1
263         fi
265         __runcmd () {
266                 if [ -z "$silent" ]; then
267                         echo >&2 "oe_libinstall: $*"
268                 fi
269                 $*
270         }
272         if [ -z "$dir" ]; then
273                 dir=`pwd`
274         fi
276         dotlai=$libname.lai
278         # Sanity check that the libname.lai is unique
279         number_of_files=`(cd $dir; find . -name "$dotlai") | wc -l`
280         if [ $number_of_files -gt 1 ]; then
281                 oefatal "oe_libinstall: $dotlai is not unique in $dir"
282         fi
285         dir=$dir`(cd $dir;find . -name "$dotlai") | sed "s/^\.//;s/\/$dotlai\$//;q"`
286         olddir=`pwd`
287         __runcmd cd $dir
289         lafile=$libname.la
291         # If such file doesn't exist, try to cut version suffix
292         if [ ! -f "$lafile" ]; then
293                 libname1=`echo "$libname" | sed 's/-[0-9.]*$//'`
294                 lafile1=$libname.la
295                 if [ -f "$lafile1" ]; then
296                         libname=$libname1
297                         lafile=$lafile1
298                 fi
299         fi
301         if [ -f "$lafile" ]; then
302                 # libtool archive
303                 eval `cat $lafile|grep "^library_names="`
304                 libtool=1
305         else
306                 library_names="$libname.so* $libname.dll.a $libname.*.dylib"
307         fi
309         __runcmd install -d $destpath/
310         dota=$libname.a
311         if [ -f "$dota" -o -n "$require_static" ]; then
312                 __runcmd install -m 0644 $dota $destpath/
313         fi
314         if [ -f "$dotlai" -a -n "$libtool" ]; then
315                 if [ -n "$staging_install" -a "${LIBTOOL_HAS_SYSROOT}" = "no" ]
316                 then
317                         # stop libtool using the final directory name for libraries
318                         # in staging:
319                         __runcmd rm -f $destpath/$libname.la
320                         __runcmd sed -e 's/^installed=yes$/installed=no/' \
321                                      -e '/^dependency_libs=/s,${WORKDIR}[[:alnum:]/\._+-]*/\([[:alnum:]\._+-]*\),${STAGING_LIBDIR}/\1,g' \
322                                      -e "/^dependency_libs=/s,\([[:space:]']\)${libdir},\1${STAGING_LIBDIR},g" \
323                                      $dotlai >$destpath/$libname.la
324                 else
325                         __runcmd install -m 0644 $dotlai $destpath/$libname.la
326                 fi
327         fi
329         for name in $library_names; do
330                 files=`eval echo $name`
331                 for f in $files; do
332                         if [ ! -e "$f" ]; then
333                                 if [ -n "$libtool" ]; then
334                                         oefatal "oe_libinstall: $dir/$f not found."
335                                 fi
336                         elif [ -L "$f" ]; then
337                                 __runcmd cp -P "$f" $destpath/
338                         elif [ ! -L "$f" ]; then
339                                 libfile="$f"
340                                 __runcmd install -m 0755 $libfile $destpath/
341                         fi
342                 done
343         done
345         if [ -z "$libfile" ]; then
346                 if  [ -n "$require_shared" ]; then
347                         oefatal "oe_libinstall: unable to locate shared library"
348                 fi
349         elif [ -z "$libtool" ]; then
350                 # special case hack for non-libtool .so.#.#.# links
351                 baselibfile=`basename "$libfile"`
352                 if (echo $baselibfile | grep -qE '^lib.*\.so\.[0-9.]*$'); then
353                         sonamelink=`${HOST_PREFIX}readelf -d $libfile |grep 'Library soname:' |sed -e 's/.*\[\(.*\)\].*/\1/'`
354                         solink=`echo $baselibfile | sed -e 's/\.so\..*/.so/'`
355                         if [ -n "$sonamelink" -a x"$baselibfile" != x"$sonamelink" ]; then
356                                 __runcmd ln -sf $baselibfile $destpath/$sonamelink
357                         fi
358                         __runcmd ln -sf $baselibfile $destpath/$solink
359                 fi
360         fi
362         __runcmd cd "$olddir"
365 oe_machinstall() {
366         # Purpose: Install machine dependent files, if available
367         #          If not available, check if there is a default
368         #          If no default, just touch the destination
369         # Example:
370         #                $1  $2   $3         $4
371         # oe_machinstall -m 0644 fstab ${D}/etc/fstab
372         #
373         # TODO: Check argument number?
374         #
375         filename=`basename $3`
376         dirname=`dirname $3`
378         for o in `echo ${OVERRIDES} | tr ':' ' '`; do
379                 if [ -e $dirname/$o/$filename ]; then
380                         oenote $dirname/$o/$filename present, installing to $4
381                         install $1 $2 $dirname/$o/$filename $4
382                         return
383                 fi
384         done
385 #       oenote overrides specific file NOT present, trying default=$3...
386         if [ -e $3 ]; then
387                 oenote $3 present, installing to $4
388                 install $1 $2 $3 $4
389         else
390                 oenote $3 NOT present, touching empty $4
391                 touch $4
392         fi
395 create_wrapper () {
396    # Create a wrapper script
397    #
398    # These are useful to work around relocation issues, by setting environment
399    # variables which point to paths in the filesystem.
400    #
401    # Usage: create_wrapper FILENAME [[VAR=VALUE]..]
403    cmd=$1
404    shift
406    # run echo via env to test syntactic validity of the variable arguments
407    env $@ echo "Generating wrapper script for $cmd"
409    mv $cmd $cmd.real
410    cmdname=`basename $cmd`.real
411    cat <<END >$cmd
412 #!/bin/sh
413 exec env $@ \`dirname \$0\`/$cmdname "\$@"
415    chmod +x $cmd
418 def check_app_exists(app, d):
419         from bb import which, data
421         app = data.expand(app, d)
422         path = data.getVar('PATH', d, 1)
423         return bool(which(path, app))
425 def explode_deps(s):
426         return bb.utils.explode_deps(s)
428 def base_set_filespath(path, d):
429         bb.note("base_set_filespath usage is deprecated, %s should be fixed" % d.getVar("P", 1))
430         filespath = []
431         # The ":" ensures we have an 'empty' override
432         overrides = (bb.data.getVar("OVERRIDES", d, 1) or "") + ":"
433         for p in path:
434                 for o in overrides.split(":"):
435                         filespath.append(os.path.join(p, o))
436         return ":".join(filespath)
438 # These directory stack functions are based upon the versions in the Korn
439 # Shell documentation - http://docstore.mik.ua/orelly/unix3/korn/ch04_07.htm.
440 dirs() {
441     echo "$_DIRSTACK"
444 pushd() {
445     dirname=$1
446     cd ${dirname:?"missing directory name."} || return 1
447     _DIRSTACK="$PWD $_DIRSTACK"
448     echo "$_DIRSTACK"
451 popd() {
452     _DIRSTACK=${_DIRSTACK#* }
453     top=${_DIRSTACK%% *}
454     cd $top || return 1
455     echo "$PWD"