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