Logo Search packages:      
Sourcecode: abakus version File versions  Download package

Util.py

import copy
import os
import os.path
import re
import stat
import string
import sys
import types
import UserDict
import UserList
import SCons.Errors
try:
    from UserString import UserString
except ImportError:
00015     class UserString:
        def __init__(self, seq):
            if is_String(seq):
                self.data=seq
            elif isinstance(seq, UserString):
                self.data=seq.data[:]
            else:
                self.data=str(seq)
        def __str__(self): return str(self.data)
        def __repr__(self): return repr(self.data)
        def __int__(self): return int(self.data)
        def __long__(self): return long(self.data)
        def __float__(self): return float(self.data)
        def __complex__(self): return complex(self.data)
        def __hash__(self): return hash(self.data)
        def __cmp__(self, string):
            if isinstance(string, UserString):
                return cmp(self.data, string.data)
            else:
                return cmp(self.data, string)
        def __contains__(self, char):
            return char in self.data
        def __len__(self): return len(self.data)
        def __getitem__(self, index): return self.__class__(self.data[index])
        def __getslice__(self, start, end):
            start=max(start, 0); end=max(end, 0)
            return self.__class__(self.data[start:end])
        def __add__(self, other):
            if isinstance(other, UserString):
                return self.__class__(self.data + other.data)
            elif is_String(other):
                return self.__class__(self.data + other)
            else:
                return self.__class__(self.data + str(other))
        def __radd__(self, other):
            if is_String(other):
                return self.__class__(other + self.data)
            else:
                return self.__class__(str(other) + self.data)
        def __mul__(self, n):
            return self.__class__(self.data*n)
        __rmul__=__mul__
_altsep=os.altsep
if _altsep:
    def rightmost_separator(path, sep, _altsep=_altsep):
        rfind=string.rfind
        return max(rfind(path, sep), rfind(path, _altsep))
else:
    rightmost_separator=string.rfind
def containsAny(str, set):
    for c in set:
        if c in str: return 1
    return 0
def containsAll(str, set):
    for c in set:
        if c not in str: return 0
    return 1
def containsOnly(str, set):
    for c in str:
        if c not in set: return 0
    return 1
def splitext(path):
    sep=rightmost_separator(path, os.sep)
    dot=string.rfind(path, '.')
    if dot > sep and not containsOnly(path[dot:], "0123456789."):
        return path[:dot],path[dot:]
    else:
        return path,""
def updrive(path):
    drive, rest=os.path.splitdrive(path)
    if drive:
        path=string.upper(drive) + rest
    return path
if hasattr(types, 'UnicodeType'):
    def to_String(s):
        if isinstance(s, UserString):
            t=type(s.data)
        else:
            t=type(s)
        if t is types.UnicodeType:
            return unicode(s)
        else:
            return str(s)
else:
    to_String=str
def to_String_for_signature(obj):
    try:
        f=obj.for_signature
    except:
        return to_String(obj)
    else:
        return f()
_strconv=[to_String, to_String, to_String_for_signature]
00108 class Literal:
    def __init__(self, lstr):
        self.lstr=lstr
    def __str__(self):
        return self.lstr
    def escape(self, escape_func):
        return escape_func(self.lstr)
    def for_signature(self):
        return self.lstr
    def is_literal(self):
        return 1
00119 class SpecialAttrWrapper:
    def __init__(self, lstr, for_signature=None):
        self.lstr=lstr
        if for_signature:
            self.forsig=for_signature
        else:
            self.forsig=lstr
    def __str__(self):
        return self.lstr
    def escape(self, escape_func):
        return escape_func(self.lstr)
    def for_signature(self):
        return self.forsig
    def is_literal(self):
        return 1
00134 class CallableComposite(UserList.UserList):
    def __call__(self, *args, **kwargs):
        retvals=map(lambda x, args=args, kwargs=kwargs: apply(x, args, kwargs), self.data)
        if self.data and (len(self.data)==len(filter(callable, retvals))):
            return self.__class__(retvals)
        return NodeList(retvals)
00140 class NodeList(UserList.UserList):
    def __nonzero__(self):
        return len(self.data) != 0
    def __str__(self):
        return string.join(map(str, self.data))
    def __getattr__(self, name):
        if not self.data:
            raise AttributeError, "NodeList has no attribute: %s" % name
        attrList=map(lambda x, n=name: getattr(x, n), self.data)
        if self.data and (len(self.data)==len(filter(callable, attrList))):
            return CallableComposite(attrList)
        return self.__class__(attrList)
