##// END OF EJS Templates
util: remove unreachable code...
Bryan O'Sullivan -
r18930:9dd5a481 default
parent child Browse files
Show More
@@ -1,1928 +1,1926 b''
1 # util.py - Mercurial utility functions and platform specific implementations
1 # util.py - Mercurial utility functions and platform specific implementations
2 #
2 #
3 # Copyright 2005 K. Thananchayan <thananck@yahoo.com>
3 # Copyright 2005 K. Thananchayan <thananck@yahoo.com>
4 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
5 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
5 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
6 #
6 #
7 # This software may be used and distributed according to the terms of the
7 # This software may be used and distributed according to the terms of the
8 # GNU General Public License version 2 or any later version.
8 # GNU General Public License version 2 or any later version.
9
9
10 """Mercurial utility functions and platform specific implementations.
10 """Mercurial utility functions and platform specific implementations.
11
11
12 This contains helper routines that are independent of the SCM core and
12 This contains helper routines that are independent of the SCM core and
13 hide platform-specific details from the core.
13 hide platform-specific details from the core.
14 """
14 """
15
15
16 from i18n import _
16 from i18n import _
17 import error, osutil, encoding, collections
17 import error, osutil, encoding, collections
18 import errno, re, shutil, sys, tempfile, traceback
18 import errno, re, shutil, sys, tempfile, traceback
19 import os, time, datetime, calendar, textwrap, signal
19 import os, time, datetime, calendar, textwrap, signal
20 import imp, socket, urllib
20 import imp, socket, urllib
21
21
22 if os.name == 'nt':
22 if os.name == 'nt':
23 import windows as platform
23 import windows as platform
24 else:
24 else:
25 import posix as platform
25 import posix as platform
26
26
27 cachestat = platform.cachestat
27 cachestat = platform.cachestat
28 checkexec = platform.checkexec
28 checkexec = platform.checkexec
29 checklink = platform.checklink
29 checklink = platform.checklink
30 copymode = platform.copymode
30 copymode = platform.copymode
31 executablepath = platform.executablepath
31 executablepath = platform.executablepath
32 expandglobs = platform.expandglobs
32 expandglobs = platform.expandglobs
33 explainexit = platform.explainexit
33 explainexit = platform.explainexit
34 findexe = platform.findexe
34 findexe = platform.findexe
35 gethgcmd = platform.gethgcmd
35 gethgcmd = platform.gethgcmd
36 getuser = platform.getuser
36 getuser = platform.getuser
37 groupmembers = platform.groupmembers
37 groupmembers = platform.groupmembers
38 groupname = platform.groupname
38 groupname = platform.groupname
39 hidewindow = platform.hidewindow
39 hidewindow = platform.hidewindow
40 isexec = platform.isexec
40 isexec = platform.isexec
41 isowner = platform.isowner
41 isowner = platform.isowner
42 localpath = platform.localpath
42 localpath = platform.localpath
43 lookupreg = platform.lookupreg
43 lookupreg = platform.lookupreg
44 makedir = platform.makedir
44 makedir = platform.makedir
45 nlinks = platform.nlinks
45 nlinks = platform.nlinks
46 normpath = platform.normpath
46 normpath = platform.normpath
47 normcase = platform.normcase
47 normcase = platform.normcase
48 openhardlinks = platform.openhardlinks
48 openhardlinks = platform.openhardlinks
49 oslink = platform.oslink
49 oslink = platform.oslink
50 parsepatchoutput = platform.parsepatchoutput
50 parsepatchoutput = platform.parsepatchoutput
51 pconvert = platform.pconvert
51 pconvert = platform.pconvert
52 popen = platform.popen
52 popen = platform.popen
53 posixfile = platform.posixfile
53 posixfile = platform.posixfile
54 quotecommand = platform.quotecommand
54 quotecommand = platform.quotecommand
55 realpath = platform.realpath
55 realpath = platform.realpath
56 rename = platform.rename
56 rename = platform.rename
57 samedevice = platform.samedevice
57 samedevice = platform.samedevice
58 samefile = platform.samefile
58 samefile = platform.samefile
59 samestat = platform.samestat
59 samestat = platform.samestat
60 setbinary = platform.setbinary
60 setbinary = platform.setbinary
61 setflags = platform.setflags
61 setflags = platform.setflags
62 setsignalhandler = platform.setsignalhandler
62 setsignalhandler = platform.setsignalhandler
63 shellquote = platform.shellquote
63 shellquote = platform.shellquote
64 spawndetached = platform.spawndetached
64 spawndetached = platform.spawndetached
65 split = platform.split
65 split = platform.split
66 sshargs = platform.sshargs
66 sshargs = platform.sshargs
67 statfiles = getattr(osutil, 'statfiles', platform.statfiles)
67 statfiles = getattr(osutil, 'statfiles', platform.statfiles)
68 statisexec = platform.statisexec
68 statisexec = platform.statisexec
69 statislink = platform.statislink
69 statislink = platform.statislink
70 termwidth = platform.termwidth
70 termwidth = platform.termwidth
71 testpid = platform.testpid
71 testpid = platform.testpid
72 umask = platform.umask
72 umask = platform.umask
73 unlink = platform.unlink
73 unlink = platform.unlink
74 unlinkpath = platform.unlinkpath
74 unlinkpath = platform.unlinkpath
75 username = platform.username
75 username = platform.username
76
76
77 # Python compatibility
77 # Python compatibility
78
78
79 _notset = object()
79 _notset = object()
80
80
81 def safehasattr(thing, attr):
81 def safehasattr(thing, attr):
82 return getattr(thing, attr, _notset) is not _notset
82 return getattr(thing, attr, _notset) is not _notset
83
83
84 def sha1(s=''):
84 def sha1(s=''):
85 '''
85 '''
86 Low-overhead wrapper around Python's SHA support
86 Low-overhead wrapper around Python's SHA support
87
87
88 >>> f = _fastsha1
88 >>> f = _fastsha1
89 >>> a = sha1()
89 >>> a = sha1()
90 >>> a = f()
90 >>> a = f()
91 >>> a.hexdigest()
91 >>> a.hexdigest()
92 'da39a3ee5e6b4b0d3255bfef95601890afd80709'
92 'da39a3ee5e6b4b0d3255bfef95601890afd80709'
93 '''
93 '''
94
94
95 return _fastsha1(s)
95 return _fastsha1(s)
96
96
97 def _fastsha1(s=''):
97 def _fastsha1(s=''):
98 # This function will import sha1 from hashlib or sha (whichever is
98 # This function will import sha1 from hashlib or sha (whichever is
99 # available) and overwrite itself with it on the first call.
99 # available) and overwrite itself with it on the first call.
100 # Subsequent calls will go directly to the imported function.
100 # Subsequent calls will go directly to the imported function.
101 if sys.version_info >= (2, 5):
101 if sys.version_info >= (2, 5):
102 from hashlib import sha1 as _sha1
102 from hashlib import sha1 as _sha1
103 else:
103 else:
104 from sha import sha as _sha1
104 from sha import sha as _sha1
105 global _fastsha1, sha1
105 global _fastsha1, sha1
106 _fastsha1 = sha1 = _sha1
106 _fastsha1 = sha1 = _sha1
107 return _sha1(s)
107 return _sha1(s)
108
108
109 try:
109 try:
110 buffer = buffer
110 buffer = buffer
111 except NameError:
111 except NameError:
112 if sys.version_info[0] < 3:
112 if sys.version_info[0] < 3:
113 def buffer(sliceable, offset=0):
113 def buffer(sliceable, offset=0):
114 return sliceable[offset:]
114 return sliceable[offset:]
115 else:
115 else:
116 def buffer(sliceable, offset=0):
116 def buffer(sliceable, offset=0):
117 return memoryview(sliceable)[offset:]
117 return memoryview(sliceable)[offset:]
118
118
119 import subprocess
119 import subprocess
120 closefds = os.name == 'posix'
120 closefds = os.name == 'posix'
121
121
122 def popen2(cmd, env=None, newlines=False):
122 def popen2(cmd, env=None, newlines=False):
123 # Setting bufsize to -1 lets the system decide the buffer size.
123 # Setting bufsize to -1 lets the system decide the buffer size.
124 # The default for bufsize is 0, meaning unbuffered. This leads to
124 # The default for bufsize is 0, meaning unbuffered. This leads to
125 # poor performance on Mac OS X: http://bugs.python.org/issue4194
125 # poor performance on Mac OS X: http://bugs.python.org/issue4194
126 p = subprocess.Popen(cmd, shell=True, bufsize=-1,
126 p = subprocess.Popen(cmd, shell=True, bufsize=-1,
127 close_fds=closefds,
127 close_fds=closefds,
128 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
128 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
129 universal_newlines=newlines,
129 universal_newlines=newlines,
130 env=env)
130 env=env)
131 return p.stdin, p.stdout
131 return p.stdin, p.stdout
132
132
133 def popen3(cmd, env=None, newlines=False):
133 def popen3(cmd, env=None, newlines=False):
134 stdin, stdout, stderr, p = popen4(cmd, env, newlines)
134 stdin, stdout, stderr, p = popen4(cmd, env, newlines)
135 return stdin, stdout, stderr
135 return stdin, stdout, stderr
136
136
137 def popen4(cmd, env=None, newlines=False):
137 def popen4(cmd, env=None, newlines=False):
138 p = subprocess.Popen(cmd, shell=True, bufsize=-1,
138 p = subprocess.Popen(cmd, shell=True, bufsize=-1,
139 close_fds=closefds,
139 close_fds=closefds,
140 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
140 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
141 stderr=subprocess.PIPE,
141 stderr=subprocess.PIPE,
142 universal_newlines=newlines,
142 universal_newlines=newlines,
143 env=env)
143 env=env)
144 return p.stdin, p.stdout, p.stderr, p
144 return p.stdin, p.stdout, p.stderr, p
145
145
146 def version():
146 def version():
147 """Return version information if available."""
147 """Return version information if available."""
148 try:
148 try:
149 import __version__
149 import __version__
150 return __version__.version
150 return __version__.version
151 except ImportError:
151 except ImportError:
152 return 'unknown'
152 return 'unknown'
153
153
154 # used by parsedate
154 # used by parsedate
155 defaultdateformats = (
155 defaultdateformats = (
156 '%Y-%m-%d %H:%M:%S',
156 '%Y-%m-%d %H:%M:%S',
157 '%Y-%m-%d %I:%M:%S%p',
157 '%Y-%m-%d %I:%M:%S%p',
158 '%Y-%m-%d %H:%M',
158 '%Y-%m-%d %H:%M',
159 '%Y-%m-%d %I:%M%p',
159 '%Y-%m-%d %I:%M%p',
160 '%Y-%m-%d',
160 '%Y-%m-%d',
161 '%m-%d',
161 '%m-%d',
162 '%m/%d',
162 '%m/%d',
163 '%m/%d/%y',
163 '%m/%d/%y',
164 '%m/%d/%Y',
164 '%m/%d/%Y',
165 '%a %b %d %H:%M:%S %Y',
165 '%a %b %d %H:%M:%S %Y',
166 '%a %b %d %I:%M:%S%p %Y',
166 '%a %b %d %I:%M:%S%p %Y',
167 '%a, %d %b %Y %H:%M:%S', # GNU coreutils "/bin/date --rfc-2822"
167 '%a, %d %b %Y %H:%M:%S', # GNU coreutils "/bin/date --rfc-2822"
168 '%b %d %H:%M:%S %Y',
168 '%b %d %H:%M:%S %Y',
169 '%b %d %I:%M:%S%p %Y',
169 '%b %d %I:%M:%S%p %Y',
170 '%b %d %H:%M:%S',
170 '%b %d %H:%M:%S',
171 '%b %d %I:%M:%S%p',
171 '%b %d %I:%M:%S%p',
172 '%b %d %H:%M',
172 '%b %d %H:%M',
173 '%b %d %I:%M%p',
173 '%b %d %I:%M%p',
174 '%b %d %Y',
174 '%b %d %Y',
175 '%b %d',
175 '%b %d',
176 '%H:%M:%S',
176 '%H:%M:%S',
177 '%I:%M:%S%p',
177 '%I:%M:%S%p',
178 '%H:%M',
178 '%H:%M',
179 '%I:%M%p',
179 '%I:%M%p',
180 )
180 )
181
181
182 extendeddateformats = defaultdateformats + (
182 extendeddateformats = defaultdateformats + (
183 "%Y",
183 "%Y",
184 "%Y-%m",
184 "%Y-%m",
185 "%b",
185 "%b",
186 "%b %Y",
186 "%b %Y",
187 )
187 )
188
188
189 def cachefunc(func):
189 def cachefunc(func):
190 '''cache the result of function calls'''
190 '''cache the result of function calls'''
191 # XXX doesn't handle keywords args
191 # XXX doesn't handle keywords args
192 cache = {}
192 cache = {}
193 if func.func_code.co_argcount == 1:
193 if func.func_code.co_argcount == 1:
194 # we gain a small amount of time because
194 # we gain a small amount of time because
195 # we don't need to pack/unpack the list
195 # we don't need to pack/unpack the list
196 def f(arg):
196 def f(arg):
197 if arg not in cache:
197 if arg not in cache:
198 cache[arg] = func(arg)
198 cache[arg] = func(arg)
199 return cache[arg]
199 return cache[arg]
200 else:
200 else:
201 def f(*args):
201 def f(*args):
202 if args not in cache:
202 if args not in cache:
203 cache[args] = func(*args)
203 cache[args] = func(*args)
204 return cache[args]
204 return cache[args]
205
205
206 return f
206 return f
207
207
208 try:
208 try:
209 collections.deque.remove
209 collections.deque.remove
210 deque = collections.deque
210 deque = collections.deque
211 except AttributeError:
211 except AttributeError:
212 # python 2.4 lacks deque.remove
212 # python 2.4 lacks deque.remove
213 class deque(collections.deque):
213 class deque(collections.deque):
214 def remove(self, val):
214 def remove(self, val):
215 for i, v in enumerate(self):
215 for i, v in enumerate(self):
216 if v == val:
216 if v == val:
217 del self[i]
217 del self[i]
218 break
218 break
219
219
220 class lrucachedict(object):
220 class lrucachedict(object):
221 '''cache most recent gets from or sets to this dictionary'''
221 '''cache most recent gets from or sets to this dictionary'''
222 def __init__(self, maxsize):
222 def __init__(self, maxsize):
223 self._cache = {}
223 self._cache = {}
224 self._maxsize = maxsize
224 self._maxsize = maxsize
225 self._order = deque()
225 self._order = deque()
226
226
227 def __getitem__(self, key):
227 def __getitem__(self, key):
228 value = self._cache[key]
228 value = self._cache[key]
229 self._order.remove(key)
229 self._order.remove(key)
230 self._order.append(key)
230 self._order.append(key)
231 return value
231 return value
232
232
233 def __setitem__(self, key, value):
233 def __setitem__(self, key, value):
234 if key not in self._cache:
234 if key not in self._cache:
235 if len(self._cache) >= self._maxsize:
235 if len(self._cache) >= self._maxsize:
236 del self._cache[self._order.popleft()]
236 del self._cache[self._order.popleft()]
237 else:
237 else:
238 self._order.remove(key)
238 self._order.remove(key)
239 self._cache[key] = value
239 self._cache[key] = value
240 self._order.append(key)
240 self._order.append(key)
241
241
242 def __contains__(self, key):
242 def __contains__(self, key):
243 return key in self._cache
243 return key in self._cache
244
244
245 def lrucachefunc(func):
245 def lrucachefunc(func):
246 '''cache most recent results of function calls'''
246 '''cache most recent results of function calls'''
247 cache = {}
247 cache = {}
248 order = deque()
248 order = deque()
249 if func.func_code.co_argcount == 1:
249 if func.func_code.co_argcount == 1:
250 def f(arg):
250 def f(arg):
251 if arg not in cache:
251 if arg not in cache:
252 if len(cache) > 20:
252 if len(cache) > 20:
253 del cache[order.popleft()]
253 del cache[order.popleft()]
254 cache[arg] = func(arg)
254 cache[arg] = func(arg)
255 else:
255 else:
256 order.remove(arg)
256 order.remove(arg)
257 order.append(arg)
257 order.append(arg)
258 return cache[arg]
258 return cache[arg]
259 else:
259 else:
260 def f(*args):
260 def f(*args):
261 if args not in cache:
261 if args not in cache:
262 if len(cache) > 20:
262 if len(cache) > 20:
263 del cache[order.popleft()]
263 del cache[order.popleft()]
264 cache[args] = func(*args)
264 cache[args] = func(*args)
265 else:
265 else:
266 order.remove(args)
266 order.remove(args)
267 order.append(args)
267 order.append(args)
268 return cache[args]
268 return cache[args]
269
269
270 return f
270 return f
271
271
272 class propertycache(object):
272 class propertycache(object):
273 def __init__(self, func):
273 def __init__(self, func):
274 self.func = func
274 self.func = func
275 self.name = func.__name__
275 self.name = func.__name__
276 def __get__(self, obj, type=None):
276 def __get__(self, obj, type=None):
277 result = self.func(obj)
277 result = self.func(obj)
278 self.cachevalue(obj, result)
278 self.cachevalue(obj, result)
279 return result
279 return result
280
280
281 def cachevalue(self, obj, value):
281 def cachevalue(self, obj, value):
282 setattr(obj, self.name, value)
282 setattr(obj, self.name, value)
283
283
284 def pipefilter(s, cmd):
284 def pipefilter(s, cmd):
285 '''filter string S through command CMD, returning its output'''
285 '''filter string S through command CMD, returning its output'''
286 p = subprocess.Popen(cmd, shell=True, close_fds=closefds,
286 p = subprocess.Popen(cmd, shell=True, close_fds=closefds,
287 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
287 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
288 pout, perr = p.communicate(s)
288 pout, perr = p.communicate(s)
289 return pout
289 return pout
290
290
291 def tempfilter(s, cmd):
291 def tempfilter(s, cmd):
292 '''filter string S through a pair of temporary files with CMD.
292 '''filter string S through a pair of temporary files with CMD.
293 CMD is used as a template to create the real command to be run,
293 CMD is used as a template to create the real command to be run,
294 with the strings INFILE and OUTFILE replaced by the real names of
294 with the strings INFILE and OUTFILE replaced by the real names of
295 the temporary files generated.'''
295 the temporary files generated.'''
296 inname, outname = None, None
296 inname, outname = None, None
297 try:
297 try:
298 infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
298 infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
299 fp = os.fdopen(infd, 'wb')
299 fp = os.fdopen(infd, 'wb')
300 fp.write(s)
300 fp.write(s)
301 fp.close()
301 fp.close()
302 outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
302 outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
303 os.close(outfd)
303 os.close(outfd)
304 cmd = cmd.replace('INFILE', inname)
304 cmd = cmd.replace('INFILE', inname)
305 cmd = cmd.replace('OUTFILE', outname)
305 cmd = cmd.replace('OUTFILE', outname)
306 code = os.system(cmd)
306 code = os.system(cmd)
307 if sys.platform == 'OpenVMS' and code & 1:
307 if sys.platform == 'OpenVMS' and code & 1:
308 code = 0
308 code = 0
309 if code:
309 if code:
310 raise Abort(_("command '%s' failed: %s") %
310 raise Abort(_("command '%s' failed: %s") %
311 (cmd, explainexit(code)))
311 (cmd, explainexit(code)))
312 fp = open(outname, 'rb')
312 fp = open(outname, 'rb')
313 r = fp.read()
313 r = fp.read()
314 fp.close()
314 fp.close()
315 return r
315 return r
316 finally:
316 finally:
317 try:
317 try:
318 if inname:
318 if inname:
319 os.unlink(inname)
319 os.unlink(inname)
320 except OSError:
320 except OSError:
321 pass
321 pass
322 try:
322 try:
323 if outname:
323 if outname:
324 os.unlink(outname)
324 os.unlink(outname)
325 except OSError:
325 except OSError:
326 pass
326 pass
327
327
328 filtertable = {
328 filtertable = {
329 'tempfile:': tempfilter,
329 'tempfile:': tempfilter,
330 'pipe:': pipefilter,
330 'pipe:': pipefilter,
331 }
331 }
332
332
333 def filter(s, cmd):
333 def filter(s, cmd):
334 "filter a string through a command that transforms its input to its output"
334 "filter a string through a command that transforms its input to its output"
335 for name, fn in filtertable.iteritems():
335 for name, fn in filtertable.iteritems():
336 if cmd.startswith(name):
336 if cmd.startswith(name):
337 return fn(s, cmd[len(name):].lstrip())
337 return fn(s, cmd[len(name):].lstrip())
338 return pipefilter(s, cmd)
338 return pipefilter(s, cmd)
339
339
340 def binary(s):
340 def binary(s):
341 """return true if a string is binary data"""
341 """return true if a string is binary data"""
342 return bool(s and '\0' in s)
342 return bool(s and '\0' in s)
343
343
344 def increasingchunks(source, min=1024, max=65536):
344 def increasingchunks(source, min=1024, max=65536):
345 '''return no less than min bytes per chunk while data remains,
345 '''return no less than min bytes per chunk while data remains,
346 doubling min after each chunk until it reaches max'''
346 doubling min after each chunk until it reaches max'''
347 def log2(x):
347 def log2(x):
348 if not x:
348 if not x:
349 return 0
349 return 0
350 i = 0
350 i = 0
351 while x:
351 while x:
352 x >>= 1
352 x >>= 1
353 i += 1
353 i += 1
354 return i - 1
354 return i - 1
355
355
356 buf = []
356 buf = []
357 blen = 0
357 blen = 0
358 for chunk in source:
358 for chunk in source:
359 buf.append(chunk)
359 buf.append(chunk)
360 blen += len(chunk)
360 blen += len(chunk)
361 if blen >= min:
361 if blen >= min:
362 if min < max:
362 if min < max:
363 min = min << 1
363 min = min << 1
364 nmin = 1 << log2(blen)
364 nmin = 1 << log2(blen)
365 if nmin > min:
365 if nmin > min:
366 min = nmin
366 min = nmin
367 if min > max:
367 if min > max:
368 min = max
368 min = max
369 yield ''.join(buf)
369 yield ''.join(buf)
370 blen = 0
370 blen = 0
371 buf = []
371 buf = []
372 if buf:
372 if buf:
373 yield ''.join(buf)
373 yield ''.join(buf)
374
374
375 Abort = error.Abort
375 Abort = error.Abort
376
376
377 def always(fn):
377 def always(fn):
378 return True
378 return True
379
379
380 def never(fn):
380 def never(fn):
381 return False
381 return False
382
382
383 def pathto(root, n1, n2):
383 def pathto(root, n1, n2):
384 '''return the relative path from one place to another.
384 '''return the relative path from one place to another.
385 root should use os.sep to separate directories
385 root should use os.sep to separate directories
386 n1 should use os.sep to separate directories
386 n1 should use os.sep to separate directories
387 n2 should use "/" to separate directories
387 n2 should use "/" to separate directories
388 returns an os.sep-separated path.
388 returns an os.sep-separated path.
389
389
390 If n1 is a relative path, it's assumed it's
390 If n1 is a relative path, it's assumed it's
391 relative to root.
391 relative to root.
392 n2 should always be relative to root.
392 n2 should always be relative to root.
393 '''
393 '''
394 if not n1:
394 if not n1:
395 return localpath(n2)
395 return localpath(n2)
396 if os.path.isabs(n1):
396 if os.path.isabs(n1):
397 if os.path.splitdrive(root)[0] != os.path.splitdrive(n1)[0]:
397 if os.path.splitdrive(root)[0] != os.path.splitdrive(n1)[0]:
398 return os.path.join(root, localpath(n2))
398 return os.path.join(root, localpath(n2))
399 n2 = '/'.join((pconvert(root), n2))
399 n2 = '/'.join((pconvert(root), n2))
400 a, b = splitpath(n1), n2.split('/')
400 a, b = splitpath(n1), n2.split('/')
401 a.reverse()
401 a.reverse()
402 b.reverse()
402 b.reverse()
403 while a and b and a[-1] == b[-1]:
403 while a and b and a[-1] == b[-1]:
404 a.pop()
404 a.pop()
405 b.pop()
405 b.pop()
406 b.reverse()
406 b.reverse()
407 return os.sep.join((['..'] * len(a)) + b) or '.'
407 return os.sep.join((['..'] * len(a)) + b) or '.'
408
408
409 _hgexecutable = None
409 _hgexecutable = None
410
410
411 def mainfrozen():
411 def mainfrozen():
412 """return True if we are a frozen executable.
412 """return True if we are a frozen executable.
413
413
414 The code supports py2exe (most common, Windows only) and tools/freeze
414 The code supports py2exe (most common, Windows only) and tools/freeze
415 (portable, not much used).
415 (portable, not much used).
416 """
416 """
417 return (safehasattr(sys, "frozen") or # new py2exe
417 return (safehasattr(sys, "frozen") or # new py2exe
418 safehasattr(sys, "importers") or # old py2exe
418 safehasattr(sys, "importers") or # old py2exe
419 imp.is_frozen("__main__")) # tools/freeze
419 imp.is_frozen("__main__")) # tools/freeze
420
420
421 def hgexecutable():
421 def hgexecutable():
422 """return location of the 'hg' executable.
422 """return location of the 'hg' executable.
423
423
424 Defaults to $HG or 'hg' in the search path.
424 Defaults to $HG or 'hg' in the search path.
425 """
425 """
426 if _hgexecutable is None:
426 if _hgexecutable is None:
427 hg = os.environ.get('HG')
427 hg = os.environ.get('HG')
428 mainmod = sys.modules['__main__']
428 mainmod = sys.modules['__main__']
429 if hg:
429 if hg:
430 _sethgexecutable(hg)
430 _sethgexecutable(hg)
431 elif mainfrozen():
431 elif mainfrozen():
432 _sethgexecutable(sys.executable)
432 _sethgexecutable(sys.executable)
433 elif os.path.basename(getattr(mainmod, '__file__', '')) == 'hg':
433 elif os.path.basename(getattr(mainmod, '__file__', '')) == 'hg':
434 _sethgexecutable(mainmod.__file__)
434 _sethgexecutable(mainmod.__file__)
435 else:
435 else:
436 exe = findexe('hg') or os.path.basename(sys.argv[0])
436 exe = findexe('hg') or os.path.basename(sys.argv[0])
437 _sethgexecutable(exe)
437 _sethgexecutable(exe)
438 return _hgexecutable
438 return _hgexecutable
439
439
440 def _sethgexecutable(path):
440 def _sethgexecutable(path):
441 """set location of the 'hg' executable"""
441 """set location of the 'hg' executable"""
442 global _hgexecutable
442 global _hgexecutable
443 _hgexecutable = path
443 _hgexecutable = path
444
444
445 def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None, out=None):
445 def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None, out=None):
446 '''enhanced shell command execution.
446 '''enhanced shell command execution.
447 run with environment maybe modified, maybe in different dir.
447 run with environment maybe modified, maybe in different dir.
448
448
449 if command fails and onerr is None, return status. if ui object,
449 if command fails and onerr is None, return status. if ui object,
450 print error message and return status, else raise onerr object as
450 print error message and return status, else raise onerr object as
451 exception.
451 exception.
452
452
453 if out is specified, it is assumed to be a file-like object that has a
453 if out is specified, it is assumed to be a file-like object that has a
454 write() method. stdout and stderr will be redirected to out.'''
454 write() method. stdout and stderr will be redirected to out.'''
455 try:
455 try:
456 sys.stdout.flush()
456 sys.stdout.flush()
457 except Exception:
457 except Exception:
458 pass
458 pass
459 def py2shell(val):
459 def py2shell(val):
460 'convert python object into string that is useful to shell'
460 'convert python object into string that is useful to shell'
461 if val is None or val is False:
461 if val is None or val is False:
462 return '0'
462 return '0'
463 if val is True:
463 if val is True:
464 return '1'
464 return '1'
465 return str(val)
465 return str(val)
466 origcmd = cmd
466 origcmd = cmd
467 cmd = quotecommand(cmd)
467 cmd = quotecommand(cmd)
468 if sys.platform == 'plan9':
468 if sys.platform == 'plan9':
469 # subprocess kludge to work around issues in half-baked Python
469 # subprocess kludge to work around issues in half-baked Python
470 # ports, notably bichued/python:
470 # ports, notably bichued/python:
471 if not cwd is None:
471 if not cwd is None:
472 os.chdir(cwd)
472 os.chdir(cwd)
473 rc = os.system(cmd)
473 rc = os.system(cmd)
474 else:
474 else:
475 env = dict(os.environ)
475 env = dict(os.environ)
476 env.update((k, py2shell(v)) for k, v in environ.iteritems())
476 env.update((k, py2shell(v)) for k, v in environ.iteritems())
477 env['HG'] = hgexecutable()
477 env['HG'] = hgexecutable()
478 if out is None or out == sys.__stdout__:
478 if out is None or out == sys.__stdout__:
479 rc = subprocess.call(cmd, shell=True, close_fds=closefds,
479 rc = subprocess.call(cmd, shell=True, close_fds=closefds,
480 env=env, cwd=cwd)
480 env=env, cwd=cwd)
481 else:
481 else:
482 proc = subprocess.Popen(cmd, shell=True, close_fds=closefds,
482 proc = subprocess.Popen(cmd, shell=True, close_fds=closefds,
483 env=env, cwd=cwd, stdout=subprocess.PIPE,
483 env=env, cwd=cwd, stdout=subprocess.PIPE,
484 stderr=subprocess.STDOUT)
484 stderr=subprocess.STDOUT)
485 for line in proc.stdout:
485 for line in proc.stdout:
486 out.write(line)
486 out.write(line)
487 proc.wait()
487 proc.wait()
488 rc = proc.returncode
488 rc = proc.returncode
489 if sys.platform == 'OpenVMS' and rc & 1:
489 if sys.platform == 'OpenVMS' and rc & 1:
490 rc = 0
490 rc = 0
491 if rc and onerr:
491 if rc and onerr:
492 errmsg = '%s %s' % (os.path.basename(origcmd.split(None, 1)[0]),
492 errmsg = '%s %s' % (os.path.basename(origcmd.split(None, 1)[0]),
493 explainexit(rc)[0])
493 explainexit(rc)[0])
494 if errprefix:
494 if errprefix:
495 errmsg = '%s: %s' % (errprefix, errmsg)
495 errmsg = '%s: %s' % (errprefix, errmsg)
496 try:
496 try:
497 onerr.warn(errmsg + '\n')
497 onerr.warn(errmsg + '\n')
498 except AttributeError:
498 except AttributeError:
499 raise onerr(errmsg)
499 raise onerr(errmsg)
500 return rc
500 return rc
501
501
502 def checksignature(func):
502 def checksignature(func):
503 '''wrap a function with code to check for calling errors'''
503 '''wrap a function with code to check for calling errors'''
504 def check(*args, **kwargs):
504 def check(*args, **kwargs):
505 try:
505 try:
506 return func(*args, **kwargs)
506 return func(*args, **kwargs)
507 except TypeError:
507 except TypeError:
508 if len(traceback.extract_tb(sys.exc_info()[2])) == 1:
508 if len(traceback.extract_tb(sys.exc_info()[2])) == 1:
509 raise error.SignatureError
509 raise error.SignatureError
510 raise
510 raise
511
511
512 return check
512 return check
513
513
514 def copyfile(src, dest):
514 def copyfile(src, dest):
515 "copy a file, preserving mode and atime/mtime"
515 "copy a file, preserving mode and atime/mtime"
516 if os.path.lexists(dest):
516 if os.path.lexists(dest):
517 unlink(dest)
517 unlink(dest)
518 if os.path.islink(src):
518 if os.path.islink(src):
519 os.symlink(os.readlink(src), dest)
519 os.symlink(os.readlink(src), dest)
520 else:
520 else:
521 try:
521 try:
522 shutil.copyfile(src, dest)
522 shutil.copyfile(src, dest)
523 shutil.copymode(src, dest)
523 shutil.copymode(src, dest)
524 except shutil.Error, inst:
524 except shutil.Error, inst:
525 raise Abort(str(inst))
525 raise Abort(str(inst))
526
526
527 def copyfiles(src, dst, hardlink=None):
527 def copyfiles(src, dst, hardlink=None):
528 """Copy a directory tree using hardlinks if possible"""
528 """Copy a directory tree using hardlinks if possible"""
529
529
530 if hardlink is None:
530 if hardlink is None:
531 hardlink = (os.stat(src).st_dev ==
531 hardlink = (os.stat(src).st_dev ==
532 os.stat(os.path.dirname(dst)).st_dev)
532 os.stat(os.path.dirname(dst)).st_dev)
533
533
534 num = 0
534 num = 0
535 if os.path.isdir(src):
535 if os.path.isdir(src):
536 os.mkdir(dst)
536 os.mkdir(dst)
537 for name, kind in osutil.listdir(src):
537 for name, kind in osutil.listdir(src):
538 srcname = os.path.join(src, name)
538 srcname = os.path.join(src, name)
539 dstname = os.path.join(dst, name)
539 dstname = os.path.join(dst, name)
540 hardlink, n = copyfiles(srcname, dstname, hardlink)
540 hardlink, n = copyfiles(srcname, dstname, hardlink)
541 num += n
541 num += n
542 else:
542 else:
543 if hardlink:
543 if hardlink:
544 try:
544 try:
545 oslink(src, dst)
545 oslink(src, dst)
546 except (IOError, OSError):
546 except (IOError, OSError):
547 hardlink = False
547 hardlink = False
548 shutil.copy(src, dst)
548 shutil.copy(src, dst)
549 else:
549 else:
550 shutil.copy(src, dst)
550 shutil.copy(src, dst)
551 num += 1
551 num += 1
552
552
553 return hardlink, num
553 return hardlink, num
554
554
555 _winreservednames = '''con prn aux nul
555 _winreservednames = '''con prn aux nul
556 com1 com2 com3 com4 com5 com6 com7 com8 com9
556 com1 com2 com3 com4 com5 com6 com7 com8 com9
557 lpt1 lpt2 lpt3 lpt4 lpt5 lpt6 lpt7 lpt8 lpt9'''.split()
557 lpt1 lpt2 lpt3 lpt4 lpt5 lpt6 lpt7 lpt8 lpt9'''.split()
558 _winreservedchars = ':*?"<>|'
558 _winreservedchars = ':*?"<>|'
559 def checkwinfilename(path):
559 def checkwinfilename(path):
560 '''Check that the base-relative path is a valid filename on Windows.
560 '''Check that the base-relative path is a valid filename on Windows.
561 Returns None if the path is ok, or a UI string describing the problem.
561 Returns None if the path is ok, or a UI string describing the problem.
562
562
563 >>> checkwinfilename("just/a/normal/path")
563 >>> checkwinfilename("just/a/normal/path")
564 >>> checkwinfilename("foo/bar/con.xml")
564 >>> checkwinfilename("foo/bar/con.xml")
565 "filename contains 'con', which is reserved on Windows"
565 "filename contains 'con', which is reserved on Windows"
566 >>> checkwinfilename("foo/con.xml/bar")
566 >>> checkwinfilename("foo/con.xml/bar")
567 "filename contains 'con', which is reserved on Windows"
567 "filename contains 'con', which is reserved on Windows"
568 >>> checkwinfilename("foo/bar/xml.con")
568 >>> checkwinfilename("foo/bar/xml.con")
569 >>> checkwinfilename("foo/bar/AUX/bla.txt")
569 >>> checkwinfilename("foo/bar/AUX/bla.txt")
570 "filename contains 'AUX', which is reserved on Windows"
570 "filename contains 'AUX', which is reserved on Windows"
571 >>> checkwinfilename("foo/bar/bla:.txt")
571 >>> checkwinfilename("foo/bar/bla:.txt")
572 "filename contains ':', which is reserved on Windows"
572 "filename contains ':', which is reserved on Windows"
573 >>> checkwinfilename("foo/bar/b\07la.txt")
573 >>> checkwinfilename("foo/bar/b\07la.txt")
574 "filename contains '\\\\x07', which is invalid on Windows"
574 "filename contains '\\\\x07', which is invalid on Windows"
575 >>> checkwinfilename("foo/bar/bla ")
575 >>> checkwinfilename("foo/bar/bla ")
576 "filename ends with ' ', which is not allowed on Windows"
576 "filename ends with ' ', which is not allowed on Windows"
577 >>> checkwinfilename("../bar")
577 >>> checkwinfilename("../bar")
578 '''
578 '''
579 for n in path.replace('\\', '/').split('/'):
579 for n in path.replace('\\', '/').split('/'):
580 if not n:
580 if not n:
581 continue
581 continue
582 for c in n:
582 for c in n:
583 if c in _winreservedchars:
583 if c in _winreservedchars:
584 return _("filename contains '%s', which is reserved "
584 return _("filename contains '%s', which is reserved "
585 "on Windows") % c
585 "on Windows") % c
586 if ord(c) <= 31:
586 if ord(c) <= 31:
587 return _("filename contains %r, which is invalid "
587 return _("filename contains %r, which is invalid "
588 "on Windows") % c
588 "on Windows") % c
589 base = n.split('.')[0]
589 base = n.split('.')[0]
590 if base and base.lower() in _winreservednames:
590 if base and base.lower() in _winreservednames:
591 return _("filename contains '%s', which is reserved "
591 return _("filename contains '%s', which is reserved "
592 "on Windows") % base
592 "on Windows") % base
593 t = n[-1]
593 t = n[-1]
594 if t in '. ' and n not in '..':
594 if t in '. ' and n not in '..':
595 return _("filename ends with '%s', which is not allowed "
595 return _("filename ends with '%s', which is not allowed "
596 "on Windows") % t
596 "on Windows") % t
597
597
598 if os.name == 'nt':
598 if os.name == 'nt':
599 checkosfilename = checkwinfilename
599 checkosfilename = checkwinfilename
600 else:
600 else:
601 checkosfilename = platform.checkosfilename
601 checkosfilename = platform.checkosfilename
602
602
603 def makelock(info, pathname):
603 def makelock(info, pathname):
604 try:
604 try:
605 return os.symlink(info, pathname)
605 return os.symlink(info, pathname)
606 except OSError, why:
606 except OSError, why:
607 if why.errno == errno.EEXIST:
607 if why.errno == errno.EEXIST:
608 raise
608 raise
609 except AttributeError: # no symlink in os
609 except AttributeError: # no symlink in os
610 pass
610 pass
611
611
612 ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
612 ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
613 os.write(ld, info)
613 os.write(ld, info)
614 os.close(ld)
614 os.close(ld)
615
615
616 def readlock(pathname):
616 def readlock(pathname):
617 try:
617 try:
618 return os.readlink(pathname)
618 return os.readlink(pathname)
619 except OSError, why:
619 except OSError, why:
620 if why.errno not in (errno.EINVAL, errno.ENOSYS):
620 if why.errno not in (errno.EINVAL, errno.ENOSYS):
621 raise
621 raise
622 except AttributeError: # no symlink in os
622 except AttributeError: # no symlink in os
623 pass
623 pass
624 fp = posixfile(pathname)
624 fp = posixfile(pathname)
625 r = fp.read()
625 r = fp.read()
626 fp.close()
626 fp.close()
627 return r
627 return r
628
628
629 def fstat(fp):
629 def fstat(fp):
630 '''stat file object that may not have fileno method.'''
630 '''stat file object that may not have fileno method.'''
631 try:
631 try:
632 return os.fstat(fp.fileno())
632 return os.fstat(fp.fileno())
633 except AttributeError:
633 except AttributeError:
634 return os.stat(fp.name)
634 return os.stat(fp.name)
635
635
636 # File system features
636 # File system features
637
637
638 def checkcase(path):
638 def checkcase(path):
639 """
639 """
640 Return true if the given path is on a case-sensitive filesystem
640 Return true if the given path is on a case-sensitive filesystem
641
641
642 Requires a path (like /foo/.hg) ending with a foldable final
642 Requires a path (like /foo/.hg) ending with a foldable final
643 directory component.
643 directory component.
644 """
644 """
645 s1 = os.stat(path)
645 s1 = os.stat(path)
646 d, b = os.path.split(path)
646 d, b = os.path.split(path)
647 b2 = b.upper()
647 b2 = b.upper()
648 if b == b2:
648 if b == b2:
649 b2 = b.lower()
649 b2 = b.lower()
650 if b == b2:
650 if b == b2:
651 return True # no evidence against case sensitivity
651 return True # no evidence against case sensitivity
652 p2 = os.path.join(d, b2)
652 p2 = os.path.join(d, b2)
653 try:
653 try:
654 s2 = os.stat(p2)
654 s2 = os.stat(p2)
655 if s2 == s1:
655 if s2 == s1:
656 return False
656 return False
657 return True
657 return True
658 except OSError:
658 except OSError:
659 return True
659 return True
660
660
661 try:
661 try:
662 import re2
662 import re2
663 _re2 = None
663 _re2 = None
664 except ImportError:
664 except ImportError:
665 _re2 = False
665 _re2 = False
666
666
667 def compilere(pat, flags=0):
667 def compilere(pat, flags=0):
668 '''Compile a regular expression, using re2 if possible
668 '''Compile a regular expression, using re2 if possible
669
669
670 For best performance, use only re2-compatible regexp features. The
670 For best performance, use only re2-compatible regexp features. The
671 only flags from the re module that are re2-compatible are
671 only flags from the re module that are re2-compatible are
672 IGNORECASE and MULTILINE.'''
672 IGNORECASE and MULTILINE.'''
673 global _re2
673 global _re2
674 if _re2 is None:
674 if _re2 is None:
675 try:
675 try:
676 re2.compile
676 re2.compile
677 _re2 = True
677 _re2 = True
678 except ImportError:
678 except ImportError:
679 _re2 = False
679 _re2 = False
680 if _re2 and (flags & ~(re.IGNORECASE | re.MULTILINE)) == 0:
680 if _re2 and (flags & ~(re.IGNORECASE | re.MULTILINE)) == 0:
681 if flags & re.IGNORECASE:
681 if flags & re.IGNORECASE:
682 pat = '(?i)' + pat
682 pat = '(?i)' + pat
683 if flags & re.MULTILINE:
683 if flags & re.MULTILINE:
684 pat = '(?m)' + pat
684 pat = '(?m)' + pat
685 try:
685 try:
686 return re2.compile(pat)
686 return re2.compile(pat)
687 except re2.error:
687 except re2.error:
688 pass
688 pass
689 return re.compile(pat, flags)
689 return re.compile(pat, flags)
690
690
691 _fspathcache = {}
691 _fspathcache = {}
692 def fspath(name, root):
692 def fspath(name, root):
693 '''Get name in the case stored in the filesystem
693 '''Get name in the case stored in the filesystem
694
694
695 The name should be relative to root, and be normcase-ed for efficiency.
695 The name should be relative to root, and be normcase-ed for efficiency.
696
696
697 Note that this function is unnecessary, and should not be
697 Note that this function is unnecessary, and should not be
698 called, for case-sensitive filesystems (simply because it's expensive).
698 called, for case-sensitive filesystems (simply because it's expensive).
699
699
700 The root should be normcase-ed, too.
700 The root should be normcase-ed, too.
701 '''
701 '''
702 def find(p, contents):
702 def find(p, contents):
703 for n in contents:
703 for n in contents:
704 if normcase(n) == p:
704 if normcase(n) == p:
705 return n
705 return n
706 return None
706 return None
707
707
708 seps = os.sep
708 seps = os.sep
709 if os.altsep:
709 if os.altsep:
710 seps = seps + os.altsep
710 seps = seps + os.altsep
711 # Protect backslashes. This gets silly very quickly.
711 # Protect backslashes. This gets silly very quickly.
712 seps.replace('\\','\\\\')
712 seps.replace('\\','\\\\')
713 pattern = re.compile(r'([^%s]+)|([%s]+)' % (seps, seps))
713 pattern = re.compile(r'([^%s]+)|([%s]+)' % (seps, seps))
714 dir = os.path.normpath(root)
714 dir = os.path.normpath(root)
715 result = []
715 result = []
716 for part, sep in pattern.findall(name):
716 for part, sep in pattern.findall(name):
717 if sep:
717 if sep:
718 result.append(sep)
718 result.append(sep)
719 continue
719 continue
720
720
721 if dir not in _fspathcache:
721 if dir not in _fspathcache:
722 _fspathcache[dir] = os.listdir(dir)
722 _fspathcache[dir] = os.listdir(dir)
723 contents = _fspathcache[dir]
723 contents = _fspathcache[dir]
724
724
725 found = find(part, contents)
725 found = find(part, contents)
726 if not found:
726 if not found:
727 # retry "once per directory" per "dirstate.walk" which
727 # retry "once per directory" per "dirstate.walk" which
728 # may take place for each patches of "hg qpush", for example
728 # may take place for each patches of "hg qpush", for example
729 contents = os.listdir(dir)
729 contents = os.listdir(dir)
730 _fspathcache[dir] = contents
730 _fspathcache[dir] = contents
731 found = find(part, contents)
731 found = find(part, contents)
732
732
733 result.append(found or part)
733 result.append(found or part)
734 dir = os.path.join(dir, part)
734 dir = os.path.join(dir, part)
735
735
736 return ''.join(result)
736 return ''.join(result)
737
737
738 def checknlink(testfile):
738 def checknlink(testfile):
739 '''check whether hardlink count reporting works properly'''
739 '''check whether hardlink count reporting works properly'''
740
740
741 # testfile may be open, so we need a separate file for checking to
741 # testfile may be open, so we need a separate file for checking to
742 # work around issue2543 (or testfile may get lost on Samba shares)
742 # work around issue2543 (or testfile may get lost on Samba shares)
743 f1 = testfile + ".hgtmp1"
743 f1 = testfile + ".hgtmp1"
744 if os.path.lexists(f1):
744 if os.path.lexists(f1):
745 return False
745 return False
746 try:
746 try:
747 posixfile(f1, 'w').close()
747 posixfile(f1, 'w').close()
748 except IOError:
748 except IOError:
749 return False
749 return False
750
750
751 f2 = testfile + ".hgtmp2"
751 f2 = testfile + ".hgtmp2"
752 fd = None
752 fd = None
753 try:
753 try:
754 try:
754 try:
755 oslink(f1, f2)
755 oslink(f1, f2)
756 except OSError:
756 except OSError:
757 return False
757 return False
758
758
759 # nlinks() may behave differently for files on Windows shares if
759 # nlinks() may behave differently for files on Windows shares if
760 # the file is open.
760 # the file is open.
761 fd = posixfile(f2)
761 fd = posixfile(f2)
762 return nlinks(f2) > 1
762 return nlinks(f2) > 1
763 finally:
763 finally:
764 if fd is not None:
764 if fd is not None:
765 fd.close()
765 fd.close()
766 for f in (f1, f2):
766 for f in (f1, f2):
767 try:
767 try:
768 os.unlink(f)
768 os.unlink(f)
769 except OSError:
769 except OSError:
770 pass
770 pass
771
771
772 return False
773
774 def endswithsep(path):
772 def endswithsep(path):
775 '''Check path ends with os.sep or os.altsep.'''
773 '''Check path ends with os.sep or os.altsep.'''
776 return path.endswith(os.sep) or os.altsep and path.endswith(os.altsep)
774 return path.endswith(os.sep) or os.altsep and path.endswith(os.altsep)
777
775
778 def splitpath(path):
776 def splitpath(path):
779 '''Split path by os.sep.
777 '''Split path by os.sep.
780 Note that this function does not use os.altsep because this is
778 Note that this function does not use os.altsep because this is
781 an alternative of simple "xxx.split(os.sep)".
779 an alternative of simple "xxx.split(os.sep)".
782 It is recommended to use os.path.normpath() before using this
780 It is recommended to use os.path.normpath() before using this
783 function if need.'''
781 function if need.'''
784 return path.split(os.sep)
782 return path.split(os.sep)
785
783
786 def gui():
784 def gui():
787 '''Are we running in a GUI?'''
785 '''Are we running in a GUI?'''
788 if sys.platform == 'darwin':
786 if sys.platform == 'darwin':
789 if 'SSH_CONNECTION' in os.environ:
787 if 'SSH_CONNECTION' in os.environ:
790 # handle SSH access to a box where the user is logged in
788 # handle SSH access to a box where the user is logged in
791 return False
789 return False
792 elif getattr(osutil, 'isgui', None):
790 elif getattr(osutil, 'isgui', None):
793 # check if a CoreGraphics session is available
791 # check if a CoreGraphics session is available
794 return osutil.isgui()
792 return osutil.isgui()
795 else:
793 else:
796 # pure build; use a safe default
794 # pure build; use a safe default
797 return True
795 return True
798 else:
796 else:
799 return os.name == "nt" or os.environ.get("DISPLAY")
797 return os.name == "nt" or os.environ.get("DISPLAY")
800
798
801 def mktempcopy(name, emptyok=False, createmode=None):
799 def mktempcopy(name, emptyok=False, createmode=None):
802 """Create a temporary file with the same contents from name
800 """Create a temporary file with the same contents from name
803
801
804 The permission bits are copied from the original file.
802 The permission bits are copied from the original file.
805
803
806 If the temporary file is going to be truncated immediately, you
804 If the temporary file is going to be truncated immediately, you
807 can use emptyok=True as an optimization.
805 can use emptyok=True as an optimization.
808
806
809 Returns the name of the temporary file.
807 Returns the name of the temporary file.
810 """
808 """
811 d, fn = os.path.split(name)
809 d, fn = os.path.split(name)
812 fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
810 fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
813 os.close(fd)
811 os.close(fd)
814 # Temporary files are created with mode 0600, which is usually not
812 # Temporary files are created with mode 0600, which is usually not
815 # what we want. If the original file already exists, just copy
813 # what we want. If the original file already exists, just copy
816 # its mode. Otherwise, manually obey umask.
814 # its mode. Otherwise, manually obey umask.
817 copymode(name, temp, createmode)
815 copymode(name, temp, createmode)
818 if emptyok:
816 if emptyok:
819 return temp
817 return temp
820 try:
818 try:
821 try:
819 try:
822 ifp = posixfile(name, "rb")
820 ifp = posixfile(name, "rb")
823 except IOError, inst:
821 except IOError, inst:
824 if inst.errno == errno.ENOENT:
822 if inst.errno == errno.ENOENT:
825 return temp
823 return temp
826 if not getattr(inst, 'filename', None):
824 if not getattr(inst, 'filename', None):
827 inst.filename = name
825 inst.filename = name
828 raise
826 raise
829 ofp = posixfile(temp, "wb")
827 ofp = posixfile(temp, "wb")
830 for chunk in filechunkiter(ifp):
828 for chunk in filechunkiter(ifp):
831 ofp.write(chunk)
829 ofp.write(chunk)
832 ifp.close()
830 ifp.close()
833 ofp.close()
831 ofp.close()
834 except: # re-raises
832 except: # re-raises
835 try: os.unlink(temp)
833 try: os.unlink(temp)
836 except OSError: pass
834 except OSError: pass
837 raise
835 raise
838 return temp
836 return temp
839
837
840 class atomictempfile(object):
838 class atomictempfile(object):
841 '''writable file object that atomically updates a file
839 '''writable file object that atomically updates a file
842
840
843 All writes will go to a temporary copy of the original file. Call
841 All writes will go to a temporary copy of the original file. Call
844 close() when you are done writing, and atomictempfile will rename
842 close() when you are done writing, and atomictempfile will rename
845 the temporary copy to the original name, making the changes
843 the temporary copy to the original name, making the changes
846 visible. If the object is destroyed without being closed, all your
844 visible. If the object is destroyed without being closed, all your
847 writes are discarded.
845 writes are discarded.
848 '''
846 '''
849 def __init__(self, name, mode='w+b', createmode=None):
847 def __init__(self, name, mode='w+b', createmode=None):
850 self.__name = name # permanent name
848 self.__name = name # permanent name
851 self._tempname = mktempcopy(name, emptyok=('w' in mode),
849 self._tempname = mktempcopy(name, emptyok=('w' in mode),
852 createmode=createmode)
850 createmode=createmode)
853 self._fp = posixfile(self._tempname, mode)
851 self._fp = posixfile(self._tempname, mode)
854
852
855 # delegated methods
853 # delegated methods
856 self.write = self._fp.write
854 self.write = self._fp.write
857 self.seek = self._fp.seek
855 self.seek = self._fp.seek
858 self.tell = self._fp.tell
856 self.tell = self._fp.tell
859 self.fileno = self._fp.fileno
857 self.fileno = self._fp.fileno
860
858
861 def close(self):
859 def close(self):
862 if not self._fp.closed:
860 if not self._fp.closed:
863 self._fp.close()
861 self._fp.close()
864 rename(self._tempname, localpath(self.__name))
862 rename(self._tempname, localpath(self.__name))
865
863
866 def discard(self):
864 def discard(self):
867 if not self._fp.closed:
865 if not self._fp.closed:
868 try:
866 try:
869 os.unlink(self._tempname)
867 os.unlink(self._tempname)
870 except OSError:
868 except OSError:
871 pass
869 pass
872 self._fp.close()
870 self._fp.close()
873
871
874 def __del__(self):
872 def __del__(self):
875 if safehasattr(self, '_fp'): # constructor actually did something
873 if safehasattr(self, '_fp'): # constructor actually did something
876 self.discard()
874 self.discard()
877
875
878 def makedirs(name, mode=None):
876 def makedirs(name, mode=None):
879 """recursive directory creation with parent mode inheritance"""
877 """recursive directory creation with parent mode inheritance"""
880 try:
878 try:
881 os.mkdir(name)
879 os.mkdir(name)
882 except OSError, err:
880 except OSError, err:
883 if err.errno == errno.EEXIST:
881 if err.errno == errno.EEXIST:
884 return
882 return
885 if err.errno != errno.ENOENT or not name:
883 if err.errno != errno.ENOENT or not name:
886 raise
884 raise
887 parent = os.path.dirname(os.path.abspath(name))
885 parent = os.path.dirname(os.path.abspath(name))
888 if parent == name:
886 if parent == name:
889 raise
887 raise
890 makedirs(parent, mode)
888 makedirs(parent, mode)
891 os.mkdir(name)
889 os.mkdir(name)
892 if mode is not None:
890 if mode is not None:
893 os.chmod(name, mode)
891 os.chmod(name, mode)
894
892
895 def ensuredirs(name, mode=None):
893 def ensuredirs(name, mode=None):
896 """race-safe recursive directory creation"""
894 """race-safe recursive directory creation"""
897 if os.path.isdir(name):
895 if os.path.isdir(name):
898 return
896 return
899 parent = os.path.dirname(os.path.abspath(name))
897 parent = os.path.dirname(os.path.abspath(name))
900 if parent != name:
898 if parent != name:
901 ensuredirs(parent, mode)
899 ensuredirs(parent, mode)
902 try:
900 try:
903 os.mkdir(name)
901 os.mkdir(name)
904 except OSError, err:
902 except OSError, err:
905 if err.errno == errno.EEXIST and os.path.isdir(name):
903 if err.errno == errno.EEXIST and os.path.isdir(name):
906 # someone else seems to have won a directory creation race
904 # someone else seems to have won a directory creation race
907 return
905 return
908 raise
906 raise
909 if mode is not None:
907 if mode is not None:
910 os.chmod(name, mode)
908 os.chmod(name, mode)
911
909
912 def readfile(path):
910 def readfile(path):
913 fp = open(path, 'rb')
911 fp = open(path, 'rb')
914 try:
912 try:
915 return fp.read()
913 return fp.read()
916 finally:
914 finally:
917 fp.close()
915 fp.close()
918
916
919 def writefile(path, text):
917 def writefile(path, text):
920 fp = open(path, 'wb')
918 fp = open(path, 'wb')
921 try:
919 try:
922 fp.write(text)
920 fp.write(text)
923 finally:
921 finally:
924 fp.close()
922 fp.close()
925
923
926 def appendfile(path, text):
924 def appendfile(path, text):
927 fp = open(path, 'ab')
925 fp = open(path, 'ab')
928 try:
926 try:
929 fp.write(text)
927 fp.write(text)
930 finally:
928 finally:
931 fp.close()
929 fp.close()
932
930
933 class chunkbuffer(object):
931 class chunkbuffer(object):
934 """Allow arbitrary sized chunks of data to be efficiently read from an
932 """Allow arbitrary sized chunks of data to be efficiently read from an
935 iterator over chunks of arbitrary size."""
933 iterator over chunks of arbitrary size."""
936
934
937 def __init__(self, in_iter):
935 def __init__(self, in_iter):
938 """in_iter is the iterator that's iterating over the input chunks.
936 """in_iter is the iterator that's iterating over the input chunks.
939 targetsize is how big a buffer to try to maintain."""
937 targetsize is how big a buffer to try to maintain."""
940 def splitbig(chunks):
938 def splitbig(chunks):
941 for chunk in chunks:
939 for chunk in chunks:
942 if len(chunk) > 2**20:
940 if len(chunk) > 2**20:
943 pos = 0
941 pos = 0
944 while pos < len(chunk):
942 while pos < len(chunk):
945 end = pos + 2 ** 18
943 end = pos + 2 ** 18
946 yield chunk[pos:end]
944 yield chunk[pos:end]
947 pos = end
945 pos = end
948 else:
946 else:
949 yield chunk
947 yield chunk
950 self.iter = splitbig(in_iter)
948 self.iter = splitbig(in_iter)
951 self._queue = deque()
949 self._queue = deque()
952
950
953 def read(self, l):
951 def read(self, l):
954 """Read L bytes of data from the iterator of chunks of data.
952 """Read L bytes of data from the iterator of chunks of data.
955 Returns less than L bytes if the iterator runs dry."""
953 Returns less than L bytes if the iterator runs dry."""
956 left = l
954 left = l
957 buf = []
955 buf = []
958 queue = self._queue
956 queue = self._queue
959 while left > 0:
957 while left > 0:
960 # refill the queue
958 # refill the queue
961 if not queue:
959 if not queue:
962 target = 2**18
960 target = 2**18
963 for chunk in self.iter:
961 for chunk in self.iter:
964 queue.append(chunk)
962 queue.append(chunk)
965 target -= len(chunk)
963 target -= len(chunk)
966 if target <= 0:
964 if target <= 0:
967 break
965 break
968 if not queue:
966 if not queue:
969 break
967 break
970
968
971 chunk = queue.popleft()
969 chunk = queue.popleft()
972 left -= len(chunk)
970 left -= len(chunk)
973 if left < 0:
971 if left < 0:
974 queue.appendleft(chunk[left:])
972 queue.appendleft(chunk[left:])
975 buf.append(chunk[:left])
973 buf.append(chunk[:left])
976 else:
974 else:
977 buf.append(chunk)
975 buf.append(chunk)
978
976
979 return ''.join(buf)
977 return ''.join(buf)
980
978
981 def filechunkiter(f, size=65536, limit=None):
979 def filechunkiter(f, size=65536, limit=None):
982 """Create a generator that produces the data in the file size
980 """Create a generator that produces the data in the file size
983 (default 65536) bytes at a time, up to optional limit (default is
981 (default 65536) bytes at a time, up to optional limit (default is
984 to read all data). Chunks may be less than size bytes if the
982 to read all data). Chunks may be less than size bytes if the
985 chunk is the last chunk in the file, or the file is a socket or
983 chunk is the last chunk in the file, or the file is a socket or
986 some other type of file that sometimes reads less data than is
984 some other type of file that sometimes reads less data than is
987 requested."""
985 requested."""
988 assert size >= 0
986 assert size >= 0
989 assert limit is None or limit >= 0
987 assert limit is None or limit >= 0
990 while True:
988 while True:
991 if limit is None:
989 if limit is None:
992 nbytes = size
990 nbytes = size
993 else:
991 else:
994 nbytes = min(limit, size)
992 nbytes = min(limit, size)
995 s = nbytes and f.read(nbytes)
993 s = nbytes and f.read(nbytes)
996 if not s:
994 if not s:
997 break
995 break
998 if limit:
996 if limit:
999 limit -= len(s)
997 limit -= len(s)
1000 yield s
998 yield s
1001
999
1002 def makedate():
1000 def makedate():
1003 ct = time.time()
1001 ct = time.time()
1004 if ct < 0:
1002 if ct < 0:
1005 hint = _("check your clock")
1003 hint = _("check your clock")
1006 raise Abort(_("negative timestamp: %d") % ct, hint=hint)
1004 raise Abort(_("negative timestamp: %d") % ct, hint=hint)
1007 delta = (datetime.datetime.utcfromtimestamp(ct) -
1005 delta = (datetime.datetime.utcfromtimestamp(ct) -
1008 datetime.datetime.fromtimestamp(ct))
1006 datetime.datetime.fromtimestamp(ct))
1009 tz = delta.days * 86400 + delta.seconds
1007 tz = delta.days * 86400 + delta.seconds
1010 return ct, tz
1008 return ct, tz
1011
1009
1012 def datestr(date=None, format='%a %b %d %H:%M:%S %Y %1%2'):
1010 def datestr(date=None, format='%a %b %d %H:%M:%S %Y %1%2'):
1013 """represent a (unixtime, offset) tuple as a localized time.
1011 """represent a (unixtime, offset) tuple as a localized time.
1014 unixtime is seconds since the epoch, and offset is the time zone's
1012 unixtime is seconds since the epoch, and offset is the time zone's
1015 number of seconds away from UTC. if timezone is false, do not
1013 number of seconds away from UTC. if timezone is false, do not
1016 append time zone to string."""
1014 append time zone to string."""
1017 t, tz = date or makedate()
1015 t, tz = date or makedate()
1018 if t < 0:
1016 if t < 0:
1019 t = 0 # time.gmtime(lt) fails on Windows for lt < -43200
1017 t = 0 # time.gmtime(lt) fails on Windows for lt < -43200
1020 tz = 0
1018 tz = 0
1021 if "%1" in format or "%2" in format:
1019 if "%1" in format or "%2" in format:
1022 sign = (tz > 0) and "-" or "+"
1020 sign = (tz > 0) and "-" or "+"
1023 minutes = abs(tz) // 60
1021 minutes = abs(tz) // 60
1024 format = format.replace("%1", "%c%02d" % (sign, minutes // 60))
1022 format = format.replace("%1", "%c%02d" % (sign, minutes // 60))
1025 format = format.replace("%2", "%02d" % (minutes % 60))
1023 format = format.replace("%2", "%02d" % (minutes % 60))
1026 try:
1024 try:
1027 t = time.gmtime(float(t) - tz)
1025 t = time.gmtime(float(t) - tz)
1028 except ValueError:
1026 except ValueError:
1029 # time was out of range
1027 # time was out of range
1030 t = time.gmtime(sys.maxint)
1028 t = time.gmtime(sys.maxint)
1031 s = time.strftime(format, t)
1029 s = time.strftime(format, t)
1032 return s
1030 return s
1033
1031
1034 def shortdate(date=None):
1032 def shortdate(date=None):
1035 """turn (timestamp, tzoff) tuple into iso 8631 date."""
1033 """turn (timestamp, tzoff) tuple into iso 8631 date."""
1036 return datestr(date, format='%Y-%m-%d')
1034 return datestr(date, format='%Y-%m-%d')
1037
1035
1038 def strdate(string, format, defaults=[]):
1036 def strdate(string, format, defaults=[]):
1039 """parse a localized time string and return a (unixtime, offset) tuple.
1037 """parse a localized time string and return a (unixtime, offset) tuple.
1040 if the string cannot be parsed, ValueError is raised."""
1038 if the string cannot be parsed, ValueError is raised."""
1041 def timezone(string):
1039 def timezone(string):
1042 tz = string.split()[-1]
1040 tz = string.split()[-1]
1043 if tz[0] in "+-" and len(tz) == 5 and tz[1:].isdigit():
1041 if tz[0] in "+-" and len(tz) == 5 and tz[1:].isdigit():
1044 sign = (tz[0] == "+") and 1 or -1
1042 sign = (tz[0] == "+") and 1 or -1
1045 hours = int(tz[1:3])
1043 hours = int(tz[1:3])
1046 minutes = int(tz[3:5])
1044 minutes = int(tz[3:5])
1047 return -sign * (hours * 60 + minutes) * 60
1045 return -sign * (hours * 60 + minutes) * 60
1048 if tz == "GMT" or tz == "UTC":
1046 if tz == "GMT" or tz == "UTC":
1049 return 0
1047 return 0
1050 return None
1048 return None
1051
1049
1052 # NOTE: unixtime = localunixtime + offset
1050 # NOTE: unixtime = localunixtime + offset
1053 offset, date = timezone(string), string
1051 offset, date = timezone(string), string
1054 if offset is not None:
1052 if offset is not None:
1055 date = " ".join(string.split()[:-1])
1053 date = " ".join(string.split()[:-1])
1056
1054
1057 # add missing elements from defaults
1055 # add missing elements from defaults
1058 usenow = False # default to using biased defaults
1056 usenow = False # default to using biased defaults
1059 for part in ("S", "M", "HI", "d", "mb", "yY"): # decreasing specificity
1057 for part in ("S", "M", "HI", "d", "mb", "yY"): # decreasing specificity
1060 found = [True for p in part if ("%"+p) in format]
1058 found = [True for p in part if ("%"+p) in format]
1061 if not found:
1059 if not found:
1062 date += "@" + defaults[part][usenow]
1060 date += "@" + defaults[part][usenow]
1063 format += "@%" + part[0]
1061 format += "@%" + part[0]
1064 else:
1062 else:
1065 # We've found a specific time element, less specific time
1063 # We've found a specific time element, less specific time
1066 # elements are relative to today
1064 # elements are relative to today
1067 usenow = True
1065 usenow = True
1068
1066
1069 timetuple = time.strptime(date, format)
1067 timetuple = time.strptime(date, format)
1070 localunixtime = int(calendar.timegm(timetuple))
1068 localunixtime = int(calendar.timegm(timetuple))
1071 if offset is None:
1069 if offset is None:
1072 # local timezone
1070 # local timezone
1073 unixtime = int(time.mktime(timetuple))
1071 unixtime = int(time.mktime(timetuple))
1074 offset = unixtime - localunixtime
1072 offset = unixtime - localunixtime
1075 else:
1073 else:
1076 unixtime = localunixtime + offset
1074 unixtime = localunixtime + offset
1077 return unixtime, offset
1075 return unixtime, offset
1078
1076
1079 def parsedate(date, formats=None, bias={}):
1077 def parsedate(date, formats=None, bias={}):
1080 """parse a localized date/time and return a (unixtime, offset) tuple.
1078 """parse a localized date/time and return a (unixtime, offset) tuple.
1081
1079
1082 The date may be a "unixtime offset" string or in one of the specified
1080 The date may be a "unixtime offset" string or in one of the specified
1083 formats. If the date already is a (unixtime, offset) tuple, it is returned.
1081 formats. If the date already is a (unixtime, offset) tuple, it is returned.
1084
1082
1085 >>> parsedate(' today ') == parsedate(\
1083 >>> parsedate(' today ') == parsedate(\
1086 datetime.date.today().strftime('%b %d'))
1084 datetime.date.today().strftime('%b %d'))
1087 True
1085 True
1088 >>> parsedate( 'yesterday ') == parsedate((datetime.date.today() -\
1086 >>> parsedate( 'yesterday ') == parsedate((datetime.date.today() -\
1089 datetime.timedelta(days=1)\
1087 datetime.timedelta(days=1)\
1090 ).strftime('%b %d'))
1088 ).strftime('%b %d'))
1091 True
1089 True
1092 >>> now, tz = makedate()
1090 >>> now, tz = makedate()
1093 >>> strnow, strtz = parsedate('now')
1091 >>> strnow, strtz = parsedate('now')
1094 >>> (strnow - now) < 1
1092 >>> (strnow - now) < 1
1095 True
1093 True
1096 >>> tz == strtz
1094 >>> tz == strtz
1097 True
1095 True
1098 """
1096 """
1099 if not date:
1097 if not date:
1100 return 0, 0
1098 return 0, 0
1101 if isinstance(date, tuple) and len(date) == 2:
1099 if isinstance(date, tuple) and len(date) == 2:
1102 return date
1100 return date
1103 if not formats:
1101 if not formats:
1104 formats = defaultdateformats
1102 formats = defaultdateformats
1105 date = date.strip()
1103 date = date.strip()
1106
1104
1107 if date == _('now'):
1105 if date == _('now'):
1108 return makedate()
1106 return makedate()
1109 if date == _('today'):
1107 if date == _('today'):
1110 date = datetime.date.today().strftime('%b %d')
1108 date = datetime.date.today().strftime('%b %d')
1111 elif date == _('yesterday'):
1109 elif date == _('yesterday'):
1112 date = (datetime.date.today() -
1110 date = (datetime.date.today() -
1113 datetime.timedelta(days=1)).strftime('%b %d')
1111 datetime.timedelta(days=1)).strftime('%b %d')
1114
1112
1115 try:
1113 try:
1116 when, offset = map(int, date.split(' '))
1114 when, offset = map(int, date.split(' '))
1117 except ValueError:
1115 except ValueError:
1118 # fill out defaults
1116 # fill out defaults
1119 now = makedate()
1117 now = makedate()
1120 defaults = {}
1118 defaults = {}
1121 for part in ("d", "mb", "yY", "HI", "M", "S"):
1119 for part in ("d", "mb", "yY", "HI", "M", "S"):
1122 # this piece is for rounding the specific end of unknowns
1120 # this piece is for rounding the specific end of unknowns
1123 b = bias.get(part)
1121 b = bias.get(part)
1124 if b is None:
1122 if b is None:
1125 if part[0] in "HMS":
1123 if part[0] in "HMS":
1126 b = "00"
1124 b = "00"
1127 else:
1125 else:
1128 b = "0"
1126 b = "0"
1129
1127
1130 # this piece is for matching the generic end to today's date
1128 # this piece is for matching the generic end to today's date
1131 n = datestr(now, "%" + part[0])
1129 n = datestr(now, "%" + part[0])
1132
1130
1133 defaults[part] = (b, n)
1131 defaults[part] = (b, n)
1134
1132
1135 for format in formats:
1133 for format in formats:
1136 try:
1134 try:
1137 when, offset = strdate(date, format, defaults)
1135 when, offset = strdate(date, format, defaults)
1138 except (ValueError, OverflowError):
1136 except (ValueError, OverflowError):
1139 pass
1137 pass
1140 else:
1138 else:
1141 break
1139 break
1142 else:
1140 else:
1143 raise Abort(_('invalid date: %r') % date)
1141 raise Abort(_('invalid date: %r') % date)
1144 # validate explicit (probably user-specified) date and
1142 # validate explicit (probably user-specified) date and
1145 # time zone offset. values must fit in signed 32 bits for
1143 # time zone offset. values must fit in signed 32 bits for
1146 # current 32-bit linux runtimes. timezones go from UTC-12
1144 # current 32-bit linux runtimes. timezones go from UTC-12
1147 # to UTC+14
1145 # to UTC+14
1148 if abs(when) > 0x7fffffff:
1146 if abs(when) > 0x7fffffff:
1149 raise Abort(_('date exceeds 32 bits: %d') % when)
1147 raise Abort(_('date exceeds 32 bits: %d') % when)
1150 if when < 0:
1148 if when < 0:
1151 raise Abort(_('negative date value: %d') % when)
1149 raise Abort(_('negative date value: %d') % when)
1152 if offset < -50400 or offset > 43200:
1150 if offset < -50400 or offset > 43200:
1153 raise Abort(_('impossible time zone offset: %d') % offset)
1151 raise Abort(_('impossible time zone offset: %d') % offset)
1154 return when, offset
1152 return when, offset
1155
1153
1156 def matchdate(date):
1154 def matchdate(date):
1157 """Return a function that matches a given date match specifier
1155 """Return a function that matches a given date match specifier
1158
1156
1159 Formats include:
1157 Formats include:
1160
1158
1161 '{date}' match a given date to the accuracy provided
1159 '{date}' match a given date to the accuracy provided
1162
1160
1163 '<{date}' on or before a given date
1161 '<{date}' on or before a given date
1164
1162
1165 '>{date}' on or after a given date
1163 '>{date}' on or after a given date
1166
1164
1167 >>> p1 = parsedate("10:29:59")
1165 >>> p1 = parsedate("10:29:59")
1168 >>> p2 = parsedate("10:30:00")
1166 >>> p2 = parsedate("10:30:00")
1169 >>> p3 = parsedate("10:30:59")
1167 >>> p3 = parsedate("10:30:59")
1170 >>> p4 = parsedate("10:31:00")
1168 >>> p4 = parsedate("10:31:00")
1171 >>> p5 = parsedate("Sep 15 10:30:00 1999")
1169 >>> p5 = parsedate("Sep 15 10:30:00 1999")
1172 >>> f = matchdate("10:30")
1170 >>> f = matchdate("10:30")
1173 >>> f(p1[0])
1171 >>> f(p1[0])
1174 False
1172 False
1175 >>> f(p2[0])
1173 >>> f(p2[0])
1176 True
1174 True
1177 >>> f(p3[0])
1175 >>> f(p3[0])
1178 True
1176 True
1179 >>> f(p4[0])
1177 >>> f(p4[0])
1180 False
1178 False
1181 >>> f(p5[0])
1179 >>> f(p5[0])
1182 False
1180 False
1183 """
1181 """
1184
1182
1185 def lower(date):
1183 def lower(date):
1186 d = dict(mb="1", d="1")
1184 d = dict(mb="1", d="1")
1187 return parsedate(date, extendeddateformats, d)[0]
1185 return parsedate(date, extendeddateformats, d)[0]
1188
1186
1189 def upper(date):
1187 def upper(date):
1190 d = dict(mb="12", HI="23", M="59", S="59")
1188 d = dict(mb="12", HI="23", M="59", S="59")
1191 for days in ("31", "30", "29"):
1189 for days in ("31", "30", "29"):
1192 try:
1190 try:
1193 d["d"] = days
1191 d["d"] = days
1194 return parsedate(date, extendeddateformats, d)[0]
1192 return parsedate(date, extendeddateformats, d)[0]
1195 except Abort:
1193 except Abort:
1196 pass
1194 pass
1197 d["d"] = "28"
1195 d["d"] = "28"
1198 return parsedate(date, extendeddateformats, d)[0]
1196 return parsedate(date, extendeddateformats, d)[0]
1199
1197
1200 date = date.strip()
1198 date = date.strip()
1201
1199
1202 if not date:
1200 if not date:
1203 raise Abort(_("dates cannot consist entirely of whitespace"))
1201 raise Abort(_("dates cannot consist entirely of whitespace"))
1204 elif date[0] == "<":
1202 elif date[0] == "<":
1205 if not date[1:]:
1203 if not date[1:]:
1206 raise Abort(_("invalid day spec, use '<DATE'"))
1204 raise Abort(_("invalid day spec, use '<DATE'"))
1207 when = upper(date[1:])
1205 when = upper(date[1:])
1208 return lambda x: x <= when
1206 return lambda x: x <= when
1209 elif date[0] == ">":
1207 elif date[0] == ">":
1210 if not date[1:]:
1208 if not date[1:]:
1211 raise Abort(_("invalid day spec, use '>DATE'"))
1209 raise Abort(_("invalid day spec, use '>DATE'"))
1212 when = lower(date[1:])
1210 when = lower(date[1:])
1213 return lambda x: x >= when
1211 return lambda x: x >= when
1214 elif date[0] == "-":
1212 elif date[0] == "-":
1215 try:
1213 try:
1216 days = int(date[1:])
1214 days = int(date[1:])
1217 except ValueError:
1215 except ValueError:
1218 raise Abort(_("invalid day spec: %s") % date[1:])
1216 raise Abort(_("invalid day spec: %s") % date[1:])
1219 if days < 0:
1217 if days < 0:
1220 raise Abort(_("%s must be nonnegative (see 'hg help dates')")
1218 raise Abort(_("%s must be nonnegative (see 'hg help dates')")
1221 % date[1:])
1219 % date[1:])
1222 when = makedate()[0] - days * 3600 * 24
1220 when = makedate()[0] - days * 3600 * 24
1223 return lambda x: x >= when
1221 return lambda x: x >= when
1224 elif " to " in date:
1222 elif " to " in date:
1225 a, b = date.split(" to ")
1223 a, b = date.split(" to ")
1226 start, stop = lower(a), upper(b)
1224 start, stop = lower(a), upper(b)
1227 return lambda x: x >= start and x <= stop
1225 return lambda x: x >= start and x <= stop
1228 else:
1226 else:
1229 start, stop = lower(date), upper(date)
1227 start, stop = lower(date), upper(date)
1230 return lambda x: x >= start and x <= stop
1228 return lambda x: x >= start and x <= stop
1231
1229
1232 def shortuser(user):
1230 def shortuser(user):
1233 """Return a short representation of a user name or email address."""
1231 """Return a short representation of a user name or email address."""
1234 f = user.find('@')
1232 f = user.find('@')
1235 if f >= 0:
1233 if f >= 0:
1236 user = user[:f]
1234 user = user[:f]
1237 f = user.find('<')
1235 f = user.find('<')
1238 if f >= 0:
1236 if f >= 0:
1239 user = user[f + 1:]
1237 user = user[f + 1:]
1240 f = user.find(' ')
1238 f = user.find(' ')
1241 if f >= 0:
1239 if f >= 0:
1242 user = user[:f]
1240 user = user[:f]
1243 f = user.find('.')
1241 f = user.find('.')
1244 if f >= 0:
1242 if f >= 0:
1245 user = user[:f]
1243 user = user[:f]
1246 return user
1244 return user
1247
1245
1248 def emailuser(user):
1246 def emailuser(user):
1249 """Return the user portion of an email address."""
1247 """Return the user portion of an email address."""
1250 f = user.find('@')
1248 f = user.find('@')
1251 if f >= 0:
1249 if f >= 0:
1252 user = user[:f]
1250 user = user[:f]
1253 f = user.find('<')
1251 f = user.find('<')
1254 if f >= 0:
1252 if f >= 0:
1255 user = user[f + 1:]
1253 user = user[f + 1:]
1256 return user
1254 return user
1257
1255
1258 def email(author):
1256 def email(author):
1259 '''get email of author.'''
1257 '''get email of author.'''
1260 r = author.find('>')
1258 r = author.find('>')
1261 if r == -1:
1259 if r == -1:
1262 r = None
1260 r = None
1263 return author[author.find('<') + 1:r]
1261 return author[author.find('<') + 1:r]
1264
1262
1265 def _ellipsis(text, maxlength):
1263 def _ellipsis(text, maxlength):
1266 if len(text) <= maxlength:
1264 if len(text) <= maxlength:
1267 return text, False
1265 return text, False
1268 else:
1266 else:
1269 return "%s..." % (text[:maxlength - 3]), True
1267 return "%s..." % (text[:maxlength - 3]), True
1270
1268
1271 def ellipsis(text, maxlength=400):
1269 def ellipsis(text, maxlength=400):
1272 """Trim string to at most maxlength (default: 400) characters."""
1270 """Trim string to at most maxlength (default: 400) characters."""
1273 try:
1271 try:
1274 # use unicode not to split at intermediate multi-byte sequence
1272 # use unicode not to split at intermediate multi-byte sequence
1275 utext, truncated = _ellipsis(text.decode(encoding.encoding),
1273 utext, truncated = _ellipsis(text.decode(encoding.encoding),
1276 maxlength)
1274 maxlength)
1277 if not truncated:
1275 if not truncated:
1278 return text
1276 return text
1279 return utext.encode(encoding.encoding)
1277 return utext.encode(encoding.encoding)
1280 except (UnicodeDecodeError, UnicodeEncodeError):
1278 except (UnicodeDecodeError, UnicodeEncodeError):
1281 return _ellipsis(text, maxlength)[0]
1279 return _ellipsis(text, maxlength)[0]
1282
1280
1283 def unitcountfn(*unittable):
1281 def unitcountfn(*unittable):
1284 '''return a function that renders a readable count of some quantity'''
1282 '''return a function that renders a readable count of some quantity'''
1285
1283
1286 def go(count):
1284 def go(count):
1287 for multiplier, divisor, format in unittable:
1285 for multiplier, divisor, format in unittable:
1288 if count >= divisor * multiplier:
1286 if count >= divisor * multiplier:
1289 return format % (count / float(divisor))
1287 return format % (count / float(divisor))
1290 return unittable[-1][2] % count
1288 return unittable[-1][2] % count
1291
1289
1292 return go
1290 return go
1293
1291
1294 bytecount = unitcountfn(
1292 bytecount = unitcountfn(
1295 (100, 1 << 30, _('%.0f GB')),
1293 (100, 1 << 30, _('%.0f GB')),
1296 (10, 1 << 30, _('%.1f GB')),
1294 (10, 1 << 30, _('%.1f GB')),
1297 (1, 1 << 30, _('%.2f GB')),
1295 (1, 1 << 30, _('%.2f GB')),
1298 (100, 1 << 20, _('%.0f MB')),
1296 (100, 1 << 20, _('%.0f MB')),
1299 (10, 1 << 20, _('%.1f MB')),
1297 (10, 1 << 20, _('%.1f MB')),
1300 (1, 1 << 20, _('%.2f MB')),
1298 (1, 1 << 20, _('%.2f MB')),
1301 (100, 1 << 10, _('%.0f KB')),
1299 (100, 1 << 10, _('%.0f KB')),
1302 (10, 1 << 10, _('%.1f KB')),
1300 (10, 1 << 10, _('%.1f KB')),
1303 (1, 1 << 10, _('%.2f KB')),
1301 (1, 1 << 10, _('%.2f KB')),
1304 (1, 1, _('%.0f bytes')),
1302 (1, 1, _('%.0f bytes')),
1305 )
1303 )
1306
1304
1307 def uirepr(s):
1305 def uirepr(s):
1308 # Avoid double backslash in Windows path repr()
1306 # Avoid double backslash in Windows path repr()
1309 return repr(s).replace('\\\\', '\\')
1307 return repr(s).replace('\\\\', '\\')
1310
1308
1311 # delay import of textwrap
1309 # delay import of textwrap
1312 def MBTextWrapper(**kwargs):
1310 def MBTextWrapper(**kwargs):
1313 class tw(textwrap.TextWrapper):
1311 class tw(textwrap.TextWrapper):
1314 """
1312 """
1315 Extend TextWrapper for width-awareness.
1313 Extend TextWrapper for width-awareness.
1316
1314
1317 Neither number of 'bytes' in any encoding nor 'characters' is
1315 Neither number of 'bytes' in any encoding nor 'characters' is
1318 appropriate to calculate terminal columns for specified string.
1316 appropriate to calculate terminal columns for specified string.
1319
1317
1320 Original TextWrapper implementation uses built-in 'len()' directly,
1318 Original TextWrapper implementation uses built-in 'len()' directly,
1321 so overriding is needed to use width information of each characters.
1319 so overriding is needed to use width information of each characters.
1322
1320
1323 In addition, characters classified into 'ambiguous' width are
1321 In addition, characters classified into 'ambiguous' width are
1324 treated as wide in East Asian area, but as narrow in other.
1322 treated as wide in East Asian area, but as narrow in other.
1325
1323
1326 This requires use decision to determine width of such characters.
1324 This requires use decision to determine width of such characters.
1327 """
1325 """
1328 def __init__(self, **kwargs):
1326 def __init__(self, **kwargs):
1329 textwrap.TextWrapper.__init__(self, **kwargs)
1327 textwrap.TextWrapper.__init__(self, **kwargs)
1330
1328
1331 # for compatibility between 2.4 and 2.6
1329 # for compatibility between 2.4 and 2.6
1332 if getattr(self, 'drop_whitespace', None) is None:
1330 if getattr(self, 'drop_whitespace', None) is None:
1333 self.drop_whitespace = kwargs.get('drop_whitespace', True)
1331 self.drop_whitespace = kwargs.get('drop_whitespace', True)
1334
1332
1335 def _cutdown(self, ucstr, space_left):
1333 def _cutdown(self, ucstr, space_left):
1336 l = 0
1334 l = 0
1337 colwidth = encoding.ucolwidth
1335 colwidth = encoding.ucolwidth
1338 for i in xrange(len(ucstr)):
1336 for i in xrange(len(ucstr)):
1339 l += colwidth(ucstr[i])
1337 l += colwidth(ucstr[i])
1340 if space_left < l:
1338 if space_left < l:
1341 return (ucstr[:i], ucstr[i:])
1339 return (ucstr[:i], ucstr[i:])
1342 return ucstr, ''
1340 return ucstr, ''
1343
1341
1344 # overriding of base class
1342 # overriding of base class
1345 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
1343 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
1346 space_left = max(width - cur_len, 1)
1344 space_left = max(width - cur_len, 1)
1347
1345
1348 if self.break_long_words:
1346 if self.break_long_words:
1349 cut, res = self._cutdown(reversed_chunks[-1], space_left)
1347 cut, res = self._cutdown(reversed_chunks[-1], space_left)
1350 cur_line.append(cut)
1348 cur_line.append(cut)
1351 reversed_chunks[-1] = res
1349 reversed_chunks[-1] = res
1352 elif not cur_line:
1350 elif not cur_line:
1353 cur_line.append(reversed_chunks.pop())
1351 cur_line.append(reversed_chunks.pop())
1354
1352
1355 # this overriding code is imported from TextWrapper of python 2.6
1353 # this overriding code is imported from TextWrapper of python 2.6
1356 # to calculate columns of string by 'encoding.ucolwidth()'
1354 # to calculate columns of string by 'encoding.ucolwidth()'
1357 def _wrap_chunks(self, chunks):
1355 def _wrap_chunks(self, chunks):
1358 colwidth = encoding.ucolwidth
1356 colwidth = encoding.ucolwidth
1359
1357
1360 lines = []
1358 lines = []
1361 if self.width <= 0:
1359 if self.width <= 0:
1362 raise ValueError("invalid width %r (must be > 0)" % self.width)
1360 raise ValueError("invalid width %r (must be > 0)" % self.width)
1363
1361
1364 # Arrange in reverse order so items can be efficiently popped
1362 # Arrange in reverse order so items can be efficiently popped
1365 # from a stack of chucks.
1363 # from a stack of chucks.
1366 chunks.reverse()
1364 chunks.reverse()
1367
1365
1368 while chunks:
1366 while chunks:
1369
1367
1370 # Start the list of chunks that will make up the current line.
1368 # Start the list of chunks that will make up the current line.
1371 # cur_len is just the length of all the chunks in cur_line.
1369 # cur_len is just the length of all the chunks in cur_line.
1372 cur_line = []
1370 cur_line = []
1373 cur_len = 0
1371 cur_len = 0
1374
1372
1375 # Figure out which static string will prefix this line.
1373 # Figure out which static string will prefix this line.
1376 if lines:
1374 if lines:
1377 indent = self.subsequent_indent
1375 indent = self.subsequent_indent
1378 else:
1376 else:
1379 indent = self.initial_indent
1377 indent = self.initial_indent
1380
1378
1381 # Maximum width for this line.
1379 # Maximum width for this line.
1382 width = self.width - len(indent)
1380 width = self.width - len(indent)
1383
1381
1384 # First chunk on line is whitespace -- drop it, unless this
1382 # First chunk on line is whitespace -- drop it, unless this
1385 # is the very beginning of the text (i.e. no lines started yet).
1383 # is the very beginning of the text (i.e. no lines started yet).
1386 if self.drop_whitespace and chunks[-1].strip() == '' and lines:
1384 if self.drop_whitespace and chunks[-1].strip() == '' and lines:
1387 del chunks[-1]
1385 del chunks[-1]
1388
1386
1389 while chunks:
1387 while chunks:
1390 l = colwidth(chunks[-1])
1388 l = colwidth(chunks[-1])
1391
1389
1392 # Can at least squeeze this chunk onto the current line.
1390 # Can at least squeeze this chunk onto the current line.
1393 if cur_len + l <= width:
1391 if cur_len + l <= width:
1394 cur_line.append(chunks.pop())
1392 cur_line.append(chunks.pop())
1395 cur_len += l
1393 cur_len += l
1396
1394
1397 # Nope, this line is full.
1395 # Nope, this line is full.
1398 else:
1396 else:
1399 break
1397 break
1400
1398
1401 # The current line is full, and the next chunk is too big to
1399 # The current line is full, and the next chunk is too big to
1402 # fit on *any* line (not just this one).
1400 # fit on *any* line (not just this one).
1403 if chunks and colwidth(chunks[-1]) > width:
1401 if chunks and colwidth(chunks[-1]) > width:
1404 self._handle_long_word(chunks, cur_line, cur_len, width)
1402 self._handle_long_word(chunks, cur_line, cur_len, width)
1405
1403
1406 # If the last chunk on this line is all whitespace, drop it.
1404 # If the last chunk on this line is all whitespace, drop it.
1407 if (self.drop_whitespace and
1405 if (self.drop_whitespace and
1408 cur_line and cur_line[-1].strip() == ''):
1406 cur_line and cur_line[-1].strip() == ''):
1409 del cur_line[-1]
1407 del cur_line[-1]
1410
1408
1411 # Convert current line back to a string and store it in list
1409 # Convert current line back to a string and store it in list
1412 # of all lines (return value).
1410 # of all lines (return value).
1413 if cur_line:
1411 if cur_line:
1414 lines.append(indent + ''.join(cur_line))
1412 lines.append(indent + ''.join(cur_line))
1415
1413
1416 return lines
1414 return lines
1417
1415
1418 global MBTextWrapper
1416 global MBTextWrapper
1419 MBTextWrapper = tw
1417 MBTextWrapper = tw
1420 return tw(**kwargs)
1418 return tw(**kwargs)
1421
1419
1422 def wrap(line, width, initindent='', hangindent=''):
1420 def wrap(line, width, initindent='', hangindent=''):
1423 maxindent = max(len(hangindent), len(initindent))
1421 maxindent = max(len(hangindent), len(initindent))
1424 if width <= maxindent:
1422 if width <= maxindent:
1425 # adjust for weird terminal size
1423 # adjust for weird terminal size
1426 width = max(78, maxindent + 1)
1424 width = max(78, maxindent + 1)
1427 line = line.decode(encoding.encoding, encoding.encodingmode)
1425 line = line.decode(encoding.encoding, encoding.encodingmode)
1428 initindent = initindent.decode(encoding.encoding, encoding.encodingmode)
1426 initindent = initindent.decode(encoding.encoding, encoding.encodingmode)
1429 hangindent = hangindent.decode(encoding.encoding, encoding.encodingmode)
1427 hangindent = hangindent.decode(encoding.encoding, encoding.encodingmode)
1430 wrapper = MBTextWrapper(width=width,
1428 wrapper = MBTextWrapper(width=width,
1431 initial_indent=initindent,
1429 initial_indent=initindent,
1432 subsequent_indent=hangindent)
1430 subsequent_indent=hangindent)
1433 return wrapper.fill(line).encode(encoding.encoding)
1431 return wrapper.fill(line).encode(encoding.encoding)
1434
1432
1435 def iterlines(iterator):
1433 def iterlines(iterator):
1436 for chunk in iterator:
1434 for chunk in iterator:
1437 for line in chunk.splitlines():
1435 for line in chunk.splitlines():
1438 yield line
1436 yield line
1439
1437
1440 def expandpath(path):
1438 def expandpath(path):
1441 return os.path.expanduser(os.path.expandvars(path))
1439 return os.path.expanduser(os.path.expandvars(path))
1442
1440
1443 def hgcmd():
1441 def hgcmd():
1444 """Return the command used to execute current hg
1442 """Return the command used to execute current hg
1445
1443
1446 This is different from hgexecutable() because on Windows we want
1444 This is different from hgexecutable() because on Windows we want
1447 to avoid things opening new shell windows like batch files, so we
1445 to avoid things opening new shell windows like batch files, so we
1448 get either the python call or current executable.
1446 get either the python call or current executable.
1449 """
1447 """
1450 if mainfrozen():
1448 if mainfrozen():
1451 return [sys.executable]
1449 return [sys.executable]
1452 return gethgcmd()
1450 return gethgcmd()
1453
1451
1454 def rundetached(args, condfn):
1452 def rundetached(args, condfn):
1455 """Execute the argument list in a detached process.
1453 """Execute the argument list in a detached process.
1456
1454
1457 condfn is a callable which is called repeatedly and should return
1455 condfn is a callable which is called repeatedly and should return
1458 True once the child process is known to have started successfully.
1456 True once the child process is known to have started successfully.
1459 At this point, the child process PID is returned. If the child
1457 At this point, the child process PID is returned. If the child
1460 process fails to start or finishes before condfn() evaluates to
1458 process fails to start or finishes before condfn() evaluates to
1461 True, return -1.
1459 True, return -1.
1462 """
1460 """
1463 # Windows case is easier because the child process is either
1461 # Windows case is easier because the child process is either
1464 # successfully starting and validating the condition or exiting
1462 # successfully starting and validating the condition or exiting
1465 # on failure. We just poll on its PID. On Unix, if the child
1463 # on failure. We just poll on its PID. On Unix, if the child
1466 # process fails to start, it will be left in a zombie state until
1464 # process fails to start, it will be left in a zombie state until
1467 # the parent wait on it, which we cannot do since we expect a long
1465 # the parent wait on it, which we cannot do since we expect a long
1468 # running process on success. Instead we listen for SIGCHLD telling
1466 # running process on success. Instead we listen for SIGCHLD telling
1469 # us our child process terminated.
1467 # us our child process terminated.
1470 terminated = set()
1468 terminated = set()
1471 def handler(signum, frame):
1469 def handler(signum, frame):
1472 terminated.add(os.wait())
1470 terminated.add(os.wait())
1473 prevhandler = None
1471 prevhandler = None
1474 SIGCHLD = getattr(signal, 'SIGCHLD', None)
1472 SIGCHLD = getattr(signal, 'SIGCHLD', None)
1475 if SIGCHLD is not None:
1473 if SIGCHLD is not None:
1476 prevhandler = signal.signal(SIGCHLD, handler)
1474 prevhandler = signal.signal(SIGCHLD, handler)
1477 try:
1475 try:
1478 pid = spawndetached(args)
1476 pid = spawndetached(args)
1479 while not condfn():
1477 while not condfn():
1480 if ((pid in terminated or not testpid(pid))
1478 if ((pid in terminated or not testpid(pid))
1481 and not condfn()):
1479 and not condfn()):
1482 return -1
1480 return -1
1483 time.sleep(0.1)
1481 time.sleep(0.1)
1484 return pid
1482 return pid
1485 finally:
1483 finally:
1486 if prevhandler is not None:
1484 if prevhandler is not None:
1487 signal.signal(signal.SIGCHLD, prevhandler)
1485 signal.signal(signal.SIGCHLD, prevhandler)
1488
1486
1489 try:
1487 try:
1490 any, all = any, all
1488 any, all = any, all
1491 except NameError:
1489 except NameError:
1492 def any(iterable):
1490 def any(iterable):
1493 for i in iterable:
1491 for i in iterable:
1494 if i:
1492 if i:
1495 return True
1493 return True
1496 return False
1494 return False
1497
1495
1498 def all(iterable):
1496 def all(iterable):
1499 for i in iterable:
1497 for i in iterable:
1500 if not i:
1498 if not i:
1501 return False
1499 return False
1502 return True
1500 return True
1503
1501
1504 def interpolate(prefix, mapping, s, fn=None, escape_prefix=False):
1502 def interpolate(prefix, mapping, s, fn=None, escape_prefix=False):
1505 """Return the result of interpolating items in the mapping into string s.
1503 """Return the result of interpolating items in the mapping into string s.
1506
1504
1507 prefix is a single character string, or a two character string with
1505 prefix is a single character string, or a two character string with
1508 a backslash as the first character if the prefix needs to be escaped in
1506 a backslash as the first character if the prefix needs to be escaped in
1509 a regular expression.
1507 a regular expression.
1510
1508
1511 fn is an optional function that will be applied to the replacement text
1509 fn is an optional function that will be applied to the replacement text
1512 just before replacement.
1510 just before replacement.
1513
1511
1514 escape_prefix is an optional flag that allows using doubled prefix for
1512 escape_prefix is an optional flag that allows using doubled prefix for
1515 its escaping.
1513 its escaping.
1516 """
1514 """
1517 fn = fn or (lambda s: s)
1515 fn = fn or (lambda s: s)
1518 patterns = '|'.join(mapping.keys())
1516 patterns = '|'.join(mapping.keys())
1519 if escape_prefix:
1517 if escape_prefix:
1520 patterns += '|' + prefix
1518 patterns += '|' + prefix
1521 if len(prefix) > 1:
1519 if len(prefix) > 1:
1522 prefix_char = prefix[1:]
1520 prefix_char = prefix[1:]
1523 else:
1521 else:
1524 prefix_char = prefix
1522 prefix_char = prefix
1525 mapping[prefix_char] = prefix_char
1523 mapping[prefix_char] = prefix_char
1526 r = re.compile(r'%s(%s)' % (prefix, patterns))
1524 r = re.compile(r'%s(%s)' % (prefix, patterns))
1527 return r.sub(lambda x: fn(mapping[x.group()[1:]]), s)
1525 return r.sub(lambda x: fn(mapping[x.group()[1:]]), s)
1528
1526
1529 def getport(port):
1527 def getport(port):
1530 """Return the port for a given network service.
1528 """Return the port for a given network service.
1531
1529
1532 If port is an integer, it's returned as is. If it's a string, it's
1530 If port is an integer, it's returned as is. If it's a string, it's
1533 looked up using socket.getservbyname(). If there's no matching
1531 looked up using socket.getservbyname(). If there's no matching
1534 service, util.Abort is raised.
1532 service, util.Abort is raised.
1535 """
1533 """
1536 try:
1534 try:
1537 return int(port)
1535 return int(port)
1538 except ValueError:
1536 except ValueError:
1539 pass
1537 pass
1540
1538
1541 try:
1539 try:
1542 return socket.getservbyname(port)
1540 return socket.getservbyname(port)
1543 except socket.error:
1541 except socket.error:
1544 raise Abort(_("no port number associated with service '%s'") % port)
1542 raise Abort(_("no port number associated with service '%s'") % port)
1545
1543
1546 _booleans = {'1': True, 'yes': True, 'true': True, 'on': True, 'always': True,
1544 _booleans = {'1': True, 'yes': True, 'true': True, 'on': True, 'always': True,
1547 '0': False, 'no': False, 'false': False, 'off': False,
1545 '0': False, 'no': False, 'false': False, 'off': False,
1548 'never': False}
1546 'never': False}
1549
1547
1550 def parsebool(s):
1548 def parsebool(s):
1551 """Parse s into a boolean.
1549 """Parse s into a boolean.
1552
1550
1553 If s is not a valid boolean, returns None.
1551 If s is not a valid boolean, returns None.
1554 """
1552 """
1555 return _booleans.get(s.lower(), None)
1553 return _booleans.get(s.lower(), None)
1556
1554
1557 _hexdig = '0123456789ABCDEFabcdef'
1555 _hexdig = '0123456789ABCDEFabcdef'
1558 _hextochr = dict((a + b, chr(int(a + b, 16)))
1556 _hextochr = dict((a + b, chr(int(a + b, 16)))
1559 for a in _hexdig for b in _hexdig)
1557 for a in _hexdig for b in _hexdig)
1560
1558
1561 def _urlunquote(s):
1559 def _urlunquote(s):
1562 """Decode HTTP/HTML % encoding.
1560 """Decode HTTP/HTML % encoding.
1563
1561
1564 >>> _urlunquote('abc%20def')
1562 >>> _urlunquote('abc%20def')
1565 'abc def'
1563 'abc def'
1566 """
1564 """
1567 res = s.split('%')
1565 res = s.split('%')
1568 # fastpath
1566 # fastpath
1569 if len(res) == 1:
1567 if len(res) == 1:
1570 return s
1568 return s
1571 s = res[0]
1569 s = res[0]
1572 for item in res[1:]:
1570 for item in res[1:]:
1573 try:
1571 try:
1574 s += _hextochr[item[:2]] + item[2:]
1572 s += _hextochr[item[:2]] + item[2:]
1575 except KeyError:
1573 except KeyError:
1576 s += '%' + item
1574 s += '%' + item
1577 except UnicodeDecodeError:
1575 except UnicodeDecodeError:
1578 s += unichr(int(item[:2], 16)) + item[2:]
1576 s += unichr(int(item[:2], 16)) + item[2:]
1579 return s
1577 return s
1580
1578
1581 class url(object):
1579 class url(object):
1582 r"""Reliable URL parser.
1580 r"""Reliable URL parser.
1583
1581
1584 This parses URLs and provides attributes for the following
1582 This parses URLs and provides attributes for the following
1585 components:
1583 components:
1586
1584
1587 <scheme>://<user>:<passwd>@<host>:<port>/<path>?<query>#<fragment>
1585 <scheme>://<user>:<passwd>@<host>:<port>/<path>?<query>#<fragment>
1588
1586
1589 Missing components are set to None. The only exception is
1587 Missing components are set to None. The only exception is
1590 fragment, which is set to '' if present but empty.
1588 fragment, which is set to '' if present but empty.
1591
1589
1592 If parsefragment is False, fragment is included in query. If
1590 If parsefragment is False, fragment is included in query. If
1593 parsequery is False, query is included in path. If both are
1591 parsequery is False, query is included in path. If both are
1594 False, both fragment and query are included in path.
1592 False, both fragment and query are included in path.
1595
1593
1596 See http://www.ietf.org/rfc/rfc2396.txt for more information.
1594 See http://www.ietf.org/rfc/rfc2396.txt for more information.
1597
1595
1598 Note that for backward compatibility reasons, bundle URLs do not
1596 Note that for backward compatibility reasons, bundle URLs do not
1599 take host names. That means 'bundle://../' has a path of '../'.
1597 take host names. That means 'bundle://../' has a path of '../'.
1600
1598
1601 Examples:
1599 Examples:
1602
1600
1603 >>> url('http://www.ietf.org/rfc/rfc2396.txt')
1601 >>> url('http://www.ietf.org/rfc/rfc2396.txt')
1604 <url scheme: 'http', host: 'www.ietf.org', path: 'rfc/rfc2396.txt'>
1602 <url scheme: 'http', host: 'www.ietf.org', path: 'rfc/rfc2396.txt'>
1605 >>> url('ssh://[::1]:2200//home/joe/repo')
1603 >>> url('ssh://[::1]:2200//home/joe/repo')
1606 <url scheme: 'ssh', host: '[::1]', port: '2200', path: '/home/joe/repo'>
1604 <url scheme: 'ssh', host: '[::1]', port: '2200', path: '/home/joe/repo'>
1607 >>> url('file:///home/joe/repo')
1605 >>> url('file:///home/joe/repo')
1608 <url scheme: 'file', path: '/home/joe/repo'>
1606 <url scheme: 'file', path: '/home/joe/repo'>
1609 >>> url('file:///c:/temp/foo/')
1607 >>> url('file:///c:/temp/foo/')
1610 <url scheme: 'file', path: 'c:/temp/foo/'>
1608 <url scheme: 'file', path: 'c:/temp/foo/'>
1611 >>> url('bundle:foo')
1609 >>> url('bundle:foo')
1612 <url scheme: 'bundle', path: 'foo'>
1610 <url scheme: 'bundle', path: 'foo'>
1613 >>> url('bundle://../foo')
1611 >>> url('bundle://../foo')
1614 <url scheme: 'bundle', path: '../foo'>
1612 <url scheme: 'bundle', path: '../foo'>
1615 >>> url(r'c:\foo\bar')
1613 >>> url(r'c:\foo\bar')
1616 <url path: 'c:\\foo\\bar'>
1614 <url path: 'c:\\foo\\bar'>
1617 >>> url(r'\\blah\blah\blah')
1615 >>> url(r'\\blah\blah\blah')
1618 <url path: '\\\\blah\\blah\\blah'>
1616 <url path: '\\\\blah\\blah\\blah'>
1619 >>> url(r'\\blah\blah\blah#baz')
1617 >>> url(r'\\blah\blah\blah#baz')
1620 <url path: '\\\\blah\\blah\\blah', fragment: 'baz'>
1618 <url path: '\\\\blah\\blah\\blah', fragment: 'baz'>
1621
1619
1622 Authentication credentials:
1620 Authentication credentials:
1623
1621
1624 >>> url('ssh://joe:xyz@x/repo')
1622 >>> url('ssh://joe:xyz@x/repo')
1625 <url scheme: 'ssh', user: 'joe', passwd: 'xyz', host: 'x', path: 'repo'>
1623 <url scheme: 'ssh', user: 'joe', passwd: 'xyz', host: 'x', path: 'repo'>
1626 >>> url('ssh://joe@x/repo')
1624 >>> url('ssh://joe@x/repo')
1627 <url scheme: 'ssh', user: 'joe', host: 'x', path: 'repo'>
1625 <url scheme: 'ssh', user: 'joe', host: 'x', path: 'repo'>
1628
1626
1629 Query strings and fragments:
1627 Query strings and fragments:
1630
1628
1631 >>> url('http://host/a?b#c')
1629 >>> url('http://host/a?b#c')
1632 <url scheme: 'http', host: 'host', path: 'a', query: 'b', fragment: 'c'>
1630 <url scheme: 'http', host: 'host', path: 'a', query: 'b', fragment: 'c'>
1633 >>> url('http://host/a?b#c', parsequery=False, parsefragment=False)
1631 >>> url('http://host/a?b#c', parsequery=False, parsefragment=False)
1634 <url scheme: 'http', host: 'host', path: 'a?b#c'>
1632 <url scheme: 'http', host: 'host', path: 'a?b#c'>
1635 """
1633 """
1636
1634
1637 _safechars = "!~*'()+"
1635 _safechars = "!~*'()+"
1638 _safepchars = "/!~*'()+:"
1636 _safepchars = "/!~*'()+:"
1639 _matchscheme = re.compile(r'^[a-zA-Z0-9+.\-]+:').match
1637 _matchscheme = re.compile(r'^[a-zA-Z0-9+.\-]+:').match
1640
1638
1641 def __init__(self, path, parsequery=True, parsefragment=True):
1639 def __init__(self, path, parsequery=True, parsefragment=True):
1642 # We slowly chomp away at path until we have only the path left
1640 # We slowly chomp away at path until we have only the path left
1643 self.scheme = self.user = self.passwd = self.host = None
1641 self.scheme = self.user = self.passwd = self.host = None
1644 self.port = self.path = self.query = self.fragment = None
1642 self.port = self.path = self.query = self.fragment = None
1645 self._localpath = True
1643 self._localpath = True
1646 self._hostport = ''
1644 self._hostport = ''
1647 self._origpath = path
1645 self._origpath = path
1648
1646
1649 if parsefragment and '#' in path:
1647 if parsefragment and '#' in path:
1650 path, self.fragment = path.split('#', 1)
1648 path, self.fragment = path.split('#', 1)
1651 if not path:
1649 if not path:
1652 path = None
1650 path = None
1653
1651
1654 # special case for Windows drive letters and UNC paths
1652 # special case for Windows drive letters and UNC paths
1655 if hasdriveletter(path) or path.startswith(r'\\'):
1653 if hasdriveletter(path) or path.startswith(r'\\'):
1656 self.path = path
1654 self.path = path
1657 return
1655 return
1658
1656
1659 # For compatibility reasons, we can't handle bundle paths as
1657 # For compatibility reasons, we can't handle bundle paths as
1660 # normal URLS
1658 # normal URLS
1661 if path.startswith('bundle:'):
1659 if path.startswith('bundle:'):
1662 self.scheme = 'bundle'
1660 self.scheme = 'bundle'
1663 path = path[7:]
1661 path = path[7:]
1664 if path.startswith('//'):
1662 if path.startswith('//'):
1665 path = path[2:]
1663 path = path[2:]
1666 self.path = path
1664 self.path = path
1667 return
1665 return
1668
1666
1669 if self._matchscheme(path):
1667 if self._matchscheme(path):
1670 parts = path.split(':', 1)
1668 parts = path.split(':', 1)
1671 if parts[0]:
1669 if parts[0]:
1672 self.scheme, path = parts
1670 self.scheme, path = parts
1673 self._localpath = False
1671 self._localpath = False
1674
1672
1675 if not path:
1673 if not path:
1676 path = None
1674 path = None
1677 if self._localpath:
1675 if self._localpath:
1678 self.path = ''
1676 self.path = ''
1679 return
1677 return
1680 else:
1678 else:
1681 if self._localpath:
1679 if self._localpath:
1682 self.path = path
1680 self.path = path
1683 return
1681 return
1684
1682
1685 if parsequery and '?' in path:
1683 if parsequery and '?' in path:
1686 path, self.query = path.split('?', 1)
1684 path, self.query = path.split('?', 1)
1687 if not path:
1685 if not path:
1688 path = None
1686 path = None
1689 if not self.query:
1687 if not self.query:
1690 self.query = None
1688 self.query = None
1691
1689
1692 # // is required to specify a host/authority
1690 # // is required to specify a host/authority
1693 if path and path.startswith('//'):
1691 if path and path.startswith('//'):
1694 parts = path[2:].split('/', 1)
1692 parts = path[2:].split('/', 1)
1695 if len(parts) > 1:
1693 if len(parts) > 1:
1696 self.host, path = parts
1694 self.host, path = parts
1697 else:
1695 else:
1698 self.host = parts[0]
1696 self.host = parts[0]
1699 path = None
1697 path = None
1700 if not self.host:
1698 if not self.host:
1701 self.host = None
1699 self.host = None
1702 # path of file:///d is /d
1700 # path of file:///d is /d
1703 # path of file:///d:/ is d:/, not /d:/
1701 # path of file:///d:/ is d:/, not /d:/
1704 if path and not hasdriveletter(path):
1702 if path and not hasdriveletter(path):
1705 path = '/' + path
1703 path = '/' + path
1706
1704
1707 if self.host and '@' in self.host:
1705 if self.host and '@' in self.host:
1708 self.user, self.host = self.host.rsplit('@', 1)
1706 self.user, self.host = self.host.rsplit('@', 1)
1709 if ':' in self.user:
1707 if ':' in self.user:
1710 self.user, self.passwd = self.user.split(':', 1)
1708 self.user, self.passwd = self.user.split(':', 1)
1711 if not self.host:
1709 if not self.host:
1712 self.host = None
1710 self.host = None
1713
1711
1714 # Don't split on colons in IPv6 addresses without ports
1712 # Don't split on colons in IPv6 addresses without ports
1715 if (self.host and ':' in self.host and
1713 if (self.host and ':' in self.host and
1716 not (self.host.startswith('[') and self.host.endswith(']'))):
1714 not (self.host.startswith('[') and self.host.endswith(']'))):
1717 self._hostport = self.host
1715 self._hostport = self.host
1718 self.host, self.port = self.host.rsplit(':', 1)
1716 self.host, self.port = self.host.rsplit(':', 1)
1719 if not self.host:
1717 if not self.host:
1720 self.host = None
1718 self.host = None
1721
1719
1722 if (self.host and self.scheme == 'file' and
1720 if (self.host and self.scheme == 'file' and
1723 self.host not in ('localhost', '127.0.0.1', '[::1]')):
1721 self.host not in ('localhost', '127.0.0.1', '[::1]')):
1724 raise Abort(_('file:// URLs can only refer to localhost'))
1722 raise Abort(_('file:// URLs can only refer to localhost'))
1725
1723
1726 self.path = path
1724 self.path = path
1727
1725
1728 # leave the query string escaped
1726 # leave the query string escaped
1729 for a in ('user', 'passwd', 'host', 'port',
1727 for a in ('user', 'passwd', 'host', 'port',
1730 'path', 'fragment'):
1728 'path', 'fragment'):
1731 v = getattr(self, a)
1729 v = getattr(self, a)
1732 if v is not None:
1730 if v is not None:
1733 setattr(self, a, _urlunquote(v))
1731 setattr(self, a, _urlunquote(v))
1734
1732
1735 def __repr__(self):
1733 def __repr__(self):
1736 attrs = []
1734 attrs = []
1737 for a in ('scheme', 'user', 'passwd', 'host', 'port', 'path',
1735 for a in ('scheme', 'user', 'passwd', 'host', 'port', 'path',
1738 'query', 'fragment'):
1736 'query', 'fragment'):
1739 v = getattr(self, a)
1737 v = getattr(self, a)
1740 if v is not None:
1738 if v is not None:
1741 attrs.append('%s: %r' % (a, v))
1739 attrs.append('%s: %r' % (a, v))
1742 return '<url %s>' % ', '.join(attrs)
1740 return '<url %s>' % ', '.join(attrs)
1743
1741
1744 def __str__(self):
1742 def __str__(self):
1745 r"""Join the URL's components back into a URL string.
1743 r"""Join the URL's components back into a URL string.
1746
1744
1747 Examples:
1745 Examples:
1748
1746
1749 >>> str(url('http://user:pw@host:80/c:/bob?fo:oo#ba:ar'))
1747 >>> str(url('http://user:pw@host:80/c:/bob?fo:oo#ba:ar'))
1750 'http://user:pw@host:80/c:/bob?fo:oo#ba:ar'
1748 'http://user:pw@host:80/c:/bob?fo:oo#ba:ar'
1751 >>> str(url('http://user:pw@host:80/?foo=bar&baz=42'))
1749 >>> str(url('http://user:pw@host:80/?foo=bar&baz=42'))
1752 'http://user:pw@host:80/?foo=bar&baz=42'
1750 'http://user:pw@host:80/?foo=bar&baz=42'
1753 >>> str(url('http://user:pw@host:80/?foo=bar%3dbaz'))
1751 >>> str(url('http://user:pw@host:80/?foo=bar%3dbaz'))
1754 'http://user:pw@host:80/?foo=bar%3dbaz'
1752 'http://user:pw@host:80/?foo=bar%3dbaz'
1755 >>> str(url('ssh://user:pw@[::1]:2200//home/joe#'))
1753 >>> str(url('ssh://user:pw@[::1]:2200//home/joe#'))
1756 'ssh://user:pw@[::1]:2200//home/joe#'
1754 'ssh://user:pw@[::1]:2200//home/joe#'
1757 >>> str(url('http://localhost:80//'))
1755 >>> str(url('http://localhost:80//'))
1758 'http://localhost:80//'
1756 'http://localhost:80//'
1759 >>> str(url('http://localhost:80/'))
1757 >>> str(url('http://localhost:80/'))
1760 'http://localhost:80/'
1758 'http://localhost:80/'
1761 >>> str(url('http://localhost:80'))
1759 >>> str(url('http://localhost:80'))
1762 'http://localhost:80/'
1760 'http://localhost:80/'
1763 >>> str(url('bundle:foo'))
1761 >>> str(url('bundle:foo'))
1764 'bundle:foo'
1762 'bundle:foo'
1765 >>> str(url('bundle://../foo'))
1763 >>> str(url('bundle://../foo'))
1766 'bundle:../foo'
1764 'bundle:../foo'
1767 >>> str(url('path'))
1765 >>> str(url('path'))
1768 'path'
1766 'path'
1769 >>> str(url('file:///tmp/foo/bar'))
1767 >>> str(url('file:///tmp/foo/bar'))
1770 'file:///tmp/foo/bar'
1768 'file:///tmp/foo/bar'
1771 >>> str(url('file:///c:/tmp/foo/bar'))
1769 >>> str(url('file:///c:/tmp/foo/bar'))
1772 'file:///c:/tmp/foo/bar'
1770 'file:///c:/tmp/foo/bar'
1773 >>> print url(r'bundle:foo\bar')
1771 >>> print url(r'bundle:foo\bar')
1774 bundle:foo\bar
1772 bundle:foo\bar
1775 """
1773 """
1776 if self._localpath:
1774 if self._localpath:
1777 s = self.path
1775 s = self.path
1778 if self.scheme == 'bundle':
1776 if self.scheme == 'bundle':
1779 s = 'bundle:' + s
1777 s = 'bundle:' + s
1780 if self.fragment:
1778 if self.fragment:
1781 s += '#' + self.fragment
1779 s += '#' + self.fragment
1782 return s
1780 return s
1783
1781
1784 s = self.scheme + ':'
1782 s = self.scheme + ':'
1785 if self.user or self.passwd or self.host:
1783 if self.user or self.passwd or self.host:
1786 s += '//'
1784 s += '//'
1787 elif self.scheme and (not self.path or self.path.startswith('/')
1785 elif self.scheme and (not self.path or self.path.startswith('/')
1788 or hasdriveletter(self.path)):
1786 or hasdriveletter(self.path)):
1789 s += '//'
1787 s += '//'
1790 if hasdriveletter(self.path):
1788 if hasdriveletter(self.path):
1791 s += '/'
1789 s += '/'
1792 if self.user:
1790 if self.user:
1793 s += urllib.quote(self.user, safe=self._safechars)
1791 s += urllib.quote(self.user, safe=self._safechars)
1794 if self.passwd:
1792 if self.passwd:
1795 s += ':' + urllib.quote(self.passwd, safe=self._safechars)
1793 s += ':' + urllib.quote(self.passwd, safe=self._safechars)
1796 if self.user or self.passwd:
1794 if self.user or self.passwd:
1797 s += '@'
1795 s += '@'
1798 if self.host:
1796 if self.host:
1799 if not (self.host.startswith('[') and self.host.endswith(']')):
1797 if not (self.host.startswith('[') and self.host.endswith(']')):
1800 s += urllib.quote(self.host)
1798 s += urllib.quote(self.host)
1801 else:
1799 else:
1802 s += self.host
1800 s += self.host
1803 if self.port:
1801 if self.port:
1804 s += ':' + urllib.quote(self.port)
1802 s += ':' + urllib.quote(self.port)
1805 if self.host:
1803 if self.host:
1806 s += '/'
1804 s += '/'
1807 if self.path:
1805 if self.path:
1808 # TODO: similar to the query string, we should not unescape the
1806 # TODO: similar to the query string, we should not unescape the
1809 # path when we store it, the path might contain '%2f' = '/',
1807 # path when we store it, the path might contain '%2f' = '/',
1810 # which we should *not* escape.
1808 # which we should *not* escape.
1811 s += urllib.quote(self.path, safe=self._safepchars)
1809 s += urllib.quote(self.path, safe=self._safepchars)
1812 if self.query:
1810 if self.query:
1813 # we store the query in escaped form.
1811 # we store the query in escaped form.
1814 s += '?' + self.query
1812 s += '?' + self.query
1815 if self.fragment is not None:
1813 if self.fragment is not None:
1816 s += '#' + urllib.quote(self.fragment, safe=self._safepchars)
1814 s += '#' + urllib.quote(self.fragment, safe=self._safepchars)
1817 return s
1815 return s
1818
1816
1819 def authinfo(self):
1817 def authinfo(self):
1820 user, passwd = self.user, self.passwd
1818 user, passwd = self.user, self.passwd
1821 try:
1819 try:
1822 self.user, self.passwd = None, None
1820 self.user, self.passwd = None, None
1823 s = str(self)
1821 s = str(self)
1824 finally:
1822 finally:
1825 self.user, self.passwd = user, passwd
1823 self.user, self.passwd = user, passwd
1826 if not self.user:
1824 if not self.user:
1827 return (s, None)
1825 return (s, None)
1828 # authinfo[1] is passed to urllib2 password manager, and its
1826 # authinfo[1] is passed to urllib2 password manager, and its
1829 # URIs must not contain credentials. The host is passed in the
1827 # URIs must not contain credentials. The host is passed in the
1830 # URIs list because Python < 2.4.3 uses only that to search for
1828 # URIs list because Python < 2.4.3 uses only that to search for
1831 # a password.
1829 # a password.
1832 return (s, (None, (s, self.host),
1830 return (s, (None, (s, self.host),
1833 self.user, self.passwd or ''))
1831 self.user, self.passwd or ''))
1834
1832
1835 def isabs(self):
1833 def isabs(self):
1836 if self.scheme and self.scheme != 'file':
1834 if self.scheme and self.scheme != 'file':
1837 return True # remote URL
1835 return True # remote URL
1838 if hasdriveletter(self.path):
1836 if hasdriveletter(self.path):
1839 return True # absolute for our purposes - can't be joined()
1837 return True # absolute for our purposes - can't be joined()
1840 if self.path.startswith(r'\\'):
1838 if self.path.startswith(r'\\'):
1841 return True # Windows UNC path
1839 return True # Windows UNC path
1842 if self.path.startswith('/'):
1840 if self.path.startswith('/'):
1843 return True # POSIX-style
1841 return True # POSIX-style
1844 return False
1842 return False
1845
1843
1846 def localpath(self):
1844 def localpath(self):
1847 if self.scheme == 'file' or self.scheme == 'bundle':
1845 if self.scheme == 'file' or self.scheme == 'bundle':
1848 path = self.path or '/'
1846 path = self.path or '/'
1849 # For Windows, we need to promote hosts containing drive
1847 # For Windows, we need to promote hosts containing drive
1850 # letters to paths with drive letters.
1848 # letters to paths with drive letters.
1851 if hasdriveletter(self._hostport):
1849 if hasdriveletter(self._hostport):
1852 path = self._hostport + '/' + self.path
1850 path = self._hostport + '/' + self.path
1853 elif (self.host is not None and self.path
1851 elif (self.host is not None and self.path
1854 and not hasdriveletter(path)):
1852 and not hasdriveletter(path)):
1855 path = '/' + path
1853 path = '/' + path
1856 return path
1854 return path
1857 return self._origpath
1855 return self._origpath
1858
1856
1859 def hasscheme(path):
1857 def hasscheme(path):
1860 return bool(url(path).scheme)
1858 return bool(url(path).scheme)
1861
1859
1862 def hasdriveletter(path):
1860 def hasdriveletter(path):
1863 return path and path[1:2] == ':' and path[0:1].isalpha()
1861 return path and path[1:2] == ':' and path[0:1].isalpha()
1864
1862
1865 def urllocalpath(path):
1863 def urllocalpath(path):
1866 return url(path, parsequery=False, parsefragment=False).localpath()
1864 return url(path, parsequery=False, parsefragment=False).localpath()
1867
1865
1868 def hidepassword(u):
1866 def hidepassword(u):
1869 '''hide user credential in a url string'''
1867 '''hide user credential in a url string'''
1870 u = url(u)
1868 u = url(u)
1871 if u.passwd:
1869 if u.passwd:
1872 u.passwd = '***'
1870 u.passwd = '***'
1873 return str(u)
1871 return str(u)
1874
1872
1875 def removeauth(u):
1873 def removeauth(u):
1876 '''remove all authentication information from a url string'''
1874 '''remove all authentication information from a url string'''
1877 u = url(u)
1875 u = url(u)
1878 u.user = u.passwd = None
1876 u.user = u.passwd = None
1879 return str(u)
1877 return str(u)
1880
1878
1881 def isatty(fd):
1879 def isatty(fd):
1882 try:
1880 try:
1883 return fd.isatty()
1881 return fd.isatty()
1884 except AttributeError:
1882 except AttributeError:
1885 return False
1883 return False
1886
1884
1887 timecount = unitcountfn(
1885 timecount = unitcountfn(
1888 (1, 1e3, _('%.0f s')),
1886 (1, 1e3, _('%.0f s')),
1889 (100, 1, _('%.1f s')),
1887 (100, 1, _('%.1f s')),
1890 (10, 1, _('%.2f s')),
1888 (10, 1, _('%.2f s')),
1891 (1, 1, _('%.3f s')),
1889 (1, 1, _('%.3f s')),
1892 (100, 0.001, _('%.1f ms')),
1890 (100, 0.001, _('%.1f ms')),
1893 (10, 0.001, _('%.2f ms')),
1891 (10, 0.001, _('%.2f ms')),
1894 (1, 0.001, _('%.3f ms')),
1892 (1, 0.001, _('%.3f ms')),
1895 (100, 0.000001, _('%.1f us')),
1893 (100, 0.000001, _('%.1f us')),
1896 (10, 0.000001, _('%.2f us')),
1894 (10, 0.000001, _('%.2f us')),
1897 (1, 0.000001, _('%.3f us')),
1895 (1, 0.000001, _('%.3f us')),
1898 (100, 0.000000001, _('%.1f ns')),
1896 (100, 0.000000001, _('%.1f ns')),
1899 (10, 0.000000001, _('%.2f ns')),
1897 (10, 0.000000001, _('%.2f ns')),
1900 (1, 0.000000001, _('%.3f ns')),
1898 (1, 0.000000001, _('%.3f ns')),
1901 )
1899 )
1902
1900
1903 _timenesting = [0]
1901 _timenesting = [0]
1904
1902
1905 def timed(func):
1903 def timed(func):
1906 '''Report the execution time of a function call to stderr.
1904 '''Report the execution time of a function call to stderr.
1907
1905
1908 During development, use as a decorator when you need to measure
1906 During development, use as a decorator when you need to measure
1909 the cost of a function, e.g. as follows:
1907 the cost of a function, e.g. as follows:
1910
1908
1911 @util.timed
1909 @util.timed
1912 def foo(a, b, c):
1910 def foo(a, b, c):
1913 pass
1911 pass
1914 '''
1912 '''
1915
1913
1916 def wrapper(*args, **kwargs):
1914 def wrapper(*args, **kwargs):
1917 start = time.time()
1915 start = time.time()
1918 indent = 2
1916 indent = 2
1919 _timenesting[0] += indent
1917 _timenesting[0] += indent
1920 try:
1918 try:
1921 return func(*args, **kwargs)
1919 return func(*args, **kwargs)
1922 finally:
1920 finally:
1923 elapsed = time.time() - start
1921 elapsed = time.time() - start
1924 _timenesting[0] -= indent
1922 _timenesting[0] -= indent
1925 sys.stderr.write('%s%s: %s\n' %
1923 sys.stderr.write('%s%s: %s\n' %
1926 (' ' * _timenesting[0], func.__name__,
1924 (' ' * _timenesting[0], func.__name__,
1927 timecount(elapsed)))
1925 timecount(elapsed)))
1928 return wrapper
1926 return wrapper
General Comments 0
You need to be logged in to leave comments. Login now