~ubuntu-branches/ubuntu/raring/xmms2/raring

« back to all changes in this revision

Viewing changes to waflib/Utils.py

  • Committer: Package Import Robot
  • Author(s): Reinhard Tartler
  • Date: 2012-11-25 19:23:15 UTC
  • mto: This revision was merged to the branch mainline in revision 51.
  • Revision ID: package-import@ubuntu.com-20121125192315-m9z6nu9wwlzrrz9z
ImportĀ upstreamĀ versionĀ 0.8+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#! /usr/bin/env python
 
2
# encoding: utf-8
 
3
# WARNING! Do not edit! http://waf.googlecode.com/svn/docs/wafbook/single.html#_obtaining_the_waf_file
 
4
 
 
5
import os,sys,errno,traceback,inspect,re,shutil,datetime,gc
 
6
try:
 
7
        import subprocess
 
8
except:
 
9
        try:
 
10
                import waflib.extras.subprocess as subprocess
 
11
        except:
 
12
                print("The subprocess module is missing (python2.3?):\n try calling 'waf update --files=subprocess'\n or add a copy of subprocess.py to the python libraries")
 
13
try:
 
14
        from collections import deque
 
15
except ImportError:
 
16
        class deque(list):
 
17
                def popleft(self):
 
18
                        return self.pop(0)
 
19
try:
 
20
        import _winreg as winreg
 
21
except:
 
22
        try:
 
23
                import winreg
 
24
        except:
 
25
                winreg=None
 
26
from waflib import Errors
 
27
try:
 
28
        from collections import UserDict
 
29
except:
 
30
        from UserDict import UserDict
 
31
try:
 
32
        from hashlib import md5
 
33
except:
 
34
        try:
 
35
                from md5 import md5
 
36
        except:
 
37
                pass
 
38
try:
 
39
        import threading
 
40
except:
 
41
        class threading(object):
 
42
                pass
 
43
        class Lock(object):
 
44
                def acquire(self):
 
45
                        pass
 
46
                def release(self):
 
47
                        pass
 
48
        threading.Lock=threading.Thread=Lock
 
49
else:
 
50
        run_old=threading.Thread.run
 
51
        def run(*args,**kwargs):
 
52
                try:
 
53
                        run_old(*args,**kwargs)
 
54
                except(KeyboardInterrupt,SystemExit):
 
55
                        raise
 
56
                except:
 
57
                        sys.excepthook(*sys.exc_info())
 
58
        threading.Thread.run=run
 
59
SIG_NIL='iluvcuteoverload'
 
60
O644=420
 
61
O755=493
 
62
rot_chr=['\\','|','/','-']
 
63
rot_idx=0
 
64
try:
 
65
        from collections import defaultdict
 
66
except ImportError:
 
67
        class defaultdict(dict):
 
68
                def __init__(self,default_factory):
 
69
                        super(defaultdict,self).__init__()
 
70
                        self.default_factory=default_factory
 
71
                def __getitem__(self,key):
 
72
                        try:
 
73
                                return super(defaultdict,self).__getitem__(key)
 
74
                        except KeyError:
 
75
                                value=self.default_factory()
 
76
                                self[key]=value
 
77
                                return value
 
78
is_win32=sys.platform in('win32','cli')
 
79
indicator='\x1b[K%s%s%s\r'
 
80
if is_win32 and'NOCOLOR'in os.environ:
 
81
        indicator='%s%s%s\r'
 
82
def readf(fname,m='r'):
 
83
        f=open(fname,m)
 
84
        try:
 
85
                txt=f.read()
 
86
        finally:
 
87
                f.close()
 
88
        return txt
 
89
def h_file(filename):
 
90
        f=open(filename,'rb')
 
91
        m=md5()
 
92
        try:
 
93
                while filename:
 
94
                        filename=f.read(100000)
 
95
                        m.update(filename)
 
96
        except:
 
97
                f.close()
 
98
        return m.digest()
 
99
try:
 
100
        x=''.encode('hex')
 
101
except:
 
102
        import binascii
 
103
        def to_hex(s):
 
104
                ret=binascii.hexlify(s)
 
105
                if not isinstance(ret,str):
 
106
                        ret=ret.decode('utf-8')
 
107
                return ret
 
108
else:
 
109
        def to_hex(s):
 
110
                return s.encode('hex')
 