_valid_var=re.compile(r'[_a-zA-Z]\w*$')
_get_env_var=re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$')
def is_valid_construction_var(varstr):
    return _valid_var.match(varstr)
def get_environment_var(varstr):
    mo=_get_env_var.match(to_String(varstr))
    if mo:
        var=mo.group(1)
        if var[0]=='{':
            return var[1:-1]
        else:
            return var
    else:
        return None
def quote_spaces(arg):
    if ' ' in arg or '\t' in arg:
        return '"%s"' % arg
    else:
        return str(arg)
00171 class CmdStringHolder(UserString):
    def __init__(self, cmd, literal=None):
        UserString.__init__(self, cmd)
        self.literal=literal
    def is_literal(self):
        return self.literal
    def escape(self, escape_func, quote_func=quote_spaces):
        if self.is_literal():
            return escape_func(self.data)
        elif ' ' in self.data or '\t' in self.data:
            return quote_func(self.data)
        else:
            return self.data
00184 class DisplayEngine:
    def __init__(self):
        self.__call__=self.print_it
    def print_it(self, text):
        sys.stdout.write(text + '\n')
    def dont_print(self, text):
        pass
    def set_mode(self, mode):
        if mode:
            self.__call__=self.print_it
        else:
            self.__call__=self.dont_print
def escape_list(list, escape_func):
    def escape(obj, escape_func=escape_func):
        try:
            e=obj.escape
        except AttributeError:
            return obj
        else:
            return e(escape_func)
    return map(escape, list)
00205 class NLWrapper:
    def __init__(self, list, func):
        self.list=list
        self.func=func
    def _create_nodelist(self):
        try:
            return self.nodelist
        except AttributeError:
            list=self.list
            if list is None:
                list=[]
            elif not is_List(list):
                list=[list]
            self.nodelist=NodeList(map(self.func, list))
        return self.nodelist
00220 class Targets_or_Sources(UserList.UserList):
    def __init__(self, nl):
        self.nl=nl
    def __getattr__(self, attr):
        nl=self.nl._create_nodelist()
        return getattr(nl, attr)
    def __getitem__(self, i):
        nl=self.nl._create_nodelist()
        return nl[i]
    def __getslice__(self, i, j):
        nl=self.nl._create_nodelist()
        i=max(i, 0); j=max(j, 0)
        return nl[i:j]
    def __str__(self):
        nl=self.nl._create_nodelist()
        return str(nl)
    def __repr__(self):
        nl=self.nl._create_nodelist()
        return repr(nl)
00239 class Target_or_Source:
    def __init__(self, nl):
        self.nl=nl
    def __getattr__(self, attr):
        nl=self.nl._create_nodelist()
        try:
            nl0=nl[0]
        except IndexError:
            raise AttributeError, "NodeList has no attribute: %s" % attr
        return getattr(nl0, attr)
    def __str__(self):
        nl=self.nl._create_nodelist()
        try:
            nl0=nl[0]
        except IndexError:
            return ''
        return str(nl0)
    def __repr__(self):
        nl=self.nl._create_nodelist()
        try:
            nl0=nl[0]
        except IndexError:
            return ''
        return repr(nl0)
def subst_dict(target, source):
    dict={}
    if target:
        tnl=NLWrapper(target, lambda x: x.get_subst_proxy())
        dict['TARGETS']=Targets_or_Sources(tnl)
        dict['TARGET']=Target_or_Source(tnl)
    if source:
        snl=NLWrapper(source, lambda x: x.rfile().get_subst_proxy())
        dict['SOURCES']=Targets_or_Sources(snl)
        dict['SOURCE']=Target_or_Source(snl)
    return dict
