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