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