SUBST_CMD=0
SUBST_RAW=1
SUBST_SIG=2
_rm=re.compile(r'\$[()]')
_remove=re.compile(r'\$\(([^\$]|\$[^\(])*?\$\)')
_regex_remove=[ _rm, None, _remove ]
_separate_args=re.compile(r'(\$[\$\(\)]|\$[_a-zA-Z][\.\w]*|\${[^}]*}|\s+|[^\s\$]+|\$)')
_space_sep=re.compile(r'[\t ]+(?![^{]*})')
def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, dict=None, conv=None, gvars=None):
    class StringSubber:
        def __init__(self, env, mode, target, source, conv, gvars):
            self.env=env
            self.mode=mode
            self.target=target
            self.source=source
            self.conv=conv
            self.gvars=gvars
        def expand(self, s, lvars):
            if is_String(s):
                try:
                    s0, s1=s[:2]
                except (IndexError, ValueError):
                    return s
                if s0=='$':
                    if s1=='$':
                        return '$'
                    elif s1 in '()':
                        return s
                    else:
                        key=s[1:]
                        if key[0]=='{':
                            key=key[1:-1]
                        try:
                            s=eval(key, self.gvars, lvars)
                        except (IndexError, NameError, TypeError):
                            return ''
                        except SyntaxError,e:
                            if self.target:
                                raise SCons.Errors.BuildError, (self.target[0], "Syntax error `%s' trying to evaluate `%s'" % (e,s))
                            else:
                                raise SCons.Errors.UserError, "Syntax error `%s' trying to evaluate `%s'" % (e,s)
                        else:
                            lv=lvars.copy()
                            var=string.split(key, '.')[0]
                            lv[var]=''
                            return self.substitute(s, lv)
                else:
                    return s
            elif is_List(s):
                r=[]
                for l in s:
                    r.append(self.conv(self.substitute(l, lvars)))
                return string.join(r)
            elif callable(s):
                s=s(target=self.target,
                     source=self.source,
                     env=self.env,
                     for_signature=(self.mode != SUBST_CMD))
                return self.substitute(s, lvars)
            elif s is None:
                return ''
            else:
                return s
        def substitute(self, args, lvars):
            if is_String(args) and not isinstance(args, CmdStringHolder):
                args=_separate_args.findall(args)
                result=[]
                for a in args:
                    result.append(self.conv(self.expand(a, lvars)))
                try:
                    result=string.join(result, '')
                except TypeError:
                    pass
                return result
            else:
                return self.expand(args, lvars)
    if dict is None:
        dict=subst_dict(target, source)
    if conv is None:
        conv=_strconv[mode]
    if gvars is None:
        gvars=env.Dictionary()
    ss=StringSubber(env, mode, target, source, conv, gvars)
    result=ss.substitute(strSubst, dict)
    if is_String(result):
        remove=_regex_remove[mode]
        if remove:
            result=remove.sub('', result)
        if mode != SUBST_RAW:
            result=string.strip(_space_sep.sub(' ', result))
    return result
def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, dict=None, conv=None, gvars=None):
    class ListSubber(UserList.UserList):
        def __init__(self, env, mode, target, source, conv, gvars):
            UserList.UserList.__init__(self, [])
            self.env=env
            self.mode=mode
            self.target=target
            self.source=source
            self.conv=conv
            self.gvars=gvars
            if self.mode==SUBST_RAW:
                self.add_strip=lambda x, s=self: s.append(x)
            else:
                self.add_strip=lambda x, s=self: None
            self.in_strip=None
            self.next_line()
        def expand(self, s, lvars, within_list):
            if is_String(s):
                try:
                    s0, s1=s[:2]
                except (IndexError, ValueError):
                    self.append(s)
                    return
                if s0=='$':
                    if s1=='$':
                        self.append('$')
                    elif s1=='(':
                        self.open_strip('$(')
                    elif s1==')':
                        self.close_strip('$)')
                    else:
                        key=s[1:]
                        if key[0]=='{':
                            key=key[1:-1]
                        try:
                            s=eval(key, self.gvars, lvars)
                        except (IndexError, NameError, TypeError):
                            return
                        except SyntaxError,e:
                            if self.target:
                                raise SCons.Errors.BuildError, (self.target[0], "Syntax error `%s' trying to evaluate `%s'" % (e,s))
                            else:
                                raise SCons.Errors.UserError, "Syntax error `%s' trying to evaluate `%s'" % (e,s)
                        else:
                            lv=lvars.copy()
                            var=string.split(key, '.')[0]
                            lv[var]=''
                            self.substitute(s, lv, 0)
                            self.this_word()
                else:
                    self.append(s)
            elif is_List(s):
                for a in s:
                    self.substitute(a, lvars, 1)
                    self.next_word()
            elif callable(s):
                s=s(target=self.target,
                     source=self.source,
                     env=self.env,
                     for_signature=(self.mode != SUBST_CMD))
                self.substitute(s, lvars, within_list)
            elif s is None:
                self.this_word()
            else:
                self.append(s)
        def substitute(self, args, lvars, within_list):
            if is_String(args) and not isinstance(args, CmdStringHolder):
                args=_separate_args.findall(args)
                for a in args:
                    if a[0] in ' \t\n\r\f\v':
                        if '\n' in a:
                            self.next_line()
                        elif within_list:
                            self.append(a)
                        else:
                            self.next_word()
                    else:
                        self.expand(a, lvars, within_list)
            else:
                self.expand(args, lvars, within_list)
        def next_line(self):
            UserList.UserList.append(self, [])
            self.next_word()
        def this_word(self):
            self.append=self.add_to_current_word
        def next_word(self):
            self.append=self.add_new_word
        def add_to_current_word(self, x):
            if not self.in_strip or self.mode != SUBST_SIG:
                try:
                    current_word=self[-1][-1]
                except IndexError:
                    self.add_new_word(x)
                else:
                    try:
                        last_char=str(current_word)[-1]
                    except IndexError:
                        last_char='\0'
                    if last_char in '<>|':
                        self.add_new_word(x)
                    else:
                        y=current_word + x
                        literal1=self.literal(self[-1][-1])
                        literal2=self.literal(x)
                        y=self.conv(y)
                        if is_String(y):
                            y=CmdStringHolder(y, literal1 or literal2)
                        self[-1][-1]=y
        def add_new_word(self, x):
            if not self.in_strip or self.mode != SUBST_SIG:
                literal=self.literal(x)
                x=self.conv(x)
                if is_String(x):
                    x=CmdStringHolder(x, literal)
                self[-1].append(x)
            self.append=self.add_to_current_word
        def literal(self, x):
            try:
                l=x.is_literal
            except AttributeError:
                return None
            else:
                return l()
        def open_strip(self, x):
            self.add_strip(x)
            self.in_strip=1
        def close_strip(self, x):
            self.add_strip(x)
            self.in_strip=None
    if dict is None:
        dict=subst_dict(target, source)
    if conv is None:
        conv=_strconv[mode]
    if gvars is None:
        gvars=env.Dictionary()
    ls=ListSubber(env, mode, target, source, conv, gvars)
    ls.substitute(strSubst, dict, 0)
    return ls.data
