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