111
to_hex.__doc__="""
 
112
Return the hexadecimal representation of a string
 
113
 
 
114
:param s: string to convert
 
115
:type s: string
 
116
"""
 
117
listdir=os.listdir
 
118
if is_win32:
 
119
        def listdir_win32(s):
 
120
                if not s:
 
121
                        try:
 
122
                                import ctypes
 
123
                        except:
 
124
                                return[x+':\\'for x in list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')]
 
125
                        else:
 
126
                                dlen=4
 
127
                                maxdrives=26
 
128
                                buf=ctypes.create_string_buffer(maxdrives*dlen)
 
129
                                ndrives=ctypes.windll.kernel32.GetLogicalDriveStringsA(maxdrives,ctypes.byref(buf))
 
130
                                return[buf.raw[4*i:4*i+3].decode('ascii')for i in range(int(ndrives/dlen))]
 
131
                if len(s)==2 and s[1]==":":
 
132
                        s+=os.sep
 
133
                if not os.path.isdir(s):
 
134
                        e=OSError()
 
135
                        e.errno=errno.ENOENT
 
136
                        raise e
 
137
                return os.listdir(s)
 
138
        listdir=listdir_win32
 
139
def num2ver(ver):
 
140
        if isinstance(ver,str):
 
141
                ver=tuple(ver.split('.'))
 
142
        if isinstance(ver,tuple):
 
143
                ret=0
 
144
                for i in range(4):
 
145
                        if i<len(ver):
 
146
                                ret+=256**(3-i)*int(ver[i])
 
147
                return ret
 
148
        return ver
 
149
def ex_stack():
 
150
        exc_type,exc_value,tb=sys.exc_info()
 
151
        exc_lines=traceback.format_exception(exc_type,exc_value,tb)
 
152
        return''.join(exc_lines)
 
153
def to_list(sth):
 
154
        if isinstance(sth,str):
 
155
                return sth.split()
 
156
        else:
 
157
                return sth
 
158
re_nl=re.compile('\r*\n',re.M)
 
159
def str_to_dict(txt):
 
160
        tbl={}
 
161
        lines=re_nl.split(txt)
 
162
        for x in lines:
 
163
                x=x.strip()
 
164
                if not x or x.startswith('#')or x.find('=')<0:
 
165
                        continue
 
166
                tmp=x.split('=')
 
167
                tbl[tmp[0].strip()]='='.join(tmp[1:]).strip()
 
168
        return tbl
 
169
def split_path(path):
 
170
        return path.split('/')
 
171
def split_path_cygwin(path):
 
172
        if path.startswith('//'):
 
173
                ret=path.split('/')[2:]
 
174
                ret[0]='/'+ret[0]
 
175
                return ret
 
176
        return path.split('/')
 
177
re_sp=re.compile('[/\\\\]')
 
178
def split_path_win32(path):
 
179
        if path.startswith('\\\\'):
 
180
                ret=re.split(re_sp,path)[2:]
 
181
                ret[0]='\\'+ret[0]
 
182
                return ret
 
183
        return re.split(re_sp,path)
 
184
if sys.platform=='cygwin':
 
185
        split_path=split_path_cygwin
 
186
elif is_win32:
 
187
        split_path=split_path_win32
 
188
split_path.__doc__="""
 
189
Split a path by / or \\. This function is not like os.path.split
 
190
 
 
191
:type  path: string
 
192
:param path: path to split
 
193
:return:     list of strings
 
194
"""
 
195
def check_dir(path):
 
196
        if not os.path.isdir(path):
 
197
                try:
 
198
                        os.makedirs(path)
 
199
                except OSError ,e:
 
200
                        if not os.path.isdir(path):
 
201
                                raise Errors.WafError('Cannot create the folder %r'%path,ex=e)
 
202
def def_attrs(cls,**kw):
 
203
        for k,v in kw.items():
 
204
                if not hasattr(cls,k):
 
205
                        setattr(cls,k,v)
 
206
def quote_define_name(s):
 
207
        fu=re.compile("[^a-zA-Z0-9]").sub("_",s)
 
208
        fu=fu.upper()
 
209
        return fu
 
210
def h_list(lst):
 
211
        m=md5()
 
212
        m.update(str(lst))
 
213
        return m.digest()
 
214
def h_fun(fun):
 
215
        try:
 
216
                return fun.code
 
217
        except AttributeError:
 
218
                try:
 
219
                        h=inspect.getsource(fun)
 
220
                except IOError:
 
221
                        h="nocode"
 
222
                try:
 
223
                        fun.code=h
 
224
                except AttributeError:
 
225
                        pass
 
226
                return h
 
227
reg_subst=re.compile(r"(\\\\)|(\$\$)|\$\{([^}]+)\}")
 
228
def subst_vars(expr,params):
 
229
        def repl_var(m):
 
230
                if m.group(1):
 
231
                        return'\\'
 
232
                if m.group(2):
 
233
                        return'$'
 
234
                try:
 
235
                        return params.get_flat(m.group(3))
 
236
                except AttributeError:
 
237
                        return params[m.group(3)]
 
238
        return reg_subst.sub(repl_var,expr)
 
239
def destos_to_binfmt(key):
 
240
        if key=='darwin':
 
241
                return'mac-o'
 
242
        elif key in('win32','cygwin','uwin','msys'):
 
243
                return'pe'
 
244
        return'elf'
 
245
def unversioned_sys_platform():
 
246
        s=sys.platform
 
247
        if s=='java':
 
248
                from java.lang import System
 
249
                s=System.getProperty('os.name')
 
250
                if s=='Mac OS X':
 
251
                        return'darwin'
 
252
                elif s.startswith('Windows '):
 
253
                        return'win32'
 
254
                elif s=='OS/2':
 
255
                        return'os2'
 
256
                elif s=='HP-UX':
 
257
                        return'hpux'
 
258
                elif s in('SunOS','Solaris'):
 
259
                        return'sunos'
 
260
                else:s=s.lower()
 
261
        if s=='win32'or s.endswith('os2')and s!='sunos2':return s
 
262
        return re.split('\d+$',s)[0]
 
263
def nada(*k,**kw):
 
264
        pass
 
265
class Timer(object):
 
266
        def __init__(self):
 
267
                self.start_time=datetime.datetime.utcnow()
 
268
        def __str__(self):
 
269
                delta=datetime.datetime.utcnow()-self.start_time
 
270
                days=int(delta.days)
 
271
                hours=delta.seconds//3600
 
272
                minutes=(delta.seconds-hours*3600)//60
 
273
                seconds=delta.seconds-hours*3600-minutes*60+float(delta.microseconds)/1000/1000
 
274
                result=''
 
275
                if days:
 
276
                        result+='%dd'%days
 
277
                if days or hours:
 
278
                        result+='%dh'%hours
 
279
                if days or hours or minutes:
 
280
                        result+='%dm'%minutes
 
281
                return'%s%.3fs'%(result,seconds)
 
282
if is_win32:
 
283
        old=shutil.copy2
 
284
        def copy2(src,dst):
 
285
                old(src,dst)
 
286
                shutil.copystat(src,src)
 
287
        setattr(shutil,'copy2',copy2)
 
288
if os.name=='java':
 
289
        try:
 
290
                gc.disable()
 
291
                gc.enable()
 
292
        except NotImplementedError:
 
293
                gc.disable=gc.enable
 
294
def read_la_file(path):
 
295
        sp=re.compile(r'^([^=]+)=\'(.*)\'$')
 
296
        dc={}
 
297
        for line in readf(path).splitlines():
 
298
                try:
 
299
                        _,left,right,_=sp.split(line.strip())
 
300
                        dc[left]=right
 
301
                except ValueError:
 
302
                        pass
 
303
        return dc
 
304
def nogc(fun):
 
305
        def f(*k,**kw):
 
306
                try:
 
307
                        gc.disable()
 
308
                        ret=fun(*k,**kw)
 
309
                finally:
 
310
                        gc.enable()
 
311
                return ret
 
312
        f.__doc__=fun.__doc__
 
313
        return f
 
314
def run_once(fun):
 
315
        cache={}
 
316
        def wrap(k):
 
317
                try:
 
318
                        return cache[k]
 
319
                except KeyError:
 
320
                        ret=fun(k)
 
321
                        cache[k]=ret
 
322
                        return ret
 
323
        wrap.__cache__=cache
 
324
        return wrap
 
325
def get_registry_app_path(key,filename):
 
326
        if not winreg:
 
327
                return None
 
328
        try:
 
329
                result=winreg.QueryValue(key,"Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\%s.exe"%filename[0])
 
330
        except WindowsError:
 
331
                pass
 
332
        else:
 
333
                if os.path.isfile(result):
 
334
                        return result