def scons_subst_once(strSubst, env, key):
    matchlist=['$' + key, '${' + key + '}']
    if is_List(strSubst):
        result=[]
        for arg in strSubst:
            if is_String(arg):
                if arg in matchlist:
                    arg=env[key]
                    if is_List(arg):
                        result.extend(arg)
                    else:
                        result.append(arg)
                else:
                    r=[]
                    for a in _separate_args.findall(arg):
                        if a in matchlist:
                            a=env[key]
                        if is_List(a):
                            r.append(string.join(map(str, a)))
                        else:
                            r.append(str(a))
                    result.append(string.join(r, ''))
            else:
                result.append(arg)
        return result
    elif is_String(strSubst):
        result=[]
        for a in _separate_args.findall(strSubst):
            if a in matchlist:
                a=env[key]
            if is_List(a):
                result.append(string.join(map(str, a)))
            else:
                result.append(str(a))
        return string.join(result, '')
    else:
        return strSubst
def render_tree(root, child_func, prune=0, margin=[0], visited={}):
    if visited.has_key(root):
        return ""
    children=child_func(root)
    retval=""
    for pipe in margin[:-1]:
        if pipe:
            retval=retval + "| "
        else:
            retval=retval + "  "
    retval=retval + "+-" + str(root) + "\n"
    if not prune:
        visited=copy.copy(visited)
    visited[root]=1
    for i in range(len(children)):
        margin.append(i<len(children)-1)
        retval=retval + render_tree(children[i], child_func, prune, margin, visited
)
        margin.pop()
    return retval
def is_Dict(e):
    return type(e) is types.DictType or isinstance(e, UserDict.UserDict)
def is_List(e):
    return type(e) is types.ListType or isinstance(e, UserList.UserList)
if hasattr(types, 'UnicodeType'):
    def is_String(e):
        return type(e) is types.StringType \
            or type(e) is types.UnicodeType \
            or isinstance(e, UserString)
else:
    def is_String(e):
        return type(e) is types.StringType or isinstance(e, UserString)
def is_Scalar(e):
    return is_String(e) or not is_List(e)
def flatten(sequence, scalarp=is_Scalar, result=None):
    if result is None:
        result=[]
    for item in sequence:
        if scalarp(item):
            result.append(item)
        else:
            flatten(item, scalarp, result)
    return result
00583 class Proxy:
    def __init__(self, subject):
        self.__subject=subject
    def __getattr__(self, name):
        return getattr(self.__subject, name)
    def get(self):
        return self.__subject
def WhereIs(file, path=None, pathext=None, reject=[]):
    if path is None:
        try:
            path=os.environ['PATH']
        except KeyError:
            return None
    if is_String(path):
        path=string.split(path, os.pathsep)
    if not is_List(reject):
        reject=[reject]
    for d in path:
        f=os.path.join(d, file)
        if os.path.isfile(f):
            try:
                st=os.stat(f)
            except OSError:
                continue
            if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
                try:
                    reject.index(f)
                except ValueError:
                    return os.path.normpath(f)
                continue
    return None
def PrependPath(oldpath, newpath, sep=os.pathsep):
    orig=oldpath
    is_list=1
    paths=orig
    if not is_List(orig):
        paths=string.split(paths, sep)
        is_list=0
    if is_List(newpath):
        newpaths=newpath
    else:
        newpaths=string.split(newpath, sep)
    newpaths=newpaths + paths
    normpaths=[]
    paths=[]
    for path in newpaths:
        normpath=os.path.normpath(os.path.normcase(path))
        if path and not normpath in normpaths:
            paths.append(path)
            normpaths.append(normpath)
    if is_list:
        return paths
    else:
        return string.join(paths, sep)
def AppendPath(oldpath, newpath, sep=os.pathsep):
    orig=oldpath
    is_list=1
    paths=orig
    if not is_List(orig):
        paths=string.split(paths, sep)
        is_list=0
    if is_List(newpath):
        newpaths=newpath
    else:
        newpaths=string.split(newpath, sep)
    newpaths=paths + newpaths
    newpaths.reverse()
    normpaths=[]
    paths=[]
    for path in newpaths:
        normpath=os.path.normpath(os.path.normcase(path))
        if path and not normpath in normpaths:
            paths.append(path)
            normpaths.append(normpath)
    paths.reverse()
    if is_list:
        return paths
    else:
        return string.join(paths, sep)
def dir_index(directory):
    files=[]
    for f in os.listdir(directory):
        fullname=os.path.join(directory, f)
        files.append(fullname)
    files.sort()
    return files
def fs_delete(path, remove=1):
    try:
        if os.path.exists(path):
            if os.path.isfile(path):
                if remove: os.unlink(path)
                display("Removed " + path)
            elif os.path.isdir(path) and not os.path.islink(path):
                for p in dir_index(path):
                    if os.path.isfile(p):
                        if remove: os.unlink(p)
                        display("Removed " + p)
                    else:
                        fs_delete(p, remove)
                if remove: os.rmdir(path)
                display("Removed directory " + path)
    except OSError, e:
        print "scons: Could not remove '%s':" % str(path), e.strerror
def get_native_path(path):
    return path
display=DisplayEngine()
def Split(arg):
    if is_List(arg):
        return arg
    elif is_String(arg):
        return string.split(arg)
    else:
        return [arg]
00696 class CLVar(UserList.UserList):
    def __init__(self, seq=[]):
        UserList.UserList.__init__(self, Split(seq))
    def __coerce__(self, other):
        return (self, CLVar(other))
    def __str__(self):
        return string.join(self.data)
00703 class Selector(UserDict.UserDict):
    def __call__(self, env, source):
        ext=splitext(str(source[0]))[1]
        try:
            return self[ext]
        except KeyError:
            s_dict={}
            for (k,v) in self.items():
                if not k is None:
                    s_k=env.subst(k)
                    if s_dict.has_key(s_k):
                        raise KeyError, (s_dict[s_k][0], k, s_k)
                    s_dict[s_k]=(k,v)
            try:
                return s_dict[ext][1]
            except KeyError:
                try:
                    return self[None]
                except KeyError:
                    return None
def case_sensitive_suffixes(s1, s2):
    return (os.path.normcase(s1) != os.path.normcase(s2))
def adjustixes(fname, pre, suf):
    if pre:
        path, fn=os.path.split(os.path.normpath(fname))
        if fn[:len(pre)] != pre:
            fname=os.path.join(path, pre + fn)
    if suf and not splitext(fname)[1] and fname[-len(suf):] != suf:
            fname=fname + suf
    return fname
def unique(s):
    n=len(s)
    if n==0:
        return []
    u={}
    try:
        for x in s:
            u[x]=1
    except TypeError:
        del u
    else:
        return u.keys()
    try:
        t=list(s)
        t.sort()
    except TypeError:
        del t
    else:
        assert n > 0
        last=t[0]
        lasti=i=1
        while i < n:
            if t[i] != last:
                t[lasti]=last=t[i]
                lasti=lasti + 1
            i=i + 1
        return t[:lasti]
    u=[]
    for x in s:
        if x not in u:
            u.append(x)
    return u

Generated by  Doxygen 1.6.0   Back to index