##// END OF EJS Templates
py3: paper over differences in future exception handling...
Augie Fackler -
r37687:1cb54e61 default
parent child Browse files
Show More
@@ -1,1009 +1,1010
1 # httppeer.py - HTTP repository proxy classes for mercurial
1 # httppeer.py - HTTP repository proxy classes for mercurial
2 #
2 #
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 from __future__ import absolute_import
9 from __future__ import absolute_import
10
10
11 import errno
11 import errno
12 import io
12 import io
13 import os
13 import os
14 import socket
14 import socket
15 import struct
15 import struct
16 import sys
16 import sys
17 import tempfile
17 import tempfile
18 import weakref
18 import weakref
19
19
20 from .i18n import _
20 from .i18n import _
21 from .thirdparty import (
21 from .thirdparty import (
22 cbor,
22 cbor,
23 )
23 )
24 from .thirdparty.zope import (
24 from .thirdparty.zope import (
25 interface as zi,
25 interface as zi,
26 )
26 )
27 from . import (
27 from . import (
28 bundle2,
28 bundle2,
29 error,
29 error,
30 httpconnection,
30 httpconnection,
31 pycompat,
31 pycompat,
32 repository,
32 repository,
33 statichttprepo,
33 statichttprepo,
34 url as urlmod,
34 url as urlmod,
35 util,
35 util,
36 wireprotoframing,
36 wireprotoframing,
37 wireprototypes,
37 wireprototypes,
38 wireprotov1peer,
38 wireprotov1peer,
39 wireprotov2server,
39 wireprotov2server,
40 )
40 )
41
41
42 httplib = util.httplib
42 httplib = util.httplib
43 urlerr = util.urlerr
43 urlerr = util.urlerr
44 urlreq = util.urlreq
44 urlreq = util.urlreq
45
45
46 def encodevalueinheaders(value, header, limit):
46 def encodevalueinheaders(value, header, limit):
47 """Encode a string value into multiple HTTP headers.
47 """Encode a string value into multiple HTTP headers.
48
48
49 ``value`` will be encoded into 1 or more HTTP headers with the names
49 ``value`` will be encoded into 1 or more HTTP headers with the names
50 ``header-<N>`` where ``<N>`` is an integer starting at 1. Each header
50 ``header-<N>`` where ``<N>`` is an integer starting at 1. Each header
51 name + value will be at most ``limit`` bytes long.
51 name + value will be at most ``limit`` bytes long.
52
52
53 Returns an iterable of 2-tuples consisting of header names and
53 Returns an iterable of 2-tuples consisting of header names and
54 values as native strings.
54 values as native strings.
55 """
55 """
56 # HTTP Headers are ASCII. Python 3 requires them to be unicodes,
56 # HTTP Headers are ASCII. Python 3 requires them to be unicodes,
57 # not bytes. This function always takes bytes in as arguments.
57 # not bytes. This function always takes bytes in as arguments.
58 fmt = pycompat.strurl(header) + r'-%s'
58 fmt = pycompat.strurl(header) + r'-%s'
59 # Note: it is *NOT* a bug that the last bit here is a bytestring
59 # Note: it is *NOT* a bug that the last bit here is a bytestring
60 # and not a unicode: we're just getting the encoded length anyway,
60 # and not a unicode: we're just getting the encoded length anyway,
61 # and using an r-string to make it portable between Python 2 and 3
61 # and using an r-string to make it portable between Python 2 and 3
62 # doesn't work because then the \r is a literal backslash-r
62 # doesn't work because then the \r is a literal backslash-r
63 # instead of a carriage return.
63 # instead of a carriage return.
64 valuelen = limit - len(fmt % r'000') - len(': \r\n')
64 valuelen = limit - len(fmt % r'000') - len(': \r\n')
65 result = []
65 result = []
66
66
67 n = 0
67 n = 0
68 for i in xrange(0, len(value), valuelen):
68 for i in xrange(0, len(value), valuelen):
69 n += 1
69 n += 1
70 result.append((fmt % str(n), pycompat.strurl(value[i:i + valuelen])))
70 result.append((fmt % str(n), pycompat.strurl(value[i:i + valuelen])))
71
71
72 return result
72 return result
73
73
74 def _wraphttpresponse(resp):
74 def _wraphttpresponse(resp):
75 """Wrap an HTTPResponse with common error handlers.
75 """Wrap an HTTPResponse with common error handlers.
76
76
77 This ensures that any I/O from any consumer raises the appropriate
77 This ensures that any I/O from any consumer raises the appropriate
78 error and messaging.
78 error and messaging.
79 """
79 """
80 origread = resp.read
80 origread = resp.read
81
81
82 class readerproxy(resp.__class__):
82 class readerproxy(resp.__class__):
83 def read(self, size=None):
83 def read(self, size=None):
84 try:
84 try:
85 return origread(size)
85 return origread(size)
86 except httplib.IncompleteRead as e:
86 except httplib.IncompleteRead as e:
87 # e.expected is an integer if length known or None otherwise.
87 # e.expected is an integer if length known or None otherwise.
88 if e.expected:
88 if e.expected:
89 msg = _('HTTP request error (incomplete response; '
89 msg = _('HTTP request error (incomplete response; '
90 'expected %d bytes got %d)') % (e.expected,
90 'expected %d bytes got %d)') % (e.expected,
91 len(e.partial))
91 len(e.partial))
92 else:
92 else:
93 msg = _('HTTP request error (incomplete response)')
93 msg = _('HTTP request error (incomplete response)')
94
94
95 raise error.PeerTransportError(
95 raise error.PeerTransportError(
96 msg,
96 msg,
97 hint=_('this may be an intermittent network failure; '
97 hint=_('this may be an intermittent network failure; '
98 'if the error persists, consider contacting the '
98 'if the error persists, consider contacting the '
99 'network or server operator'))
99 'network or server operator'))
100 except httplib.HTTPException as e:
100 except httplib.HTTPException as e:
101 raise error.PeerTransportError(
101 raise error.PeerTransportError(
102 _('HTTP request error (%s)') % e,
102 _('HTTP request error (%s)') % e,
103 hint=_('this may be an intermittent network failure; '
103 hint=_('this may be an intermittent network failure; '
104 'if the error persists, consider contacting the '
104 'if the error persists, consider contacting the '
105 'network or server operator'))
105 'network or server operator'))
106
106
107 resp.__class__ = readerproxy
107 resp.__class__ = readerproxy
108
108
109 class _multifile(object):
109 class _multifile(object):
110 def __init__(self, *fileobjs):
110 def __init__(self, *fileobjs):
111 for f in fileobjs:
111 for f in fileobjs:
112 if not util.safehasattr(f, 'length'):
112 if not util.safehasattr(f, 'length'):
113 raise ValueError(
113 raise ValueError(
114 '_multifile only supports file objects that '
114 '_multifile only supports file objects that '
115 'have a length but this one does not:', type(f), f)
115 'have a length but this one does not:', type(f), f)
116 self._fileobjs = fileobjs
116 self._fileobjs = fileobjs
117 self._index = 0
117 self._index = 0
118
118
119 @property
119 @property
120 def length(self):
120 def length(self):
121 return sum(f.length for f in self._fileobjs)
121 return sum(f.length for f in self._fileobjs)
122
122
123 def read(self, amt=None):
123 def read(self, amt=None):
124 if amt <= 0:
124 if amt <= 0:
125 return ''.join(f.read() for f in self._fileobjs)
125 return ''.join(f.read() for f in self._fileobjs)
126 parts = []
126 parts = []
127 while amt and self._index < len(self._fileobjs):
127 while amt and self._index < len(self._fileobjs):
128 parts.append(self._fileobjs[self._index].read(amt))
128 parts.append(self._fileobjs[self._index].read(amt))
129 got = len(parts[-1])
129 got = len(parts[-1])
130 if got < amt:
130 if got < amt:
131 self._index += 1
131 self._index += 1
132 amt -= got
132 amt -= got
133 return ''.join(parts)
133 return ''.join(parts)
134
134
135 def seek(self, offset, whence=os.SEEK_SET):
135 def seek(self, offset, whence=os.SEEK_SET):
136 if whence != os.SEEK_SET:
136 if whence != os.SEEK_SET:
137 raise NotImplementedError(
137 raise NotImplementedError(
138 '_multifile does not support anything other'
138 '_multifile does not support anything other'
139 ' than os.SEEK_SET for whence on seek()')
139 ' than os.SEEK_SET for whence on seek()')
140 if offset != 0:
140 if offset != 0:
141 raise NotImplementedError(
141 raise NotImplementedError(
142 '_multifile only supports seeking to start, but that '
142 '_multifile only supports seeking to start, but that '
143 'could be fixed if you need it')
143 'could be fixed if you need it')
144 for f in self._fileobjs:
144 for f in self._fileobjs:
145 f.seek(0)
145 f.seek(0)
146 self._index = 0
146 self._index = 0
147
147
148 def makev1commandrequest(ui, requestbuilder, caps, capablefn,
148 def makev1commandrequest(ui, requestbuilder, caps, capablefn,
149 repobaseurl, cmd, args):
149 repobaseurl, cmd, args):
150 """Make an HTTP request to run a command for a version 1 client.
150 """Make an HTTP request to run a command for a version 1 client.
151
151
152 ``caps`` is a set of known server capabilities. The value may be
152 ``caps`` is a set of known server capabilities. The value may be
153 None if capabilities are not yet known.
153 None if capabilities are not yet known.
154
154
155 ``capablefn`` is a function to evaluate a capability.
155 ``capablefn`` is a function to evaluate a capability.
156
156
157 ``cmd``, ``args``, and ``data`` define the command, its arguments, and
157 ``cmd``, ``args``, and ``data`` define the command, its arguments, and
158 raw data to pass to it.
158 raw data to pass to it.
159 """
159 """
160 if cmd == 'pushkey':
160 if cmd == 'pushkey':
161 args['data'] = ''
161 args['data'] = ''
162 data = args.pop('data', None)
162 data = args.pop('data', None)
163 headers = args.pop('headers', {})
163 headers = args.pop('headers', {})
164
164
165 ui.debug("sending %s command\n" % cmd)
165 ui.debug("sending %s command\n" % cmd)
166 q = [('cmd', cmd)]
166 q = [('cmd', cmd)]
167 headersize = 0
167 headersize = 0
168 # Important: don't use self.capable() here or else you end up
168 # Important: don't use self.capable() here or else you end up
169 # with infinite recursion when trying to look up capabilities
169 # with infinite recursion when trying to look up capabilities
170 # for the first time.
170 # for the first time.
171 postargsok = caps is not None and 'httppostargs' in caps
171 postargsok = caps is not None and 'httppostargs' in caps
172
172
173 # Send arguments via POST.
173 # Send arguments via POST.
174 if postargsok and args:
174 if postargsok and args:
175 strargs = urlreq.urlencode(sorted(args.items()))
175 strargs = urlreq.urlencode(sorted(args.items()))
176 if not data:
176 if not data:
177 data = strargs
177 data = strargs
178 else:
178 else:
179 if isinstance(data, bytes):
179 if isinstance(data, bytes):
180 i = io.BytesIO(data)
180 i = io.BytesIO(data)
181 i.length = len(data)
181 i.length = len(data)
182 data = i
182 data = i
183 argsio = io.BytesIO(strargs)
183 argsio = io.BytesIO(strargs)
184 argsio.length = len(strargs)
184 argsio.length = len(strargs)
185 data = _multifile(argsio, data)
185 data = _multifile(argsio, data)
186 headers[r'X-HgArgs-Post'] = len(strargs)
186 headers[r'X-HgArgs-Post'] = len(strargs)
187 elif args:
187 elif args:
188 # Calling self.capable() can infinite loop if we are calling
188 # Calling self.capable() can infinite loop if we are calling
189 # "capabilities". But that command should never accept wire
189 # "capabilities". But that command should never accept wire
190 # protocol arguments. So this should never happen.
190 # protocol arguments. So this should never happen.
191 assert cmd != 'capabilities'
191 assert cmd != 'capabilities'
192 httpheader = capablefn('httpheader')
192 httpheader = capablefn('httpheader')
193 if httpheader:
193 if httpheader:
194 headersize = int(httpheader.split(',', 1)[0])
194 headersize = int(httpheader.split(',', 1)[0])
195
195
196 # Send arguments via HTTP headers.
196 # Send arguments via HTTP headers.
197 if headersize > 0:
197 if headersize > 0:
198 # The headers can typically carry more data than the URL.
198 # The headers can typically carry more data than the URL.
199 encargs = urlreq.urlencode(sorted(args.items()))
199 encargs = urlreq.urlencode(sorted(args.items()))
200 for header, value in encodevalueinheaders(encargs, 'X-HgArg',
200 for header, value in encodevalueinheaders(encargs, 'X-HgArg',
201 headersize):
201 headersize):
202 headers[header] = value
202 headers[header] = value
203 # Send arguments via query string (Mercurial <1.9).
203 # Send arguments via query string (Mercurial <1.9).
204 else:
204 else:
205 q += sorted(args.items())
205 q += sorted(args.items())
206
206
207 qs = '?%s' % urlreq.urlencode(q)
207 qs = '?%s' % urlreq.urlencode(q)
208 cu = "%s%s" % (repobaseurl, qs)
208 cu = "%s%s" % (repobaseurl, qs)
209 size = 0
209 size = 0
210 if util.safehasattr(data, 'length'):
210 if util.safehasattr(data, 'length'):
211 size = data.length
211 size = data.length
212 elif data is not None:
212 elif data is not None:
213 size = len(data)
213 size = len(data)
214 if data is not None and r'Content-Type' not in headers:
214 if data is not None and r'Content-Type' not in headers:
215 headers[r'Content-Type'] = r'application/mercurial-0.1'
215 headers[r'Content-Type'] = r'application/mercurial-0.1'
216
216
217 # Tell the server we accept application/mercurial-0.2 and multiple
217 # Tell the server we accept application/mercurial-0.2 and multiple
218 # compression formats if the server is capable of emitting those
218 # compression formats if the server is capable of emitting those
219 # payloads.
219 # payloads.
220 # Note: Keep this set empty by default, as client advertisement of
220 # Note: Keep this set empty by default, as client advertisement of
221 # protocol parameters should only occur after the handshake.
221 # protocol parameters should only occur after the handshake.
222 protoparams = set()
222 protoparams = set()
223
223
224 mediatypes = set()
224 mediatypes = set()
225 if caps is not None:
225 if caps is not None:
226 mt = capablefn('httpmediatype')
226 mt = capablefn('httpmediatype')
227 if mt:
227 if mt:
228 protoparams.add('0.1')
228 protoparams.add('0.1')
229 mediatypes = set(mt.split(','))
229 mediatypes = set(mt.split(','))
230
230
231 protoparams.add('partial-pull')
231 protoparams.add('partial-pull')
232
232
233 if '0.2tx' in mediatypes:
233 if '0.2tx' in mediatypes:
234 protoparams.add('0.2')
234 protoparams.add('0.2')
235
235
236 if '0.2tx' in mediatypes and capablefn('compression'):
236 if '0.2tx' in mediatypes and capablefn('compression'):
237 # We /could/ compare supported compression formats and prune
237 # We /could/ compare supported compression formats and prune
238 # non-mutually supported or error if nothing is mutually supported.
238 # non-mutually supported or error if nothing is mutually supported.
239 # For now, send the full list to the server and have it error.
239 # For now, send the full list to the server and have it error.
240 comps = [e.wireprotosupport().name for e in
240 comps = [e.wireprotosupport().name for e in
241 util.compengines.supportedwireengines(util.CLIENTROLE)]
241 util.compengines.supportedwireengines(util.CLIENTROLE)]
242 protoparams.add('comp=%s' % ','.join(comps))
242 protoparams.add('comp=%s' % ','.join(comps))
243
243
244 if protoparams:
244 if protoparams:
245 protoheaders = encodevalueinheaders(' '.join(sorted(protoparams)),
245 protoheaders = encodevalueinheaders(' '.join(sorted(protoparams)),
246 'X-HgProto',
246 'X-HgProto',
247 headersize or 1024)
247 headersize or 1024)
248 for header, value in protoheaders:
248 for header, value in protoheaders:
249 headers[header] = value
249 headers[header] = value
250
250
251 varyheaders = []
251 varyheaders = []
252 for header in headers:
252 for header in headers:
253 if header.lower().startswith(r'x-hg'):
253 if header.lower().startswith(r'x-hg'):
254 varyheaders.append(header)
254 varyheaders.append(header)
255
255
256 if varyheaders:
256 if varyheaders:
257 headers[r'Vary'] = r','.join(sorted(varyheaders))
257 headers[r'Vary'] = r','.join(sorted(varyheaders))
258
258
259 req = requestbuilder(pycompat.strurl(cu), data, headers)
259 req = requestbuilder(pycompat.strurl(cu), data, headers)
260
260
261 if data is not None:
261 if data is not None:
262 ui.debug("sending %d bytes\n" % size)
262 ui.debug("sending %d bytes\n" % size)
263 req.add_unredirected_header(r'Content-Length', r'%d' % size)
263 req.add_unredirected_header(r'Content-Length', r'%d' % size)
264
264
265 return req, cu, qs
265 return req, cu, qs
266
266
267 def sendrequest(ui, opener, req):
267 def sendrequest(ui, opener, req):
268 """Send a prepared HTTP request.
268 """Send a prepared HTTP request.
269
269
270 Returns the response object.
270 Returns the response object.
271 """
271 """
272 if (ui.debugflag
272 if (ui.debugflag
273 and ui.configbool('devel', 'debug.peer-request')):
273 and ui.configbool('devel', 'debug.peer-request')):
274 dbg = ui.debug
274 dbg = ui.debug
275 line = 'devel-peer-request: %s\n'
275 line = 'devel-peer-request: %s\n'
276 dbg(line % '%s %s' % (req.get_method(), req.get_full_url()))
276 dbg(line % '%s %s' % (req.get_method(), req.get_full_url()))
277 hgargssize = None
277 hgargssize = None
278
278
279 for header, value in sorted(req.header_items()):
279 for header, value in sorted(req.header_items()):
280 if header.startswith('X-hgarg-'):
280 if header.startswith('X-hgarg-'):
281 if hgargssize is None:
281 if hgargssize is None:
282 hgargssize = 0
282 hgargssize = 0
283 hgargssize += len(value)
283 hgargssize += len(value)
284 else:
284 else:
285 dbg(line % ' %s %s' % (header, value))
285 dbg(line % ' %s %s' % (header, value))
286
286
287 if hgargssize is not None:
287 if hgargssize is not None:
288 dbg(line % ' %d bytes of commands arguments in headers'
288 dbg(line % ' %d bytes of commands arguments in headers'
289 % hgargssize)
289 % hgargssize)
290
290
291 if req.has_data():
291 if req.has_data():
292 data = req.get_data()
292 data = req.get_data()
293 length = getattr(data, 'length', None)
293 length = getattr(data, 'length', None)
294 if length is None:
294 if length is None:
295 length = len(data)
295 length = len(data)
296 dbg(line % ' %d bytes of data' % length)
296 dbg(line % ' %d bytes of data' % length)
297
297
298 start = util.timer()
298 start = util.timer()
299
299
300 try:
300 try:
301 res = opener.open(req)
301 res = opener.open(req)
302 except urlerr.httperror as inst:
302 except urlerr.httperror as inst:
303 if inst.code == 401:
303 if inst.code == 401:
304 raise error.Abort(_('authorization failed'))
304 raise error.Abort(_('authorization failed'))
305 raise
305 raise
306 except httplib.HTTPException as inst:
306 except httplib.HTTPException as inst:
307 ui.debug('http error requesting %s\n' %
307 ui.debug('http error requesting %s\n' %
308 util.hidepassword(req.get_full_url()))
308 util.hidepassword(req.get_full_url()))
309 ui.traceback()
309 ui.traceback()
310 raise IOError(None, inst)
310 raise IOError(None, inst)
311 finally:
311 finally:
312 if ui.configbool('devel', 'debug.peer-request'):
312 if ui.configbool('devel', 'debug.peer-request'):
313 dbg(line % ' finished in %.4f seconds (%s)'
313 dbg(line % ' finished in %.4f seconds (%s)'
314 % (util.timer() - start, res.code))
314 % (util.timer() - start, res.code))
315
315
316 # Insert error handlers for common I/O failures.
316 # Insert error handlers for common I/O failures.
317 _wraphttpresponse(res)
317 _wraphttpresponse(res)
318
318
319 return res
319 return res
320
320
321 def parsev1commandresponse(ui, baseurl, requrl, qs, resp, compressible,
321 def parsev1commandresponse(ui, baseurl, requrl, qs, resp, compressible,
322 allowcbor=False):
322 allowcbor=False):
323 # record the url we got redirected to
323 # record the url we got redirected to
324 respurl = pycompat.bytesurl(resp.geturl())
324 respurl = pycompat.bytesurl(resp.geturl())
325 if respurl.endswith(qs):
325 if respurl.endswith(qs):
326 respurl = respurl[:-len(qs)]
326 respurl = respurl[:-len(qs)]
327 if baseurl.rstrip('/') != respurl.rstrip('/'):
327 if baseurl.rstrip('/') != respurl.rstrip('/'):
328 if not ui.quiet:
328 if not ui.quiet:
329 ui.warn(_('real URL is %s\n') % respurl)
329 ui.warn(_('real URL is %s\n') % respurl)
330
330
331 try:
331 try:
332 proto = pycompat.bytesurl(resp.getheader(r'content-type', r''))
332 proto = pycompat.bytesurl(resp.getheader(r'content-type', r''))
333 except AttributeError:
333 except AttributeError:
334 proto = pycompat.bytesurl(resp.headers.get(r'content-type', r''))
334 proto = pycompat.bytesurl(resp.headers.get(r'content-type', r''))
335
335
336 safeurl = util.hidepassword(baseurl)
336 safeurl = util.hidepassword(baseurl)
337 if proto.startswith('application/hg-error'):
337 if proto.startswith('application/hg-error'):
338 raise error.OutOfBandError(resp.read())
338 raise error.OutOfBandError(resp.read())
339
339
340 # Pre 1.0 versions of Mercurial used text/plain and
340 # Pre 1.0 versions of Mercurial used text/plain and
341 # application/hg-changegroup. We don't support such old servers.
341 # application/hg-changegroup. We don't support such old servers.
342 if not proto.startswith('application/mercurial-'):
342 if not proto.startswith('application/mercurial-'):
343 ui.debug("requested URL: '%s'\n" % util.hidepassword(requrl))
343 ui.debug("requested URL: '%s'\n" % util.hidepassword(requrl))
344 raise error.RepoError(
344 raise error.RepoError(
345 _("'%s' does not appear to be an hg repository:\n"
345 _("'%s' does not appear to be an hg repository:\n"
346 "---%%<--- (%s)\n%s\n---%%<---\n")
346 "---%%<--- (%s)\n%s\n---%%<---\n")
347 % (safeurl, proto or 'no content-type', resp.read(1024)))
347 % (safeurl, proto or 'no content-type', resp.read(1024)))
348
348
349 try:
349 try:
350 subtype = proto.split('-', 1)[1]
350 subtype = proto.split('-', 1)[1]
351
351
352 # Unless we end up supporting CBOR in the legacy wire protocol,
352 # Unless we end up supporting CBOR in the legacy wire protocol,
353 # this should ONLY be encountered for the initial capabilities
353 # this should ONLY be encountered for the initial capabilities
354 # request during handshake.
354 # request during handshake.
355 if subtype == 'cbor':
355 if subtype == 'cbor':
356 if allowcbor:
356 if allowcbor:
357 return respurl, proto, resp
357 return respurl, proto, resp
358 else:
358 else:
359 raise error.RepoError(_('unexpected CBOR response from '
359 raise error.RepoError(_('unexpected CBOR response from '
360 'server'))
360 'server'))
361
361
362 version_info = tuple([int(n) for n in subtype.split('.')])
362 version_info = tuple([int(n) for n in subtype.split('.')])
363 except ValueError:
363 except ValueError:
364 raise error.RepoError(_("'%s' sent a broken Content-Type "
364 raise error.RepoError(_("'%s' sent a broken Content-Type "
365 "header (%s)") % (safeurl, proto))
365 "header (%s)") % (safeurl, proto))
366
366
367 # TODO consider switching to a decompression reader that uses
367 # TODO consider switching to a decompression reader that uses
368 # generators.
368 # generators.
369 if version_info == (0, 1):
369 if version_info == (0, 1):
370 if compressible:
370 if compressible:
371 resp = util.compengines['zlib'].decompressorreader(resp)
371 resp = util.compengines['zlib'].decompressorreader(resp)
372
372
373 elif version_info == (0, 2):
373 elif version_info == (0, 2):
374 # application/mercurial-0.2 always identifies the compression
374 # application/mercurial-0.2 always identifies the compression
375 # engine in the payload header.
375 # engine in the payload header.
376 elen = struct.unpack('B', resp.read(1))[0]
376 elen = struct.unpack('B', resp.read(1))[0]
377 ename = resp.read(elen)
377 ename = resp.read(elen)
378 engine = util.compengines.forwiretype(ename)
378 engine = util.compengines.forwiretype(ename)
379
379
380 resp = engine.decompressorreader(resp)
380 resp = engine.decompressorreader(resp)
381 else:
381 else:
382 raise error.RepoError(_("'%s' uses newer protocol %s") %
382 raise error.RepoError(_("'%s' uses newer protocol %s") %
383 (safeurl, subtype))
383 (safeurl, subtype))
384
384
385 return respurl, proto, resp
385 return respurl, proto, resp
386
386
387 class httppeer(wireprotov1peer.wirepeer):
387 class httppeer(wireprotov1peer.wirepeer):
388 def __init__(self, ui, path, url, opener, requestbuilder, caps):
388 def __init__(self, ui, path, url, opener, requestbuilder, caps):
389 self.ui = ui
389 self.ui = ui
390 self._path = path
390 self._path = path
391 self._url = url
391 self._url = url
392 self._caps = caps
392 self._caps = caps
393 self._urlopener = opener
393 self._urlopener = opener
394 self._requestbuilder = requestbuilder
394 self._requestbuilder = requestbuilder
395
395
396 def __del__(self):
396 def __del__(self):
397 for h in self._urlopener.handlers:
397 for h in self._urlopener.handlers:
398 h.close()
398 h.close()
399 getattr(h, "close_all", lambda: None)()
399 getattr(h, "close_all", lambda: None)()
400
400
401 # Begin of ipeerconnection interface.
401 # Begin of ipeerconnection interface.
402
402
403 def url(self):
403 def url(self):
404 return self._path
404 return self._path
405
405
406 def local(self):
406 def local(self):
407 return None
407 return None
408
408
409 def peer(self):
409 def peer(self):
410 return self
410 return self
411
411
412 def canpush(self):
412 def canpush(self):
413 return True
413 return True
414
414
415 def close(self):
415 def close(self):
416 pass
416 pass
417
417
418 # End of ipeerconnection interface.
418 # End of ipeerconnection interface.
419
419
420 # Begin of ipeercommands interface.
420 # Begin of ipeercommands interface.
421
421
422 def capabilities(self):
422 def capabilities(self):
423 return self._caps
423 return self._caps
424
424
425 # End of ipeercommands interface.
425 # End of ipeercommands interface.
426
426
427 # look up capabilities only when needed
427 # look up capabilities only when needed
428
428
429 def _callstream(self, cmd, _compressible=False, **args):
429 def _callstream(self, cmd, _compressible=False, **args):
430 args = pycompat.byteskwargs(args)
430 args = pycompat.byteskwargs(args)
431
431
432 req, cu, qs = makev1commandrequest(self.ui, self._requestbuilder,
432 req, cu, qs = makev1commandrequest(self.ui, self._requestbuilder,
433 self._caps, self.capable,
433 self._caps, self.capable,
434 self._url, cmd, args)
434 self._url, cmd, args)
435
435
436 resp = sendrequest(self.ui, self._urlopener, req)
436 resp = sendrequest(self.ui, self._urlopener, req)
437
437
438 self._url, ct, resp = parsev1commandresponse(self.ui, self._url, cu, qs,
438 self._url, ct, resp = parsev1commandresponse(self.ui, self._url, cu, qs,
439 resp, _compressible)
439 resp, _compressible)
440
440
441 return resp
441 return resp
442
442
443 def _call(self, cmd, **args):
443 def _call(self, cmd, **args):
444 fp = self._callstream(cmd, **args)
444 fp = self._callstream(cmd, **args)
445 try:
445 try:
446 return fp.read()
446 return fp.read()
447 finally:
447 finally:
448 # if using keepalive, allow connection to be reused
448 # if using keepalive, allow connection to be reused
449 fp.close()
449 fp.close()
450
450
451 def _callpush(self, cmd, cg, **args):
451 def _callpush(self, cmd, cg, **args):
452 # have to stream bundle to a temp file because we do not have
452 # have to stream bundle to a temp file because we do not have
453 # http 1.1 chunked transfer.
453 # http 1.1 chunked transfer.
454
454
455 types = self.capable('unbundle')
455 types = self.capable('unbundle')
456 try:
456 try:
457 types = types.split(',')
457 types = types.split(',')
458 except AttributeError:
458 except AttributeError:
459 # servers older than d1b16a746db6 will send 'unbundle' as a
459 # servers older than d1b16a746db6 will send 'unbundle' as a
460 # boolean capability. They only support headerless/uncompressed
460 # boolean capability. They only support headerless/uncompressed
461 # bundles.
461 # bundles.
462 types = [""]
462 types = [""]
463 for x in types:
463 for x in types:
464 if x in bundle2.bundletypes:
464 if x in bundle2.bundletypes:
465 type = x
465 type = x
466 break
466 break
467
467
468 tempname = bundle2.writebundle(self.ui, cg, None, type)
468 tempname = bundle2.writebundle(self.ui, cg, None, type)
469 fp = httpconnection.httpsendfile(self.ui, tempname, "rb")
469 fp = httpconnection.httpsendfile(self.ui, tempname, "rb")
470 headers = {r'Content-Type': r'application/mercurial-0.1'}
470 headers = {r'Content-Type': r'application/mercurial-0.1'}
471
471
472 try:
472 try:
473 r = self._call(cmd, data=fp, headers=headers, **args)
473 r = self._call(cmd, data=fp, headers=headers, **args)
474 vals = r.split('\n', 1)
474 vals = r.split('\n', 1)
475 if len(vals) < 2:
475 if len(vals) < 2:
476 raise error.ResponseError(_("unexpected response:"), r)
476 raise error.ResponseError(_("unexpected response:"), r)
477 return vals
477 return vals
478 except urlerr.httperror:
478 except urlerr.httperror:
479 # Catch and re-raise these so we don't try and treat them
479 # Catch and re-raise these so we don't try and treat them
480 # like generic socket errors. They lack any values in
480 # like generic socket errors. They lack any values in
481 # .args on Python 3 which breaks our socket.error block.
481 # .args on Python 3 which breaks our socket.error block.
482 raise
482 raise
483 except socket.error as err:
483 except socket.error as err:
484 if err.args[0] in (errno.ECONNRESET, errno.EPIPE):
484 if err.args[0] in (errno.ECONNRESET, errno.EPIPE):
485 raise error.Abort(_('push failed: %s') % err.args[1])
485 raise error.Abort(_('push failed: %s') % err.args[1])
486 raise error.Abort(err.args[1])
486 raise error.Abort(err.args[1])
487 finally:
487 finally:
488 fp.close()
488 fp.close()
489 os.unlink(tempname)
489 os.unlink(tempname)
490
490
491 def _calltwowaystream(self, cmd, fp, **args):
491 def _calltwowaystream(self, cmd, fp, **args):
492 fh = None
492 fh = None
493 fp_ = None
493 fp_ = None
494 filename = None
494 filename = None
495 try:
495 try:
496 # dump bundle to disk
496 # dump bundle to disk
497 fd, filename = tempfile.mkstemp(prefix="hg-bundle-", suffix=".hg")
497 fd, filename = tempfile.mkstemp(prefix="hg-bundle-", suffix=".hg")
498 fh = os.fdopen(fd, r"wb")
498 fh = os.fdopen(fd, r"wb")
499 d = fp.read(4096)
499 d = fp.read(4096)
500 while d:
500 while d:
501 fh.write(d)
501 fh.write(d)
502 d = fp.read(4096)
502 d = fp.read(4096)
503 fh.close()
503 fh.close()
504 # start http push
504 # start http push
505 fp_ = httpconnection.httpsendfile(self.ui, filename, "rb")
505 fp_ = httpconnection.httpsendfile(self.ui, filename, "rb")
506 headers = {r'Content-Type': r'application/mercurial-0.1'}
506 headers = {r'Content-Type': r'application/mercurial-0.1'}
507 return self._callstream(cmd, data=fp_, headers=headers, **args)
507 return self._callstream(cmd, data=fp_, headers=headers, **args)
508 finally:
508 finally:
509 if fp_ is not None:
509 if fp_ is not None:
510 fp_.close()
510 fp_.close()
511 if fh is not None:
511 if fh is not None:
512 fh.close()
512 fh.close()
513 os.unlink(filename)
513 os.unlink(filename)
514
514
515 def _callcompressable(self, cmd, **args):
515 def _callcompressable(self, cmd, **args):
516 return self._callstream(cmd, _compressible=True, **args)
516 return self._callstream(cmd, _compressible=True, **args)
517
517
518 def _abort(self, exception):
518 def _abort(self, exception):
519 raise exception
519 raise exception
520
520
521 def sendv2request(ui, opener, requestbuilder, apiurl, permission, requests):
521 def sendv2request(ui, opener, requestbuilder, apiurl, permission, requests):
522 reactor = wireprotoframing.clientreactor(hasmultiplesend=False,
522 reactor = wireprotoframing.clientreactor(hasmultiplesend=False,
523 buffersends=True)
523 buffersends=True)
524
524
525 url = '%s/%s' % (apiurl, permission)
525 url = '%s/%s' % (apiurl, permission)
526
526
527 if len(requests) > 1:
527 if len(requests) > 1:
528 url += '/multirequest'
528 url += '/multirequest'
529 else:
529 else:
530 url += '/%s' % requests[0][0]
530 url += '/%s' % requests[0][0]
531
531
532 # Request ID to (request, future)
532 # Request ID to (request, future)
533 requestmap = {}
533 requestmap = {}
534
534
535 for command, args, f in requests:
535 for command, args, f in requests:
536 request, action, meta = reactor.callcommand(command, args)
536 request, action, meta = reactor.callcommand(command, args)
537 assert action == 'noop'
537 assert action == 'noop'
538
538
539 requestmap[request.requestid] = (request, f)
539 requestmap[request.requestid] = (request, f)
540
540
541 action, meta = reactor.flushcommands()
541 action, meta = reactor.flushcommands()
542 assert action == 'sendframes'
542 assert action == 'sendframes'
543
543
544 # TODO stream this.
544 # TODO stream this.
545 body = b''.join(map(bytes, meta['framegen']))
545 body = b''.join(map(bytes, meta['framegen']))
546
546
547 # TODO modify user-agent to reflect v2
547 # TODO modify user-agent to reflect v2
548 headers = {
548 headers = {
549 r'Accept': wireprotov2server.FRAMINGTYPE,
549 r'Accept': wireprotov2server.FRAMINGTYPE,
550 r'Content-Type': wireprotov2server.FRAMINGTYPE,
550 r'Content-Type': wireprotov2server.FRAMINGTYPE,
551 }
551 }
552
552
553 req = requestbuilder(pycompat.strurl(url), body, headers)
553 req = requestbuilder(pycompat.strurl(url), body, headers)
554 req.add_unredirected_header(r'Content-Length', r'%d' % len(body))
554 req.add_unredirected_header(r'Content-Length', r'%d' % len(body))
555
555
556 try:
556 try:
557 res = opener.open(req)
557 res = opener.open(req)
558 except urlerr.httperror as e:
558 except urlerr.httperror as e:
559 if e.code == 401:
559 if e.code == 401:
560 raise error.Abort(_('authorization failed'))
560 raise error.Abort(_('authorization failed'))
561
561
562 raise
562 raise
563 except httplib.HTTPException as e:
563 except httplib.HTTPException as e:
564 ui.traceback()
564 ui.traceback()
565 raise IOError(None, e)
565 raise IOError(None, e)
566
566
567 return reactor, requestmap, res
567 return reactor, requestmap, res
568
568
569 class queuedcommandfuture(pycompat.futures.Future):
569 class queuedcommandfuture(pycompat.futures.Future):
570 """Wraps result() on command futures to trigger submission on call."""
570 """Wraps result() on command futures to trigger submission on call."""
571
571
572 def result(self, timeout=None):
572 def result(self, timeout=None):
573 if self.done():
573 if self.done():
574 return pycompat.futures.Future.result(self, timeout)
574 return pycompat.futures.Future.result(self, timeout)
575
575
576 self._peerexecutor.sendcommands()
576 self._peerexecutor.sendcommands()
577
577
578 # sendcommands() will restore the original __class__ and self.result
578 # sendcommands() will restore the original __class__ and self.result
579 # will resolve to Future.result.
579 # will resolve to Future.result.
580 return self.result(timeout)
580 return self.result(timeout)
581
581
582 @zi.implementer(repository.ipeercommandexecutor)
582 @zi.implementer(repository.ipeercommandexecutor)
583 class httpv2executor(object):
583 class httpv2executor(object):
584 def __init__(self, ui, opener, requestbuilder, apiurl, descriptor):
584 def __init__(self, ui, opener, requestbuilder, apiurl, descriptor):
585 self._ui = ui
585 self._ui = ui
586 self._opener = opener
586 self._opener = opener
587 self._requestbuilder = requestbuilder
587 self._requestbuilder = requestbuilder
588 self._apiurl = apiurl
588 self._apiurl = apiurl
589 self._descriptor = descriptor
589 self._descriptor = descriptor
590 self._sent = False
590 self._sent = False
591 self._closed = False
591 self._closed = False
592 self._neededpermissions = set()
592 self._neededpermissions = set()
593 self._calls = []
593 self._calls = []
594 self._futures = weakref.WeakSet()
594 self._futures = weakref.WeakSet()
595 self._responseexecutor = None
595 self._responseexecutor = None
596 self._responsef = None
596 self._responsef = None
597
597
598 def __enter__(self):
598 def __enter__(self):
599 return self
599 return self
600
600
601 def __exit__(self, exctype, excvalue, exctb):
601 def __exit__(self, exctype, excvalue, exctb):
602 self.close()
602 self.close()
603
603
604 def callcommand(self, command, args):
604 def callcommand(self, command, args):
605 if self._sent:
605 if self._sent:
606 raise error.ProgrammingError('callcommand() cannot be used after '
606 raise error.ProgrammingError('callcommand() cannot be used after '
607 'commands are sent')
607 'commands are sent')
608
608
609 if self._closed:
609 if self._closed:
610 raise error.ProgrammingError('callcommand() cannot be used after '
610 raise error.ProgrammingError('callcommand() cannot be used after '
611 'close()')
611 'close()')
612
612
613 # The service advertises which commands are available. So if we attempt
613 # The service advertises which commands are available. So if we attempt
614 # to call an unknown command or pass an unknown argument, we can screen
614 # to call an unknown command or pass an unknown argument, we can screen
615 # for this.
615 # for this.
616 if command not in self._descriptor['commands']:
616 if command not in self._descriptor['commands']:
617 raise error.ProgrammingError(
617 raise error.ProgrammingError(
618 'wire protocol command %s is not available' % command)
618 'wire protocol command %s is not available' % command)
619
619
620 cmdinfo = self._descriptor['commands'][command]
620 cmdinfo = self._descriptor['commands'][command]
621 unknownargs = set(args.keys()) - set(cmdinfo.get('args', {}))
621 unknownargs = set(args.keys()) - set(cmdinfo.get('args', {}))
622
622
623 if unknownargs:
623 if unknownargs:
624 raise error.ProgrammingError(
624 raise error.ProgrammingError(
625 'wire protocol command %s does not accept argument: %s' % (
625 'wire protocol command %s does not accept argument: %s' % (
626 command, ', '.join(sorted(unknownargs))))
626 command, ', '.join(sorted(unknownargs))))
627
627
628 self._neededpermissions |= set(cmdinfo['permissions'])
628 self._neededpermissions |= set(cmdinfo['permissions'])
629
629
630 # TODO we /could/ also validate types here, since the API descriptor
630 # TODO we /could/ also validate types here, since the API descriptor
631 # includes types...
631 # includes types...
632
632
633 f = pycompat.futures.Future()
633 f = pycompat.futures.Future()
634
634
635 # Monkeypatch it so result() triggers sendcommands(), otherwise result()
635 # Monkeypatch it so result() triggers sendcommands(), otherwise result()
636 # could deadlock.
636 # could deadlock.
637 f.__class__ = queuedcommandfuture
637 f.__class__ = queuedcommandfuture
638 f._peerexecutor = self
638 f._peerexecutor = self
639
639
640 self._futures.add(f)
640 self._futures.add(f)
641 self._calls.append((command, args, f))
641 self._calls.append((command, args, f))
642
642
643 return f
643 return f
644
644
645 def sendcommands(self):
645 def sendcommands(self):
646 if self._sent:
646 if self._sent:
647 return
647 return
648
648
649 if not self._calls:
649 if not self._calls:
650 return
650 return
651
651
652 self._sent = True
652 self._sent = True
653
653
654 # Unhack any future types so caller sees a clean type and so we
654 # Unhack any future types so caller sees a clean type and so we
655 # break reference cycle.
655 # break reference cycle.
656 for f in self._futures:
656 for f in self._futures:
657 if isinstance(f, queuedcommandfuture):
657 if isinstance(f, queuedcommandfuture):
658 f.__class__ = pycompat.futures.Future
658 f.__class__ = pycompat.futures.Future
659 f._peerexecutor = None
659 f._peerexecutor = None
660
660
661 # Mark the future as running and filter out cancelled futures.
661 # Mark the future as running and filter out cancelled futures.
662 calls = [(command, args, f)
662 calls = [(command, args, f)
663 for command, args, f in self._calls
663 for command, args, f in self._calls
664 if f.set_running_or_notify_cancel()]
664 if f.set_running_or_notify_cancel()]
665
665
666 # Clear out references, prevent improper object usage.
666 # Clear out references, prevent improper object usage.
667 self._calls = None
667 self._calls = None
668
668
669 if not calls:
669 if not calls:
670 return
670 return
671
671
672 permissions = set(self._neededpermissions)
672 permissions = set(self._neededpermissions)
673
673
674 if 'push' in permissions and 'pull' in permissions:
674 if 'push' in permissions and 'pull' in permissions:
675 permissions.remove('pull')
675 permissions.remove('pull')
676
676
677 if len(permissions) > 1:
677 if len(permissions) > 1:
678 raise error.RepoError(_('cannot make request requiring multiple '
678 raise error.RepoError(_('cannot make request requiring multiple '
679 'permissions: %s') %
679 'permissions: %s') %
680 _(', ').join(sorted(permissions)))
680 _(', ').join(sorted(permissions)))
681
681
682 permission = {
682 permission = {
683 'push': 'rw',
683 'push': 'rw',
684 'pull': 'ro',
684 'pull': 'ro',
685 }[permissions.pop()]
685 }[permissions.pop()]
686
686
687 reactor, requests, resp = sendv2request(
687 reactor, requests, resp = sendv2request(
688 self._ui, self._opener, self._requestbuilder, self._apiurl,
688 self._ui, self._opener, self._requestbuilder, self._apiurl,
689 permission, calls)
689 permission, calls)
690
690
691 # TODO we probably want to validate the HTTP code, media type, etc.
691 # TODO we probably want to validate the HTTP code, media type, etc.
692
692
693 self._responseexecutor = pycompat.futures.ThreadPoolExecutor(1)
693 self._responseexecutor = pycompat.futures.ThreadPoolExecutor(1)
694 self._responsef = self._responseexecutor.submit(self._handleresponse,
694 self._responsef = self._responseexecutor.submit(self._handleresponse,
695 reactor,
695 reactor,
696 requests,
696 requests,
697 resp)
697 resp)
698
698
699 def close(self):
699 def close(self):
700 if self._closed:
700 if self._closed:
701 return
701 return
702
702
703 self.sendcommands()
703 self.sendcommands()
704
704
705 self._closed = True
705 self._closed = True
706
706
707 if not self._responsef:
707 if not self._responsef:
708 return
708 return
709
709
710 try:
710 try:
711 self._responsef.result()
711 self._responsef.result()
712 finally:
712 finally:
713 self._responseexecutor.shutdown(wait=True)
713 self._responseexecutor.shutdown(wait=True)
714 self._responsef = None
714 self._responsef = None
715 self._responseexecutor = None
715 self._responseexecutor = None
716
716
717 # If any of our futures are still in progress, mark them as
717 # If any of our futures are still in progress, mark them as
718 # errored, otherwise a result() could wait indefinitely.
718 # errored, otherwise a result() could wait indefinitely.
719 for f in self._futures:
719 for f in self._futures:
720 if not f.done():
720 if not f.done():
721 f.set_exception(error.ResponseError(
721 f.set_exception(error.ResponseError(
722 _('unfulfilled command response')))
722 _('unfulfilled command response')))
723
723
724 self._futures = None
724 self._futures = None
725
725
726 def _handleresponse(self, reactor, requests, resp):
726 def _handleresponse(self, reactor, requests, resp):
727 # Called in a thread to read the response.
727 # Called in a thread to read the response.
728
728
729 results = {k: [] for k in requests}
729 results = {k: [] for k in requests}
730
730
731 while True:
731 while True:
732 frame = wireprotoframing.readframe(resp)
732 frame = wireprotoframing.readframe(resp)
733 if frame is None:
733 if frame is None:
734 break
734 break
735
735
736 self._ui.note(_('received %r\n') % frame)
736 self._ui.note(_('received %r\n') % frame)
737
737
738 # Guard against receiving a frame with a request ID that we
738 # Guard against receiving a frame with a request ID that we
739 # didn't issue. This should never happen.
739 # didn't issue. This should never happen.
740 request, f = requests.get(frame.requestid, [None, None])
740 request, f = requests.get(frame.requestid, [None, None])
741
741
742 action, meta = reactor.onframerecv(frame)
742 action, meta = reactor.onframerecv(frame)
743
743
744 if action == 'responsedata':
744 if action == 'responsedata':
745 assert request.requestid == meta['request'].requestid
745 assert request.requestid == meta['request'].requestid
746
746
747 result = results[request.requestid]
747 result = results[request.requestid]
748
748
749 if meta['cbor']:
749 if meta['cbor']:
750 payload = util.bytesio(meta['data'])
750 payload = util.bytesio(meta['data'])
751
751
752 decoder = cbor.CBORDecoder(payload)
752 decoder = cbor.CBORDecoder(payload)
753 while payload.tell() + 1 < len(meta['data']):
753 while payload.tell() + 1 < len(meta['data']):
754 try:
754 try:
755 result.append(decoder.decode())
755 result.append(decoder.decode())
756 except Exception:
756 except Exception:
757 f.set_exception_info(*sys.exc_info()[1:])
757 pycompat.future_set_exception_info(
758 f, sys.exc_info()[1:])
758 continue
759 continue
759 else:
760 else:
760 result.append(meta['data'])
761 result.append(meta['data'])
761
762
762 if meta['eos']:
763 if meta['eos']:
763 f.set_result(result)
764 f.set_result(result)
764 del results[request.requestid]
765 del results[request.requestid]
765
766
766 elif action == 'error':
767 elif action == 'error':
767 e = error.RepoError(meta['message'])
768 e = error.RepoError(meta['message'])
768
769
769 if f:
770 if f:
770 f.set_exception(e)
771 f.set_exception(e)
771 else:
772 else:
772 raise e
773 raise e
773
774
774 else:
775 else:
775 e = error.ProgrammingError('unhandled action: %s' % action)
776 e = error.ProgrammingError('unhandled action: %s' % action)
776
777
777 if f:
778 if f:
778 f.set_exception(e)
779 f.set_exception(e)
779 else:
780 else:
780 raise e
781 raise e
781
782
782 # TODO implement interface for version 2 peers
783 # TODO implement interface for version 2 peers
783 @zi.implementer(repository.ipeerconnection, repository.ipeercapabilities,
784 @zi.implementer(repository.ipeerconnection, repository.ipeercapabilities,
784 repository.ipeerrequests)
785 repository.ipeerrequests)
785 class httpv2peer(object):
786 class httpv2peer(object):
786 def __init__(self, ui, repourl, apipath, opener, requestbuilder,
787 def __init__(self, ui, repourl, apipath, opener, requestbuilder,
787 apidescriptor):
788 apidescriptor):
788 self.ui = ui
789 self.ui = ui
789
790
790 if repourl.endswith('/'):
791 if repourl.endswith('/'):
791 repourl = repourl[:-1]
792 repourl = repourl[:-1]
792
793
793 self._url = repourl
794 self._url = repourl
794 self._apipath = apipath
795 self._apipath = apipath
795 self._apiurl = '%s/%s' % (repourl, apipath)
796 self._apiurl = '%s/%s' % (repourl, apipath)
796 self._opener = opener
797 self._opener = opener
797 self._requestbuilder = requestbuilder
798 self._requestbuilder = requestbuilder
798 self._descriptor = apidescriptor
799 self._descriptor = apidescriptor
799
800
800 # Start of ipeerconnection.
801 # Start of ipeerconnection.
801
802
802 def url(self):
803 def url(self):
803 return self._url
804 return self._url
804
805
805 def local(self):
806 def local(self):
806 return None
807 return None
807
808
808 def peer(self):
809 def peer(self):
809 return self
810 return self
810
811
811 def canpush(self):
812 def canpush(self):
812 # TODO change once implemented.
813 # TODO change once implemented.
813 return False
814 return False
814
815
815 def close(self):
816 def close(self):
816 pass
817 pass
817
818
818 # End of ipeerconnection.
819 # End of ipeerconnection.
819
820
820 # Start of ipeercapabilities.
821 # Start of ipeercapabilities.
821
822
822 def capable(self, name):
823 def capable(self, name):
823 # The capabilities used internally historically map to capabilities
824 # The capabilities used internally historically map to capabilities
824 # advertised from the "capabilities" wire protocol command. However,
825 # advertised from the "capabilities" wire protocol command. However,
825 # version 2 of that command works differently.
826 # version 2 of that command works differently.
826
827
827 # Maps to commands that are available.
828 # Maps to commands that are available.
828 if name in ('branchmap', 'getbundle', 'known', 'lookup', 'pushkey'):
829 if name in ('branchmap', 'getbundle', 'known', 'lookup', 'pushkey'):
829 return True
830 return True
830
831
831 # Other concepts.
832 # Other concepts.
832 if name in ('bundle2',):
833 if name in ('bundle2',):
833 return True
834 return True
834
835
835 return False
836 return False
836
837
837 def requirecap(self, name, purpose):
838 def requirecap(self, name, purpose):
838 if self.capable(name):
839 if self.capable(name):
839 return
840 return
840
841
841 raise error.CapabilityError(
842 raise error.CapabilityError(
842 _('cannot %s; client or remote repository does not support the %r '
843 _('cannot %s; client or remote repository does not support the %r '
843 'capability') % (purpose, name))
844 'capability') % (purpose, name))
844
845
845 # End of ipeercapabilities.
846 # End of ipeercapabilities.
846
847
847 def _call(self, name, **args):
848 def _call(self, name, **args):
848 with self.commandexecutor() as e:
849 with self.commandexecutor() as e:
849 return e.callcommand(name, args).result()
850 return e.callcommand(name, args).result()
850
851
851 def commandexecutor(self):
852 def commandexecutor(self):
852 return httpv2executor(self.ui, self._opener, self._requestbuilder,
853 return httpv2executor(self.ui, self._opener, self._requestbuilder,
853 self._apiurl, self._descriptor)
854 self._apiurl, self._descriptor)
854
855
855 # Registry of API service names to metadata about peers that handle it.
856 # Registry of API service names to metadata about peers that handle it.
856 #
857 #
857 # The following keys are meaningful:
858 # The following keys are meaningful:
858 #
859 #
859 # init
860 # init
860 # Callable receiving (ui, repourl, servicepath, opener, requestbuilder,
861 # Callable receiving (ui, repourl, servicepath, opener, requestbuilder,
861 # apidescriptor) to create a peer.
862 # apidescriptor) to create a peer.
862 #
863 #
863 # priority
864 # priority
864 # Integer priority for the service. If we could choose from multiple
865 # Integer priority for the service. If we could choose from multiple
865 # services, we choose the one with the highest priority.
866 # services, we choose the one with the highest priority.
866 API_PEERS = {
867 API_PEERS = {
867 wireprototypes.HTTP_WIREPROTO_V2: {
868 wireprototypes.HTTP_WIREPROTO_V2: {
868 'init': httpv2peer,
869 'init': httpv2peer,
869 'priority': 50,
870 'priority': 50,
870 },
871 },
871 }
872 }
872
873
873 def performhandshake(ui, url, opener, requestbuilder):
874 def performhandshake(ui, url, opener, requestbuilder):
874 # The handshake is a request to the capabilities command.
875 # The handshake is a request to the capabilities command.
875
876
876 caps = None
877 caps = None
877 def capable(x):
878 def capable(x):
878 raise error.ProgrammingError('should not be called')
879 raise error.ProgrammingError('should not be called')
879
880
880 args = {}
881 args = {}
881
882
882 # The client advertises support for newer protocols by adding an
883 # The client advertises support for newer protocols by adding an
883 # X-HgUpgrade-* header with a list of supported APIs and an
884 # X-HgUpgrade-* header with a list of supported APIs and an
884 # X-HgProto-* header advertising which serializing formats it supports.
885 # X-HgProto-* header advertising which serializing formats it supports.
885 # We only support the HTTP version 2 transport and CBOR responses for
886 # We only support the HTTP version 2 transport and CBOR responses for
886 # now.
887 # now.
887 advertisev2 = ui.configbool('experimental', 'httppeer.advertise-v2')
888 advertisev2 = ui.configbool('experimental', 'httppeer.advertise-v2')
888
889
889 if advertisev2:
890 if advertisev2:
890 args['headers'] = {
891 args['headers'] = {
891 r'X-HgProto-1': r'cbor',
892 r'X-HgProto-1': r'cbor',
892 }
893 }
893
894
894 args['headers'].update(
895 args['headers'].update(
895 encodevalueinheaders(' '.join(sorted(API_PEERS)),
896 encodevalueinheaders(' '.join(sorted(API_PEERS)),
896 'X-HgUpgrade',
897 'X-HgUpgrade',
897 # We don't know the header limit this early.
898 # We don't know the header limit this early.
898 # So make it small.
899 # So make it small.
899 1024))
900 1024))
900
901
901 req, requrl, qs = makev1commandrequest(ui, requestbuilder, caps,
902 req, requrl, qs = makev1commandrequest(ui, requestbuilder, caps,
902 capable, url, 'capabilities',
903 capable, url, 'capabilities',
903 args)
904 args)
904
905
905 resp = sendrequest(ui, opener, req)
906 resp = sendrequest(ui, opener, req)
906
907
907 respurl, ct, resp = parsev1commandresponse(ui, url, requrl, qs, resp,
908 respurl, ct, resp = parsev1commandresponse(ui, url, requrl, qs, resp,
908 compressible=False,
909 compressible=False,
909 allowcbor=advertisev2)
910 allowcbor=advertisev2)
910
911
911 try:
912 try:
912 rawdata = resp.read()
913 rawdata = resp.read()
913 finally:
914 finally:
914 resp.close()
915 resp.close()
915
916
916 if not ct.startswith('application/mercurial-'):
917 if not ct.startswith('application/mercurial-'):
917 raise error.ProgrammingError('unexpected content-type: %s' % ct)
918 raise error.ProgrammingError('unexpected content-type: %s' % ct)
918
919
919 if advertisev2:
920 if advertisev2:
920 if ct == 'application/mercurial-cbor':
921 if ct == 'application/mercurial-cbor':
921 try:
922 try:
922 info = cbor.loads(rawdata)
923 info = cbor.loads(rawdata)
923 except cbor.CBORDecodeError:
924 except cbor.CBORDecodeError:
924 raise error.Abort(_('error decoding CBOR from remote server'),
925 raise error.Abort(_('error decoding CBOR from remote server'),
925 hint=_('try again and consider contacting '
926 hint=_('try again and consider contacting '
926 'the server operator'))
927 'the server operator'))
927
928
928 # We got a legacy response. That's fine.
929 # We got a legacy response. That's fine.
929 elif ct in ('application/mercurial-0.1', 'application/mercurial-0.2'):
930 elif ct in ('application/mercurial-0.1', 'application/mercurial-0.2'):
930 info = {
931 info = {
931 'v1capabilities': set(rawdata.split())
932 'v1capabilities': set(rawdata.split())
932 }
933 }
933
934
934 else:
935 else:
935 raise error.RepoError(
936 raise error.RepoError(
936 _('unexpected response type from server: %s') % ct)
937 _('unexpected response type from server: %s') % ct)
937 else:
938 else:
938 info = {
939 info = {
939 'v1capabilities': set(rawdata.split())
940 'v1capabilities': set(rawdata.split())
940 }
941 }
941
942
942 return respurl, info
943 return respurl, info
943
944
944 def makepeer(ui, path, opener=None, requestbuilder=urlreq.request):
945 def makepeer(ui, path, opener=None, requestbuilder=urlreq.request):
945 """Construct an appropriate HTTP peer instance.
946 """Construct an appropriate HTTP peer instance.
946
947
947 ``opener`` is an ``url.opener`` that should be used to establish
948 ``opener`` is an ``url.opener`` that should be used to establish
948 connections, perform HTTP requests.
949 connections, perform HTTP requests.
949
950
950 ``requestbuilder`` is the type used for constructing HTTP requests.
951 ``requestbuilder`` is the type used for constructing HTTP requests.
951 It exists as an argument so extensions can override the default.
952 It exists as an argument so extensions can override the default.
952 """
953 """
953 u = util.url(path)
954 u = util.url(path)
954 if u.query or u.fragment:
955 if u.query or u.fragment:
955 raise error.Abort(_('unsupported URL component: "%s"') %
956 raise error.Abort(_('unsupported URL component: "%s"') %
956 (u.query or u.fragment))
957 (u.query or u.fragment))
957
958
958 # urllib cannot handle URLs with embedded user or passwd.
959 # urllib cannot handle URLs with embedded user or passwd.
959 url, authinfo = u.authinfo()
960 url, authinfo = u.authinfo()
960 ui.debug('using %s\n' % url)
961 ui.debug('using %s\n' % url)
961
962
962 opener = opener or urlmod.opener(ui, authinfo)
963 opener = opener or urlmod.opener(ui, authinfo)
963
964
964 respurl, info = performhandshake(ui, url, opener, requestbuilder)
965 respurl, info = performhandshake(ui, url, opener, requestbuilder)
965
966
966 # Given the intersection of APIs that both we and the server support,
967 # Given the intersection of APIs that both we and the server support,
967 # sort by their advertised priority and pick the first one.
968 # sort by their advertised priority and pick the first one.
968 #
969 #
969 # TODO consider making this request-based and interface driven. For
970 # TODO consider making this request-based and interface driven. For
970 # example, the caller could say "I want a peer that does X." It's quite
971 # example, the caller could say "I want a peer that does X." It's quite
971 # possible that not all peers would do that. Since we know the service
972 # possible that not all peers would do that. Since we know the service
972 # capabilities, we could filter out services not meeting the
973 # capabilities, we could filter out services not meeting the
973 # requirements. Possibly by consulting the interfaces defined by the
974 # requirements. Possibly by consulting the interfaces defined by the
974 # peer type.
975 # peer type.
975 apipeerchoices = set(info.get('apis', {}).keys()) & set(API_PEERS.keys())
976 apipeerchoices = set(info.get('apis', {}).keys()) & set(API_PEERS.keys())
976
977
977 preferredchoices = sorted(apipeerchoices,
978 preferredchoices = sorted(apipeerchoices,
978 key=lambda x: API_PEERS[x]['priority'],
979 key=lambda x: API_PEERS[x]['priority'],
979 reverse=True)
980 reverse=True)
980
981
981 for service in preferredchoices:
982 for service in preferredchoices:
982 apipath = '%s/%s' % (info['apibase'].rstrip('/'), service)
983 apipath = '%s/%s' % (info['apibase'].rstrip('/'), service)
983
984
984 return API_PEERS[service]['init'](ui, respurl, apipath, opener,
985 return API_PEERS[service]['init'](ui, respurl, apipath, opener,
985 requestbuilder,
986 requestbuilder,
986 info['apis'][service])
987 info['apis'][service])
987
988
988 # Failed to construct an API peer. Fall back to legacy.
989 # Failed to construct an API peer. Fall back to legacy.
989 return httppeer(ui, path, respurl, opener, requestbuilder,
990 return httppeer(ui, path, respurl, opener, requestbuilder,
990 info['v1capabilities'])
991 info['v1capabilities'])
991
992
992 def instance(ui, path, create):
993 def instance(ui, path, create):
993 if create:
994 if create:
994 raise error.Abort(_('cannot create new http repository'))
995 raise error.Abort(_('cannot create new http repository'))
995 try:
996 try:
996 if path.startswith('https:') and not urlmod.has_https:
997 if path.startswith('https:') and not urlmod.has_https:
997 raise error.Abort(_('Python support for SSL and HTTPS '
998 raise error.Abort(_('Python support for SSL and HTTPS '
998 'is not installed'))
999 'is not installed'))
999
1000
1000 inst = makepeer(ui, path)
1001 inst = makepeer(ui, path)
1001
1002
1002 return inst
1003 return inst
1003 except error.RepoError as httpexception:
1004 except error.RepoError as httpexception:
1004 try:
1005 try:
1005 r = statichttprepo.instance(ui, "static-" + path, create)
1006 r = statichttprepo.instance(ui, "static-" + path, create)
1006 ui.note(_('(falling back to static-http)\n'))
1007 ui.note(_('(falling back to static-http)\n'))
1007 return r
1008 return r
1008 except error.RepoError:
1009 except error.RepoError:
1009 raise httpexception # use the original http RepoError instead
1010 raise httpexception # use the original http RepoError instead
@@ -1,2379 +1,2379
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import hashlib
11 import hashlib
12 import os
12 import os
13 import random
13 import random
14 import sys
14 import sys
15 import time
15 import time
16 import weakref
16 import weakref
17
17
18 from .i18n import _
18 from .i18n import _
19 from .node import (
19 from .node import (
20 hex,
20 hex,
21 nullid,
21 nullid,
22 short,
22 short,
23 )
23 )
24 from .thirdparty.zope import (
24 from .thirdparty.zope import (
25 interface as zi,
25 interface as zi,
26 )
26 )
27 from . import (
27 from . import (
28 bookmarks,
28 bookmarks,
29 branchmap,
29 branchmap,
30 bundle2,
30 bundle2,
31 changegroup,
31 changegroup,
32 changelog,
32 changelog,
33 color,
33 color,
34 context,
34 context,
35 dirstate,
35 dirstate,
36 dirstateguard,
36 dirstateguard,
37 discovery,
37 discovery,
38 encoding,
38 encoding,
39 error,
39 error,
40 exchange,
40 exchange,
41 extensions,
41 extensions,
42 filelog,
42 filelog,
43 hook,
43 hook,
44 lock as lockmod,
44 lock as lockmod,
45 manifest,
45 manifest,
46 match as matchmod,
46 match as matchmod,
47 merge as mergemod,
47 merge as mergemod,
48 mergeutil,
48 mergeutil,
49 namespaces,
49 namespaces,
50 narrowspec,
50 narrowspec,
51 obsolete,
51 obsolete,
52 pathutil,
52 pathutil,
53 phases,
53 phases,
54 pushkey,
54 pushkey,
55 pycompat,
55 pycompat,
56 repository,
56 repository,
57 repoview,
57 repoview,
58 revset,
58 revset,
59 revsetlang,
59 revsetlang,
60 scmutil,
60 scmutil,
61 sparse,
61 sparse,
62 store,
62 store,
63 subrepoutil,
63 subrepoutil,
64 tags as tagsmod,
64 tags as tagsmod,
65 transaction,
65 transaction,
66 txnutil,
66 txnutil,
67 util,
67 util,
68 vfs as vfsmod,
68 vfs as vfsmod,
69 )
69 )
70 from .utils import (
70 from .utils import (
71 procutil,
71 procutil,
72 stringutil,
72 stringutil,
73 )
73 )
74
74
75 release = lockmod.release
75 release = lockmod.release
76 urlerr = util.urlerr
76 urlerr = util.urlerr
77 urlreq = util.urlreq
77 urlreq = util.urlreq
78
78
79 # set of (path, vfs-location) tuples. vfs-location is:
79 # set of (path, vfs-location) tuples. vfs-location is:
80 # - 'plain for vfs relative paths
80 # - 'plain for vfs relative paths
81 # - '' for svfs relative paths
81 # - '' for svfs relative paths
82 _cachedfiles = set()
82 _cachedfiles = set()
83
83
84 class _basefilecache(scmutil.filecache):
84 class _basefilecache(scmutil.filecache):
85 """All filecache usage on repo are done for logic that should be unfiltered
85 """All filecache usage on repo are done for logic that should be unfiltered
86 """
86 """
87 def __get__(self, repo, type=None):
87 def __get__(self, repo, type=None):
88 if repo is None:
88 if repo is None:
89 return self
89 return self
90 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
90 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
91 def __set__(self, repo, value):
91 def __set__(self, repo, value):
92 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
92 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
93 def __delete__(self, repo):
93 def __delete__(self, repo):
94 return super(_basefilecache, self).__delete__(repo.unfiltered())
94 return super(_basefilecache, self).__delete__(repo.unfiltered())
95
95
96 class repofilecache(_basefilecache):
96 class repofilecache(_basefilecache):
97 """filecache for files in .hg but outside of .hg/store"""
97 """filecache for files in .hg but outside of .hg/store"""
98 def __init__(self, *paths):
98 def __init__(self, *paths):
99 super(repofilecache, self).__init__(*paths)
99 super(repofilecache, self).__init__(*paths)
100 for path in paths:
100 for path in paths:
101 _cachedfiles.add((path, 'plain'))
101 _cachedfiles.add((path, 'plain'))
102
102
103 def join(self, obj, fname):
103 def join(self, obj, fname):
104 return obj.vfs.join(fname)
104 return obj.vfs.join(fname)
105
105
106 class storecache(_basefilecache):
106 class storecache(_basefilecache):
107 """filecache for files in the store"""
107 """filecache for files in the store"""
108 def __init__(self, *paths):
108 def __init__(self, *paths):
109 super(storecache, self).__init__(*paths)
109 super(storecache, self).__init__(*paths)
110 for path in paths:
110 for path in paths:
111 _cachedfiles.add((path, ''))
111 _cachedfiles.add((path, ''))
112
112
113 def join(self, obj, fname):
113 def join(self, obj, fname):
114 return obj.sjoin(fname)
114 return obj.sjoin(fname)
115
115
116 def isfilecached(repo, name):
116 def isfilecached(repo, name):
117 """check if a repo has already cached "name" filecache-ed property
117 """check if a repo has already cached "name" filecache-ed property
118
118
119 This returns (cachedobj-or-None, iscached) tuple.
119 This returns (cachedobj-or-None, iscached) tuple.
120 """
120 """
121 cacheentry = repo.unfiltered()._filecache.get(name, None)
121 cacheentry = repo.unfiltered()._filecache.get(name, None)
122 if not cacheentry:
122 if not cacheentry:
123 return None, False
123 return None, False
124 return cacheentry.obj, True
124 return cacheentry.obj, True
125
125
126 class unfilteredpropertycache(util.propertycache):
126 class unfilteredpropertycache(util.propertycache):
127 """propertycache that apply to unfiltered repo only"""
127 """propertycache that apply to unfiltered repo only"""
128
128
129 def __get__(self, repo, type=None):
129 def __get__(self, repo, type=None):
130 unfi = repo.unfiltered()
130 unfi = repo.unfiltered()
131 if unfi is repo:
131 if unfi is repo:
132 return super(unfilteredpropertycache, self).__get__(unfi)
132 return super(unfilteredpropertycache, self).__get__(unfi)
133 return getattr(unfi, self.name)
133 return getattr(unfi, self.name)
134
134
135 class filteredpropertycache(util.propertycache):
135 class filteredpropertycache(util.propertycache):
136 """propertycache that must take filtering in account"""
136 """propertycache that must take filtering in account"""
137
137
138 def cachevalue(self, obj, value):
138 def cachevalue(self, obj, value):
139 object.__setattr__(obj, self.name, value)
139 object.__setattr__(obj, self.name, value)
140
140
141
141
142 def hasunfilteredcache(repo, name):
142 def hasunfilteredcache(repo, name):
143 """check if a repo has an unfilteredpropertycache value for <name>"""
143 """check if a repo has an unfilteredpropertycache value for <name>"""
144 return name in vars(repo.unfiltered())
144 return name in vars(repo.unfiltered())
145
145
146 def unfilteredmethod(orig):
146 def unfilteredmethod(orig):
147 """decorate method that always need to be run on unfiltered version"""
147 """decorate method that always need to be run on unfiltered version"""
148 def wrapper(repo, *args, **kwargs):
148 def wrapper(repo, *args, **kwargs):
149 return orig(repo.unfiltered(), *args, **kwargs)
149 return orig(repo.unfiltered(), *args, **kwargs)
150 return wrapper
150 return wrapper
151
151
152 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
152 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
153 'unbundle'}
153 'unbundle'}
154 legacycaps = moderncaps.union({'changegroupsubset'})
154 legacycaps = moderncaps.union({'changegroupsubset'})
155
155
156 @zi.implementer(repository.ipeercommandexecutor)
156 @zi.implementer(repository.ipeercommandexecutor)
157 class localcommandexecutor(object):
157 class localcommandexecutor(object):
158 def __init__(self, peer):
158 def __init__(self, peer):
159 self._peer = peer
159 self._peer = peer
160 self._sent = False
160 self._sent = False
161 self._closed = False
161 self._closed = False
162
162
163 def __enter__(self):
163 def __enter__(self):
164 return self
164 return self
165
165
166 def __exit__(self, exctype, excvalue, exctb):
166 def __exit__(self, exctype, excvalue, exctb):
167 self.close()
167 self.close()
168
168
169 def callcommand(self, command, args):
169 def callcommand(self, command, args):
170 if self._sent:
170 if self._sent:
171 raise error.ProgrammingError('callcommand() cannot be used after '
171 raise error.ProgrammingError('callcommand() cannot be used after '
172 'sendcommands()')
172 'sendcommands()')
173
173
174 if self._closed:
174 if self._closed:
175 raise error.ProgrammingError('callcommand() cannot be used after '
175 raise error.ProgrammingError('callcommand() cannot be used after '
176 'close()')
176 'close()')
177
177
178 # We don't need to support anything fancy. Just call the named
178 # We don't need to support anything fancy. Just call the named
179 # method on the peer and return a resolved future.
179 # method on the peer and return a resolved future.
180 fn = getattr(self._peer, pycompat.sysstr(command))
180 fn = getattr(self._peer, pycompat.sysstr(command))
181
181
182 f = pycompat.futures.Future()
182 f = pycompat.futures.Future()
183
183
184 try:
184 try:
185 result = fn(**args)
185 result = fn(**args)
186 except Exception:
186 except Exception:
187 f.set_exception_info(*sys.exc_info()[1:])
187 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
188 else:
188 else:
189 f.set_result(result)
189 f.set_result(result)
190
190
191 return f
191 return f
192
192
193 def sendcommands(self):
193 def sendcommands(self):
194 self._sent = True
194 self._sent = True
195
195
196 def close(self):
196 def close(self):
197 self._closed = True
197 self._closed = True
198
198
199 @zi.implementer(repository.ipeercommands)
199 @zi.implementer(repository.ipeercommands)
200 class localpeer(repository.peer):
200 class localpeer(repository.peer):
201 '''peer for a local repo; reflects only the most recent API'''
201 '''peer for a local repo; reflects only the most recent API'''
202
202
203 def __init__(self, repo, caps=None):
203 def __init__(self, repo, caps=None):
204 super(localpeer, self).__init__()
204 super(localpeer, self).__init__()
205
205
206 if caps is None:
206 if caps is None:
207 caps = moderncaps.copy()
207 caps = moderncaps.copy()
208 self._repo = repo.filtered('served')
208 self._repo = repo.filtered('served')
209 self.ui = repo.ui
209 self.ui = repo.ui
210 self._caps = repo._restrictcapabilities(caps)
210 self._caps = repo._restrictcapabilities(caps)
211
211
212 # Begin of _basepeer interface.
212 # Begin of _basepeer interface.
213
213
214 def url(self):
214 def url(self):
215 return self._repo.url()
215 return self._repo.url()
216
216
217 def local(self):
217 def local(self):
218 return self._repo
218 return self._repo
219
219
220 def peer(self):
220 def peer(self):
221 return self
221 return self
222
222
223 def canpush(self):
223 def canpush(self):
224 return True
224 return True
225
225
226 def close(self):
226 def close(self):
227 self._repo.close()
227 self._repo.close()
228
228
229 # End of _basepeer interface.
229 # End of _basepeer interface.
230
230
231 # Begin of _basewirecommands interface.
231 # Begin of _basewirecommands interface.
232
232
233 def branchmap(self):
233 def branchmap(self):
234 return self._repo.branchmap()
234 return self._repo.branchmap()
235
235
236 def capabilities(self):
236 def capabilities(self):
237 return self._caps
237 return self._caps
238
238
239 def clonebundles(self):
239 def clonebundles(self):
240 return self._repo.tryread('clonebundles.manifest')
240 return self._repo.tryread('clonebundles.manifest')
241
241
242 def debugwireargs(self, one, two, three=None, four=None, five=None):
242 def debugwireargs(self, one, two, three=None, four=None, five=None):
243 """Used to test argument passing over the wire"""
243 """Used to test argument passing over the wire"""
244 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
244 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
245 pycompat.bytestr(four),
245 pycompat.bytestr(four),
246 pycompat.bytestr(five))
246 pycompat.bytestr(five))
247
247
248 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
248 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
249 **kwargs):
249 **kwargs):
250 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
250 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
251 common=common, bundlecaps=bundlecaps,
251 common=common, bundlecaps=bundlecaps,
252 **kwargs)[1]
252 **kwargs)[1]
253 cb = util.chunkbuffer(chunks)
253 cb = util.chunkbuffer(chunks)
254
254
255 if exchange.bundle2requested(bundlecaps):
255 if exchange.bundle2requested(bundlecaps):
256 # When requesting a bundle2, getbundle returns a stream to make the
256 # When requesting a bundle2, getbundle returns a stream to make the
257 # wire level function happier. We need to build a proper object
257 # wire level function happier. We need to build a proper object
258 # from it in local peer.
258 # from it in local peer.
259 return bundle2.getunbundler(self.ui, cb)
259 return bundle2.getunbundler(self.ui, cb)
260 else:
260 else:
261 return changegroup.getunbundler('01', cb, None)
261 return changegroup.getunbundler('01', cb, None)
262
262
263 def heads(self):
263 def heads(self):
264 return self._repo.heads()
264 return self._repo.heads()
265
265
266 def known(self, nodes):
266 def known(self, nodes):
267 return self._repo.known(nodes)
267 return self._repo.known(nodes)
268
268
269 def listkeys(self, namespace):
269 def listkeys(self, namespace):
270 return self._repo.listkeys(namespace)
270 return self._repo.listkeys(namespace)
271
271
272 def lookup(self, key):
272 def lookup(self, key):
273 return self._repo.lookup(key)
273 return self._repo.lookup(key)
274
274
275 def pushkey(self, namespace, key, old, new):
275 def pushkey(self, namespace, key, old, new):
276 return self._repo.pushkey(namespace, key, old, new)
276 return self._repo.pushkey(namespace, key, old, new)
277
277
278 def stream_out(self):
278 def stream_out(self):
279 raise error.Abort(_('cannot perform stream clone against local '
279 raise error.Abort(_('cannot perform stream clone against local '
280 'peer'))
280 'peer'))
281
281
282 def unbundle(self, bundle, heads, url):
282 def unbundle(self, bundle, heads, url):
283 """apply a bundle on a repo
283 """apply a bundle on a repo
284
284
285 This function handles the repo locking itself."""
285 This function handles the repo locking itself."""
286 try:
286 try:
287 try:
287 try:
288 bundle = exchange.readbundle(self.ui, bundle, None)
288 bundle = exchange.readbundle(self.ui, bundle, None)
289 ret = exchange.unbundle(self._repo, bundle, heads, 'push', url)
289 ret = exchange.unbundle(self._repo, bundle, heads, 'push', url)
290 if util.safehasattr(ret, 'getchunks'):
290 if util.safehasattr(ret, 'getchunks'):
291 # This is a bundle20 object, turn it into an unbundler.
291 # This is a bundle20 object, turn it into an unbundler.
292 # This little dance should be dropped eventually when the
292 # This little dance should be dropped eventually when the
293 # API is finally improved.
293 # API is finally improved.
294 stream = util.chunkbuffer(ret.getchunks())
294 stream = util.chunkbuffer(ret.getchunks())
295 ret = bundle2.getunbundler(self.ui, stream)
295 ret = bundle2.getunbundler(self.ui, stream)
296 return ret
296 return ret
297 except Exception as exc:
297 except Exception as exc:
298 # If the exception contains output salvaged from a bundle2
298 # If the exception contains output salvaged from a bundle2
299 # reply, we need to make sure it is printed before continuing
299 # reply, we need to make sure it is printed before continuing
300 # to fail. So we build a bundle2 with such output and consume
300 # to fail. So we build a bundle2 with such output and consume
301 # it directly.
301 # it directly.
302 #
302 #
303 # This is not very elegant but allows a "simple" solution for
303 # This is not very elegant but allows a "simple" solution for
304 # issue4594
304 # issue4594
305 output = getattr(exc, '_bundle2salvagedoutput', ())
305 output = getattr(exc, '_bundle2salvagedoutput', ())
306 if output:
306 if output:
307 bundler = bundle2.bundle20(self._repo.ui)
307 bundler = bundle2.bundle20(self._repo.ui)
308 for out in output:
308 for out in output:
309 bundler.addpart(out)
309 bundler.addpart(out)
310 stream = util.chunkbuffer(bundler.getchunks())
310 stream = util.chunkbuffer(bundler.getchunks())
311 b = bundle2.getunbundler(self.ui, stream)
311 b = bundle2.getunbundler(self.ui, stream)
312 bundle2.processbundle(self._repo, b)
312 bundle2.processbundle(self._repo, b)
313 raise
313 raise
314 except error.PushRaced as exc:
314 except error.PushRaced as exc:
315 raise error.ResponseError(_('push failed:'),
315 raise error.ResponseError(_('push failed:'),
316 stringutil.forcebytestr(exc))
316 stringutil.forcebytestr(exc))
317
317
318 # End of _basewirecommands interface.
318 # End of _basewirecommands interface.
319
319
320 # Begin of peer interface.
320 # Begin of peer interface.
321
321
322 def commandexecutor(self):
322 def commandexecutor(self):
323 return localcommandexecutor(self)
323 return localcommandexecutor(self)
324
324
325 # End of peer interface.
325 # End of peer interface.
326
326
327 @zi.implementer(repository.ipeerlegacycommands)
327 @zi.implementer(repository.ipeerlegacycommands)
328 class locallegacypeer(localpeer):
328 class locallegacypeer(localpeer):
329 '''peer extension which implements legacy methods too; used for tests with
329 '''peer extension which implements legacy methods too; used for tests with
330 restricted capabilities'''
330 restricted capabilities'''
331
331
332 def __init__(self, repo):
332 def __init__(self, repo):
333 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
333 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
334
334
335 # Begin of baselegacywirecommands interface.
335 # Begin of baselegacywirecommands interface.
336
336
337 def between(self, pairs):
337 def between(self, pairs):
338 return self._repo.between(pairs)
338 return self._repo.between(pairs)
339
339
340 def branches(self, nodes):
340 def branches(self, nodes):
341 return self._repo.branches(nodes)
341 return self._repo.branches(nodes)
342
342
343 def changegroup(self, nodes, source):
343 def changegroup(self, nodes, source):
344 outgoing = discovery.outgoing(self._repo, missingroots=nodes,
344 outgoing = discovery.outgoing(self._repo, missingroots=nodes,
345 missingheads=self._repo.heads())
345 missingheads=self._repo.heads())
346 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
346 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
347
347
348 def changegroupsubset(self, bases, heads, source):
348 def changegroupsubset(self, bases, heads, source):
349 outgoing = discovery.outgoing(self._repo, missingroots=bases,
349 outgoing = discovery.outgoing(self._repo, missingroots=bases,
350 missingheads=heads)
350 missingheads=heads)
351 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
351 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
352
352
353 # End of baselegacywirecommands interface.
353 # End of baselegacywirecommands interface.
354
354
355 # Increment the sub-version when the revlog v2 format changes to lock out old
355 # Increment the sub-version when the revlog v2 format changes to lock out old
356 # clients.
356 # clients.
357 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
357 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
358
358
359 # Functions receiving (ui, features) that extensions can register to impact
359 # Functions receiving (ui, features) that extensions can register to impact
360 # the ability to load repositories with custom requirements. Only
360 # the ability to load repositories with custom requirements. Only
361 # functions defined in loaded extensions are called.
361 # functions defined in loaded extensions are called.
362 #
362 #
363 # The function receives a set of requirement strings that the repository
363 # The function receives a set of requirement strings that the repository
364 # is capable of opening. Functions will typically add elements to the
364 # is capable of opening. Functions will typically add elements to the
365 # set to reflect that the extension knows how to handle that requirements.
365 # set to reflect that the extension knows how to handle that requirements.
366 featuresetupfuncs = set()
366 featuresetupfuncs = set()
367
367
368 @zi.implementer(repository.completelocalrepository)
368 @zi.implementer(repository.completelocalrepository)
369 class localrepository(object):
369 class localrepository(object):
370
370
371 # obsolete experimental requirements:
371 # obsolete experimental requirements:
372 # - manifestv2: An experimental new manifest format that allowed
372 # - manifestv2: An experimental new manifest format that allowed
373 # for stem compression of long paths. Experiment ended up not
373 # for stem compression of long paths. Experiment ended up not
374 # being successful (repository sizes went up due to worse delta
374 # being successful (repository sizes went up due to worse delta
375 # chains), and the code was deleted in 4.6.
375 # chains), and the code was deleted in 4.6.
376 supportedformats = {
376 supportedformats = {
377 'revlogv1',
377 'revlogv1',
378 'generaldelta',
378 'generaldelta',
379 'treemanifest',
379 'treemanifest',
380 REVLOGV2_REQUIREMENT,
380 REVLOGV2_REQUIREMENT,
381 }
381 }
382 _basesupported = supportedformats | {
382 _basesupported = supportedformats | {
383 'store',
383 'store',
384 'fncache',
384 'fncache',
385 'shared',
385 'shared',
386 'relshared',
386 'relshared',
387 'dotencode',
387 'dotencode',
388 'exp-sparse',
388 'exp-sparse',
389 }
389 }
390 openerreqs = {
390 openerreqs = {
391 'revlogv1',
391 'revlogv1',
392 'generaldelta',
392 'generaldelta',
393 'treemanifest',
393 'treemanifest',
394 }
394 }
395
395
396 # list of prefix for file which can be written without 'wlock'
396 # list of prefix for file which can be written without 'wlock'
397 # Extensions should extend this list when needed
397 # Extensions should extend this list when needed
398 _wlockfreeprefix = {
398 _wlockfreeprefix = {
399 # We migh consider requiring 'wlock' for the next
399 # We migh consider requiring 'wlock' for the next
400 # two, but pretty much all the existing code assume
400 # two, but pretty much all the existing code assume
401 # wlock is not needed so we keep them excluded for
401 # wlock is not needed so we keep them excluded for
402 # now.
402 # now.
403 'hgrc',
403 'hgrc',
404 'requires',
404 'requires',
405 # XXX cache is a complicatged business someone
405 # XXX cache is a complicatged business someone
406 # should investigate this in depth at some point
406 # should investigate this in depth at some point
407 'cache/',
407 'cache/',
408 # XXX shouldn't be dirstate covered by the wlock?
408 # XXX shouldn't be dirstate covered by the wlock?
409 'dirstate',
409 'dirstate',
410 # XXX bisect was still a bit too messy at the time
410 # XXX bisect was still a bit too messy at the time
411 # this changeset was introduced. Someone should fix
411 # this changeset was introduced. Someone should fix
412 # the remainig bit and drop this line
412 # the remainig bit and drop this line
413 'bisect.state',
413 'bisect.state',
414 }
414 }
415
415
416 def __init__(self, baseui, path, create=False):
416 def __init__(self, baseui, path, create=False):
417 self.requirements = set()
417 self.requirements = set()
418 self.filtername = None
418 self.filtername = None
419 # wvfs: rooted at the repository root, used to access the working copy
419 # wvfs: rooted at the repository root, used to access the working copy
420 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
420 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
421 # vfs: rooted at .hg, used to access repo files outside of .hg/store
421 # vfs: rooted at .hg, used to access repo files outside of .hg/store
422 self.vfs = None
422 self.vfs = None
423 # svfs: usually rooted at .hg/store, used to access repository history
423 # svfs: usually rooted at .hg/store, used to access repository history
424 # If this is a shared repository, this vfs may point to another
424 # If this is a shared repository, this vfs may point to another
425 # repository's .hg/store directory.
425 # repository's .hg/store directory.
426 self.svfs = None
426 self.svfs = None
427 self.root = self.wvfs.base
427 self.root = self.wvfs.base
428 self.path = self.wvfs.join(".hg")
428 self.path = self.wvfs.join(".hg")
429 self.origroot = path
429 self.origroot = path
430 # This is only used by context.workingctx.match in order to
430 # This is only used by context.workingctx.match in order to
431 # detect files in subrepos.
431 # detect files in subrepos.
432 self.auditor = pathutil.pathauditor(
432 self.auditor = pathutil.pathauditor(
433 self.root, callback=self._checknested)
433 self.root, callback=self._checknested)
434 # This is only used by context.basectx.match in order to detect
434 # This is only used by context.basectx.match in order to detect
435 # files in subrepos.
435 # files in subrepos.
436 self.nofsauditor = pathutil.pathauditor(
436 self.nofsauditor = pathutil.pathauditor(
437 self.root, callback=self._checknested, realfs=False, cached=True)
437 self.root, callback=self._checknested, realfs=False, cached=True)
438 self.baseui = baseui
438 self.baseui = baseui
439 self.ui = baseui.copy()
439 self.ui = baseui.copy()
440 self.ui.copy = baseui.copy # prevent copying repo configuration
440 self.ui.copy = baseui.copy # prevent copying repo configuration
441 self.vfs = vfsmod.vfs(self.path, cacheaudited=True)
441 self.vfs = vfsmod.vfs(self.path, cacheaudited=True)
442 if (self.ui.configbool('devel', 'all-warnings') or
442 if (self.ui.configbool('devel', 'all-warnings') or
443 self.ui.configbool('devel', 'check-locks')):
443 self.ui.configbool('devel', 'check-locks')):
444 self.vfs.audit = self._getvfsward(self.vfs.audit)
444 self.vfs.audit = self._getvfsward(self.vfs.audit)
445 # A list of callback to shape the phase if no data were found.
445 # A list of callback to shape the phase if no data were found.
446 # Callback are in the form: func(repo, roots) --> processed root.
446 # Callback are in the form: func(repo, roots) --> processed root.
447 # This list it to be filled by extension during repo setup
447 # This list it to be filled by extension during repo setup
448 self._phasedefaults = []
448 self._phasedefaults = []
449 try:
449 try:
450 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
450 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
451 self._loadextensions()
451 self._loadextensions()
452 except IOError:
452 except IOError:
453 pass
453 pass
454
454
455 if featuresetupfuncs:
455 if featuresetupfuncs:
456 self.supported = set(self._basesupported) # use private copy
456 self.supported = set(self._basesupported) # use private copy
457 extmods = set(m.__name__ for n, m
457 extmods = set(m.__name__ for n, m
458 in extensions.extensions(self.ui))
458 in extensions.extensions(self.ui))
459 for setupfunc in featuresetupfuncs:
459 for setupfunc in featuresetupfuncs:
460 if setupfunc.__module__ in extmods:
460 if setupfunc.__module__ in extmods:
461 setupfunc(self.ui, self.supported)
461 setupfunc(self.ui, self.supported)
462 else:
462 else:
463 self.supported = self._basesupported
463 self.supported = self._basesupported
464 color.setup(self.ui)
464 color.setup(self.ui)
465
465
466 # Add compression engines.
466 # Add compression engines.
467 for name in util.compengines:
467 for name in util.compengines:
468 engine = util.compengines[name]
468 engine = util.compengines[name]
469 if engine.revlogheader():
469 if engine.revlogheader():
470 self.supported.add('exp-compression-%s' % name)
470 self.supported.add('exp-compression-%s' % name)
471
471
472 if not self.vfs.isdir():
472 if not self.vfs.isdir():
473 if create:
473 if create:
474 self.requirements = newreporequirements(self)
474 self.requirements = newreporequirements(self)
475
475
476 if not self.wvfs.exists():
476 if not self.wvfs.exists():
477 self.wvfs.makedirs()
477 self.wvfs.makedirs()
478 self.vfs.makedir(notindexed=True)
478 self.vfs.makedir(notindexed=True)
479
479
480 if 'store' in self.requirements:
480 if 'store' in self.requirements:
481 self.vfs.mkdir("store")
481 self.vfs.mkdir("store")
482
482
483 # create an invalid changelog
483 # create an invalid changelog
484 self.vfs.append(
484 self.vfs.append(
485 "00changelog.i",
485 "00changelog.i",
486 '\0\0\0\2' # represents revlogv2
486 '\0\0\0\2' # represents revlogv2
487 ' dummy changelog to prevent using the old repo layout'
487 ' dummy changelog to prevent using the old repo layout'
488 )
488 )
489 else:
489 else:
490 raise error.RepoError(_("repository %s not found") % path)
490 raise error.RepoError(_("repository %s not found") % path)
491 elif create:
491 elif create:
492 raise error.RepoError(_("repository %s already exists") % path)
492 raise error.RepoError(_("repository %s already exists") % path)
493 else:
493 else:
494 try:
494 try:
495 self.requirements = scmutil.readrequires(
495 self.requirements = scmutil.readrequires(
496 self.vfs, self.supported)
496 self.vfs, self.supported)
497 except IOError as inst:
497 except IOError as inst:
498 if inst.errno != errno.ENOENT:
498 if inst.errno != errno.ENOENT:
499 raise
499 raise
500
500
501 cachepath = self.vfs.join('cache')
501 cachepath = self.vfs.join('cache')
502 self.sharedpath = self.path
502 self.sharedpath = self.path
503 try:
503 try:
504 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
504 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
505 if 'relshared' in self.requirements:
505 if 'relshared' in self.requirements:
506 sharedpath = self.vfs.join(sharedpath)
506 sharedpath = self.vfs.join(sharedpath)
507 vfs = vfsmod.vfs(sharedpath, realpath=True)
507 vfs = vfsmod.vfs(sharedpath, realpath=True)
508 cachepath = vfs.join('cache')
508 cachepath = vfs.join('cache')
509 s = vfs.base
509 s = vfs.base
510 if not vfs.exists():
510 if not vfs.exists():
511 raise error.RepoError(
511 raise error.RepoError(
512 _('.hg/sharedpath points to nonexistent directory %s') % s)
512 _('.hg/sharedpath points to nonexistent directory %s') % s)
513 self.sharedpath = s
513 self.sharedpath = s
514 except IOError as inst:
514 except IOError as inst:
515 if inst.errno != errno.ENOENT:
515 if inst.errno != errno.ENOENT:
516 raise
516 raise
517
517
518 if 'exp-sparse' in self.requirements and not sparse.enabled:
518 if 'exp-sparse' in self.requirements and not sparse.enabled:
519 raise error.RepoError(_('repository is using sparse feature but '
519 raise error.RepoError(_('repository is using sparse feature but '
520 'sparse is not enabled; enable the '
520 'sparse is not enabled; enable the '
521 '"sparse" extensions to access'))
521 '"sparse" extensions to access'))
522
522
523 self.store = store.store(
523 self.store = store.store(
524 self.requirements, self.sharedpath,
524 self.requirements, self.sharedpath,
525 lambda base: vfsmod.vfs(base, cacheaudited=True))
525 lambda base: vfsmod.vfs(base, cacheaudited=True))
526 self.spath = self.store.path
526 self.spath = self.store.path
527 self.svfs = self.store.vfs
527 self.svfs = self.store.vfs
528 self.sjoin = self.store.join
528 self.sjoin = self.store.join
529 self.vfs.createmode = self.store.createmode
529 self.vfs.createmode = self.store.createmode
530 self.cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
530 self.cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
531 self.cachevfs.createmode = self.store.createmode
531 self.cachevfs.createmode = self.store.createmode
532 if (self.ui.configbool('devel', 'all-warnings') or
532 if (self.ui.configbool('devel', 'all-warnings') or
533 self.ui.configbool('devel', 'check-locks')):
533 self.ui.configbool('devel', 'check-locks')):
534 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
534 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
535 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
535 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
536 else: # standard vfs
536 else: # standard vfs
537 self.svfs.audit = self._getsvfsward(self.svfs.audit)
537 self.svfs.audit = self._getsvfsward(self.svfs.audit)
538 self._applyopenerreqs()
538 self._applyopenerreqs()
539 if create:
539 if create:
540 self._writerequirements()
540 self._writerequirements()
541
541
542 self._dirstatevalidatewarned = False
542 self._dirstatevalidatewarned = False
543
543
544 self._branchcaches = {}
544 self._branchcaches = {}
545 self._revbranchcache = None
545 self._revbranchcache = None
546 self._filterpats = {}
546 self._filterpats = {}
547 self._datafilters = {}
547 self._datafilters = {}
548 self._transref = self._lockref = self._wlockref = None
548 self._transref = self._lockref = self._wlockref = None
549
549
550 # A cache for various files under .hg/ that tracks file changes,
550 # A cache for various files under .hg/ that tracks file changes,
551 # (used by the filecache decorator)
551 # (used by the filecache decorator)
552 #
552 #
553 # Maps a property name to its util.filecacheentry
553 # Maps a property name to its util.filecacheentry
554 self._filecache = {}
554 self._filecache = {}
555
555
556 # hold sets of revision to be filtered
556 # hold sets of revision to be filtered
557 # should be cleared when something might have changed the filter value:
557 # should be cleared when something might have changed the filter value:
558 # - new changesets,
558 # - new changesets,
559 # - phase change,
559 # - phase change,
560 # - new obsolescence marker,
560 # - new obsolescence marker,
561 # - working directory parent change,
561 # - working directory parent change,
562 # - bookmark changes
562 # - bookmark changes
563 self.filteredrevcache = {}
563 self.filteredrevcache = {}
564
564
565 # post-dirstate-status hooks
565 # post-dirstate-status hooks
566 self._postdsstatus = []
566 self._postdsstatus = []
567
567
568 # generic mapping between names and nodes
568 # generic mapping between names and nodes
569 self.names = namespaces.namespaces()
569 self.names = namespaces.namespaces()
570
570
571 # Key to signature value.
571 # Key to signature value.
572 self._sparsesignaturecache = {}
572 self._sparsesignaturecache = {}
573 # Signature to cached matcher instance.
573 # Signature to cached matcher instance.
574 self._sparsematchercache = {}
574 self._sparsematchercache = {}
575
575
576 def _getvfsward(self, origfunc):
576 def _getvfsward(self, origfunc):
577 """build a ward for self.vfs"""
577 """build a ward for self.vfs"""
578 rref = weakref.ref(self)
578 rref = weakref.ref(self)
579 def checkvfs(path, mode=None):
579 def checkvfs(path, mode=None):
580 ret = origfunc(path, mode=mode)
580 ret = origfunc(path, mode=mode)
581 repo = rref()
581 repo = rref()
582 if (repo is None
582 if (repo is None
583 or not util.safehasattr(repo, '_wlockref')
583 or not util.safehasattr(repo, '_wlockref')
584 or not util.safehasattr(repo, '_lockref')):
584 or not util.safehasattr(repo, '_lockref')):
585 return
585 return
586 if mode in (None, 'r', 'rb'):
586 if mode in (None, 'r', 'rb'):
587 return
587 return
588 if path.startswith(repo.path):
588 if path.startswith(repo.path):
589 # truncate name relative to the repository (.hg)
589 # truncate name relative to the repository (.hg)
590 path = path[len(repo.path) + 1:]
590 path = path[len(repo.path) + 1:]
591 if path.startswith('cache/'):
591 if path.startswith('cache/'):
592 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
592 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
593 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
593 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
594 if path.startswith('journal.'):
594 if path.startswith('journal.'):
595 # journal is covered by 'lock'
595 # journal is covered by 'lock'
596 if repo._currentlock(repo._lockref) is None:
596 if repo._currentlock(repo._lockref) is None:
597 repo.ui.develwarn('write with no lock: "%s"' % path,
597 repo.ui.develwarn('write with no lock: "%s"' % path,
598 stacklevel=2, config='check-locks')
598 stacklevel=2, config='check-locks')
599 elif repo._currentlock(repo._wlockref) is None:
599 elif repo._currentlock(repo._wlockref) is None:
600 # rest of vfs files are covered by 'wlock'
600 # rest of vfs files are covered by 'wlock'
601 #
601 #
602 # exclude special files
602 # exclude special files
603 for prefix in self._wlockfreeprefix:
603 for prefix in self._wlockfreeprefix:
604 if path.startswith(prefix):
604 if path.startswith(prefix):
605 return
605 return
606 repo.ui.develwarn('write with no wlock: "%s"' % path,
606 repo.ui.develwarn('write with no wlock: "%s"' % path,
607 stacklevel=2, config='check-locks')
607 stacklevel=2, config='check-locks')
608 return ret
608 return ret
609 return checkvfs
609 return checkvfs
610
610
611 def _getsvfsward(self, origfunc):
611 def _getsvfsward(self, origfunc):
612 """build a ward for self.svfs"""
612 """build a ward for self.svfs"""
613 rref = weakref.ref(self)
613 rref = weakref.ref(self)
614 def checksvfs(path, mode=None):
614 def checksvfs(path, mode=None):
615 ret = origfunc(path, mode=mode)
615 ret = origfunc(path, mode=mode)
616 repo = rref()
616 repo = rref()
617 if repo is None or not util.safehasattr(repo, '_lockref'):
617 if repo is None or not util.safehasattr(repo, '_lockref'):
618 return
618 return
619 if mode in (None, 'r', 'rb'):
619 if mode in (None, 'r', 'rb'):
620 return
620 return
621 if path.startswith(repo.sharedpath):
621 if path.startswith(repo.sharedpath):
622 # truncate name relative to the repository (.hg)
622 # truncate name relative to the repository (.hg)
623 path = path[len(repo.sharedpath) + 1:]
623 path = path[len(repo.sharedpath) + 1:]
624 if repo._currentlock(repo._lockref) is None:
624 if repo._currentlock(repo._lockref) is None:
625 repo.ui.develwarn('write with no lock: "%s"' % path,
625 repo.ui.develwarn('write with no lock: "%s"' % path,
626 stacklevel=3)
626 stacklevel=3)
627 return ret
627 return ret
628 return checksvfs
628 return checksvfs
629
629
630 def close(self):
630 def close(self):
631 self._writecaches()
631 self._writecaches()
632
632
633 def _loadextensions(self):
633 def _loadextensions(self):
634 extensions.loadall(self.ui)
634 extensions.loadall(self.ui)
635
635
636 def _writecaches(self):
636 def _writecaches(self):
637 if self._revbranchcache:
637 if self._revbranchcache:
638 self._revbranchcache.write()
638 self._revbranchcache.write()
639
639
640 def _restrictcapabilities(self, caps):
640 def _restrictcapabilities(self, caps):
641 if self.ui.configbool('experimental', 'bundle2-advertise'):
641 if self.ui.configbool('experimental', 'bundle2-advertise'):
642 caps = set(caps)
642 caps = set(caps)
643 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self,
643 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self,
644 role='client'))
644 role='client'))
645 caps.add('bundle2=' + urlreq.quote(capsblob))
645 caps.add('bundle2=' + urlreq.quote(capsblob))
646 return caps
646 return caps
647
647
648 def _applyopenerreqs(self):
648 def _applyopenerreqs(self):
649 self.svfs.options = dict((r, 1) for r in self.requirements
649 self.svfs.options = dict((r, 1) for r in self.requirements
650 if r in self.openerreqs)
650 if r in self.openerreqs)
651 # experimental config: format.chunkcachesize
651 # experimental config: format.chunkcachesize
652 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
652 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
653 if chunkcachesize is not None:
653 if chunkcachesize is not None:
654 self.svfs.options['chunkcachesize'] = chunkcachesize
654 self.svfs.options['chunkcachesize'] = chunkcachesize
655 # experimental config: format.maxchainlen
655 # experimental config: format.maxchainlen
656 maxchainlen = self.ui.configint('format', 'maxchainlen')
656 maxchainlen = self.ui.configint('format', 'maxchainlen')
657 if maxchainlen is not None:
657 if maxchainlen is not None:
658 self.svfs.options['maxchainlen'] = maxchainlen
658 self.svfs.options['maxchainlen'] = maxchainlen
659 # experimental config: format.manifestcachesize
659 # experimental config: format.manifestcachesize
660 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
660 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
661 if manifestcachesize is not None:
661 if manifestcachesize is not None:
662 self.svfs.options['manifestcachesize'] = manifestcachesize
662 self.svfs.options['manifestcachesize'] = manifestcachesize
663 # experimental config: format.aggressivemergedeltas
663 # experimental config: format.aggressivemergedeltas
664 aggressivemergedeltas = self.ui.configbool('format',
664 aggressivemergedeltas = self.ui.configbool('format',
665 'aggressivemergedeltas')
665 'aggressivemergedeltas')
666 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
666 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
667 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
667 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
668 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan')
668 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan')
669 if 0 <= chainspan:
669 if 0 <= chainspan:
670 self.svfs.options['maxdeltachainspan'] = chainspan
670 self.svfs.options['maxdeltachainspan'] = chainspan
671 mmapindexthreshold = self.ui.configbytes('experimental',
671 mmapindexthreshold = self.ui.configbytes('experimental',
672 'mmapindexthreshold')
672 'mmapindexthreshold')
673 if mmapindexthreshold is not None:
673 if mmapindexthreshold is not None:
674 self.svfs.options['mmapindexthreshold'] = mmapindexthreshold
674 self.svfs.options['mmapindexthreshold'] = mmapindexthreshold
675 withsparseread = self.ui.configbool('experimental', 'sparse-read')
675 withsparseread = self.ui.configbool('experimental', 'sparse-read')
676 srdensitythres = float(self.ui.config('experimental',
676 srdensitythres = float(self.ui.config('experimental',
677 'sparse-read.density-threshold'))
677 'sparse-read.density-threshold'))
678 srmingapsize = self.ui.configbytes('experimental',
678 srmingapsize = self.ui.configbytes('experimental',
679 'sparse-read.min-gap-size')
679 'sparse-read.min-gap-size')
680 self.svfs.options['with-sparse-read'] = withsparseread
680 self.svfs.options['with-sparse-read'] = withsparseread
681 self.svfs.options['sparse-read-density-threshold'] = srdensitythres
681 self.svfs.options['sparse-read-density-threshold'] = srdensitythres
682 self.svfs.options['sparse-read-min-gap-size'] = srmingapsize
682 self.svfs.options['sparse-read-min-gap-size'] = srmingapsize
683
683
684 for r in self.requirements:
684 for r in self.requirements:
685 if r.startswith('exp-compression-'):
685 if r.startswith('exp-compression-'):
686 self.svfs.options['compengine'] = r[len('exp-compression-'):]
686 self.svfs.options['compengine'] = r[len('exp-compression-'):]
687
687
688 # TODO move "revlogv2" to openerreqs once finalized.
688 # TODO move "revlogv2" to openerreqs once finalized.
689 if REVLOGV2_REQUIREMENT in self.requirements:
689 if REVLOGV2_REQUIREMENT in self.requirements:
690 self.svfs.options['revlogv2'] = True
690 self.svfs.options['revlogv2'] = True
691
691
692 def _writerequirements(self):
692 def _writerequirements(self):
693 scmutil.writerequires(self.vfs, self.requirements)
693 scmutil.writerequires(self.vfs, self.requirements)
694
694
695 def _checknested(self, path):
695 def _checknested(self, path):
696 """Determine if path is a legal nested repository."""
696 """Determine if path is a legal nested repository."""
697 if not path.startswith(self.root):
697 if not path.startswith(self.root):
698 return False
698 return False
699 subpath = path[len(self.root) + 1:]
699 subpath = path[len(self.root) + 1:]
700 normsubpath = util.pconvert(subpath)
700 normsubpath = util.pconvert(subpath)
701
701
702 # XXX: Checking against the current working copy is wrong in
702 # XXX: Checking against the current working copy is wrong in
703 # the sense that it can reject things like
703 # the sense that it can reject things like
704 #
704 #
705 # $ hg cat -r 10 sub/x.txt
705 # $ hg cat -r 10 sub/x.txt
706 #
706 #
707 # if sub/ is no longer a subrepository in the working copy
707 # if sub/ is no longer a subrepository in the working copy
708 # parent revision.
708 # parent revision.
709 #
709 #
710 # However, it can of course also allow things that would have
710 # However, it can of course also allow things that would have
711 # been rejected before, such as the above cat command if sub/
711 # been rejected before, such as the above cat command if sub/
712 # is a subrepository now, but was a normal directory before.
712 # is a subrepository now, but was a normal directory before.
713 # The old path auditor would have rejected by mistake since it
713 # The old path auditor would have rejected by mistake since it
714 # panics when it sees sub/.hg/.
714 # panics when it sees sub/.hg/.
715 #
715 #
716 # All in all, checking against the working copy seems sensible
716 # All in all, checking against the working copy seems sensible
717 # since we want to prevent access to nested repositories on
717 # since we want to prevent access to nested repositories on
718 # the filesystem *now*.
718 # the filesystem *now*.
719 ctx = self[None]
719 ctx = self[None]
720 parts = util.splitpath(subpath)
720 parts = util.splitpath(subpath)
721 while parts:
721 while parts:
722 prefix = '/'.join(parts)
722 prefix = '/'.join(parts)
723 if prefix in ctx.substate:
723 if prefix in ctx.substate:
724 if prefix == normsubpath:
724 if prefix == normsubpath:
725 return True
725 return True
726 else:
726 else:
727 sub = ctx.sub(prefix)
727 sub = ctx.sub(prefix)
728 return sub.checknested(subpath[len(prefix) + 1:])
728 return sub.checknested(subpath[len(prefix) + 1:])
729 else:
729 else:
730 parts.pop()
730 parts.pop()
731 return False
731 return False
732
732
733 def peer(self):
733 def peer(self):
734 return localpeer(self) # not cached to avoid reference cycle
734 return localpeer(self) # not cached to avoid reference cycle
735
735
736 def unfiltered(self):
736 def unfiltered(self):
737 """Return unfiltered version of the repository
737 """Return unfiltered version of the repository
738
738
739 Intended to be overwritten by filtered repo."""
739 Intended to be overwritten by filtered repo."""
740 return self
740 return self
741
741
742 def filtered(self, name, visibilityexceptions=None):
742 def filtered(self, name, visibilityexceptions=None):
743 """Return a filtered version of a repository"""
743 """Return a filtered version of a repository"""
744 cls = repoview.newtype(self.unfiltered().__class__)
744 cls = repoview.newtype(self.unfiltered().__class__)
745 return cls(self, name, visibilityexceptions)
745 return cls(self, name, visibilityexceptions)
746
746
747 @repofilecache('bookmarks', 'bookmarks.current')
747 @repofilecache('bookmarks', 'bookmarks.current')
748 def _bookmarks(self):
748 def _bookmarks(self):
749 return bookmarks.bmstore(self)
749 return bookmarks.bmstore(self)
750
750
751 @property
751 @property
752 def _activebookmark(self):
752 def _activebookmark(self):
753 return self._bookmarks.active
753 return self._bookmarks.active
754
754
755 # _phasesets depend on changelog. what we need is to call
755 # _phasesets depend on changelog. what we need is to call
756 # _phasecache.invalidate() if '00changelog.i' was changed, but it
756 # _phasecache.invalidate() if '00changelog.i' was changed, but it
757 # can't be easily expressed in filecache mechanism.
757 # can't be easily expressed in filecache mechanism.
758 @storecache('phaseroots', '00changelog.i')
758 @storecache('phaseroots', '00changelog.i')
759 def _phasecache(self):
759 def _phasecache(self):
760 return phases.phasecache(self, self._phasedefaults)
760 return phases.phasecache(self, self._phasedefaults)
761
761
762 @storecache('obsstore')
762 @storecache('obsstore')
763 def obsstore(self):
763 def obsstore(self):
764 return obsolete.makestore(self.ui, self)
764 return obsolete.makestore(self.ui, self)
765
765
766 @storecache('00changelog.i')
766 @storecache('00changelog.i')
767 def changelog(self):
767 def changelog(self):
768 return changelog.changelog(self.svfs,
768 return changelog.changelog(self.svfs,
769 trypending=txnutil.mayhavepending(self.root))
769 trypending=txnutil.mayhavepending(self.root))
770
770
771 def _constructmanifest(self):
771 def _constructmanifest(self):
772 # This is a temporary function while we migrate from manifest to
772 # This is a temporary function while we migrate from manifest to
773 # manifestlog. It allows bundlerepo and unionrepo to intercept the
773 # manifestlog. It allows bundlerepo and unionrepo to intercept the
774 # manifest creation.
774 # manifest creation.
775 return manifest.manifestrevlog(self.svfs)
775 return manifest.manifestrevlog(self.svfs)
776
776
777 @storecache('00manifest.i')
777 @storecache('00manifest.i')
778 def manifestlog(self):
778 def manifestlog(self):
779 return manifest.manifestlog(self.svfs, self)
779 return manifest.manifestlog(self.svfs, self)
780
780
781 @repofilecache('dirstate')
781 @repofilecache('dirstate')
782 def dirstate(self):
782 def dirstate(self):
783 sparsematchfn = lambda: sparse.matcher(self)
783 sparsematchfn = lambda: sparse.matcher(self)
784
784
785 return dirstate.dirstate(self.vfs, self.ui, self.root,
785 return dirstate.dirstate(self.vfs, self.ui, self.root,
786 self._dirstatevalidate, sparsematchfn)
786 self._dirstatevalidate, sparsematchfn)
787
787
788 def _dirstatevalidate(self, node):
788 def _dirstatevalidate(self, node):
789 try:
789 try:
790 self.changelog.rev(node)
790 self.changelog.rev(node)
791 return node
791 return node
792 except error.LookupError:
792 except error.LookupError:
793 if not self._dirstatevalidatewarned:
793 if not self._dirstatevalidatewarned:
794 self._dirstatevalidatewarned = True
794 self._dirstatevalidatewarned = True
795 self.ui.warn(_("warning: ignoring unknown"
795 self.ui.warn(_("warning: ignoring unknown"
796 " working parent %s!\n") % short(node))
796 " working parent %s!\n") % short(node))
797 return nullid
797 return nullid
798
798
799 @repofilecache(narrowspec.FILENAME)
799 @repofilecache(narrowspec.FILENAME)
800 def narrowpats(self):
800 def narrowpats(self):
801 """matcher patterns for this repository's narrowspec
801 """matcher patterns for this repository's narrowspec
802
802
803 A tuple of (includes, excludes).
803 A tuple of (includes, excludes).
804 """
804 """
805 source = self
805 source = self
806 if self.shared():
806 if self.shared():
807 from . import hg
807 from . import hg
808 source = hg.sharedreposource(self)
808 source = hg.sharedreposource(self)
809 return narrowspec.load(source)
809 return narrowspec.load(source)
810
810
811 @repofilecache(narrowspec.FILENAME)
811 @repofilecache(narrowspec.FILENAME)
812 def _narrowmatch(self):
812 def _narrowmatch(self):
813 if changegroup.NARROW_REQUIREMENT not in self.requirements:
813 if changegroup.NARROW_REQUIREMENT not in self.requirements:
814 return matchmod.always(self.root, '')
814 return matchmod.always(self.root, '')
815 include, exclude = self.narrowpats
815 include, exclude = self.narrowpats
816 return narrowspec.match(self.root, include=include, exclude=exclude)
816 return narrowspec.match(self.root, include=include, exclude=exclude)
817
817
818 # TODO(martinvonz): make this property-like instead?
818 # TODO(martinvonz): make this property-like instead?
819 def narrowmatch(self):
819 def narrowmatch(self):
820 return self._narrowmatch
820 return self._narrowmatch
821
821
822 def setnarrowpats(self, newincludes, newexcludes):
822 def setnarrowpats(self, newincludes, newexcludes):
823 target = self
823 target = self
824 if self.shared():
824 if self.shared():
825 from . import hg
825 from . import hg
826 target = hg.sharedreposource(self)
826 target = hg.sharedreposource(self)
827 narrowspec.save(target, newincludes, newexcludes)
827 narrowspec.save(target, newincludes, newexcludes)
828 self.invalidate(clearfilecache=True)
828 self.invalidate(clearfilecache=True)
829
829
830 def __getitem__(self, changeid):
830 def __getitem__(self, changeid):
831 if changeid is None:
831 if changeid is None:
832 return context.workingctx(self)
832 return context.workingctx(self)
833 if isinstance(changeid, context.basectx):
833 if isinstance(changeid, context.basectx):
834 return changeid
834 return changeid
835 if isinstance(changeid, slice):
835 if isinstance(changeid, slice):
836 # wdirrev isn't contiguous so the slice shouldn't include it
836 # wdirrev isn't contiguous so the slice shouldn't include it
837 return [context.changectx(self, i)
837 return [context.changectx(self, i)
838 for i in xrange(*changeid.indices(len(self)))
838 for i in xrange(*changeid.indices(len(self)))
839 if i not in self.changelog.filteredrevs]
839 if i not in self.changelog.filteredrevs]
840 try:
840 try:
841 return context.changectx(self, changeid)
841 return context.changectx(self, changeid)
842 except error.WdirUnsupported:
842 except error.WdirUnsupported:
843 return context.workingctx(self)
843 return context.workingctx(self)
844
844
845 def __contains__(self, changeid):
845 def __contains__(self, changeid):
846 """True if the given changeid exists
846 """True if the given changeid exists
847
847
848 error.LookupError is raised if an ambiguous node specified.
848 error.LookupError is raised if an ambiguous node specified.
849 """
849 """
850 try:
850 try:
851 self[changeid]
851 self[changeid]
852 return True
852 return True
853 except (error.RepoLookupError, error.FilteredIndexError,
853 except (error.RepoLookupError, error.FilteredIndexError,
854 error.FilteredLookupError):
854 error.FilteredLookupError):
855 return False
855 return False
856
856
857 def __nonzero__(self):
857 def __nonzero__(self):
858 return True
858 return True
859
859
860 __bool__ = __nonzero__
860 __bool__ = __nonzero__
861
861
862 def __len__(self):
862 def __len__(self):
863 # no need to pay the cost of repoview.changelog
863 # no need to pay the cost of repoview.changelog
864 unfi = self.unfiltered()
864 unfi = self.unfiltered()
865 return len(unfi.changelog)
865 return len(unfi.changelog)
866
866
867 def __iter__(self):
867 def __iter__(self):
868 return iter(self.changelog)
868 return iter(self.changelog)
869
869
870 def revs(self, expr, *args):
870 def revs(self, expr, *args):
871 '''Find revisions matching a revset.
871 '''Find revisions matching a revset.
872
872
873 The revset is specified as a string ``expr`` that may contain
873 The revset is specified as a string ``expr`` that may contain
874 %-formatting to escape certain types. See ``revsetlang.formatspec``.
874 %-formatting to escape certain types. See ``revsetlang.formatspec``.
875
875
876 Revset aliases from the configuration are not expanded. To expand
876 Revset aliases from the configuration are not expanded. To expand
877 user aliases, consider calling ``scmutil.revrange()`` or
877 user aliases, consider calling ``scmutil.revrange()`` or
878 ``repo.anyrevs([expr], user=True)``.
878 ``repo.anyrevs([expr], user=True)``.
879
879
880 Returns a revset.abstractsmartset, which is a list-like interface
880 Returns a revset.abstractsmartset, which is a list-like interface
881 that contains integer revisions.
881 that contains integer revisions.
882 '''
882 '''
883 expr = revsetlang.formatspec(expr, *args)
883 expr = revsetlang.formatspec(expr, *args)
884 m = revset.match(None, expr)
884 m = revset.match(None, expr)
885 return m(self)
885 return m(self)
886
886
887 def set(self, expr, *args):
887 def set(self, expr, *args):
888 '''Find revisions matching a revset and emit changectx instances.
888 '''Find revisions matching a revset and emit changectx instances.
889
889
890 This is a convenience wrapper around ``revs()`` that iterates the
890 This is a convenience wrapper around ``revs()`` that iterates the
891 result and is a generator of changectx instances.
891 result and is a generator of changectx instances.
892
892
893 Revset aliases from the configuration are not expanded. To expand
893 Revset aliases from the configuration are not expanded. To expand
894 user aliases, consider calling ``scmutil.revrange()``.
894 user aliases, consider calling ``scmutil.revrange()``.
895 '''
895 '''
896 for r in self.revs(expr, *args):
896 for r in self.revs(expr, *args):
897 yield self[r]
897 yield self[r]
898
898
899 def anyrevs(self, specs, user=False, localalias=None):
899 def anyrevs(self, specs, user=False, localalias=None):
900 '''Find revisions matching one of the given revsets.
900 '''Find revisions matching one of the given revsets.
901
901
902 Revset aliases from the configuration are not expanded by default. To
902 Revset aliases from the configuration are not expanded by default. To
903 expand user aliases, specify ``user=True``. To provide some local
903 expand user aliases, specify ``user=True``. To provide some local
904 definitions overriding user aliases, set ``localalias`` to
904 definitions overriding user aliases, set ``localalias`` to
905 ``{name: definitionstring}``.
905 ``{name: definitionstring}``.
906 '''
906 '''
907 if user:
907 if user:
908 m = revset.matchany(self.ui, specs, repo=self,
908 m = revset.matchany(self.ui, specs, repo=self,
909 localalias=localalias)
909 localalias=localalias)
910 else:
910 else:
911 m = revset.matchany(None, specs, localalias=localalias)
911 m = revset.matchany(None, specs, localalias=localalias)
912 return m(self)
912 return m(self)
913
913
914 def url(self):
914 def url(self):
915 return 'file:' + self.root
915 return 'file:' + self.root
916
916
917 def hook(self, name, throw=False, **args):
917 def hook(self, name, throw=False, **args):
918 """Call a hook, passing this repo instance.
918 """Call a hook, passing this repo instance.
919
919
920 This a convenience method to aid invoking hooks. Extensions likely
920 This a convenience method to aid invoking hooks. Extensions likely
921 won't call this unless they have registered a custom hook or are
921 won't call this unless they have registered a custom hook or are
922 replacing code that is expected to call a hook.
922 replacing code that is expected to call a hook.
923 """
923 """
924 return hook.hook(self.ui, self, name, throw, **args)
924 return hook.hook(self.ui, self, name, throw, **args)
925
925
926 @filteredpropertycache
926 @filteredpropertycache
927 def _tagscache(self):
927 def _tagscache(self):
928 '''Returns a tagscache object that contains various tags related
928 '''Returns a tagscache object that contains various tags related
929 caches.'''
929 caches.'''
930
930
931 # This simplifies its cache management by having one decorated
931 # This simplifies its cache management by having one decorated
932 # function (this one) and the rest simply fetch things from it.
932 # function (this one) and the rest simply fetch things from it.
933 class tagscache(object):
933 class tagscache(object):
934 def __init__(self):
934 def __init__(self):
935 # These two define the set of tags for this repository. tags
935 # These two define the set of tags for this repository. tags
936 # maps tag name to node; tagtypes maps tag name to 'global' or
936 # maps tag name to node; tagtypes maps tag name to 'global' or
937 # 'local'. (Global tags are defined by .hgtags across all
937 # 'local'. (Global tags are defined by .hgtags across all
938 # heads, and local tags are defined in .hg/localtags.)
938 # heads, and local tags are defined in .hg/localtags.)
939 # They constitute the in-memory cache of tags.
939 # They constitute the in-memory cache of tags.
940 self.tags = self.tagtypes = None
940 self.tags = self.tagtypes = None
941
941
942 self.nodetagscache = self.tagslist = None
942 self.nodetagscache = self.tagslist = None
943
943
944 cache = tagscache()
944 cache = tagscache()
945 cache.tags, cache.tagtypes = self._findtags()
945 cache.tags, cache.tagtypes = self._findtags()
946
946
947 return cache
947 return cache
948
948
949 def tags(self):
949 def tags(self):
950 '''return a mapping of tag to node'''
950 '''return a mapping of tag to node'''
951 t = {}
951 t = {}
952 if self.changelog.filteredrevs:
952 if self.changelog.filteredrevs:
953 tags, tt = self._findtags()
953 tags, tt = self._findtags()
954 else:
954 else:
955 tags = self._tagscache.tags
955 tags = self._tagscache.tags
956 for k, v in tags.iteritems():
956 for k, v in tags.iteritems():
957 try:
957 try:
958 # ignore tags to unknown nodes
958 # ignore tags to unknown nodes
959 self.changelog.rev(v)
959 self.changelog.rev(v)
960 t[k] = v
960 t[k] = v
961 except (error.LookupError, ValueError):
961 except (error.LookupError, ValueError):
962 pass
962 pass
963 return t
963 return t
964
964
965 def _findtags(self):
965 def _findtags(self):
966 '''Do the hard work of finding tags. Return a pair of dicts
966 '''Do the hard work of finding tags. Return a pair of dicts
967 (tags, tagtypes) where tags maps tag name to node, and tagtypes
967 (tags, tagtypes) where tags maps tag name to node, and tagtypes
968 maps tag name to a string like \'global\' or \'local\'.
968 maps tag name to a string like \'global\' or \'local\'.
969 Subclasses or extensions are free to add their own tags, but
969 Subclasses or extensions are free to add their own tags, but
970 should be aware that the returned dicts will be retained for the
970 should be aware that the returned dicts will be retained for the
971 duration of the localrepo object.'''
971 duration of the localrepo object.'''
972
972
973 # XXX what tagtype should subclasses/extensions use? Currently
973 # XXX what tagtype should subclasses/extensions use? Currently
974 # mq and bookmarks add tags, but do not set the tagtype at all.
974 # mq and bookmarks add tags, but do not set the tagtype at all.
975 # Should each extension invent its own tag type? Should there
975 # Should each extension invent its own tag type? Should there
976 # be one tagtype for all such "virtual" tags? Or is the status
976 # be one tagtype for all such "virtual" tags? Or is the status
977 # quo fine?
977 # quo fine?
978
978
979
979
980 # map tag name to (node, hist)
980 # map tag name to (node, hist)
981 alltags = tagsmod.findglobaltags(self.ui, self)
981 alltags = tagsmod.findglobaltags(self.ui, self)
982 # map tag name to tag type
982 # map tag name to tag type
983 tagtypes = dict((tag, 'global') for tag in alltags)
983 tagtypes = dict((tag, 'global') for tag in alltags)
984
984
985 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
985 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
986
986
987 # Build the return dicts. Have to re-encode tag names because
987 # Build the return dicts. Have to re-encode tag names because
988 # the tags module always uses UTF-8 (in order not to lose info
988 # the tags module always uses UTF-8 (in order not to lose info
989 # writing to the cache), but the rest of Mercurial wants them in
989 # writing to the cache), but the rest of Mercurial wants them in
990 # local encoding.
990 # local encoding.
991 tags = {}
991 tags = {}
992 for (name, (node, hist)) in alltags.iteritems():
992 for (name, (node, hist)) in alltags.iteritems():
993 if node != nullid:
993 if node != nullid:
994 tags[encoding.tolocal(name)] = node
994 tags[encoding.tolocal(name)] = node
995 tags['tip'] = self.changelog.tip()
995 tags['tip'] = self.changelog.tip()
996 tagtypes = dict([(encoding.tolocal(name), value)
996 tagtypes = dict([(encoding.tolocal(name), value)
997 for (name, value) in tagtypes.iteritems()])
997 for (name, value) in tagtypes.iteritems()])
998 return (tags, tagtypes)
998 return (tags, tagtypes)
999
999
1000 def tagtype(self, tagname):
1000 def tagtype(self, tagname):
1001 '''
1001 '''
1002 return the type of the given tag. result can be:
1002 return the type of the given tag. result can be:
1003
1003
1004 'local' : a local tag
1004 'local' : a local tag
1005 'global' : a global tag
1005 'global' : a global tag
1006 None : tag does not exist
1006 None : tag does not exist
1007 '''
1007 '''
1008
1008
1009 return self._tagscache.tagtypes.get(tagname)
1009 return self._tagscache.tagtypes.get(tagname)
1010
1010
1011 def tagslist(self):
1011 def tagslist(self):
1012 '''return a list of tags ordered by revision'''
1012 '''return a list of tags ordered by revision'''
1013 if not self._tagscache.tagslist:
1013 if not self._tagscache.tagslist:
1014 l = []
1014 l = []
1015 for t, n in self.tags().iteritems():
1015 for t, n in self.tags().iteritems():
1016 l.append((self.changelog.rev(n), t, n))
1016 l.append((self.changelog.rev(n), t, n))
1017 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
1017 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
1018
1018
1019 return self._tagscache.tagslist
1019 return self._tagscache.tagslist
1020
1020
1021 def nodetags(self, node):
1021 def nodetags(self, node):
1022 '''return the tags associated with a node'''
1022 '''return the tags associated with a node'''
1023 if not self._tagscache.nodetagscache:
1023 if not self._tagscache.nodetagscache:
1024 nodetagscache = {}
1024 nodetagscache = {}
1025 for t, n in self._tagscache.tags.iteritems():
1025 for t, n in self._tagscache.tags.iteritems():
1026 nodetagscache.setdefault(n, []).append(t)
1026 nodetagscache.setdefault(n, []).append(t)
1027 for tags in nodetagscache.itervalues():
1027 for tags in nodetagscache.itervalues():
1028 tags.sort()
1028 tags.sort()
1029 self._tagscache.nodetagscache = nodetagscache
1029 self._tagscache.nodetagscache = nodetagscache
1030 return self._tagscache.nodetagscache.get(node, [])
1030 return self._tagscache.nodetagscache.get(node, [])
1031
1031
1032 def nodebookmarks(self, node):
1032 def nodebookmarks(self, node):
1033 """return the list of bookmarks pointing to the specified node"""
1033 """return the list of bookmarks pointing to the specified node"""
1034 marks = []
1034 marks = []
1035 for bookmark, n in self._bookmarks.iteritems():
1035 for bookmark, n in self._bookmarks.iteritems():
1036 if n == node:
1036 if n == node:
1037 marks.append(bookmark)
1037 marks.append(bookmark)
1038 return sorted(marks)
1038 return sorted(marks)
1039
1039
1040 def branchmap(self):
1040 def branchmap(self):
1041 '''returns a dictionary {branch: [branchheads]} with branchheads
1041 '''returns a dictionary {branch: [branchheads]} with branchheads
1042 ordered by increasing revision number'''
1042 ordered by increasing revision number'''
1043 branchmap.updatecache(self)
1043 branchmap.updatecache(self)
1044 return self._branchcaches[self.filtername]
1044 return self._branchcaches[self.filtername]
1045
1045
1046 @unfilteredmethod
1046 @unfilteredmethod
1047 def revbranchcache(self):
1047 def revbranchcache(self):
1048 if not self._revbranchcache:
1048 if not self._revbranchcache:
1049 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
1049 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
1050 return self._revbranchcache
1050 return self._revbranchcache
1051
1051
1052 def branchtip(self, branch, ignoremissing=False):
1052 def branchtip(self, branch, ignoremissing=False):
1053 '''return the tip node for a given branch
1053 '''return the tip node for a given branch
1054
1054
1055 If ignoremissing is True, then this method will not raise an error.
1055 If ignoremissing is True, then this method will not raise an error.
1056 This is helpful for callers that only expect None for a missing branch
1056 This is helpful for callers that only expect None for a missing branch
1057 (e.g. namespace).
1057 (e.g. namespace).
1058
1058
1059 '''
1059 '''
1060 try:
1060 try:
1061 return self.branchmap().branchtip(branch)
1061 return self.branchmap().branchtip(branch)
1062 except KeyError:
1062 except KeyError:
1063 if not ignoremissing:
1063 if not ignoremissing:
1064 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
1064 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
1065 else:
1065 else:
1066 pass
1066 pass
1067
1067
1068 def lookup(self, key):
1068 def lookup(self, key):
1069 return scmutil.revsymbol(self, key).node()
1069 return scmutil.revsymbol(self, key).node()
1070
1070
1071 def lookupbranch(self, key):
1071 def lookupbranch(self, key):
1072 if key in self.branchmap():
1072 if key in self.branchmap():
1073 return key
1073 return key
1074
1074
1075 return scmutil.revsymbol(self, key).branch()
1075 return scmutil.revsymbol(self, key).branch()
1076
1076
1077 def known(self, nodes):
1077 def known(self, nodes):
1078 cl = self.changelog
1078 cl = self.changelog
1079 nm = cl.nodemap
1079 nm = cl.nodemap
1080 filtered = cl.filteredrevs
1080 filtered = cl.filteredrevs
1081 result = []
1081 result = []
1082 for n in nodes:
1082 for n in nodes:
1083 r = nm.get(n)
1083 r = nm.get(n)
1084 resp = not (r is None or r in filtered)
1084 resp = not (r is None or r in filtered)
1085 result.append(resp)
1085 result.append(resp)
1086 return result
1086 return result
1087
1087
1088 def local(self):
1088 def local(self):
1089 return self
1089 return self
1090
1090
1091 def publishing(self):
1091 def publishing(self):
1092 # it's safe (and desirable) to trust the publish flag unconditionally
1092 # it's safe (and desirable) to trust the publish flag unconditionally
1093 # so that we don't finalize changes shared between users via ssh or nfs
1093 # so that we don't finalize changes shared between users via ssh or nfs
1094 return self.ui.configbool('phases', 'publish', untrusted=True)
1094 return self.ui.configbool('phases', 'publish', untrusted=True)
1095
1095
1096 def cancopy(self):
1096 def cancopy(self):
1097 # so statichttprepo's override of local() works
1097 # so statichttprepo's override of local() works
1098 if not self.local():
1098 if not self.local():
1099 return False
1099 return False
1100 if not self.publishing():
1100 if not self.publishing():
1101 return True
1101 return True
1102 # if publishing we can't copy if there is filtered content
1102 # if publishing we can't copy if there is filtered content
1103 return not self.filtered('visible').changelog.filteredrevs
1103 return not self.filtered('visible').changelog.filteredrevs
1104
1104
1105 def shared(self):
1105 def shared(self):
1106 '''the type of shared repository (None if not shared)'''
1106 '''the type of shared repository (None if not shared)'''
1107 if self.sharedpath != self.path:
1107 if self.sharedpath != self.path:
1108 return 'store'
1108 return 'store'
1109 return None
1109 return None
1110
1110
1111 def wjoin(self, f, *insidef):
1111 def wjoin(self, f, *insidef):
1112 return self.vfs.reljoin(self.root, f, *insidef)
1112 return self.vfs.reljoin(self.root, f, *insidef)
1113
1113
1114 def file(self, f):
1114 def file(self, f):
1115 if f[0] == '/':
1115 if f[0] == '/':
1116 f = f[1:]
1116 f = f[1:]
1117 return filelog.filelog(self.svfs, f)
1117 return filelog.filelog(self.svfs, f)
1118
1118
1119 def setparents(self, p1, p2=nullid):
1119 def setparents(self, p1, p2=nullid):
1120 with self.dirstate.parentchange():
1120 with self.dirstate.parentchange():
1121 copies = self.dirstate.setparents(p1, p2)
1121 copies = self.dirstate.setparents(p1, p2)
1122 pctx = self[p1]
1122 pctx = self[p1]
1123 if copies:
1123 if copies:
1124 # Adjust copy records, the dirstate cannot do it, it
1124 # Adjust copy records, the dirstate cannot do it, it
1125 # requires access to parents manifests. Preserve them
1125 # requires access to parents manifests. Preserve them
1126 # only for entries added to first parent.
1126 # only for entries added to first parent.
1127 for f in copies:
1127 for f in copies:
1128 if f not in pctx and copies[f] in pctx:
1128 if f not in pctx and copies[f] in pctx:
1129 self.dirstate.copy(copies[f], f)
1129 self.dirstate.copy(copies[f], f)
1130 if p2 == nullid:
1130 if p2 == nullid:
1131 for f, s in sorted(self.dirstate.copies().items()):
1131 for f, s in sorted(self.dirstate.copies().items()):
1132 if f not in pctx and s not in pctx:
1132 if f not in pctx and s not in pctx:
1133 self.dirstate.copy(None, f)
1133 self.dirstate.copy(None, f)
1134
1134
1135 def filectx(self, path, changeid=None, fileid=None, changectx=None):
1135 def filectx(self, path, changeid=None, fileid=None, changectx=None):
1136 """changeid can be a changeset revision, node, or tag.
1136 """changeid can be a changeset revision, node, or tag.
1137 fileid can be a file revision or node."""
1137 fileid can be a file revision or node."""
1138 return context.filectx(self, path, changeid, fileid,
1138 return context.filectx(self, path, changeid, fileid,
1139 changectx=changectx)
1139 changectx=changectx)
1140
1140
1141 def getcwd(self):
1141 def getcwd(self):
1142 return self.dirstate.getcwd()
1142 return self.dirstate.getcwd()
1143
1143
1144 def pathto(self, f, cwd=None):
1144 def pathto(self, f, cwd=None):
1145 return self.dirstate.pathto(f, cwd)
1145 return self.dirstate.pathto(f, cwd)
1146
1146
1147 def _loadfilter(self, filter):
1147 def _loadfilter(self, filter):
1148 if filter not in self._filterpats:
1148 if filter not in self._filterpats:
1149 l = []
1149 l = []
1150 for pat, cmd in self.ui.configitems(filter):
1150 for pat, cmd in self.ui.configitems(filter):
1151 if cmd == '!':
1151 if cmd == '!':
1152 continue
1152 continue
1153 mf = matchmod.match(self.root, '', [pat])
1153 mf = matchmod.match(self.root, '', [pat])
1154 fn = None
1154 fn = None
1155 params = cmd
1155 params = cmd
1156 for name, filterfn in self._datafilters.iteritems():
1156 for name, filterfn in self._datafilters.iteritems():
1157 if cmd.startswith(name):
1157 if cmd.startswith(name):
1158 fn = filterfn
1158 fn = filterfn
1159 params = cmd[len(name):].lstrip()
1159 params = cmd[len(name):].lstrip()
1160 break
1160 break
1161 if not fn:
1161 if not fn:
1162 fn = lambda s, c, **kwargs: procutil.filter(s, c)
1162 fn = lambda s, c, **kwargs: procutil.filter(s, c)
1163 # Wrap old filters not supporting keyword arguments
1163 # Wrap old filters not supporting keyword arguments
1164 if not pycompat.getargspec(fn)[2]:
1164 if not pycompat.getargspec(fn)[2]:
1165 oldfn = fn
1165 oldfn = fn
1166 fn = lambda s, c, **kwargs: oldfn(s, c)
1166 fn = lambda s, c, **kwargs: oldfn(s, c)
1167 l.append((mf, fn, params))
1167 l.append((mf, fn, params))
1168 self._filterpats[filter] = l
1168 self._filterpats[filter] = l
1169 return self._filterpats[filter]
1169 return self._filterpats[filter]
1170
1170
1171 def _filter(self, filterpats, filename, data):
1171 def _filter(self, filterpats, filename, data):
1172 for mf, fn, cmd in filterpats:
1172 for mf, fn, cmd in filterpats:
1173 if mf(filename):
1173 if mf(filename):
1174 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1174 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1175 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1175 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1176 break
1176 break
1177
1177
1178 return data
1178 return data
1179
1179
1180 @unfilteredpropertycache
1180 @unfilteredpropertycache
1181 def _encodefilterpats(self):
1181 def _encodefilterpats(self):
1182 return self._loadfilter('encode')
1182 return self._loadfilter('encode')
1183
1183
1184 @unfilteredpropertycache
1184 @unfilteredpropertycache
1185 def _decodefilterpats(self):
1185 def _decodefilterpats(self):
1186 return self._loadfilter('decode')
1186 return self._loadfilter('decode')
1187
1187
1188 def adddatafilter(self, name, filter):
1188 def adddatafilter(self, name, filter):
1189 self._datafilters[name] = filter
1189 self._datafilters[name] = filter
1190
1190
1191 def wread(self, filename):
1191 def wread(self, filename):
1192 if self.wvfs.islink(filename):
1192 if self.wvfs.islink(filename):
1193 data = self.wvfs.readlink(filename)
1193 data = self.wvfs.readlink(filename)
1194 else:
1194 else:
1195 data = self.wvfs.read(filename)
1195 data = self.wvfs.read(filename)
1196 return self._filter(self._encodefilterpats, filename, data)
1196 return self._filter(self._encodefilterpats, filename, data)
1197
1197
1198 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
1198 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
1199 """write ``data`` into ``filename`` in the working directory
1199 """write ``data`` into ``filename`` in the working directory
1200
1200
1201 This returns length of written (maybe decoded) data.
1201 This returns length of written (maybe decoded) data.
1202 """
1202 """
1203 data = self._filter(self._decodefilterpats, filename, data)
1203 data = self._filter(self._decodefilterpats, filename, data)
1204 if 'l' in flags:
1204 if 'l' in flags:
1205 self.wvfs.symlink(data, filename)
1205 self.wvfs.symlink(data, filename)
1206 else:
1206 else:
1207 self.wvfs.write(filename, data, backgroundclose=backgroundclose,
1207 self.wvfs.write(filename, data, backgroundclose=backgroundclose,
1208 **kwargs)
1208 **kwargs)
1209 if 'x' in flags:
1209 if 'x' in flags:
1210 self.wvfs.setflags(filename, False, True)
1210 self.wvfs.setflags(filename, False, True)
1211 else:
1211 else:
1212 self.wvfs.setflags(filename, False, False)
1212 self.wvfs.setflags(filename, False, False)
1213 return len(data)
1213 return len(data)
1214
1214
1215 def wwritedata(self, filename, data):
1215 def wwritedata(self, filename, data):
1216 return self._filter(self._decodefilterpats, filename, data)
1216 return self._filter(self._decodefilterpats, filename, data)
1217
1217
1218 def currenttransaction(self):
1218 def currenttransaction(self):
1219 """return the current transaction or None if non exists"""
1219 """return the current transaction or None if non exists"""
1220 if self._transref:
1220 if self._transref:
1221 tr = self._transref()
1221 tr = self._transref()
1222 else:
1222 else:
1223 tr = None
1223 tr = None
1224
1224
1225 if tr and tr.running():
1225 if tr and tr.running():
1226 return tr
1226 return tr
1227 return None
1227 return None
1228
1228
1229 def transaction(self, desc, report=None):
1229 def transaction(self, desc, report=None):
1230 if (self.ui.configbool('devel', 'all-warnings')
1230 if (self.ui.configbool('devel', 'all-warnings')
1231 or self.ui.configbool('devel', 'check-locks')):
1231 or self.ui.configbool('devel', 'check-locks')):
1232 if self._currentlock(self._lockref) is None:
1232 if self._currentlock(self._lockref) is None:
1233 raise error.ProgrammingError('transaction requires locking')
1233 raise error.ProgrammingError('transaction requires locking')
1234 tr = self.currenttransaction()
1234 tr = self.currenttransaction()
1235 if tr is not None:
1235 if tr is not None:
1236 return tr.nest(name=desc)
1236 return tr.nest(name=desc)
1237
1237
1238 # abort here if the journal already exists
1238 # abort here if the journal already exists
1239 if self.svfs.exists("journal"):
1239 if self.svfs.exists("journal"):
1240 raise error.RepoError(
1240 raise error.RepoError(
1241 _("abandoned transaction found"),
1241 _("abandoned transaction found"),
1242 hint=_("run 'hg recover' to clean up transaction"))
1242 hint=_("run 'hg recover' to clean up transaction"))
1243
1243
1244 idbase = "%.40f#%f" % (random.random(), time.time())
1244 idbase = "%.40f#%f" % (random.random(), time.time())
1245 ha = hex(hashlib.sha1(idbase).digest())
1245 ha = hex(hashlib.sha1(idbase).digest())
1246 txnid = 'TXN:' + ha
1246 txnid = 'TXN:' + ha
1247 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1247 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1248
1248
1249 self._writejournal(desc)
1249 self._writejournal(desc)
1250 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1250 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1251 if report:
1251 if report:
1252 rp = report
1252 rp = report
1253 else:
1253 else:
1254 rp = self.ui.warn
1254 rp = self.ui.warn
1255 vfsmap = {'plain': self.vfs} # root of .hg/
1255 vfsmap = {'plain': self.vfs} # root of .hg/
1256 # we must avoid cyclic reference between repo and transaction.
1256 # we must avoid cyclic reference between repo and transaction.
1257 reporef = weakref.ref(self)
1257 reporef = weakref.ref(self)
1258 # Code to track tag movement
1258 # Code to track tag movement
1259 #
1259 #
1260 # Since tags are all handled as file content, it is actually quite hard
1260 # Since tags are all handled as file content, it is actually quite hard
1261 # to track these movement from a code perspective. So we fallback to a
1261 # to track these movement from a code perspective. So we fallback to a
1262 # tracking at the repository level. One could envision to track changes
1262 # tracking at the repository level. One could envision to track changes
1263 # to the '.hgtags' file through changegroup apply but that fails to
1263 # to the '.hgtags' file through changegroup apply but that fails to
1264 # cope with case where transaction expose new heads without changegroup
1264 # cope with case where transaction expose new heads without changegroup
1265 # being involved (eg: phase movement).
1265 # being involved (eg: phase movement).
1266 #
1266 #
1267 # For now, We gate the feature behind a flag since this likely comes
1267 # For now, We gate the feature behind a flag since this likely comes
1268 # with performance impacts. The current code run more often than needed
1268 # with performance impacts. The current code run more often than needed
1269 # and do not use caches as much as it could. The current focus is on
1269 # and do not use caches as much as it could. The current focus is on
1270 # the behavior of the feature so we disable it by default. The flag
1270 # the behavior of the feature so we disable it by default. The flag
1271 # will be removed when we are happy with the performance impact.
1271 # will be removed when we are happy with the performance impact.
1272 #
1272 #
1273 # Once this feature is no longer experimental move the following
1273 # Once this feature is no longer experimental move the following
1274 # documentation to the appropriate help section:
1274 # documentation to the appropriate help section:
1275 #
1275 #
1276 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1276 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1277 # tags (new or changed or deleted tags). In addition the details of
1277 # tags (new or changed or deleted tags). In addition the details of
1278 # these changes are made available in a file at:
1278 # these changes are made available in a file at:
1279 # ``REPOROOT/.hg/changes/tags.changes``.
1279 # ``REPOROOT/.hg/changes/tags.changes``.
1280 # Make sure you check for HG_TAG_MOVED before reading that file as it
1280 # Make sure you check for HG_TAG_MOVED before reading that file as it
1281 # might exist from a previous transaction even if no tag were touched
1281 # might exist from a previous transaction even if no tag were touched
1282 # in this one. Changes are recorded in a line base format::
1282 # in this one. Changes are recorded in a line base format::
1283 #
1283 #
1284 # <action> <hex-node> <tag-name>\n
1284 # <action> <hex-node> <tag-name>\n
1285 #
1285 #
1286 # Actions are defined as follow:
1286 # Actions are defined as follow:
1287 # "-R": tag is removed,
1287 # "-R": tag is removed,
1288 # "+A": tag is added,
1288 # "+A": tag is added,
1289 # "-M": tag is moved (old value),
1289 # "-M": tag is moved (old value),
1290 # "+M": tag is moved (new value),
1290 # "+M": tag is moved (new value),
1291 tracktags = lambda x: None
1291 tracktags = lambda x: None
1292 # experimental config: experimental.hook-track-tags
1292 # experimental config: experimental.hook-track-tags
1293 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1293 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1294 if desc != 'strip' and shouldtracktags:
1294 if desc != 'strip' and shouldtracktags:
1295 oldheads = self.changelog.headrevs()
1295 oldheads = self.changelog.headrevs()
1296 def tracktags(tr2):
1296 def tracktags(tr2):
1297 repo = reporef()
1297 repo = reporef()
1298 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1298 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1299 newheads = repo.changelog.headrevs()
1299 newheads = repo.changelog.headrevs()
1300 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1300 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1301 # notes: we compare lists here.
1301 # notes: we compare lists here.
1302 # As we do it only once buiding set would not be cheaper
1302 # As we do it only once buiding set would not be cheaper
1303 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1303 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1304 if changes:
1304 if changes:
1305 tr2.hookargs['tag_moved'] = '1'
1305 tr2.hookargs['tag_moved'] = '1'
1306 with repo.vfs('changes/tags.changes', 'w',
1306 with repo.vfs('changes/tags.changes', 'w',
1307 atomictemp=True) as changesfile:
1307 atomictemp=True) as changesfile:
1308 # note: we do not register the file to the transaction
1308 # note: we do not register the file to the transaction
1309 # because we needs it to still exist on the transaction
1309 # because we needs it to still exist on the transaction
1310 # is close (for txnclose hooks)
1310 # is close (for txnclose hooks)
1311 tagsmod.writediff(changesfile, changes)
1311 tagsmod.writediff(changesfile, changes)
1312 def validate(tr2):
1312 def validate(tr2):
1313 """will run pre-closing hooks"""
1313 """will run pre-closing hooks"""
1314 # XXX the transaction API is a bit lacking here so we take a hacky
1314 # XXX the transaction API is a bit lacking here so we take a hacky
1315 # path for now
1315 # path for now
1316 #
1316 #
1317 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1317 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1318 # dict is copied before these run. In addition we needs the data
1318 # dict is copied before these run. In addition we needs the data
1319 # available to in memory hooks too.
1319 # available to in memory hooks too.
1320 #
1320 #
1321 # Moreover, we also need to make sure this runs before txnclose
1321 # Moreover, we also need to make sure this runs before txnclose
1322 # hooks and there is no "pending" mechanism that would execute
1322 # hooks and there is no "pending" mechanism that would execute
1323 # logic only if hooks are about to run.
1323 # logic only if hooks are about to run.
1324 #
1324 #
1325 # Fixing this limitation of the transaction is also needed to track
1325 # Fixing this limitation of the transaction is also needed to track
1326 # other families of changes (bookmarks, phases, obsolescence).
1326 # other families of changes (bookmarks, phases, obsolescence).
1327 #
1327 #
1328 # This will have to be fixed before we remove the experimental
1328 # This will have to be fixed before we remove the experimental
1329 # gating.
1329 # gating.
1330 tracktags(tr2)
1330 tracktags(tr2)
1331 repo = reporef()
1331 repo = reporef()
1332 if repo.ui.configbool('experimental', 'single-head-per-branch'):
1332 if repo.ui.configbool('experimental', 'single-head-per-branch'):
1333 scmutil.enforcesinglehead(repo, tr2, desc)
1333 scmutil.enforcesinglehead(repo, tr2, desc)
1334 if hook.hashook(repo.ui, 'pretxnclose-bookmark'):
1334 if hook.hashook(repo.ui, 'pretxnclose-bookmark'):
1335 for name, (old, new) in sorted(tr.changes['bookmarks'].items()):
1335 for name, (old, new) in sorted(tr.changes['bookmarks'].items()):
1336 args = tr.hookargs.copy()
1336 args = tr.hookargs.copy()
1337 args.update(bookmarks.preparehookargs(name, old, new))
1337 args.update(bookmarks.preparehookargs(name, old, new))
1338 repo.hook('pretxnclose-bookmark', throw=True,
1338 repo.hook('pretxnclose-bookmark', throw=True,
1339 txnname=desc,
1339 txnname=desc,
1340 **pycompat.strkwargs(args))
1340 **pycompat.strkwargs(args))
1341 if hook.hashook(repo.ui, 'pretxnclose-phase'):
1341 if hook.hashook(repo.ui, 'pretxnclose-phase'):
1342 cl = repo.unfiltered().changelog
1342 cl = repo.unfiltered().changelog
1343 for rev, (old, new) in tr.changes['phases'].items():
1343 for rev, (old, new) in tr.changes['phases'].items():
1344 args = tr.hookargs.copy()
1344 args = tr.hookargs.copy()
1345 node = hex(cl.node(rev))
1345 node = hex(cl.node(rev))
1346 args.update(phases.preparehookargs(node, old, new))
1346 args.update(phases.preparehookargs(node, old, new))
1347 repo.hook('pretxnclose-phase', throw=True, txnname=desc,
1347 repo.hook('pretxnclose-phase', throw=True, txnname=desc,
1348 **pycompat.strkwargs(args))
1348 **pycompat.strkwargs(args))
1349
1349
1350 repo.hook('pretxnclose', throw=True,
1350 repo.hook('pretxnclose', throw=True,
1351 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1351 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1352 def releasefn(tr, success):
1352 def releasefn(tr, success):
1353 repo = reporef()
1353 repo = reporef()
1354 if success:
1354 if success:
1355 # this should be explicitly invoked here, because
1355 # this should be explicitly invoked here, because
1356 # in-memory changes aren't written out at closing
1356 # in-memory changes aren't written out at closing
1357 # transaction, if tr.addfilegenerator (via
1357 # transaction, if tr.addfilegenerator (via
1358 # dirstate.write or so) isn't invoked while
1358 # dirstate.write or so) isn't invoked while
1359 # transaction running
1359 # transaction running
1360 repo.dirstate.write(None)
1360 repo.dirstate.write(None)
1361 else:
1361 else:
1362 # discard all changes (including ones already written
1362 # discard all changes (including ones already written
1363 # out) in this transaction
1363 # out) in this transaction
1364 repo.dirstate.restorebackup(None, 'journal.dirstate')
1364 repo.dirstate.restorebackup(None, 'journal.dirstate')
1365
1365
1366 repo.invalidate(clearfilecache=True)
1366 repo.invalidate(clearfilecache=True)
1367
1367
1368 tr = transaction.transaction(rp, self.svfs, vfsmap,
1368 tr = transaction.transaction(rp, self.svfs, vfsmap,
1369 "journal",
1369 "journal",
1370 "undo",
1370 "undo",
1371 aftertrans(renames),
1371 aftertrans(renames),
1372 self.store.createmode,
1372 self.store.createmode,
1373 validator=validate,
1373 validator=validate,
1374 releasefn=releasefn,
1374 releasefn=releasefn,
1375 checkambigfiles=_cachedfiles,
1375 checkambigfiles=_cachedfiles,
1376 name=desc)
1376 name=desc)
1377 tr.changes['revs'] = xrange(0, 0)
1377 tr.changes['revs'] = xrange(0, 0)
1378 tr.changes['obsmarkers'] = set()
1378 tr.changes['obsmarkers'] = set()
1379 tr.changes['phases'] = {}
1379 tr.changes['phases'] = {}
1380 tr.changes['bookmarks'] = {}
1380 tr.changes['bookmarks'] = {}
1381
1381
1382 tr.hookargs['txnid'] = txnid
1382 tr.hookargs['txnid'] = txnid
1383 # note: writing the fncache only during finalize mean that the file is
1383 # note: writing the fncache only during finalize mean that the file is
1384 # outdated when running hooks. As fncache is used for streaming clone,
1384 # outdated when running hooks. As fncache is used for streaming clone,
1385 # this is not expected to break anything that happen during the hooks.
1385 # this is not expected to break anything that happen during the hooks.
1386 tr.addfinalize('flush-fncache', self.store.write)
1386 tr.addfinalize('flush-fncache', self.store.write)
1387 def txnclosehook(tr2):
1387 def txnclosehook(tr2):
1388 """To be run if transaction is successful, will schedule a hook run
1388 """To be run if transaction is successful, will schedule a hook run
1389 """
1389 """
1390 # Don't reference tr2 in hook() so we don't hold a reference.
1390 # Don't reference tr2 in hook() so we don't hold a reference.
1391 # This reduces memory consumption when there are multiple
1391 # This reduces memory consumption when there are multiple
1392 # transactions per lock. This can likely go away if issue5045
1392 # transactions per lock. This can likely go away if issue5045
1393 # fixes the function accumulation.
1393 # fixes the function accumulation.
1394 hookargs = tr2.hookargs
1394 hookargs = tr2.hookargs
1395
1395
1396 def hookfunc():
1396 def hookfunc():
1397 repo = reporef()
1397 repo = reporef()
1398 if hook.hashook(repo.ui, 'txnclose-bookmark'):
1398 if hook.hashook(repo.ui, 'txnclose-bookmark'):
1399 bmchanges = sorted(tr.changes['bookmarks'].items())
1399 bmchanges = sorted(tr.changes['bookmarks'].items())
1400 for name, (old, new) in bmchanges:
1400 for name, (old, new) in bmchanges:
1401 args = tr.hookargs.copy()
1401 args = tr.hookargs.copy()
1402 args.update(bookmarks.preparehookargs(name, old, new))
1402 args.update(bookmarks.preparehookargs(name, old, new))
1403 repo.hook('txnclose-bookmark', throw=False,
1403 repo.hook('txnclose-bookmark', throw=False,
1404 txnname=desc, **pycompat.strkwargs(args))
1404 txnname=desc, **pycompat.strkwargs(args))
1405
1405
1406 if hook.hashook(repo.ui, 'txnclose-phase'):
1406 if hook.hashook(repo.ui, 'txnclose-phase'):
1407 cl = repo.unfiltered().changelog
1407 cl = repo.unfiltered().changelog
1408 phasemv = sorted(tr.changes['phases'].items())
1408 phasemv = sorted(tr.changes['phases'].items())
1409 for rev, (old, new) in phasemv:
1409 for rev, (old, new) in phasemv:
1410 args = tr.hookargs.copy()
1410 args = tr.hookargs.copy()
1411 node = hex(cl.node(rev))
1411 node = hex(cl.node(rev))
1412 args.update(phases.preparehookargs(node, old, new))
1412 args.update(phases.preparehookargs(node, old, new))
1413 repo.hook('txnclose-phase', throw=False, txnname=desc,
1413 repo.hook('txnclose-phase', throw=False, txnname=desc,
1414 **pycompat.strkwargs(args))
1414 **pycompat.strkwargs(args))
1415
1415
1416 repo.hook('txnclose', throw=False, txnname=desc,
1416 repo.hook('txnclose', throw=False, txnname=desc,
1417 **pycompat.strkwargs(hookargs))
1417 **pycompat.strkwargs(hookargs))
1418 reporef()._afterlock(hookfunc)
1418 reporef()._afterlock(hookfunc)
1419 tr.addfinalize('txnclose-hook', txnclosehook)
1419 tr.addfinalize('txnclose-hook', txnclosehook)
1420 # Include a leading "-" to make it happen before the transaction summary
1420 # Include a leading "-" to make it happen before the transaction summary
1421 # reports registered via scmutil.registersummarycallback() whose names
1421 # reports registered via scmutil.registersummarycallback() whose names
1422 # are 00-txnreport etc. That way, the caches will be warm when the
1422 # are 00-txnreport etc. That way, the caches will be warm when the
1423 # callbacks run.
1423 # callbacks run.
1424 tr.addpostclose('-warm-cache', self._buildcacheupdater(tr))
1424 tr.addpostclose('-warm-cache', self._buildcacheupdater(tr))
1425 def txnaborthook(tr2):
1425 def txnaborthook(tr2):
1426 """To be run if transaction is aborted
1426 """To be run if transaction is aborted
1427 """
1427 """
1428 reporef().hook('txnabort', throw=False, txnname=desc,
1428 reporef().hook('txnabort', throw=False, txnname=desc,
1429 **pycompat.strkwargs(tr2.hookargs))
1429 **pycompat.strkwargs(tr2.hookargs))
1430 tr.addabort('txnabort-hook', txnaborthook)
1430 tr.addabort('txnabort-hook', txnaborthook)
1431 # avoid eager cache invalidation. in-memory data should be identical
1431 # avoid eager cache invalidation. in-memory data should be identical
1432 # to stored data if transaction has no error.
1432 # to stored data if transaction has no error.
1433 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1433 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1434 self._transref = weakref.ref(tr)
1434 self._transref = weakref.ref(tr)
1435 scmutil.registersummarycallback(self, tr, desc)
1435 scmutil.registersummarycallback(self, tr, desc)
1436 return tr
1436 return tr
1437
1437
1438 def _journalfiles(self):
1438 def _journalfiles(self):
1439 return ((self.svfs, 'journal'),
1439 return ((self.svfs, 'journal'),
1440 (self.vfs, 'journal.dirstate'),
1440 (self.vfs, 'journal.dirstate'),
1441 (self.vfs, 'journal.branch'),
1441 (self.vfs, 'journal.branch'),
1442 (self.vfs, 'journal.desc'),
1442 (self.vfs, 'journal.desc'),
1443 (self.vfs, 'journal.bookmarks'),
1443 (self.vfs, 'journal.bookmarks'),
1444 (self.svfs, 'journal.phaseroots'))
1444 (self.svfs, 'journal.phaseroots'))
1445
1445
1446 def undofiles(self):
1446 def undofiles(self):
1447 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1447 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1448
1448
1449 @unfilteredmethod
1449 @unfilteredmethod
1450 def _writejournal(self, desc):
1450 def _writejournal(self, desc):
1451 self.dirstate.savebackup(None, 'journal.dirstate')
1451 self.dirstate.savebackup(None, 'journal.dirstate')
1452 self.vfs.write("journal.branch",
1452 self.vfs.write("journal.branch",
1453 encoding.fromlocal(self.dirstate.branch()))
1453 encoding.fromlocal(self.dirstate.branch()))
1454 self.vfs.write("journal.desc",
1454 self.vfs.write("journal.desc",
1455 "%d\n%s\n" % (len(self), desc))
1455 "%d\n%s\n" % (len(self), desc))
1456 self.vfs.write("journal.bookmarks",
1456 self.vfs.write("journal.bookmarks",
1457 self.vfs.tryread("bookmarks"))
1457 self.vfs.tryread("bookmarks"))
1458 self.svfs.write("journal.phaseroots",
1458 self.svfs.write("journal.phaseroots",
1459 self.svfs.tryread("phaseroots"))
1459 self.svfs.tryread("phaseroots"))
1460
1460
1461 def recover(self):
1461 def recover(self):
1462 with self.lock():
1462 with self.lock():
1463 if self.svfs.exists("journal"):
1463 if self.svfs.exists("journal"):
1464 self.ui.status(_("rolling back interrupted transaction\n"))
1464 self.ui.status(_("rolling back interrupted transaction\n"))
1465 vfsmap = {'': self.svfs,
1465 vfsmap = {'': self.svfs,
1466 'plain': self.vfs,}
1466 'plain': self.vfs,}
1467 transaction.rollback(self.svfs, vfsmap, "journal",
1467 transaction.rollback(self.svfs, vfsmap, "journal",
1468 self.ui.warn,
1468 self.ui.warn,
1469 checkambigfiles=_cachedfiles)
1469 checkambigfiles=_cachedfiles)
1470 self.invalidate()
1470 self.invalidate()
1471 return True
1471 return True
1472 else:
1472 else:
1473 self.ui.warn(_("no interrupted transaction available\n"))
1473 self.ui.warn(_("no interrupted transaction available\n"))
1474 return False
1474 return False
1475
1475
1476 def rollback(self, dryrun=False, force=False):
1476 def rollback(self, dryrun=False, force=False):
1477 wlock = lock = dsguard = None
1477 wlock = lock = dsguard = None
1478 try:
1478 try:
1479 wlock = self.wlock()
1479 wlock = self.wlock()
1480 lock = self.lock()
1480 lock = self.lock()
1481 if self.svfs.exists("undo"):
1481 if self.svfs.exists("undo"):
1482 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1482 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1483
1483
1484 return self._rollback(dryrun, force, dsguard)
1484 return self._rollback(dryrun, force, dsguard)
1485 else:
1485 else:
1486 self.ui.warn(_("no rollback information available\n"))
1486 self.ui.warn(_("no rollback information available\n"))
1487 return 1
1487 return 1
1488 finally:
1488 finally:
1489 release(dsguard, lock, wlock)
1489 release(dsguard, lock, wlock)
1490
1490
1491 @unfilteredmethod # Until we get smarter cache management
1491 @unfilteredmethod # Until we get smarter cache management
1492 def _rollback(self, dryrun, force, dsguard):
1492 def _rollback(self, dryrun, force, dsguard):
1493 ui = self.ui
1493 ui = self.ui
1494 try:
1494 try:
1495 args = self.vfs.read('undo.desc').splitlines()
1495 args = self.vfs.read('undo.desc').splitlines()
1496 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1496 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1497 if len(args) >= 3:
1497 if len(args) >= 3:
1498 detail = args[2]
1498 detail = args[2]
1499 oldtip = oldlen - 1
1499 oldtip = oldlen - 1
1500
1500
1501 if detail and ui.verbose:
1501 if detail and ui.verbose:
1502 msg = (_('repository tip rolled back to revision %d'
1502 msg = (_('repository tip rolled back to revision %d'
1503 ' (undo %s: %s)\n')
1503 ' (undo %s: %s)\n')
1504 % (oldtip, desc, detail))
1504 % (oldtip, desc, detail))
1505 else:
1505 else:
1506 msg = (_('repository tip rolled back to revision %d'
1506 msg = (_('repository tip rolled back to revision %d'
1507 ' (undo %s)\n')
1507 ' (undo %s)\n')
1508 % (oldtip, desc))
1508 % (oldtip, desc))
1509 except IOError:
1509 except IOError:
1510 msg = _('rolling back unknown transaction\n')
1510 msg = _('rolling back unknown transaction\n')
1511 desc = None
1511 desc = None
1512
1512
1513 if not force and self['.'] != self['tip'] and desc == 'commit':
1513 if not force and self['.'] != self['tip'] and desc == 'commit':
1514 raise error.Abort(
1514 raise error.Abort(
1515 _('rollback of last commit while not checked out '
1515 _('rollback of last commit while not checked out '
1516 'may lose data'), hint=_('use -f to force'))
1516 'may lose data'), hint=_('use -f to force'))
1517
1517
1518 ui.status(msg)
1518 ui.status(msg)
1519 if dryrun:
1519 if dryrun:
1520 return 0
1520 return 0
1521
1521
1522 parents = self.dirstate.parents()
1522 parents = self.dirstate.parents()
1523 self.destroying()
1523 self.destroying()
1524 vfsmap = {'plain': self.vfs, '': self.svfs}
1524 vfsmap = {'plain': self.vfs, '': self.svfs}
1525 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1525 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1526 checkambigfiles=_cachedfiles)
1526 checkambigfiles=_cachedfiles)
1527 if self.vfs.exists('undo.bookmarks'):
1527 if self.vfs.exists('undo.bookmarks'):
1528 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1528 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1529 if self.svfs.exists('undo.phaseroots'):
1529 if self.svfs.exists('undo.phaseroots'):
1530 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1530 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1531 self.invalidate()
1531 self.invalidate()
1532
1532
1533 parentgone = (parents[0] not in self.changelog.nodemap or
1533 parentgone = (parents[0] not in self.changelog.nodemap or
1534 parents[1] not in self.changelog.nodemap)
1534 parents[1] not in self.changelog.nodemap)
1535 if parentgone:
1535 if parentgone:
1536 # prevent dirstateguard from overwriting already restored one
1536 # prevent dirstateguard from overwriting already restored one
1537 dsguard.close()
1537 dsguard.close()
1538
1538
1539 self.dirstate.restorebackup(None, 'undo.dirstate')
1539 self.dirstate.restorebackup(None, 'undo.dirstate')
1540 try:
1540 try:
1541 branch = self.vfs.read('undo.branch')
1541 branch = self.vfs.read('undo.branch')
1542 self.dirstate.setbranch(encoding.tolocal(branch))
1542 self.dirstate.setbranch(encoding.tolocal(branch))
1543 except IOError:
1543 except IOError:
1544 ui.warn(_('named branch could not be reset: '
1544 ui.warn(_('named branch could not be reset: '
1545 'current branch is still \'%s\'\n')
1545 'current branch is still \'%s\'\n')
1546 % self.dirstate.branch())
1546 % self.dirstate.branch())
1547
1547
1548 parents = tuple([p.rev() for p in self[None].parents()])
1548 parents = tuple([p.rev() for p in self[None].parents()])
1549 if len(parents) > 1:
1549 if len(parents) > 1:
1550 ui.status(_('working directory now based on '
1550 ui.status(_('working directory now based on '
1551 'revisions %d and %d\n') % parents)
1551 'revisions %d and %d\n') % parents)
1552 else:
1552 else:
1553 ui.status(_('working directory now based on '
1553 ui.status(_('working directory now based on '
1554 'revision %d\n') % parents)
1554 'revision %d\n') % parents)
1555 mergemod.mergestate.clean(self, self['.'].node())
1555 mergemod.mergestate.clean(self, self['.'].node())
1556
1556
1557 # TODO: if we know which new heads may result from this rollback, pass
1557 # TODO: if we know which new heads may result from this rollback, pass
1558 # them to destroy(), which will prevent the branchhead cache from being
1558 # them to destroy(), which will prevent the branchhead cache from being
1559 # invalidated.
1559 # invalidated.
1560 self.destroyed()
1560 self.destroyed()
1561 return 0
1561 return 0
1562
1562
1563 def _buildcacheupdater(self, newtransaction):
1563 def _buildcacheupdater(self, newtransaction):
1564 """called during transaction to build the callback updating cache
1564 """called during transaction to build the callback updating cache
1565
1565
1566 Lives on the repository to help extension who might want to augment
1566 Lives on the repository to help extension who might want to augment
1567 this logic. For this purpose, the created transaction is passed to the
1567 this logic. For this purpose, the created transaction is passed to the
1568 method.
1568 method.
1569 """
1569 """
1570 # we must avoid cyclic reference between repo and transaction.
1570 # we must avoid cyclic reference between repo and transaction.
1571 reporef = weakref.ref(self)
1571 reporef = weakref.ref(self)
1572 def updater(tr):
1572 def updater(tr):
1573 repo = reporef()
1573 repo = reporef()
1574 repo.updatecaches(tr)
1574 repo.updatecaches(tr)
1575 return updater
1575 return updater
1576
1576
1577 @unfilteredmethod
1577 @unfilteredmethod
1578 def updatecaches(self, tr=None, full=False):
1578 def updatecaches(self, tr=None, full=False):
1579 """warm appropriate caches
1579 """warm appropriate caches
1580
1580
1581 If this function is called after a transaction closed. The transaction
1581 If this function is called after a transaction closed. The transaction
1582 will be available in the 'tr' argument. This can be used to selectively
1582 will be available in the 'tr' argument. This can be used to selectively
1583 update caches relevant to the changes in that transaction.
1583 update caches relevant to the changes in that transaction.
1584
1584
1585 If 'full' is set, make sure all caches the function knows about have
1585 If 'full' is set, make sure all caches the function knows about have
1586 up-to-date data. Even the ones usually loaded more lazily.
1586 up-to-date data. Even the ones usually loaded more lazily.
1587 """
1587 """
1588 if tr is not None and tr.hookargs.get('source') == 'strip':
1588 if tr is not None and tr.hookargs.get('source') == 'strip':
1589 # During strip, many caches are invalid but
1589 # During strip, many caches are invalid but
1590 # later call to `destroyed` will refresh them.
1590 # later call to `destroyed` will refresh them.
1591 return
1591 return
1592
1592
1593 if tr is None or tr.changes['revs']:
1593 if tr is None or tr.changes['revs']:
1594 # updating the unfiltered branchmap should refresh all the others,
1594 # updating the unfiltered branchmap should refresh all the others,
1595 self.ui.debug('updating the branch cache\n')
1595 self.ui.debug('updating the branch cache\n')
1596 branchmap.updatecache(self.filtered('served'))
1596 branchmap.updatecache(self.filtered('served'))
1597
1597
1598 if full:
1598 if full:
1599 rbc = self.revbranchcache()
1599 rbc = self.revbranchcache()
1600 for r in self.changelog:
1600 for r in self.changelog:
1601 rbc.branchinfo(r)
1601 rbc.branchinfo(r)
1602 rbc.write()
1602 rbc.write()
1603
1603
1604 def invalidatecaches(self):
1604 def invalidatecaches(self):
1605
1605
1606 if '_tagscache' in vars(self):
1606 if '_tagscache' in vars(self):
1607 # can't use delattr on proxy
1607 # can't use delattr on proxy
1608 del self.__dict__['_tagscache']
1608 del self.__dict__['_tagscache']
1609
1609
1610 self.unfiltered()._branchcaches.clear()
1610 self.unfiltered()._branchcaches.clear()
1611 self.invalidatevolatilesets()
1611 self.invalidatevolatilesets()
1612 self._sparsesignaturecache.clear()
1612 self._sparsesignaturecache.clear()
1613
1613
1614 def invalidatevolatilesets(self):
1614 def invalidatevolatilesets(self):
1615 self.filteredrevcache.clear()
1615 self.filteredrevcache.clear()
1616 obsolete.clearobscaches(self)
1616 obsolete.clearobscaches(self)
1617
1617
1618 def invalidatedirstate(self):
1618 def invalidatedirstate(self):
1619 '''Invalidates the dirstate, causing the next call to dirstate
1619 '''Invalidates the dirstate, causing the next call to dirstate
1620 to check if it was modified since the last time it was read,
1620 to check if it was modified since the last time it was read,
1621 rereading it if it has.
1621 rereading it if it has.
1622
1622
1623 This is different to dirstate.invalidate() that it doesn't always
1623 This is different to dirstate.invalidate() that it doesn't always
1624 rereads the dirstate. Use dirstate.invalidate() if you want to
1624 rereads the dirstate. Use dirstate.invalidate() if you want to
1625 explicitly read the dirstate again (i.e. restoring it to a previous
1625 explicitly read the dirstate again (i.e. restoring it to a previous
1626 known good state).'''
1626 known good state).'''
1627 if hasunfilteredcache(self, 'dirstate'):
1627 if hasunfilteredcache(self, 'dirstate'):
1628 for k in self.dirstate._filecache:
1628 for k in self.dirstate._filecache:
1629 try:
1629 try:
1630 delattr(self.dirstate, k)
1630 delattr(self.dirstate, k)
1631 except AttributeError:
1631 except AttributeError:
1632 pass
1632 pass
1633 delattr(self.unfiltered(), 'dirstate')
1633 delattr(self.unfiltered(), 'dirstate')
1634
1634
1635 def invalidate(self, clearfilecache=False):
1635 def invalidate(self, clearfilecache=False):
1636 '''Invalidates both store and non-store parts other than dirstate
1636 '''Invalidates both store and non-store parts other than dirstate
1637
1637
1638 If a transaction is running, invalidation of store is omitted,
1638 If a transaction is running, invalidation of store is omitted,
1639 because discarding in-memory changes might cause inconsistency
1639 because discarding in-memory changes might cause inconsistency
1640 (e.g. incomplete fncache causes unintentional failure, but
1640 (e.g. incomplete fncache causes unintentional failure, but
1641 redundant one doesn't).
1641 redundant one doesn't).
1642 '''
1642 '''
1643 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1643 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1644 for k in list(self._filecache.keys()):
1644 for k in list(self._filecache.keys()):
1645 # dirstate is invalidated separately in invalidatedirstate()
1645 # dirstate is invalidated separately in invalidatedirstate()
1646 if k == 'dirstate':
1646 if k == 'dirstate':
1647 continue
1647 continue
1648 if (k == 'changelog' and
1648 if (k == 'changelog' and
1649 self.currenttransaction() and
1649 self.currenttransaction() and
1650 self.changelog._delayed):
1650 self.changelog._delayed):
1651 # The changelog object may store unwritten revisions. We don't
1651 # The changelog object may store unwritten revisions. We don't
1652 # want to lose them.
1652 # want to lose them.
1653 # TODO: Solve the problem instead of working around it.
1653 # TODO: Solve the problem instead of working around it.
1654 continue
1654 continue
1655
1655
1656 if clearfilecache:
1656 if clearfilecache:
1657 del self._filecache[k]
1657 del self._filecache[k]
1658 try:
1658 try:
1659 delattr(unfiltered, k)
1659 delattr(unfiltered, k)
1660 except AttributeError:
1660 except AttributeError:
1661 pass
1661 pass
1662 self.invalidatecaches()
1662 self.invalidatecaches()
1663 if not self.currenttransaction():
1663 if not self.currenttransaction():
1664 # TODO: Changing contents of store outside transaction
1664 # TODO: Changing contents of store outside transaction
1665 # causes inconsistency. We should make in-memory store
1665 # causes inconsistency. We should make in-memory store
1666 # changes detectable, and abort if changed.
1666 # changes detectable, and abort if changed.
1667 self.store.invalidatecaches()
1667 self.store.invalidatecaches()
1668
1668
1669 def invalidateall(self):
1669 def invalidateall(self):
1670 '''Fully invalidates both store and non-store parts, causing the
1670 '''Fully invalidates both store and non-store parts, causing the
1671 subsequent operation to reread any outside changes.'''
1671 subsequent operation to reread any outside changes.'''
1672 # extension should hook this to invalidate its caches
1672 # extension should hook this to invalidate its caches
1673 self.invalidate()
1673 self.invalidate()
1674 self.invalidatedirstate()
1674 self.invalidatedirstate()
1675
1675
1676 @unfilteredmethod
1676 @unfilteredmethod
1677 def _refreshfilecachestats(self, tr):
1677 def _refreshfilecachestats(self, tr):
1678 """Reload stats of cached files so that they are flagged as valid"""
1678 """Reload stats of cached files so that they are flagged as valid"""
1679 for k, ce in self._filecache.items():
1679 for k, ce in self._filecache.items():
1680 k = pycompat.sysstr(k)
1680 k = pycompat.sysstr(k)
1681 if k == r'dirstate' or k not in self.__dict__:
1681 if k == r'dirstate' or k not in self.__dict__:
1682 continue
1682 continue
1683 ce.refresh()
1683 ce.refresh()
1684
1684
1685 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1685 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1686 inheritchecker=None, parentenvvar=None):
1686 inheritchecker=None, parentenvvar=None):
1687 parentlock = None
1687 parentlock = None
1688 # the contents of parentenvvar are used by the underlying lock to
1688 # the contents of parentenvvar are used by the underlying lock to
1689 # determine whether it can be inherited
1689 # determine whether it can be inherited
1690 if parentenvvar is not None:
1690 if parentenvvar is not None:
1691 parentlock = encoding.environ.get(parentenvvar)
1691 parentlock = encoding.environ.get(parentenvvar)
1692
1692
1693 timeout = 0
1693 timeout = 0
1694 warntimeout = 0
1694 warntimeout = 0
1695 if wait:
1695 if wait:
1696 timeout = self.ui.configint("ui", "timeout")
1696 timeout = self.ui.configint("ui", "timeout")
1697 warntimeout = self.ui.configint("ui", "timeout.warn")
1697 warntimeout = self.ui.configint("ui", "timeout.warn")
1698
1698
1699 l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout,
1699 l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout,
1700 releasefn=releasefn,
1700 releasefn=releasefn,
1701 acquirefn=acquirefn, desc=desc,
1701 acquirefn=acquirefn, desc=desc,
1702 inheritchecker=inheritchecker,
1702 inheritchecker=inheritchecker,
1703 parentlock=parentlock)
1703 parentlock=parentlock)
1704 return l
1704 return l
1705
1705
1706 def _afterlock(self, callback):
1706 def _afterlock(self, callback):
1707 """add a callback to be run when the repository is fully unlocked
1707 """add a callback to be run when the repository is fully unlocked
1708
1708
1709 The callback will be executed when the outermost lock is released
1709 The callback will be executed when the outermost lock is released
1710 (with wlock being higher level than 'lock')."""
1710 (with wlock being higher level than 'lock')."""
1711 for ref in (self._wlockref, self._lockref):
1711 for ref in (self._wlockref, self._lockref):
1712 l = ref and ref()
1712 l = ref and ref()
1713 if l and l.held:
1713 if l and l.held:
1714 l.postrelease.append(callback)
1714 l.postrelease.append(callback)
1715 break
1715 break
1716 else: # no lock have been found.
1716 else: # no lock have been found.
1717 callback()
1717 callback()
1718
1718
1719 def lock(self, wait=True):
1719 def lock(self, wait=True):
1720 '''Lock the repository store (.hg/store) and return a weak reference
1720 '''Lock the repository store (.hg/store) and return a weak reference
1721 to the lock. Use this before modifying the store (e.g. committing or
1721 to the lock. Use this before modifying the store (e.g. committing or
1722 stripping). If you are opening a transaction, get a lock as well.)
1722 stripping). If you are opening a transaction, get a lock as well.)
1723
1723
1724 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1724 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1725 'wlock' first to avoid a dead-lock hazard.'''
1725 'wlock' first to avoid a dead-lock hazard.'''
1726 l = self._currentlock(self._lockref)
1726 l = self._currentlock(self._lockref)
1727 if l is not None:
1727 if l is not None:
1728 l.lock()
1728 l.lock()
1729 return l
1729 return l
1730
1730
1731 l = self._lock(self.svfs, "lock", wait, None,
1731 l = self._lock(self.svfs, "lock", wait, None,
1732 self.invalidate, _('repository %s') % self.origroot)
1732 self.invalidate, _('repository %s') % self.origroot)
1733 self._lockref = weakref.ref(l)
1733 self._lockref = weakref.ref(l)
1734 return l
1734 return l
1735
1735
1736 def _wlockchecktransaction(self):
1736 def _wlockchecktransaction(self):
1737 if self.currenttransaction() is not None:
1737 if self.currenttransaction() is not None:
1738 raise error.LockInheritanceContractViolation(
1738 raise error.LockInheritanceContractViolation(
1739 'wlock cannot be inherited in the middle of a transaction')
1739 'wlock cannot be inherited in the middle of a transaction')
1740
1740
1741 def wlock(self, wait=True):
1741 def wlock(self, wait=True):
1742 '''Lock the non-store parts of the repository (everything under
1742 '''Lock the non-store parts of the repository (everything under
1743 .hg except .hg/store) and return a weak reference to the lock.
1743 .hg except .hg/store) and return a weak reference to the lock.
1744
1744
1745 Use this before modifying files in .hg.
1745 Use this before modifying files in .hg.
1746
1746
1747 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1747 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1748 'wlock' first to avoid a dead-lock hazard.'''
1748 'wlock' first to avoid a dead-lock hazard.'''
1749 l = self._wlockref and self._wlockref()
1749 l = self._wlockref and self._wlockref()
1750 if l is not None and l.held:
1750 if l is not None and l.held:
1751 l.lock()
1751 l.lock()
1752 return l
1752 return l
1753
1753
1754 # We do not need to check for non-waiting lock acquisition. Such
1754 # We do not need to check for non-waiting lock acquisition. Such
1755 # acquisition would not cause dead-lock as they would just fail.
1755 # acquisition would not cause dead-lock as they would just fail.
1756 if wait and (self.ui.configbool('devel', 'all-warnings')
1756 if wait and (self.ui.configbool('devel', 'all-warnings')
1757 or self.ui.configbool('devel', 'check-locks')):
1757 or self.ui.configbool('devel', 'check-locks')):
1758 if self._currentlock(self._lockref) is not None:
1758 if self._currentlock(self._lockref) is not None:
1759 self.ui.develwarn('"wlock" acquired after "lock"')
1759 self.ui.develwarn('"wlock" acquired after "lock"')
1760
1760
1761 def unlock():
1761 def unlock():
1762 if self.dirstate.pendingparentchange():
1762 if self.dirstate.pendingparentchange():
1763 self.dirstate.invalidate()
1763 self.dirstate.invalidate()
1764 else:
1764 else:
1765 self.dirstate.write(None)
1765 self.dirstate.write(None)
1766
1766
1767 self._filecache['dirstate'].refresh()
1767 self._filecache['dirstate'].refresh()
1768
1768
1769 l = self._lock(self.vfs, "wlock", wait, unlock,
1769 l = self._lock(self.vfs, "wlock", wait, unlock,
1770 self.invalidatedirstate, _('working directory of %s') %
1770 self.invalidatedirstate, _('working directory of %s') %
1771 self.origroot,
1771 self.origroot,
1772 inheritchecker=self._wlockchecktransaction,
1772 inheritchecker=self._wlockchecktransaction,
1773 parentenvvar='HG_WLOCK_LOCKER')
1773 parentenvvar='HG_WLOCK_LOCKER')
1774 self._wlockref = weakref.ref(l)
1774 self._wlockref = weakref.ref(l)
1775 return l
1775 return l
1776
1776
1777 def _currentlock(self, lockref):
1777 def _currentlock(self, lockref):
1778 """Returns the lock if it's held, or None if it's not."""
1778 """Returns the lock if it's held, or None if it's not."""
1779 if lockref is None:
1779 if lockref is None:
1780 return None
1780 return None
1781 l = lockref()
1781 l = lockref()
1782 if l is None or not l.held:
1782 if l is None or not l.held:
1783 return None
1783 return None
1784 return l
1784 return l
1785
1785
1786 def currentwlock(self):
1786 def currentwlock(self):
1787 """Returns the wlock if it's held, or None if it's not."""
1787 """Returns the wlock if it's held, or None if it's not."""
1788 return self._currentlock(self._wlockref)
1788 return self._currentlock(self._wlockref)
1789
1789
1790 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1790 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1791 """
1791 """
1792 commit an individual file as part of a larger transaction
1792 commit an individual file as part of a larger transaction
1793 """
1793 """
1794
1794
1795 fname = fctx.path()
1795 fname = fctx.path()
1796 fparent1 = manifest1.get(fname, nullid)
1796 fparent1 = manifest1.get(fname, nullid)
1797 fparent2 = manifest2.get(fname, nullid)
1797 fparent2 = manifest2.get(fname, nullid)
1798 if isinstance(fctx, context.filectx):
1798 if isinstance(fctx, context.filectx):
1799 node = fctx.filenode()
1799 node = fctx.filenode()
1800 if node in [fparent1, fparent2]:
1800 if node in [fparent1, fparent2]:
1801 self.ui.debug('reusing %s filelog entry\n' % fname)
1801 self.ui.debug('reusing %s filelog entry\n' % fname)
1802 if manifest1.flags(fname) != fctx.flags():
1802 if manifest1.flags(fname) != fctx.flags():
1803 changelist.append(fname)
1803 changelist.append(fname)
1804 return node
1804 return node
1805
1805
1806 flog = self.file(fname)
1806 flog = self.file(fname)
1807 meta = {}
1807 meta = {}
1808 copy = fctx.renamed()
1808 copy = fctx.renamed()
1809 if copy and copy[0] != fname:
1809 if copy and copy[0] != fname:
1810 # Mark the new revision of this file as a copy of another
1810 # Mark the new revision of this file as a copy of another
1811 # file. This copy data will effectively act as a parent
1811 # file. This copy data will effectively act as a parent
1812 # of this new revision. If this is a merge, the first
1812 # of this new revision. If this is a merge, the first
1813 # parent will be the nullid (meaning "look up the copy data")
1813 # parent will be the nullid (meaning "look up the copy data")
1814 # and the second one will be the other parent. For example:
1814 # and the second one will be the other parent. For example:
1815 #
1815 #
1816 # 0 --- 1 --- 3 rev1 changes file foo
1816 # 0 --- 1 --- 3 rev1 changes file foo
1817 # \ / rev2 renames foo to bar and changes it
1817 # \ / rev2 renames foo to bar and changes it
1818 # \- 2 -/ rev3 should have bar with all changes and
1818 # \- 2 -/ rev3 should have bar with all changes and
1819 # should record that bar descends from
1819 # should record that bar descends from
1820 # bar in rev2 and foo in rev1
1820 # bar in rev2 and foo in rev1
1821 #
1821 #
1822 # this allows this merge to succeed:
1822 # this allows this merge to succeed:
1823 #
1823 #
1824 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1824 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1825 # \ / merging rev3 and rev4 should use bar@rev2
1825 # \ / merging rev3 and rev4 should use bar@rev2
1826 # \- 2 --- 4 as the merge base
1826 # \- 2 --- 4 as the merge base
1827 #
1827 #
1828
1828
1829 cfname = copy[0]
1829 cfname = copy[0]
1830 crev = manifest1.get(cfname)
1830 crev = manifest1.get(cfname)
1831 newfparent = fparent2
1831 newfparent = fparent2
1832
1832
1833 if manifest2: # branch merge
1833 if manifest2: # branch merge
1834 if fparent2 == nullid or crev is None: # copied on remote side
1834 if fparent2 == nullid or crev is None: # copied on remote side
1835 if cfname in manifest2:
1835 if cfname in manifest2:
1836 crev = manifest2[cfname]
1836 crev = manifest2[cfname]
1837 newfparent = fparent1
1837 newfparent = fparent1
1838
1838
1839 # Here, we used to search backwards through history to try to find
1839 # Here, we used to search backwards through history to try to find
1840 # where the file copy came from if the source of a copy was not in
1840 # where the file copy came from if the source of a copy was not in
1841 # the parent directory. However, this doesn't actually make sense to
1841 # the parent directory. However, this doesn't actually make sense to
1842 # do (what does a copy from something not in your working copy even
1842 # do (what does a copy from something not in your working copy even
1843 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1843 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1844 # the user that copy information was dropped, so if they didn't
1844 # the user that copy information was dropped, so if they didn't
1845 # expect this outcome it can be fixed, but this is the correct
1845 # expect this outcome it can be fixed, but this is the correct
1846 # behavior in this circumstance.
1846 # behavior in this circumstance.
1847
1847
1848 if crev:
1848 if crev:
1849 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1849 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1850 meta["copy"] = cfname
1850 meta["copy"] = cfname
1851 meta["copyrev"] = hex(crev)
1851 meta["copyrev"] = hex(crev)
1852 fparent1, fparent2 = nullid, newfparent
1852 fparent1, fparent2 = nullid, newfparent
1853 else:
1853 else:
1854 self.ui.warn(_("warning: can't find ancestor for '%s' "
1854 self.ui.warn(_("warning: can't find ancestor for '%s' "
1855 "copied from '%s'!\n") % (fname, cfname))
1855 "copied from '%s'!\n") % (fname, cfname))
1856
1856
1857 elif fparent1 == nullid:
1857 elif fparent1 == nullid:
1858 fparent1, fparent2 = fparent2, nullid
1858 fparent1, fparent2 = fparent2, nullid
1859 elif fparent2 != nullid:
1859 elif fparent2 != nullid:
1860 # is one parent an ancestor of the other?
1860 # is one parent an ancestor of the other?
1861 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1861 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1862 if fparent1 in fparentancestors:
1862 if fparent1 in fparentancestors:
1863 fparent1, fparent2 = fparent2, nullid
1863 fparent1, fparent2 = fparent2, nullid
1864 elif fparent2 in fparentancestors:
1864 elif fparent2 in fparentancestors:
1865 fparent2 = nullid
1865 fparent2 = nullid
1866
1866
1867 # is the file changed?
1867 # is the file changed?
1868 text = fctx.data()
1868 text = fctx.data()
1869 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1869 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1870 changelist.append(fname)
1870 changelist.append(fname)
1871 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1871 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1872 # are just the flags changed during merge?
1872 # are just the flags changed during merge?
1873 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1873 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1874 changelist.append(fname)
1874 changelist.append(fname)
1875
1875
1876 return fparent1
1876 return fparent1
1877
1877
1878 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1878 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1879 """check for commit arguments that aren't committable"""
1879 """check for commit arguments that aren't committable"""
1880 if match.isexact() or match.prefix():
1880 if match.isexact() or match.prefix():
1881 matched = set(status.modified + status.added + status.removed)
1881 matched = set(status.modified + status.added + status.removed)
1882
1882
1883 for f in match.files():
1883 for f in match.files():
1884 f = self.dirstate.normalize(f)
1884 f = self.dirstate.normalize(f)
1885 if f == '.' or f in matched or f in wctx.substate:
1885 if f == '.' or f in matched or f in wctx.substate:
1886 continue
1886 continue
1887 if f in status.deleted:
1887 if f in status.deleted:
1888 fail(f, _('file not found!'))
1888 fail(f, _('file not found!'))
1889 if f in vdirs: # visited directory
1889 if f in vdirs: # visited directory
1890 d = f + '/'
1890 d = f + '/'
1891 for mf in matched:
1891 for mf in matched:
1892 if mf.startswith(d):
1892 if mf.startswith(d):
1893 break
1893 break
1894 else:
1894 else:
1895 fail(f, _("no match under directory!"))
1895 fail(f, _("no match under directory!"))
1896 elif f not in self.dirstate:
1896 elif f not in self.dirstate:
1897 fail(f, _("file not tracked!"))
1897 fail(f, _("file not tracked!"))
1898
1898
1899 @unfilteredmethod
1899 @unfilteredmethod
1900 def commit(self, text="", user=None, date=None, match=None, force=False,
1900 def commit(self, text="", user=None, date=None, match=None, force=False,
1901 editor=False, extra=None):
1901 editor=False, extra=None):
1902 """Add a new revision to current repository.
1902 """Add a new revision to current repository.
1903
1903
1904 Revision information is gathered from the working directory,
1904 Revision information is gathered from the working directory,
1905 match can be used to filter the committed files. If editor is
1905 match can be used to filter the committed files. If editor is
1906 supplied, it is called to get a commit message.
1906 supplied, it is called to get a commit message.
1907 """
1907 """
1908 if extra is None:
1908 if extra is None:
1909 extra = {}
1909 extra = {}
1910
1910
1911 def fail(f, msg):
1911 def fail(f, msg):
1912 raise error.Abort('%s: %s' % (f, msg))
1912 raise error.Abort('%s: %s' % (f, msg))
1913
1913
1914 if not match:
1914 if not match:
1915 match = matchmod.always(self.root, '')
1915 match = matchmod.always(self.root, '')
1916
1916
1917 if not force:
1917 if not force:
1918 vdirs = []
1918 vdirs = []
1919 match.explicitdir = vdirs.append
1919 match.explicitdir = vdirs.append
1920 match.bad = fail
1920 match.bad = fail
1921
1921
1922 wlock = lock = tr = None
1922 wlock = lock = tr = None
1923 try:
1923 try:
1924 wlock = self.wlock()
1924 wlock = self.wlock()
1925 lock = self.lock() # for recent changelog (see issue4368)
1925 lock = self.lock() # for recent changelog (see issue4368)
1926
1926
1927 wctx = self[None]
1927 wctx = self[None]
1928 merge = len(wctx.parents()) > 1
1928 merge = len(wctx.parents()) > 1
1929
1929
1930 if not force and merge and not match.always():
1930 if not force and merge and not match.always():
1931 raise error.Abort(_('cannot partially commit a merge '
1931 raise error.Abort(_('cannot partially commit a merge '
1932 '(do not specify files or patterns)'))
1932 '(do not specify files or patterns)'))
1933
1933
1934 status = self.status(match=match, clean=force)
1934 status = self.status(match=match, clean=force)
1935 if force:
1935 if force:
1936 status.modified.extend(status.clean) # mq may commit clean files
1936 status.modified.extend(status.clean) # mq may commit clean files
1937
1937
1938 # check subrepos
1938 # check subrepos
1939 subs, commitsubs, newstate = subrepoutil.precommit(
1939 subs, commitsubs, newstate = subrepoutil.precommit(
1940 self.ui, wctx, status, match, force=force)
1940 self.ui, wctx, status, match, force=force)
1941
1941
1942 # make sure all explicit patterns are matched
1942 # make sure all explicit patterns are matched
1943 if not force:
1943 if not force:
1944 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1944 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1945
1945
1946 cctx = context.workingcommitctx(self, status,
1946 cctx = context.workingcommitctx(self, status,
1947 text, user, date, extra)
1947 text, user, date, extra)
1948
1948
1949 # internal config: ui.allowemptycommit
1949 # internal config: ui.allowemptycommit
1950 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1950 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1951 or extra.get('close') or merge or cctx.files()
1951 or extra.get('close') or merge or cctx.files()
1952 or self.ui.configbool('ui', 'allowemptycommit'))
1952 or self.ui.configbool('ui', 'allowemptycommit'))
1953 if not allowemptycommit:
1953 if not allowemptycommit:
1954 return None
1954 return None
1955
1955
1956 if merge and cctx.deleted():
1956 if merge and cctx.deleted():
1957 raise error.Abort(_("cannot commit merge with missing files"))
1957 raise error.Abort(_("cannot commit merge with missing files"))
1958
1958
1959 ms = mergemod.mergestate.read(self)
1959 ms = mergemod.mergestate.read(self)
1960 mergeutil.checkunresolved(ms)
1960 mergeutil.checkunresolved(ms)
1961
1961
1962 if editor:
1962 if editor:
1963 cctx._text = editor(self, cctx, subs)
1963 cctx._text = editor(self, cctx, subs)
1964 edited = (text != cctx._text)
1964 edited = (text != cctx._text)
1965
1965
1966 # Save commit message in case this transaction gets rolled back
1966 # Save commit message in case this transaction gets rolled back
1967 # (e.g. by a pretxncommit hook). Leave the content alone on
1967 # (e.g. by a pretxncommit hook). Leave the content alone on
1968 # the assumption that the user will use the same editor again.
1968 # the assumption that the user will use the same editor again.
1969 msgfn = self.savecommitmessage(cctx._text)
1969 msgfn = self.savecommitmessage(cctx._text)
1970
1970
1971 # commit subs and write new state
1971 # commit subs and write new state
1972 if subs:
1972 if subs:
1973 for s in sorted(commitsubs):
1973 for s in sorted(commitsubs):
1974 sub = wctx.sub(s)
1974 sub = wctx.sub(s)
1975 self.ui.status(_('committing subrepository %s\n') %
1975 self.ui.status(_('committing subrepository %s\n') %
1976 subrepoutil.subrelpath(sub))
1976 subrepoutil.subrelpath(sub))
1977 sr = sub.commit(cctx._text, user, date)
1977 sr = sub.commit(cctx._text, user, date)
1978 newstate[s] = (newstate[s][0], sr)
1978 newstate[s] = (newstate[s][0], sr)
1979 subrepoutil.writestate(self, newstate)
1979 subrepoutil.writestate(self, newstate)
1980
1980
1981 p1, p2 = self.dirstate.parents()
1981 p1, p2 = self.dirstate.parents()
1982 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1982 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1983 try:
1983 try:
1984 self.hook("precommit", throw=True, parent1=hookp1,
1984 self.hook("precommit", throw=True, parent1=hookp1,
1985 parent2=hookp2)
1985 parent2=hookp2)
1986 tr = self.transaction('commit')
1986 tr = self.transaction('commit')
1987 ret = self.commitctx(cctx, True)
1987 ret = self.commitctx(cctx, True)
1988 except: # re-raises
1988 except: # re-raises
1989 if edited:
1989 if edited:
1990 self.ui.write(
1990 self.ui.write(
1991 _('note: commit message saved in %s\n') % msgfn)
1991 _('note: commit message saved in %s\n') % msgfn)
1992 raise
1992 raise
1993 # update bookmarks, dirstate and mergestate
1993 # update bookmarks, dirstate and mergestate
1994 bookmarks.update(self, [p1, p2], ret)
1994 bookmarks.update(self, [p1, p2], ret)
1995 cctx.markcommitted(ret)
1995 cctx.markcommitted(ret)
1996 ms.reset()
1996 ms.reset()
1997 tr.close()
1997 tr.close()
1998
1998
1999 finally:
1999 finally:
2000 lockmod.release(tr, lock, wlock)
2000 lockmod.release(tr, lock, wlock)
2001
2001
2002 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
2002 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
2003 # hack for command that use a temporary commit (eg: histedit)
2003 # hack for command that use a temporary commit (eg: histedit)
2004 # temporary commit got stripped before hook release
2004 # temporary commit got stripped before hook release
2005 if self.changelog.hasnode(ret):
2005 if self.changelog.hasnode(ret):
2006 self.hook("commit", node=node, parent1=parent1,
2006 self.hook("commit", node=node, parent1=parent1,
2007 parent2=parent2)
2007 parent2=parent2)
2008 self._afterlock(commithook)
2008 self._afterlock(commithook)
2009 return ret
2009 return ret
2010
2010
2011 @unfilteredmethod
2011 @unfilteredmethod
2012 def commitctx(self, ctx, error=False):
2012 def commitctx(self, ctx, error=False):
2013 """Add a new revision to current repository.
2013 """Add a new revision to current repository.
2014 Revision information is passed via the context argument.
2014 Revision information is passed via the context argument.
2015 """
2015 """
2016
2016
2017 tr = None
2017 tr = None
2018 p1, p2 = ctx.p1(), ctx.p2()
2018 p1, p2 = ctx.p1(), ctx.p2()
2019 user = ctx.user()
2019 user = ctx.user()
2020
2020
2021 lock = self.lock()
2021 lock = self.lock()
2022 try:
2022 try:
2023 tr = self.transaction("commit")
2023 tr = self.transaction("commit")
2024 trp = weakref.proxy(tr)
2024 trp = weakref.proxy(tr)
2025
2025
2026 if ctx.manifestnode():
2026 if ctx.manifestnode():
2027 # reuse an existing manifest revision
2027 # reuse an existing manifest revision
2028 mn = ctx.manifestnode()
2028 mn = ctx.manifestnode()
2029 files = ctx.files()
2029 files = ctx.files()
2030 elif ctx.files():
2030 elif ctx.files():
2031 m1ctx = p1.manifestctx()
2031 m1ctx = p1.manifestctx()
2032 m2ctx = p2.manifestctx()
2032 m2ctx = p2.manifestctx()
2033 mctx = m1ctx.copy()
2033 mctx = m1ctx.copy()
2034
2034
2035 m = mctx.read()
2035 m = mctx.read()
2036 m1 = m1ctx.read()
2036 m1 = m1ctx.read()
2037 m2 = m2ctx.read()
2037 m2 = m2ctx.read()
2038
2038
2039 # check in files
2039 # check in files
2040 added = []
2040 added = []
2041 changed = []
2041 changed = []
2042 removed = list(ctx.removed())
2042 removed = list(ctx.removed())
2043 linkrev = len(self)
2043 linkrev = len(self)
2044 self.ui.note(_("committing files:\n"))
2044 self.ui.note(_("committing files:\n"))
2045 for f in sorted(ctx.modified() + ctx.added()):
2045 for f in sorted(ctx.modified() + ctx.added()):
2046 self.ui.note(f + "\n")
2046 self.ui.note(f + "\n")
2047 try:
2047 try:
2048 fctx = ctx[f]
2048 fctx = ctx[f]
2049 if fctx is None:
2049 if fctx is None:
2050 removed.append(f)
2050 removed.append(f)
2051 else:
2051 else:
2052 added.append(f)
2052 added.append(f)
2053 m[f] = self._filecommit(fctx, m1, m2, linkrev,
2053 m[f] = self._filecommit(fctx, m1, m2, linkrev,
2054 trp, changed)
2054 trp, changed)
2055 m.setflag(f, fctx.flags())
2055 m.setflag(f, fctx.flags())
2056 except OSError as inst:
2056 except OSError as inst:
2057 self.ui.warn(_("trouble committing %s!\n") % f)
2057 self.ui.warn(_("trouble committing %s!\n") % f)
2058 raise
2058 raise
2059 except IOError as inst:
2059 except IOError as inst:
2060 errcode = getattr(inst, 'errno', errno.ENOENT)
2060 errcode = getattr(inst, 'errno', errno.ENOENT)
2061 if error or errcode and errcode != errno.ENOENT:
2061 if error or errcode and errcode != errno.ENOENT:
2062 self.ui.warn(_("trouble committing %s!\n") % f)
2062 self.ui.warn(_("trouble committing %s!\n") % f)
2063 raise
2063 raise
2064
2064
2065 # update manifest
2065 # update manifest
2066 self.ui.note(_("committing manifest\n"))
2066 self.ui.note(_("committing manifest\n"))
2067 removed = [f for f in sorted(removed) if f in m1 or f in m2]
2067 removed = [f for f in sorted(removed) if f in m1 or f in m2]
2068 drop = [f for f in removed if f in m]
2068 drop = [f for f in removed if f in m]
2069 for f in drop:
2069 for f in drop:
2070 del m[f]
2070 del m[f]
2071 mn = mctx.write(trp, linkrev,
2071 mn = mctx.write(trp, linkrev,
2072 p1.manifestnode(), p2.manifestnode(),
2072 p1.manifestnode(), p2.manifestnode(),
2073 added, drop)
2073 added, drop)
2074 files = changed + removed
2074 files = changed + removed
2075 else:
2075 else:
2076 mn = p1.manifestnode()
2076 mn = p1.manifestnode()
2077 files = []
2077 files = []
2078
2078
2079 # update changelog
2079 # update changelog
2080 self.ui.note(_("committing changelog\n"))
2080 self.ui.note(_("committing changelog\n"))
2081 self.changelog.delayupdate(tr)
2081 self.changelog.delayupdate(tr)
2082 n = self.changelog.add(mn, files, ctx.description(),
2082 n = self.changelog.add(mn, files, ctx.description(),
2083 trp, p1.node(), p2.node(),
2083 trp, p1.node(), p2.node(),
2084 user, ctx.date(), ctx.extra().copy())
2084 user, ctx.date(), ctx.extra().copy())
2085 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
2085 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
2086 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
2086 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
2087 parent2=xp2)
2087 parent2=xp2)
2088 # set the new commit is proper phase
2088 # set the new commit is proper phase
2089 targetphase = subrepoutil.newcommitphase(self.ui, ctx)
2089 targetphase = subrepoutil.newcommitphase(self.ui, ctx)
2090 if targetphase:
2090 if targetphase:
2091 # retract boundary do not alter parent changeset.
2091 # retract boundary do not alter parent changeset.
2092 # if a parent have higher the resulting phase will
2092 # if a parent have higher the resulting phase will
2093 # be compliant anyway
2093 # be compliant anyway
2094 #
2094 #
2095 # if minimal phase was 0 we don't need to retract anything
2095 # if minimal phase was 0 we don't need to retract anything
2096 phases.registernew(self, tr, targetphase, [n])
2096 phases.registernew(self, tr, targetphase, [n])
2097 tr.close()
2097 tr.close()
2098 return n
2098 return n
2099 finally:
2099 finally:
2100 if tr:
2100 if tr:
2101 tr.release()
2101 tr.release()
2102 lock.release()
2102 lock.release()
2103
2103
2104 @unfilteredmethod
2104 @unfilteredmethod
2105 def destroying(self):
2105 def destroying(self):
2106 '''Inform the repository that nodes are about to be destroyed.
2106 '''Inform the repository that nodes are about to be destroyed.
2107 Intended for use by strip and rollback, so there's a common
2107 Intended for use by strip and rollback, so there's a common
2108 place for anything that has to be done before destroying history.
2108 place for anything that has to be done before destroying history.
2109
2109
2110 This is mostly useful for saving state that is in memory and waiting
2110 This is mostly useful for saving state that is in memory and waiting
2111 to be flushed when the current lock is released. Because a call to
2111 to be flushed when the current lock is released. Because a call to
2112 destroyed is imminent, the repo will be invalidated causing those
2112 destroyed is imminent, the repo will be invalidated causing those
2113 changes to stay in memory (waiting for the next unlock), or vanish
2113 changes to stay in memory (waiting for the next unlock), or vanish
2114 completely.
2114 completely.
2115 '''
2115 '''
2116 # When using the same lock to commit and strip, the phasecache is left
2116 # When using the same lock to commit and strip, the phasecache is left
2117 # dirty after committing. Then when we strip, the repo is invalidated,
2117 # dirty after committing. Then when we strip, the repo is invalidated,
2118 # causing those changes to disappear.
2118 # causing those changes to disappear.
2119 if '_phasecache' in vars(self):
2119 if '_phasecache' in vars(self):
2120 self._phasecache.write()
2120 self._phasecache.write()
2121
2121
2122 @unfilteredmethod
2122 @unfilteredmethod
2123 def destroyed(self):
2123 def destroyed(self):
2124 '''Inform the repository that nodes have been destroyed.
2124 '''Inform the repository that nodes have been destroyed.
2125 Intended for use by strip and rollback, so there's a common
2125 Intended for use by strip and rollback, so there's a common
2126 place for anything that has to be done after destroying history.
2126 place for anything that has to be done after destroying history.
2127 '''
2127 '''
2128 # When one tries to:
2128 # When one tries to:
2129 # 1) destroy nodes thus calling this method (e.g. strip)
2129 # 1) destroy nodes thus calling this method (e.g. strip)
2130 # 2) use phasecache somewhere (e.g. commit)
2130 # 2) use phasecache somewhere (e.g. commit)
2131 #
2131 #
2132 # then 2) will fail because the phasecache contains nodes that were
2132 # then 2) will fail because the phasecache contains nodes that were
2133 # removed. We can either remove phasecache from the filecache,
2133 # removed. We can either remove phasecache from the filecache,
2134 # causing it to reload next time it is accessed, or simply filter
2134 # causing it to reload next time it is accessed, or simply filter
2135 # the removed nodes now and write the updated cache.
2135 # the removed nodes now and write the updated cache.
2136 self._phasecache.filterunknown(self)
2136 self._phasecache.filterunknown(self)
2137 self._phasecache.write()
2137 self._phasecache.write()
2138
2138
2139 # refresh all repository caches
2139 # refresh all repository caches
2140 self.updatecaches()
2140 self.updatecaches()
2141
2141
2142 # Ensure the persistent tag cache is updated. Doing it now
2142 # Ensure the persistent tag cache is updated. Doing it now
2143 # means that the tag cache only has to worry about destroyed
2143 # means that the tag cache only has to worry about destroyed
2144 # heads immediately after a strip/rollback. That in turn
2144 # heads immediately after a strip/rollback. That in turn
2145 # guarantees that "cachetip == currenttip" (comparing both rev
2145 # guarantees that "cachetip == currenttip" (comparing both rev
2146 # and node) always means no nodes have been added or destroyed.
2146 # and node) always means no nodes have been added or destroyed.
2147
2147
2148 # XXX this is suboptimal when qrefresh'ing: we strip the current
2148 # XXX this is suboptimal when qrefresh'ing: we strip the current
2149 # head, refresh the tag cache, then immediately add a new head.
2149 # head, refresh the tag cache, then immediately add a new head.
2150 # But I think doing it this way is necessary for the "instant
2150 # But I think doing it this way is necessary for the "instant
2151 # tag cache retrieval" case to work.
2151 # tag cache retrieval" case to work.
2152 self.invalidate()
2152 self.invalidate()
2153
2153
2154 def status(self, node1='.', node2=None, match=None,
2154 def status(self, node1='.', node2=None, match=None,
2155 ignored=False, clean=False, unknown=False,
2155 ignored=False, clean=False, unknown=False,
2156 listsubrepos=False):
2156 listsubrepos=False):
2157 '''a convenience method that calls node1.status(node2)'''
2157 '''a convenience method that calls node1.status(node2)'''
2158 return self[node1].status(node2, match, ignored, clean, unknown,
2158 return self[node1].status(node2, match, ignored, clean, unknown,
2159 listsubrepos)
2159 listsubrepos)
2160
2160
2161 def addpostdsstatus(self, ps):
2161 def addpostdsstatus(self, ps):
2162 """Add a callback to run within the wlock, at the point at which status
2162 """Add a callback to run within the wlock, at the point at which status
2163 fixups happen.
2163 fixups happen.
2164
2164
2165 On status completion, callback(wctx, status) will be called with the
2165 On status completion, callback(wctx, status) will be called with the
2166 wlock held, unless the dirstate has changed from underneath or the wlock
2166 wlock held, unless the dirstate has changed from underneath or the wlock
2167 couldn't be grabbed.
2167 couldn't be grabbed.
2168
2168
2169 Callbacks should not capture and use a cached copy of the dirstate --
2169 Callbacks should not capture and use a cached copy of the dirstate --
2170 it might change in the meanwhile. Instead, they should access the
2170 it might change in the meanwhile. Instead, they should access the
2171 dirstate via wctx.repo().dirstate.
2171 dirstate via wctx.repo().dirstate.
2172
2172
2173 This list is emptied out after each status run -- extensions should
2173 This list is emptied out after each status run -- extensions should
2174 make sure it adds to this list each time dirstate.status is called.
2174 make sure it adds to this list each time dirstate.status is called.
2175 Extensions should also make sure they don't call this for statuses
2175 Extensions should also make sure they don't call this for statuses
2176 that don't involve the dirstate.
2176 that don't involve the dirstate.
2177 """
2177 """
2178
2178
2179 # The list is located here for uniqueness reasons -- it is actually
2179 # The list is located here for uniqueness reasons -- it is actually
2180 # managed by the workingctx, but that isn't unique per-repo.
2180 # managed by the workingctx, but that isn't unique per-repo.
2181 self._postdsstatus.append(ps)
2181 self._postdsstatus.append(ps)
2182
2182
2183 def postdsstatus(self):
2183 def postdsstatus(self):
2184 """Used by workingctx to get the list of post-dirstate-status hooks."""
2184 """Used by workingctx to get the list of post-dirstate-status hooks."""
2185 return self._postdsstatus
2185 return self._postdsstatus
2186
2186
2187 def clearpostdsstatus(self):
2187 def clearpostdsstatus(self):
2188 """Used by workingctx to clear post-dirstate-status hooks."""
2188 """Used by workingctx to clear post-dirstate-status hooks."""
2189 del self._postdsstatus[:]
2189 del self._postdsstatus[:]
2190
2190
2191 def heads(self, start=None):
2191 def heads(self, start=None):
2192 if start is None:
2192 if start is None:
2193 cl = self.changelog
2193 cl = self.changelog
2194 headrevs = reversed(cl.headrevs())
2194 headrevs = reversed(cl.headrevs())
2195 return [cl.node(rev) for rev in headrevs]
2195 return [cl.node(rev) for rev in headrevs]
2196
2196
2197 heads = self.changelog.heads(start)
2197 heads = self.changelog.heads(start)
2198 # sort the output in rev descending order
2198 # sort the output in rev descending order
2199 return sorted(heads, key=self.changelog.rev, reverse=True)
2199 return sorted(heads, key=self.changelog.rev, reverse=True)
2200
2200
2201 def branchheads(self, branch=None, start=None, closed=False):
2201 def branchheads(self, branch=None, start=None, closed=False):
2202 '''return a (possibly filtered) list of heads for the given branch
2202 '''return a (possibly filtered) list of heads for the given branch
2203
2203
2204 Heads are returned in topological order, from newest to oldest.
2204 Heads are returned in topological order, from newest to oldest.
2205 If branch is None, use the dirstate branch.
2205 If branch is None, use the dirstate branch.
2206 If start is not None, return only heads reachable from start.
2206 If start is not None, return only heads reachable from start.
2207 If closed is True, return heads that are marked as closed as well.
2207 If closed is True, return heads that are marked as closed as well.
2208 '''
2208 '''
2209 if branch is None:
2209 if branch is None:
2210 branch = self[None].branch()
2210 branch = self[None].branch()
2211 branches = self.branchmap()
2211 branches = self.branchmap()
2212 if branch not in branches:
2212 if branch not in branches:
2213 return []
2213 return []
2214 # the cache returns heads ordered lowest to highest
2214 # the cache returns heads ordered lowest to highest
2215 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2215 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2216 if start is not None:
2216 if start is not None:
2217 # filter out the heads that cannot be reached from startrev
2217 # filter out the heads that cannot be reached from startrev
2218 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2218 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2219 bheads = [h for h in bheads if h in fbheads]
2219 bheads = [h for h in bheads if h in fbheads]
2220 return bheads
2220 return bheads
2221
2221
2222 def branches(self, nodes):
2222 def branches(self, nodes):
2223 if not nodes:
2223 if not nodes:
2224 nodes = [self.changelog.tip()]
2224 nodes = [self.changelog.tip()]
2225 b = []
2225 b = []
2226 for n in nodes:
2226 for n in nodes:
2227 t = n
2227 t = n
2228 while True:
2228 while True:
2229 p = self.changelog.parents(n)
2229 p = self.changelog.parents(n)
2230 if p[1] != nullid or p[0] == nullid:
2230 if p[1] != nullid or p[0] == nullid:
2231 b.append((t, n, p[0], p[1]))
2231 b.append((t, n, p[0], p[1]))
2232 break
2232 break
2233 n = p[0]
2233 n = p[0]
2234 return b
2234 return b
2235
2235
2236 def between(self, pairs):
2236 def between(self, pairs):
2237 r = []
2237 r = []
2238
2238
2239 for top, bottom in pairs:
2239 for top, bottom in pairs:
2240 n, l, i = top, [], 0
2240 n, l, i = top, [], 0
2241 f = 1
2241 f = 1
2242
2242
2243 while n != bottom and n != nullid:
2243 while n != bottom and n != nullid:
2244 p = self.changelog.parents(n)[0]
2244 p = self.changelog.parents(n)[0]
2245 if i == f:
2245 if i == f:
2246 l.append(n)
2246 l.append(n)
2247 f = f * 2
2247 f = f * 2
2248 n = p
2248 n = p
2249 i += 1
2249 i += 1
2250
2250
2251 r.append(l)
2251 r.append(l)
2252
2252
2253 return r
2253 return r
2254
2254
2255 def checkpush(self, pushop):
2255 def checkpush(self, pushop):
2256 """Extensions can override this function if additional checks have
2256 """Extensions can override this function if additional checks have
2257 to be performed before pushing, or call it if they override push
2257 to be performed before pushing, or call it if they override push
2258 command.
2258 command.
2259 """
2259 """
2260
2260
2261 @unfilteredpropertycache
2261 @unfilteredpropertycache
2262 def prepushoutgoinghooks(self):
2262 def prepushoutgoinghooks(self):
2263 """Return util.hooks consists of a pushop with repo, remote, outgoing
2263 """Return util.hooks consists of a pushop with repo, remote, outgoing
2264 methods, which are called before pushing changesets.
2264 methods, which are called before pushing changesets.
2265 """
2265 """
2266 return util.hooks()
2266 return util.hooks()
2267
2267
2268 def pushkey(self, namespace, key, old, new):
2268 def pushkey(self, namespace, key, old, new):
2269 try:
2269 try:
2270 tr = self.currenttransaction()
2270 tr = self.currenttransaction()
2271 hookargs = {}
2271 hookargs = {}
2272 if tr is not None:
2272 if tr is not None:
2273 hookargs.update(tr.hookargs)
2273 hookargs.update(tr.hookargs)
2274 hookargs = pycompat.strkwargs(hookargs)
2274 hookargs = pycompat.strkwargs(hookargs)
2275 hookargs[r'namespace'] = namespace
2275 hookargs[r'namespace'] = namespace
2276 hookargs[r'key'] = key
2276 hookargs[r'key'] = key
2277 hookargs[r'old'] = old
2277 hookargs[r'old'] = old
2278 hookargs[r'new'] = new
2278 hookargs[r'new'] = new
2279 self.hook('prepushkey', throw=True, **hookargs)
2279 self.hook('prepushkey', throw=True, **hookargs)
2280 except error.HookAbort as exc:
2280 except error.HookAbort as exc:
2281 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2281 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2282 if exc.hint:
2282 if exc.hint:
2283 self.ui.write_err(_("(%s)\n") % exc.hint)
2283 self.ui.write_err(_("(%s)\n") % exc.hint)
2284 return False
2284 return False
2285 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2285 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2286 ret = pushkey.push(self, namespace, key, old, new)
2286 ret = pushkey.push(self, namespace, key, old, new)
2287 def runhook():
2287 def runhook():
2288 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2288 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2289 ret=ret)
2289 ret=ret)
2290 self._afterlock(runhook)
2290 self._afterlock(runhook)
2291 return ret
2291 return ret
2292
2292
2293 def listkeys(self, namespace):
2293 def listkeys(self, namespace):
2294 self.hook('prelistkeys', throw=True, namespace=namespace)
2294 self.hook('prelistkeys', throw=True, namespace=namespace)
2295 self.ui.debug('listing keys for "%s"\n' % namespace)
2295 self.ui.debug('listing keys for "%s"\n' % namespace)
2296 values = pushkey.list(self, namespace)
2296 values = pushkey.list(self, namespace)
2297 self.hook('listkeys', namespace=namespace, values=values)
2297 self.hook('listkeys', namespace=namespace, values=values)
2298 return values
2298 return values
2299
2299
2300 def debugwireargs(self, one, two, three=None, four=None, five=None):
2300 def debugwireargs(self, one, two, three=None, four=None, five=None):
2301 '''used to test argument passing over the wire'''
2301 '''used to test argument passing over the wire'''
2302 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
2302 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
2303 pycompat.bytestr(four),
2303 pycompat.bytestr(four),
2304 pycompat.bytestr(five))
2304 pycompat.bytestr(five))
2305
2305
2306 def savecommitmessage(self, text):
2306 def savecommitmessage(self, text):
2307 fp = self.vfs('last-message.txt', 'wb')
2307 fp = self.vfs('last-message.txt', 'wb')
2308 try:
2308 try:
2309 fp.write(text)
2309 fp.write(text)
2310 finally:
2310 finally:
2311 fp.close()
2311 fp.close()
2312 return self.pathto(fp.name[len(self.root) + 1:])
2312 return self.pathto(fp.name[len(self.root) + 1:])
2313
2313
2314 # used to avoid circular references so destructors work
2314 # used to avoid circular references so destructors work
2315 def aftertrans(files):
2315 def aftertrans(files):
2316 renamefiles = [tuple(t) for t in files]
2316 renamefiles = [tuple(t) for t in files]
2317 def a():
2317 def a():
2318 for vfs, src, dest in renamefiles:
2318 for vfs, src, dest in renamefiles:
2319 # if src and dest refer to a same file, vfs.rename is a no-op,
2319 # if src and dest refer to a same file, vfs.rename is a no-op,
2320 # leaving both src and dest on disk. delete dest to make sure
2320 # leaving both src and dest on disk. delete dest to make sure
2321 # the rename couldn't be such a no-op.
2321 # the rename couldn't be such a no-op.
2322 vfs.tryunlink(dest)
2322 vfs.tryunlink(dest)
2323 try:
2323 try:
2324 vfs.rename(src, dest)
2324 vfs.rename(src, dest)
2325 except OSError: # journal file does not yet exist
2325 except OSError: # journal file does not yet exist
2326 pass
2326 pass
2327 return a
2327 return a
2328
2328
2329 def undoname(fn):
2329 def undoname(fn):
2330 base, name = os.path.split(fn)
2330 base, name = os.path.split(fn)
2331 assert name.startswith('journal')
2331 assert name.startswith('journal')
2332 return os.path.join(base, name.replace('journal', 'undo', 1))
2332 return os.path.join(base, name.replace('journal', 'undo', 1))
2333
2333
2334 def instance(ui, path, create):
2334 def instance(ui, path, create):
2335 return localrepository(ui, util.urllocalpath(path), create)
2335 return localrepository(ui, util.urllocalpath(path), create)
2336
2336
2337 def islocal(path):
2337 def islocal(path):
2338 return True
2338 return True
2339
2339
2340 def newreporequirements(repo):
2340 def newreporequirements(repo):
2341 """Determine the set of requirements for a new local repository.
2341 """Determine the set of requirements for a new local repository.
2342
2342
2343 Extensions can wrap this function to specify custom requirements for
2343 Extensions can wrap this function to specify custom requirements for
2344 new repositories.
2344 new repositories.
2345 """
2345 """
2346 ui = repo.ui
2346 ui = repo.ui
2347 requirements = {'revlogv1'}
2347 requirements = {'revlogv1'}
2348 if ui.configbool('format', 'usestore'):
2348 if ui.configbool('format', 'usestore'):
2349 requirements.add('store')
2349 requirements.add('store')
2350 if ui.configbool('format', 'usefncache'):
2350 if ui.configbool('format', 'usefncache'):
2351 requirements.add('fncache')
2351 requirements.add('fncache')
2352 if ui.configbool('format', 'dotencode'):
2352 if ui.configbool('format', 'dotencode'):
2353 requirements.add('dotencode')
2353 requirements.add('dotencode')
2354
2354
2355 compengine = ui.config('experimental', 'format.compression')
2355 compengine = ui.config('experimental', 'format.compression')
2356 if compengine not in util.compengines:
2356 if compengine not in util.compengines:
2357 raise error.Abort(_('compression engine %s defined by '
2357 raise error.Abort(_('compression engine %s defined by '
2358 'experimental.format.compression not available') %
2358 'experimental.format.compression not available') %
2359 compengine,
2359 compengine,
2360 hint=_('run "hg debuginstall" to list available '
2360 hint=_('run "hg debuginstall" to list available '
2361 'compression engines'))
2361 'compression engines'))
2362
2362
2363 # zlib is the historical default and doesn't need an explicit requirement.
2363 # zlib is the historical default and doesn't need an explicit requirement.
2364 if compengine != 'zlib':
2364 if compengine != 'zlib':
2365 requirements.add('exp-compression-%s' % compengine)
2365 requirements.add('exp-compression-%s' % compengine)
2366
2366
2367 if scmutil.gdinitconfig(ui):
2367 if scmutil.gdinitconfig(ui):
2368 requirements.add('generaldelta')
2368 requirements.add('generaldelta')
2369 if ui.configbool('experimental', 'treemanifest'):
2369 if ui.configbool('experimental', 'treemanifest'):
2370 requirements.add('treemanifest')
2370 requirements.add('treemanifest')
2371
2371
2372 revlogv2 = ui.config('experimental', 'revlogv2')
2372 revlogv2 = ui.config('experimental', 'revlogv2')
2373 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2373 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2374 requirements.remove('revlogv1')
2374 requirements.remove('revlogv1')
2375 # generaldelta is implied by revlogv2.
2375 # generaldelta is implied by revlogv2.
2376 requirements.discard('generaldelta')
2376 requirements.discard('generaldelta')
2377 requirements.add(REVLOGV2_REQUIREMENT)
2377 requirements.add(REVLOGV2_REQUIREMENT)
2378
2378
2379 return requirements
2379 return requirements
@@ -1,383 +1,389
1 # pycompat.py - portability shim for python 3
1 # pycompat.py - portability shim for python 3
2 #
2 #
3 # This software may be used and distributed according to the terms of the
3 # This software may be used and distributed according to the terms of the
4 # GNU General Public License version 2 or any later version.
4 # GNU General Public License version 2 or any later version.
5
5
6 """Mercurial portability shim for python 3.
6 """Mercurial portability shim for python 3.
7
7
8 This contains aliases to hide python version-specific details from the core.
8 This contains aliases to hide python version-specific details from the core.
9 """
9 """
10
10
11 from __future__ import absolute_import
11 from __future__ import absolute_import
12
12
13 import getopt
13 import getopt
14 import inspect
14 import inspect
15 import os
15 import os
16 import shlex
16 import shlex
17 import sys
17 import sys
18
18
19 ispy3 = (sys.version_info[0] >= 3)
19 ispy3 = (sys.version_info[0] >= 3)
20 ispypy = (r'__pypy__' in sys.builtin_module_names)
20 ispypy = (r'__pypy__' in sys.builtin_module_names)
21
21
22 if not ispy3:
22 if not ispy3:
23 import cookielib
23 import cookielib
24 import cPickle as pickle
24 import cPickle as pickle
25 import httplib
25 import httplib
26 import Queue as _queue
26 import Queue as _queue
27 import SocketServer as socketserver
27 import SocketServer as socketserver
28 import xmlrpclib
28 import xmlrpclib
29
29
30 from .thirdparty.concurrent import futures
30 from .thirdparty.concurrent import futures
31
32 def future_set_exception_info(f, exc_info):
33 f.set_exception_info(*exc_info)
31 else:
34 else:
32 import concurrent.futures as futures
35 import concurrent.futures as futures
33 import http.cookiejar as cookielib
36 import http.cookiejar as cookielib
34 import http.client as httplib
37 import http.client as httplib
35 import pickle
38 import pickle
36 import queue as _queue
39 import queue as _queue
37 import socketserver
40 import socketserver
38 import xmlrpc.client as xmlrpclib
41 import xmlrpc.client as xmlrpclib
39
42
43 def future_set_exception_info(f, exc_info):
44 f.set_exception(exc_info[0])
45
40 empty = _queue.Empty
46 empty = _queue.Empty
41 queue = _queue.Queue
47 queue = _queue.Queue
42
48
43 def identity(a):
49 def identity(a):
44 return a
50 return a
45
51
46 if ispy3:
52 if ispy3:
47 import builtins
53 import builtins
48 import functools
54 import functools
49 import io
55 import io
50 import struct
56 import struct
51
57
52 fsencode = os.fsencode
58 fsencode = os.fsencode
53 fsdecode = os.fsdecode
59 fsdecode = os.fsdecode
54 oscurdir = os.curdir.encode('ascii')
60 oscurdir = os.curdir.encode('ascii')
55 oslinesep = os.linesep.encode('ascii')
61 oslinesep = os.linesep.encode('ascii')
56 osname = os.name.encode('ascii')
62 osname = os.name.encode('ascii')
57 ospathsep = os.pathsep.encode('ascii')
63 ospathsep = os.pathsep.encode('ascii')
58 ospardir = os.pardir.encode('ascii')
64 ospardir = os.pardir.encode('ascii')
59 ossep = os.sep.encode('ascii')
65 ossep = os.sep.encode('ascii')
60 osaltsep = os.altsep
66 osaltsep = os.altsep
61 if osaltsep:
67 if osaltsep:
62 osaltsep = osaltsep.encode('ascii')
68 osaltsep = osaltsep.encode('ascii')
63 # os.getcwd() on Python 3 returns string, but it has os.getcwdb() which
69 # os.getcwd() on Python 3 returns string, but it has os.getcwdb() which
64 # returns bytes.
70 # returns bytes.
65 getcwd = os.getcwdb
71 getcwd = os.getcwdb
66 sysplatform = sys.platform.encode('ascii')
72 sysplatform = sys.platform.encode('ascii')
67 sysexecutable = sys.executable
73 sysexecutable = sys.executable
68 if sysexecutable:
74 if sysexecutable:
69 sysexecutable = os.fsencode(sysexecutable)
75 sysexecutable = os.fsencode(sysexecutable)
70 bytesio = io.BytesIO
76 bytesio = io.BytesIO
71 # TODO deprecate stringio name, as it is a lie on Python 3.
77 # TODO deprecate stringio name, as it is a lie on Python 3.
72 stringio = bytesio
78 stringio = bytesio
73
79
74 def maplist(*args):
80 def maplist(*args):
75 return list(map(*args))
81 return list(map(*args))
76
82
77 def rangelist(*args):
83 def rangelist(*args):
78 return list(range(*args))
84 return list(range(*args))
79
85
80 def ziplist(*args):
86 def ziplist(*args):
81 return list(zip(*args))
87 return list(zip(*args))
82
88
83 rawinput = input
89 rawinput = input
84 getargspec = inspect.getfullargspec
90 getargspec = inspect.getfullargspec
85
91
86 # TODO: .buffer might not exist if std streams were replaced; we'll need
92 # TODO: .buffer might not exist if std streams were replaced; we'll need
87 # a silly wrapper to make a bytes stream backed by a unicode one.
93 # a silly wrapper to make a bytes stream backed by a unicode one.
88 stdin = sys.stdin.buffer
94 stdin = sys.stdin.buffer
89 stdout = sys.stdout.buffer
95 stdout = sys.stdout.buffer
90 stderr = sys.stderr.buffer
96 stderr = sys.stderr.buffer
91
97
92 # Since Python 3 converts argv to wchar_t type by Py_DecodeLocale() on Unix,
98 # Since Python 3 converts argv to wchar_t type by Py_DecodeLocale() on Unix,
93 # we can use os.fsencode() to get back bytes argv.
99 # we can use os.fsencode() to get back bytes argv.
94 #
100 #
95 # https://hg.python.org/cpython/file/v3.5.1/Programs/python.c#l55
101 # https://hg.python.org/cpython/file/v3.5.1/Programs/python.c#l55
96 #
102 #
97 # TODO: On Windows, the native argv is wchar_t, so we'll need a different
103 # TODO: On Windows, the native argv is wchar_t, so we'll need a different
98 # workaround to simulate the Python 2 (i.e. ANSI Win32 API) behavior.
104 # workaround to simulate the Python 2 (i.e. ANSI Win32 API) behavior.
99 if getattr(sys, 'argv', None) is not None:
105 if getattr(sys, 'argv', None) is not None:
100 sysargv = list(map(os.fsencode, sys.argv))
106 sysargv = list(map(os.fsencode, sys.argv))
101
107
102 bytechr = struct.Struct('>B').pack
108 bytechr = struct.Struct('>B').pack
103 byterepr = b'%r'.__mod__
109 byterepr = b'%r'.__mod__
104
110
105 class bytestr(bytes):
111 class bytestr(bytes):
106 """A bytes which mostly acts as a Python 2 str
112 """A bytes which mostly acts as a Python 2 str
107
113
108 >>> bytestr(), bytestr(bytearray(b'foo')), bytestr(u'ascii'), bytestr(1)
114 >>> bytestr(), bytestr(bytearray(b'foo')), bytestr(u'ascii'), bytestr(1)
109 ('', 'foo', 'ascii', '1')
115 ('', 'foo', 'ascii', '1')
110 >>> s = bytestr(b'foo')
116 >>> s = bytestr(b'foo')
111 >>> assert s is bytestr(s)
117 >>> assert s is bytestr(s)
112
118
113 __bytes__() should be called if provided:
119 __bytes__() should be called if provided:
114
120
115 >>> class bytesable(object):
121 >>> class bytesable(object):
116 ... def __bytes__(self):
122 ... def __bytes__(self):
117 ... return b'bytes'
123 ... return b'bytes'
118 >>> bytestr(bytesable())
124 >>> bytestr(bytesable())
119 'bytes'
125 'bytes'
120
126
121 There's no implicit conversion from non-ascii str as its encoding is
127 There's no implicit conversion from non-ascii str as its encoding is
122 unknown:
128 unknown:
123
129
124 >>> bytestr(chr(0x80)) # doctest: +ELLIPSIS
130 >>> bytestr(chr(0x80)) # doctest: +ELLIPSIS
125 Traceback (most recent call last):
131 Traceback (most recent call last):
126 ...
132 ...
127 UnicodeEncodeError: ...
133 UnicodeEncodeError: ...
128
134
129 Comparison between bytestr and bytes should work:
135 Comparison between bytestr and bytes should work:
130
136
131 >>> assert bytestr(b'foo') == b'foo'
137 >>> assert bytestr(b'foo') == b'foo'
132 >>> assert b'foo' == bytestr(b'foo')
138 >>> assert b'foo' == bytestr(b'foo')
133 >>> assert b'f' in bytestr(b'foo')
139 >>> assert b'f' in bytestr(b'foo')
134 >>> assert bytestr(b'f') in b'foo'
140 >>> assert bytestr(b'f') in b'foo'
135
141
136 Sliced elements should be bytes, not integer:
142 Sliced elements should be bytes, not integer:
137
143
138 >>> s[1], s[:2]
144 >>> s[1], s[:2]
139 (b'o', b'fo')
145 (b'o', b'fo')
140 >>> list(s), list(reversed(s))
146 >>> list(s), list(reversed(s))
141 ([b'f', b'o', b'o'], [b'o', b'o', b'f'])
147 ([b'f', b'o', b'o'], [b'o', b'o', b'f'])
142
148
143 As bytestr type isn't propagated across operations, you need to cast
149 As bytestr type isn't propagated across operations, you need to cast
144 bytes to bytestr explicitly:
150 bytes to bytestr explicitly:
145
151
146 >>> s = bytestr(b'foo').upper()
152 >>> s = bytestr(b'foo').upper()
147 >>> t = bytestr(s)
153 >>> t = bytestr(s)
148 >>> s[0], t[0]
154 >>> s[0], t[0]
149 (70, b'F')
155 (70, b'F')
150
156
151 Be careful to not pass a bytestr object to a function which expects
157 Be careful to not pass a bytestr object to a function which expects
152 bytearray-like behavior.
158 bytearray-like behavior.
153
159
154 >>> t = bytes(t) # cast to bytes
160 >>> t = bytes(t) # cast to bytes
155 >>> assert type(t) is bytes
161 >>> assert type(t) is bytes
156 """
162 """
157
163
158 def __new__(cls, s=b''):
164 def __new__(cls, s=b''):
159 if isinstance(s, bytestr):
165 if isinstance(s, bytestr):
160 return s
166 return s
161 if (not isinstance(s, (bytes, bytearray))
167 if (not isinstance(s, (bytes, bytearray))
162 and not hasattr(s, u'__bytes__')): # hasattr-py3-only
168 and not hasattr(s, u'__bytes__')): # hasattr-py3-only
163 s = str(s).encode(u'ascii')
169 s = str(s).encode(u'ascii')
164 return bytes.__new__(cls, s)
170 return bytes.__new__(cls, s)
165
171
166 def __getitem__(self, key):
172 def __getitem__(self, key):
167 s = bytes.__getitem__(self, key)
173 s = bytes.__getitem__(self, key)
168 if not isinstance(s, bytes):
174 if not isinstance(s, bytes):
169 s = bytechr(s)
175 s = bytechr(s)
170 return s
176 return s
171
177
172 def __iter__(self):
178 def __iter__(self):
173 return iterbytestr(bytes.__iter__(self))
179 return iterbytestr(bytes.__iter__(self))
174
180
175 def __repr__(self):
181 def __repr__(self):
176 return bytes.__repr__(self)[1:] # drop b''
182 return bytes.__repr__(self)[1:] # drop b''
177
183
178 def iterbytestr(s):
184 def iterbytestr(s):
179 """Iterate bytes as if it were a str object of Python 2"""
185 """Iterate bytes as if it were a str object of Python 2"""
180 return map(bytechr, s)
186 return map(bytechr, s)
181
187
182 def maybebytestr(s):
188 def maybebytestr(s):
183 """Promote bytes to bytestr"""
189 """Promote bytes to bytestr"""
184 if isinstance(s, bytes):
190 if isinstance(s, bytes):
185 return bytestr(s)
191 return bytestr(s)
186 return s
192 return s
187
193
188 def sysbytes(s):
194 def sysbytes(s):
189 """Convert an internal str (e.g. keyword, __doc__) back to bytes
195 """Convert an internal str (e.g. keyword, __doc__) back to bytes
190
196
191 This never raises UnicodeEncodeError, but only ASCII characters
197 This never raises UnicodeEncodeError, but only ASCII characters
192 can be round-trip by sysstr(sysbytes(s)).
198 can be round-trip by sysstr(sysbytes(s)).
193 """
199 """
194 return s.encode(u'utf-8')
200 return s.encode(u'utf-8')
195
201
196 def sysstr(s):
202 def sysstr(s):
197 """Return a keyword str to be passed to Python functions such as
203 """Return a keyword str to be passed to Python functions such as
198 getattr() and str.encode()
204 getattr() and str.encode()
199
205
200 This never raises UnicodeDecodeError. Non-ascii characters are
206 This never raises UnicodeDecodeError. Non-ascii characters are
201 considered invalid and mapped to arbitrary but unique code points
207 considered invalid and mapped to arbitrary but unique code points
202 such that 'sysstr(a) != sysstr(b)' for all 'a != b'.
208 such that 'sysstr(a) != sysstr(b)' for all 'a != b'.
203 """
209 """
204 if isinstance(s, builtins.str):
210 if isinstance(s, builtins.str):
205 return s
211 return s
206 return s.decode(u'latin-1')
212 return s.decode(u'latin-1')
207
213
208 def strurl(url):
214 def strurl(url):
209 """Converts a bytes url back to str"""
215 """Converts a bytes url back to str"""
210 if isinstance(url, bytes):
216 if isinstance(url, bytes):
211 return url.decode(u'ascii')
217 return url.decode(u'ascii')
212 return url
218 return url
213
219
214 def bytesurl(url):
220 def bytesurl(url):
215 """Converts a str url to bytes by encoding in ascii"""
221 """Converts a str url to bytes by encoding in ascii"""
216 if isinstance(url, str):
222 if isinstance(url, str):
217 return url.encode(u'ascii')
223 return url.encode(u'ascii')
218 return url
224 return url
219
225
220 def raisewithtb(exc, tb):
226 def raisewithtb(exc, tb):
221 """Raise exception with the given traceback"""
227 """Raise exception with the given traceback"""
222 raise exc.with_traceback(tb)
228 raise exc.with_traceback(tb)
223
229
224 def getdoc(obj):
230 def getdoc(obj):
225 """Get docstring as bytes; may be None so gettext() won't confuse it
231 """Get docstring as bytes; may be None so gettext() won't confuse it
226 with _('')"""
232 with _('')"""
227 doc = getattr(obj, u'__doc__', None)
233 doc = getattr(obj, u'__doc__', None)
228 if doc is None:
234 if doc is None:
229 return doc
235 return doc
230 return sysbytes(doc)
236 return sysbytes(doc)
231
237
232 def _wrapattrfunc(f):
238 def _wrapattrfunc(f):
233 @functools.wraps(f)
239 @functools.wraps(f)
234 def w(object, name, *args):
240 def w(object, name, *args):
235 return f(object, sysstr(name), *args)
241 return f(object, sysstr(name), *args)
236 return w
242 return w
237
243
238 # these wrappers are automagically imported by hgloader
244 # these wrappers are automagically imported by hgloader
239 delattr = _wrapattrfunc(builtins.delattr)
245 delattr = _wrapattrfunc(builtins.delattr)
240 getattr = _wrapattrfunc(builtins.getattr)
246 getattr = _wrapattrfunc(builtins.getattr)
241 hasattr = _wrapattrfunc(builtins.hasattr)
247 hasattr = _wrapattrfunc(builtins.hasattr)
242 setattr = _wrapattrfunc(builtins.setattr)
248 setattr = _wrapattrfunc(builtins.setattr)
243 xrange = builtins.range
249 xrange = builtins.range
244 unicode = str
250 unicode = str
245
251
246 def open(name, mode='r', buffering=-1, encoding=None):
252 def open(name, mode='r', buffering=-1, encoding=None):
247 return builtins.open(name, sysstr(mode), buffering, encoding)
253 return builtins.open(name, sysstr(mode), buffering, encoding)
248
254
249 safehasattr = _wrapattrfunc(builtins.hasattr)
255 safehasattr = _wrapattrfunc(builtins.hasattr)
250
256
251 def _getoptbwrapper(orig, args, shortlist, namelist):
257 def _getoptbwrapper(orig, args, shortlist, namelist):
252 """
258 """
253 Takes bytes arguments, converts them to unicode, pass them to
259 Takes bytes arguments, converts them to unicode, pass them to
254 getopt.getopt(), convert the returned values back to bytes and then
260 getopt.getopt(), convert the returned values back to bytes and then
255 return them for Python 3 compatibility as getopt.getopt() don't accepts
261 return them for Python 3 compatibility as getopt.getopt() don't accepts
256 bytes on Python 3.
262 bytes on Python 3.
257 """
263 """
258 args = [a.decode('latin-1') for a in args]
264 args = [a.decode('latin-1') for a in args]
259 shortlist = shortlist.decode('latin-1')
265 shortlist = shortlist.decode('latin-1')
260 namelist = [a.decode('latin-1') for a in namelist]
266 namelist = [a.decode('latin-1') for a in namelist]
261 opts, args = orig(args, shortlist, namelist)
267 opts, args = orig(args, shortlist, namelist)
262 opts = [(a[0].encode('latin-1'), a[1].encode('latin-1'))
268 opts = [(a[0].encode('latin-1'), a[1].encode('latin-1'))
263 for a in opts]
269 for a in opts]
264 args = [a.encode('latin-1') for a in args]
270 args = [a.encode('latin-1') for a in args]
265 return opts, args
271 return opts, args
266
272
267 def strkwargs(dic):
273 def strkwargs(dic):
268 """
274 """
269 Converts the keys of a python dictonary to str i.e. unicodes so that
275 Converts the keys of a python dictonary to str i.e. unicodes so that
270 they can be passed as keyword arguments as dictonaries with bytes keys
276 they can be passed as keyword arguments as dictonaries with bytes keys
271 can't be passed as keyword arguments to functions on Python 3.
277 can't be passed as keyword arguments to functions on Python 3.
272 """
278 """
273 dic = dict((k.decode('latin-1'), v) for k, v in dic.iteritems())
279 dic = dict((k.decode('latin-1'), v) for k, v in dic.iteritems())
274 return dic
280 return dic
275
281
276 def byteskwargs(dic):
282 def byteskwargs(dic):
277 """
283 """
278 Converts keys of python dictonaries to bytes as they were converted to
284 Converts keys of python dictonaries to bytes as they were converted to
279 str to pass that dictonary as a keyword argument on Python 3.
285 str to pass that dictonary as a keyword argument on Python 3.
280 """
286 """
281 dic = dict((k.encode('latin-1'), v) for k, v in dic.iteritems())
287 dic = dict((k.encode('latin-1'), v) for k, v in dic.iteritems())
282 return dic
288 return dic
283
289
284 # TODO: handle shlex.shlex().
290 # TODO: handle shlex.shlex().
285 def shlexsplit(s, comments=False, posix=True):
291 def shlexsplit(s, comments=False, posix=True):
286 """
292 """
287 Takes bytes argument, convert it to str i.e. unicodes, pass that into
293 Takes bytes argument, convert it to str i.e. unicodes, pass that into
288 shlex.split(), convert the returned value to bytes and return that for
294 shlex.split(), convert the returned value to bytes and return that for
289 Python 3 compatibility as shelx.split() don't accept bytes on Python 3.
295 Python 3 compatibility as shelx.split() don't accept bytes on Python 3.
290 """
296 """
291 ret = shlex.split(s.decode('latin-1'), comments, posix)
297 ret = shlex.split(s.decode('latin-1'), comments, posix)
292 return [a.encode('latin-1') for a in ret]
298 return [a.encode('latin-1') for a in ret]
293
299
294 def emailparser(*args, **kwargs):
300 def emailparser(*args, **kwargs):
295 import email.parser
301 import email.parser
296 return email.parser.BytesParser(*args, **kwargs)
302 return email.parser.BytesParser(*args, **kwargs)
297
303
298 else:
304 else:
299 import cStringIO
305 import cStringIO
300
306
301 bytechr = chr
307 bytechr = chr
302 byterepr = repr
308 byterepr = repr
303 bytestr = str
309 bytestr = str
304 iterbytestr = iter
310 iterbytestr = iter
305 maybebytestr = identity
311 maybebytestr = identity
306 sysbytes = identity
312 sysbytes = identity
307 sysstr = identity
313 sysstr = identity
308 strurl = identity
314 strurl = identity
309 bytesurl = identity
315 bytesurl = identity
310
316
311 # this can't be parsed on Python 3
317 # this can't be parsed on Python 3
312 exec('def raisewithtb(exc, tb):\n'
318 exec('def raisewithtb(exc, tb):\n'
313 ' raise exc, None, tb\n')
319 ' raise exc, None, tb\n')
314
320
315 def fsencode(filename):
321 def fsencode(filename):
316 """
322 """
317 Partial backport from os.py in Python 3, which only accepts bytes.
323 Partial backport from os.py in Python 3, which only accepts bytes.
318 In Python 2, our paths should only ever be bytes, a unicode path
324 In Python 2, our paths should only ever be bytes, a unicode path
319 indicates a bug.
325 indicates a bug.
320 """
326 """
321 if isinstance(filename, str):
327 if isinstance(filename, str):
322 return filename
328 return filename
323 else:
329 else:
324 raise TypeError(
330 raise TypeError(
325 "expect str, not %s" % type(filename).__name__)
331 "expect str, not %s" % type(filename).__name__)
326
332
327 # In Python 2, fsdecode() has a very chance to receive bytes. So it's
333 # In Python 2, fsdecode() has a very chance to receive bytes. So it's
328 # better not to touch Python 2 part as it's already working fine.
334 # better not to touch Python 2 part as it's already working fine.
329 fsdecode = identity
335 fsdecode = identity
330
336
331 def getdoc(obj):
337 def getdoc(obj):
332 return getattr(obj, '__doc__', None)
338 return getattr(obj, '__doc__', None)
333
339
334 _notset = object()
340 _notset = object()
335
341
336 def safehasattr(thing, attr):
342 def safehasattr(thing, attr):
337 return getattr(thing, attr, _notset) is not _notset
343 return getattr(thing, attr, _notset) is not _notset
338
344
339 def _getoptbwrapper(orig, args, shortlist, namelist):
345 def _getoptbwrapper(orig, args, shortlist, namelist):
340 return orig(args, shortlist, namelist)
346 return orig(args, shortlist, namelist)
341
347
342 strkwargs = identity
348 strkwargs = identity
343 byteskwargs = identity
349 byteskwargs = identity
344
350
345 oscurdir = os.curdir
351 oscurdir = os.curdir
346 oslinesep = os.linesep
352 oslinesep = os.linesep
347 osname = os.name
353 osname = os.name
348 ospathsep = os.pathsep
354 ospathsep = os.pathsep
349 ospardir = os.pardir
355 ospardir = os.pardir
350 ossep = os.sep
356 ossep = os.sep
351 osaltsep = os.altsep
357 osaltsep = os.altsep
352 stdin = sys.stdin
358 stdin = sys.stdin
353 stdout = sys.stdout
359 stdout = sys.stdout
354 stderr = sys.stderr
360 stderr = sys.stderr
355 if getattr(sys, 'argv', None) is not None:
361 if getattr(sys, 'argv', None) is not None:
356 sysargv = sys.argv
362 sysargv = sys.argv
357 sysplatform = sys.platform
363 sysplatform = sys.platform
358 getcwd = os.getcwd
364 getcwd = os.getcwd
359 sysexecutable = sys.executable
365 sysexecutable = sys.executable
360 shlexsplit = shlex.split
366 shlexsplit = shlex.split
361 bytesio = cStringIO.StringIO
367 bytesio = cStringIO.StringIO
362 stringio = bytesio
368 stringio = bytesio
363 maplist = map
369 maplist = map
364 rangelist = range
370 rangelist = range
365 ziplist = zip
371 ziplist = zip
366 rawinput = raw_input
372 rawinput = raw_input
367 getargspec = inspect.getargspec
373 getargspec = inspect.getargspec
368
374
369 def emailparser(*args, **kwargs):
375 def emailparser(*args, **kwargs):
370 import email.parser
376 import email.parser
371 return email.parser.Parser(*args, **kwargs)
377 return email.parser.Parser(*args, **kwargs)
372
378
373 isjython = sysplatform.startswith('java')
379 isjython = sysplatform.startswith('java')
374
380
375 isdarwin = sysplatform == 'darwin'
381 isdarwin = sysplatform == 'darwin'
376 isposix = osname == 'posix'
382 isposix = osname == 'posix'
377 iswindows = osname == 'nt'
383 iswindows = osname == 'nt'
378
384
379 def getoptb(args, shortlist, namelist):
385 def getoptb(args, shortlist, namelist):
380 return _getoptbwrapper(getopt.getopt, args, shortlist, namelist)
386 return _getoptbwrapper(getopt.getopt, args, shortlist, namelist)
381
387
382 def gnugetoptb(args, shortlist, namelist):
388 def gnugetoptb(args, shortlist, namelist):
383 return _getoptbwrapper(getopt.gnu_getopt, args, shortlist, namelist)
389 return _getoptbwrapper(getopt.gnu_getopt, args, shortlist, namelist)
@@ -1,619 +1,619
1 # wireprotov1peer.py - Client-side functionality for wire protocol version 1.
1 # wireprotov1peer.py - Client-side functionality for wire protocol version 1.
2 #
2 #
3 # Copyright 2005-2010 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2010 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import hashlib
10 import hashlib
11 import sys
11 import sys
12 import weakref
12 import weakref
13
13
14 from .i18n import _
14 from .i18n import _
15 from .node import (
15 from .node import (
16 bin,
16 bin,
17 )
17 )
18 from .thirdparty.zope import (
18 from .thirdparty.zope import (
19 interface as zi,
19 interface as zi,
20 )
20 )
21 from . import (
21 from . import (
22 bundle2,
22 bundle2,
23 changegroup as changegroupmod,
23 changegroup as changegroupmod,
24 encoding,
24 encoding,
25 error,
25 error,
26 pushkey as pushkeymod,
26 pushkey as pushkeymod,
27 pycompat,
27 pycompat,
28 repository,
28 repository,
29 util,
29 util,
30 wireprototypes,
30 wireprototypes,
31 )
31 )
32
32
33 urlreq = util.urlreq
33 urlreq = util.urlreq
34
34
35 def batchable(f):
35 def batchable(f):
36 '''annotation for batchable methods
36 '''annotation for batchable methods
37
37
38 Such methods must implement a coroutine as follows:
38 Such methods must implement a coroutine as follows:
39
39
40 @batchable
40 @batchable
41 def sample(self, one, two=None):
41 def sample(self, one, two=None):
42 # Build list of encoded arguments suitable for your wire protocol:
42 # Build list of encoded arguments suitable for your wire protocol:
43 encargs = [('one', encode(one),), ('two', encode(two),)]
43 encargs = [('one', encode(one),), ('two', encode(two),)]
44 # Create future for injection of encoded result:
44 # Create future for injection of encoded result:
45 encresref = future()
45 encresref = future()
46 # Return encoded arguments and future:
46 # Return encoded arguments and future:
47 yield encargs, encresref
47 yield encargs, encresref
48 # Assuming the future to be filled with the result from the batched
48 # Assuming the future to be filled with the result from the batched
49 # request now. Decode it:
49 # request now. Decode it:
50 yield decode(encresref.value)
50 yield decode(encresref.value)
51
51
52 The decorator returns a function which wraps this coroutine as a plain
52 The decorator returns a function which wraps this coroutine as a plain
53 method, but adds the original method as an attribute called "batchable",
53 method, but adds the original method as an attribute called "batchable",
54 which is used by remotebatch to split the call into separate encoding and
54 which is used by remotebatch to split the call into separate encoding and
55 decoding phases.
55 decoding phases.
56 '''
56 '''
57 def plain(*args, **opts):
57 def plain(*args, **opts):
58 batchable = f(*args, **opts)
58 batchable = f(*args, **opts)
59 encargsorres, encresref = next(batchable)
59 encargsorres, encresref = next(batchable)
60 if not encresref:
60 if not encresref:
61 return encargsorres # a local result in this case
61 return encargsorres # a local result in this case
62 self = args[0]
62 self = args[0]
63 cmd = pycompat.bytesurl(f.__name__) # ensure cmd is ascii bytestr
63 cmd = pycompat.bytesurl(f.__name__) # ensure cmd is ascii bytestr
64 encresref.set(self._submitone(cmd, encargsorres))
64 encresref.set(self._submitone(cmd, encargsorres))
65 return next(batchable)
65 return next(batchable)
66 setattr(plain, 'batchable', f)
66 setattr(plain, 'batchable', f)
67 return plain
67 return plain
68
68
69 class future(object):
69 class future(object):
70 '''placeholder for a value to be set later'''
70 '''placeholder for a value to be set later'''
71 def set(self, value):
71 def set(self, value):
72 if util.safehasattr(self, 'value'):
72 if util.safehasattr(self, 'value'):
73 raise error.RepoError("future is already set")
73 raise error.RepoError("future is already set")
74 self.value = value
74 self.value = value
75
75
76 def encodebatchcmds(req):
76 def encodebatchcmds(req):
77 """Return a ``cmds`` argument value for the ``batch`` command."""
77 """Return a ``cmds`` argument value for the ``batch`` command."""
78 escapearg = wireprototypes.escapebatcharg
78 escapearg = wireprototypes.escapebatcharg
79
79
80 cmds = []
80 cmds = []
81 for op, argsdict in req:
81 for op, argsdict in req:
82 # Old servers didn't properly unescape argument names. So prevent
82 # Old servers didn't properly unescape argument names. So prevent
83 # the sending of argument names that may not be decoded properly by
83 # the sending of argument names that may not be decoded properly by
84 # servers.
84 # servers.
85 assert all(escapearg(k) == k for k in argsdict)
85 assert all(escapearg(k) == k for k in argsdict)
86
86
87 args = ','.join('%s=%s' % (escapearg(k), escapearg(v))
87 args = ','.join('%s=%s' % (escapearg(k), escapearg(v))
88 for k, v in argsdict.iteritems())
88 for k, v in argsdict.iteritems())
89 cmds.append('%s %s' % (op, args))
89 cmds.append('%s %s' % (op, args))
90
90
91 return ';'.join(cmds)
91 return ';'.join(cmds)
92
92
93 class unsentfuture(pycompat.futures.Future):
93 class unsentfuture(pycompat.futures.Future):
94 """A Future variation to represent an unsent command.
94 """A Future variation to represent an unsent command.
95
95
96 Because we buffer commands and don't submit them immediately, calling
96 Because we buffer commands and don't submit them immediately, calling
97 ``result()`` on an unsent future could deadlock. Futures for buffered
97 ``result()`` on an unsent future could deadlock. Futures for buffered
98 commands are represented by this type, which wraps ``result()`` to
98 commands are represented by this type, which wraps ``result()`` to
99 call ``sendcommands()``.
99 call ``sendcommands()``.
100 """
100 """
101
101
102 def result(self, timeout=None):
102 def result(self, timeout=None):
103 if self.done():
103 if self.done():
104 return pycompat.futures.Future.result(self, timeout)
104 return pycompat.futures.Future.result(self, timeout)
105
105
106 self._peerexecutor.sendcommands()
106 self._peerexecutor.sendcommands()
107
107
108 # This looks like it will infinitely recurse. However,
108 # This looks like it will infinitely recurse. However,
109 # sendcommands() should modify __class__. This call serves as a check
109 # sendcommands() should modify __class__. This call serves as a check
110 # on that.
110 # on that.
111 return self.result(timeout)
111 return self.result(timeout)
112
112
113 @zi.implementer(repository.ipeercommandexecutor)
113 @zi.implementer(repository.ipeercommandexecutor)
114 class peerexecutor(object):
114 class peerexecutor(object):
115 def __init__(self, peer):
115 def __init__(self, peer):
116 self._peer = peer
116 self._peer = peer
117 self._sent = False
117 self._sent = False
118 self._closed = False
118 self._closed = False
119 self._calls = []
119 self._calls = []
120 self._futures = weakref.WeakSet()
120 self._futures = weakref.WeakSet()
121 self._responseexecutor = None
121 self._responseexecutor = None
122 self._responsef = None
122 self._responsef = None
123
123
124 def __enter__(self):
124 def __enter__(self):
125 return self
125 return self
126
126
127 def __exit__(self, exctype, excvalee, exctb):
127 def __exit__(self, exctype, excvalee, exctb):
128 self.close()
128 self.close()
129
129
130 def callcommand(self, command, args):
130 def callcommand(self, command, args):
131 if self._sent:
131 if self._sent:
132 raise error.ProgrammingError('callcommand() cannot be used '
132 raise error.ProgrammingError('callcommand() cannot be used '
133 'after commands are sent')
133 'after commands are sent')
134
134
135 if self._closed:
135 if self._closed:
136 raise error.ProgrammingError('callcommand() cannot be used '
136 raise error.ProgrammingError('callcommand() cannot be used '
137 'after close()')
137 'after close()')
138
138
139 # Commands are dispatched through methods on the peer.
139 # Commands are dispatched through methods on the peer.
140 fn = getattr(self._peer, pycompat.sysstr(command), None)
140 fn = getattr(self._peer, pycompat.sysstr(command), None)
141
141
142 if not fn:
142 if not fn:
143 raise error.ProgrammingError(
143 raise error.ProgrammingError(
144 'cannot call command %s: method of same name not available '
144 'cannot call command %s: method of same name not available '
145 'on peer' % command)
145 'on peer' % command)
146
146
147 # Commands are either batchable or they aren't. If a command
147 # Commands are either batchable or they aren't. If a command
148 # isn't batchable, we send it immediately because the executor
148 # isn't batchable, we send it immediately because the executor
149 # can no longer accept new commands after a non-batchable command.
149 # can no longer accept new commands after a non-batchable command.
150 # If a command is batchable, we queue it for later. But we have
150 # If a command is batchable, we queue it for later. But we have
151 # to account for the case of a non-batchable command arriving after
151 # to account for the case of a non-batchable command arriving after
152 # a batchable one and refuse to service it.
152 # a batchable one and refuse to service it.
153
153
154 def addcall():
154 def addcall():
155 f = pycompat.futures.Future()
155 f = pycompat.futures.Future()
156 self._futures.add(f)
156 self._futures.add(f)
157 self._calls.append((command, args, fn, f))
157 self._calls.append((command, args, fn, f))
158 return f
158 return f
159
159
160 if getattr(fn, 'batchable', False):
160 if getattr(fn, 'batchable', False):
161 f = addcall()
161 f = addcall()
162
162
163 # But since we don't issue it immediately, we wrap its result()
163 # But since we don't issue it immediately, we wrap its result()
164 # to trigger sending so we avoid deadlocks.
164 # to trigger sending so we avoid deadlocks.
165 f.__class__ = unsentfuture
165 f.__class__ = unsentfuture
166 f._peerexecutor = self
166 f._peerexecutor = self
167 else:
167 else:
168 if self._calls:
168 if self._calls:
169 raise error.ProgrammingError(
169 raise error.ProgrammingError(
170 '%s is not batchable and cannot be called on a command '
170 '%s is not batchable and cannot be called on a command '
171 'executor along with other commands' % command)
171 'executor along with other commands' % command)
172
172
173 f = addcall()
173 f = addcall()
174
174
175 # Non-batchable commands can never coexist with another command
175 # Non-batchable commands can never coexist with another command
176 # in this executor. So send the command immediately.
176 # in this executor. So send the command immediately.
177 self.sendcommands()
177 self.sendcommands()
178
178
179 return f
179 return f
180
180
181 def sendcommands(self):
181 def sendcommands(self):
182 if self._sent:
182 if self._sent:
183 return
183 return
184
184
185 if not self._calls:
185 if not self._calls:
186 return
186 return
187
187
188 self._sent = True
188 self._sent = True
189
189
190 # Unhack any future types so caller seens a clean type and to break
190 # Unhack any future types so caller seens a clean type and to break
191 # cycle between us and futures.
191 # cycle between us and futures.
192 for f in self._futures:
192 for f in self._futures:
193 if isinstance(f, unsentfuture):
193 if isinstance(f, unsentfuture):
194 f.__class__ = pycompat.futures.Future
194 f.__class__ = pycompat.futures.Future
195 f._peerexecutor = None
195 f._peerexecutor = None
196
196
197 calls = self._calls
197 calls = self._calls
198 # Mainly to destroy references to futures.
198 # Mainly to destroy references to futures.
199 self._calls = None
199 self._calls = None
200
200
201 # Simple case of a single command. We call it synchronously.
201 # Simple case of a single command. We call it synchronously.
202 if len(calls) == 1:
202 if len(calls) == 1:
203 command, args, fn, f = calls[0]
203 command, args, fn, f = calls[0]
204
204
205 # Future was cancelled. Ignore it.
205 # Future was cancelled. Ignore it.
206 if not f.set_running_or_notify_cancel():
206 if not f.set_running_or_notify_cancel():
207 return
207 return
208
208
209 try:
209 try:
210 result = fn(**pycompat.strkwargs(args))
210 result = fn(**pycompat.strkwargs(args))
211 except Exception:
211 except Exception:
212 f.set_exception_info(*sys.exc_info()[1:])
212 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
213 else:
213 else:
214 f.set_result(result)
214 f.set_result(result)
215
215
216 return
216 return
217
217
218 # Batch commands are a bit harder. First, we have to deal with the
218 # Batch commands are a bit harder. First, we have to deal with the
219 # @batchable coroutine. That's a bit annoying. Furthermore, we also
219 # @batchable coroutine. That's a bit annoying. Furthermore, we also
220 # need to preserve streaming. i.e. it should be possible for the
220 # need to preserve streaming. i.e. it should be possible for the
221 # futures to resolve as data is coming in off the wire without having
221 # futures to resolve as data is coming in off the wire without having
222 # to wait for the final byte of the final response. We do this by
222 # to wait for the final byte of the final response. We do this by
223 # spinning up a thread to read the responses.
223 # spinning up a thread to read the responses.
224
224
225 requests = []
225 requests = []
226 states = []
226 states = []
227
227
228 for command, args, fn, f in calls:
228 for command, args, fn, f in calls:
229 # Future was cancelled. Ignore it.
229 # Future was cancelled. Ignore it.
230 if not f.set_running_or_notify_cancel():
230 if not f.set_running_or_notify_cancel():
231 continue
231 continue
232
232
233 try:
233 try:
234 batchable = fn.batchable(fn.__self__,
234 batchable = fn.batchable(fn.__self__,
235 **pycompat.strkwargs(args))
235 **pycompat.strkwargs(args))
236 except Exception:
236 except Exception:
237 f.set_exception_info(*sys.exc_info()[1:])
237 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
238 return
238 return
239
239
240 # Encoded arguments and future holding remote result.
240 # Encoded arguments and future holding remote result.
241 try:
241 try:
242 encodedargs, fremote = next(batchable)
242 encodedargs, fremote = next(batchable)
243 except Exception:
243 except Exception:
244 f.set_exception_info(*sys.exc_info()[1:])
244 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
245 return
245 return
246
246
247 requests.append((command, encodedargs))
247 requests.append((command, encodedargs))
248 states.append((command, f, batchable, fremote))
248 states.append((command, f, batchable, fremote))
249
249
250 if not requests:
250 if not requests:
251 return
251 return
252
252
253 # This will emit responses in order they were executed.
253 # This will emit responses in order they were executed.
254 wireresults = self._peer._submitbatch(requests)
254 wireresults = self._peer._submitbatch(requests)
255
255
256 # The use of a thread pool executor here is a bit weird for something
256 # The use of a thread pool executor here is a bit weird for something
257 # that only spins up a single thread. However, thread management is
257 # that only spins up a single thread. However, thread management is
258 # hard and it is easy to encounter race conditions, deadlocks, etc.
258 # hard and it is easy to encounter race conditions, deadlocks, etc.
259 # concurrent.futures already solves these problems and its thread pool
259 # concurrent.futures already solves these problems and its thread pool
260 # executor has minimal overhead. So we use it.
260 # executor has minimal overhead. So we use it.
261 self._responseexecutor = pycompat.futures.ThreadPoolExecutor(1)
261 self._responseexecutor = pycompat.futures.ThreadPoolExecutor(1)
262 self._responsef = self._responseexecutor.submit(self._readbatchresponse,
262 self._responsef = self._responseexecutor.submit(self._readbatchresponse,
263 states, wireresults)
263 states, wireresults)
264
264
265 def close(self):
265 def close(self):
266 self.sendcommands()
266 self.sendcommands()
267
267
268 if self._closed:
268 if self._closed:
269 return
269 return
270
270
271 self._closed = True
271 self._closed = True
272
272
273 if not self._responsef:
273 if not self._responsef:
274 return
274 return
275
275
276 # We need to wait on our in-flight response and then shut down the
276 # We need to wait on our in-flight response and then shut down the
277 # executor once we have a result.
277 # executor once we have a result.
278 try:
278 try:
279 self._responsef.result()
279 self._responsef.result()
280 finally:
280 finally:
281 self._responseexecutor.shutdown(wait=True)
281 self._responseexecutor.shutdown(wait=True)
282 self._responsef = None
282 self._responsef = None
283 self._responseexecutor = None
283 self._responseexecutor = None
284
284
285 # If any of our futures are still in progress, mark them as
285 # If any of our futures are still in progress, mark them as
286 # errored. Otherwise a result() could wait indefinitely.
286 # errored. Otherwise a result() could wait indefinitely.
287 for f in self._futures:
287 for f in self._futures:
288 if not f.done():
288 if not f.done():
289 f.set_exception(error.ResponseError(
289 f.set_exception(error.ResponseError(
290 _('unfulfilled batch command response')))
290 _('unfulfilled batch command response')))
291
291
292 self._futures = None
292 self._futures = None
293
293
294 def _readbatchresponse(self, states, wireresults):
294 def _readbatchresponse(self, states, wireresults):
295 # Executes in a thread to read data off the wire.
295 # Executes in a thread to read data off the wire.
296
296
297 for command, f, batchable, fremote in states:
297 for command, f, batchable, fremote in states:
298 # Grab raw result off the wire and teach the internal future
298 # Grab raw result off the wire and teach the internal future
299 # about it.
299 # about it.
300 remoteresult = next(wireresults)
300 remoteresult = next(wireresults)
301 fremote.set(remoteresult)
301 fremote.set(remoteresult)
302
302
303 # And ask the coroutine to decode that value.
303 # And ask the coroutine to decode that value.
304 try:
304 try:
305 result = next(batchable)
305 result = next(batchable)
306 except Exception:
306 except Exception:
307 f.set_exception_info(*sys.exc_info()[1:])
307 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
308 else:
308 else:
309 f.set_result(result)
309 f.set_result(result)
310
310
311 @zi.implementer(repository.ipeercommands, repository.ipeerlegacycommands)
311 @zi.implementer(repository.ipeercommands, repository.ipeerlegacycommands)
312 class wirepeer(repository.peer):
312 class wirepeer(repository.peer):
313 """Client-side interface for communicating with a peer repository.
313 """Client-side interface for communicating with a peer repository.
314
314
315 Methods commonly call wire protocol commands of the same name.
315 Methods commonly call wire protocol commands of the same name.
316
316
317 See also httppeer.py and sshpeer.py for protocol-specific
317 See also httppeer.py and sshpeer.py for protocol-specific
318 implementations of this interface.
318 implementations of this interface.
319 """
319 """
320 def commandexecutor(self):
320 def commandexecutor(self):
321 return peerexecutor(self)
321 return peerexecutor(self)
322
322
323 # Begin of ipeercommands interface.
323 # Begin of ipeercommands interface.
324
324
325 def clonebundles(self):
325 def clonebundles(self):
326 self.requirecap('clonebundles', _('clone bundles'))
326 self.requirecap('clonebundles', _('clone bundles'))
327 return self._call('clonebundles')
327 return self._call('clonebundles')
328
328
329 @batchable
329 @batchable
330 def lookup(self, key):
330 def lookup(self, key):
331 self.requirecap('lookup', _('look up remote revision'))
331 self.requirecap('lookup', _('look up remote revision'))
332 f = future()
332 f = future()
333 yield {'key': encoding.fromlocal(key)}, f
333 yield {'key': encoding.fromlocal(key)}, f
334 d = f.value
334 d = f.value
335 success, data = d[:-1].split(" ", 1)
335 success, data = d[:-1].split(" ", 1)
336 if int(success):
336 if int(success):
337 yield bin(data)
337 yield bin(data)
338 else:
338 else:
339 self._abort(error.RepoError(data))
339 self._abort(error.RepoError(data))
340
340
341 @batchable
341 @batchable
342 def heads(self):
342 def heads(self):
343 f = future()
343 f = future()
344 yield {}, f
344 yield {}, f
345 d = f.value
345 d = f.value
346 try:
346 try:
347 yield wireprototypes.decodelist(d[:-1])
347 yield wireprototypes.decodelist(d[:-1])
348 except ValueError:
348 except ValueError:
349 self._abort(error.ResponseError(_("unexpected response:"), d))
349 self._abort(error.ResponseError(_("unexpected response:"), d))
350
350
351 @batchable
351 @batchable
352 def known(self, nodes):
352 def known(self, nodes):
353 f = future()
353 f = future()
354 yield {'nodes': wireprototypes.encodelist(nodes)}, f
354 yield {'nodes': wireprototypes.encodelist(nodes)}, f
355 d = f.value
355 d = f.value
356 try:
356 try:
357 yield [bool(int(b)) for b in d]
357 yield [bool(int(b)) for b in d]
358 except ValueError:
358 except ValueError:
359 self._abort(error.ResponseError(_("unexpected response:"), d))
359 self._abort(error.ResponseError(_("unexpected response:"), d))
360
360
361 @batchable
361 @batchable
362 def branchmap(self):
362 def branchmap(self):
363 f = future()
363 f = future()
364 yield {}, f
364 yield {}, f
365 d = f.value
365 d = f.value
366 try:
366 try:
367 branchmap = {}
367 branchmap = {}
368 for branchpart in d.splitlines():
368 for branchpart in d.splitlines():
369 branchname, branchheads = branchpart.split(' ', 1)
369 branchname, branchheads = branchpart.split(' ', 1)
370 branchname = encoding.tolocal(urlreq.unquote(branchname))
370 branchname = encoding.tolocal(urlreq.unquote(branchname))
371 branchheads = wireprototypes.decodelist(branchheads)
371 branchheads = wireprototypes.decodelist(branchheads)
372 branchmap[branchname] = branchheads
372 branchmap[branchname] = branchheads
373 yield branchmap
373 yield branchmap
374 except TypeError:
374 except TypeError:
375 self._abort(error.ResponseError(_("unexpected response:"), d))
375 self._abort(error.ResponseError(_("unexpected response:"), d))
376
376
377 @batchable
377 @batchable
378 def listkeys(self, namespace):
378 def listkeys(self, namespace):
379 if not self.capable('pushkey'):
379 if not self.capable('pushkey'):
380 yield {}, None
380 yield {}, None
381 f = future()
381 f = future()
382 self.ui.debug('preparing listkeys for "%s"\n' % namespace)
382 self.ui.debug('preparing listkeys for "%s"\n' % namespace)
383 yield {'namespace': encoding.fromlocal(namespace)}, f
383 yield {'namespace': encoding.fromlocal(namespace)}, f
384 d = f.value
384 d = f.value
385 self.ui.debug('received listkey for "%s": %i bytes\n'
385 self.ui.debug('received listkey for "%s": %i bytes\n'
386 % (namespace, len(d)))
386 % (namespace, len(d)))
387 yield pushkeymod.decodekeys(d)
387 yield pushkeymod.decodekeys(d)
388
388
389 @batchable
389 @batchable
390 def pushkey(self, namespace, key, old, new):
390 def pushkey(self, namespace, key, old, new):
391 if not self.capable('pushkey'):
391 if not self.capable('pushkey'):
392 yield False, None
392 yield False, None
393 f = future()
393 f = future()
394 self.ui.debug('preparing pushkey for "%s:%s"\n' % (namespace, key))
394 self.ui.debug('preparing pushkey for "%s:%s"\n' % (namespace, key))
395 yield {'namespace': encoding.fromlocal(namespace),
395 yield {'namespace': encoding.fromlocal(namespace),
396 'key': encoding.fromlocal(key),
396 'key': encoding.fromlocal(key),
397 'old': encoding.fromlocal(old),
397 'old': encoding.fromlocal(old),
398 'new': encoding.fromlocal(new)}, f
398 'new': encoding.fromlocal(new)}, f
399 d = f.value
399 d = f.value
400 d, output = d.split('\n', 1)
400 d, output = d.split('\n', 1)
401 try:
401 try:
402 d = bool(int(d))
402 d = bool(int(d))
403 except ValueError:
403 except ValueError:
404 raise error.ResponseError(
404 raise error.ResponseError(
405 _('push failed (unexpected response):'), d)
405 _('push failed (unexpected response):'), d)
406 for l in output.splitlines(True):
406 for l in output.splitlines(True):
407 self.ui.status(_('remote: '), l)
407 self.ui.status(_('remote: '), l)
408 yield d
408 yield d
409
409
410 def stream_out(self):
410 def stream_out(self):
411 return self._callstream('stream_out')
411 return self._callstream('stream_out')
412
412
413 def getbundle(self, source, **kwargs):
413 def getbundle(self, source, **kwargs):
414 kwargs = pycompat.byteskwargs(kwargs)
414 kwargs = pycompat.byteskwargs(kwargs)
415 self.requirecap('getbundle', _('look up remote changes'))
415 self.requirecap('getbundle', _('look up remote changes'))
416 opts = {}
416 opts = {}
417 bundlecaps = kwargs.get('bundlecaps') or set()
417 bundlecaps = kwargs.get('bundlecaps') or set()
418 for key, value in kwargs.iteritems():
418 for key, value in kwargs.iteritems():
419 if value is None:
419 if value is None:
420 continue
420 continue
421 keytype = wireprototypes.GETBUNDLE_ARGUMENTS.get(key)
421 keytype = wireprototypes.GETBUNDLE_ARGUMENTS.get(key)
422 if keytype is None:
422 if keytype is None:
423 raise error.ProgrammingError(
423 raise error.ProgrammingError(
424 'Unexpectedly None keytype for key %s' % key)
424 'Unexpectedly None keytype for key %s' % key)
425 elif keytype == 'nodes':
425 elif keytype == 'nodes':
426 value = wireprototypes.encodelist(value)
426 value = wireprototypes.encodelist(value)
427 elif keytype == 'csv':
427 elif keytype == 'csv':
428 value = ','.join(value)
428 value = ','.join(value)
429 elif keytype == 'scsv':
429 elif keytype == 'scsv':
430 value = ','.join(sorted(value))
430 value = ','.join(sorted(value))
431 elif keytype == 'boolean':
431 elif keytype == 'boolean':
432 value = '%i' % bool(value)
432 value = '%i' % bool(value)
433 elif keytype != 'plain':
433 elif keytype != 'plain':
434 raise KeyError('unknown getbundle option type %s'
434 raise KeyError('unknown getbundle option type %s'
435 % keytype)
435 % keytype)
436 opts[key] = value
436 opts[key] = value
437 f = self._callcompressable("getbundle", **pycompat.strkwargs(opts))
437 f = self._callcompressable("getbundle", **pycompat.strkwargs(opts))
438 if any((cap.startswith('HG2') for cap in bundlecaps)):
438 if any((cap.startswith('HG2') for cap in bundlecaps)):
439 return bundle2.getunbundler(self.ui, f)
439 return bundle2.getunbundler(self.ui, f)
440 else:
440 else:
441 return changegroupmod.cg1unpacker(f, 'UN')
441 return changegroupmod.cg1unpacker(f, 'UN')
442
442
443 def unbundle(self, bundle, heads, url):
443 def unbundle(self, bundle, heads, url):
444 '''Send cg (a readable file-like object representing the
444 '''Send cg (a readable file-like object representing the
445 changegroup to push, typically a chunkbuffer object) to the
445 changegroup to push, typically a chunkbuffer object) to the
446 remote server as a bundle.
446 remote server as a bundle.
447
447
448 When pushing a bundle10 stream, return an integer indicating the
448 When pushing a bundle10 stream, return an integer indicating the
449 result of the push (see changegroup.apply()).
449 result of the push (see changegroup.apply()).
450
450
451 When pushing a bundle20 stream, return a bundle20 stream.
451 When pushing a bundle20 stream, return a bundle20 stream.
452
452
453 `url` is the url the client thinks it's pushing to, which is
453 `url` is the url the client thinks it's pushing to, which is
454 visible to hooks.
454 visible to hooks.
455 '''
455 '''
456
456
457 if heads != ['force'] and self.capable('unbundlehash'):
457 if heads != ['force'] and self.capable('unbundlehash'):
458 heads = wireprototypes.encodelist(
458 heads = wireprototypes.encodelist(
459 ['hashed', hashlib.sha1(''.join(sorted(heads))).digest()])
459 ['hashed', hashlib.sha1(''.join(sorted(heads))).digest()])
460 else:
460 else:
461 heads = wireprototypes.encodelist(heads)
461 heads = wireprototypes.encodelist(heads)
462
462
463 if util.safehasattr(bundle, 'deltaheader'):
463 if util.safehasattr(bundle, 'deltaheader'):
464 # this a bundle10, do the old style call sequence
464 # this a bundle10, do the old style call sequence
465 ret, output = self._callpush("unbundle", bundle, heads=heads)
465 ret, output = self._callpush("unbundle", bundle, heads=heads)
466 if ret == "":
466 if ret == "":
467 raise error.ResponseError(
467 raise error.ResponseError(
468 _('push failed:'), output)
468 _('push failed:'), output)
469 try:
469 try:
470 ret = int(ret)
470 ret = int(ret)
471 except ValueError:
471 except ValueError:
472 raise error.ResponseError(
472 raise error.ResponseError(
473 _('push failed (unexpected response):'), ret)
473 _('push failed (unexpected response):'), ret)
474
474
475 for l in output.splitlines(True):
475 for l in output.splitlines(True):
476 self.ui.status(_('remote: '), l)
476 self.ui.status(_('remote: '), l)
477 else:
477 else:
478 # bundle2 push. Send a stream, fetch a stream.
478 # bundle2 push. Send a stream, fetch a stream.
479 stream = self._calltwowaystream('unbundle', bundle, heads=heads)
479 stream = self._calltwowaystream('unbundle', bundle, heads=heads)
480 ret = bundle2.getunbundler(self.ui, stream)
480 ret = bundle2.getunbundler(self.ui, stream)
481 return ret
481 return ret
482
482
483 # End of ipeercommands interface.
483 # End of ipeercommands interface.
484
484
485 # Begin of ipeerlegacycommands interface.
485 # Begin of ipeerlegacycommands interface.
486
486
487 def branches(self, nodes):
487 def branches(self, nodes):
488 n = wireprototypes.encodelist(nodes)
488 n = wireprototypes.encodelist(nodes)
489 d = self._call("branches", nodes=n)
489 d = self._call("branches", nodes=n)
490 try:
490 try:
491 br = [tuple(wireprototypes.decodelist(b)) for b in d.splitlines()]
491 br = [tuple(wireprototypes.decodelist(b)) for b in d.splitlines()]
492 return br
492 return br
493 except ValueError:
493 except ValueError:
494 self._abort(error.ResponseError(_("unexpected response:"), d))
494 self._abort(error.ResponseError(_("unexpected response:"), d))
495
495
496 def between(self, pairs):
496 def between(self, pairs):
497 batch = 8 # avoid giant requests
497 batch = 8 # avoid giant requests
498 r = []
498 r = []
499 for i in xrange(0, len(pairs), batch):
499 for i in xrange(0, len(pairs), batch):
500 n = " ".join([wireprototypes.encodelist(p, '-')
500 n = " ".join([wireprototypes.encodelist(p, '-')
501 for p in pairs[i:i + batch]])
501 for p in pairs[i:i + batch]])
502 d = self._call("between", pairs=n)
502 d = self._call("between", pairs=n)
503 try:
503 try:
504 r.extend(l and wireprototypes.decodelist(l) or []
504 r.extend(l and wireprototypes.decodelist(l) or []
505 for l in d.splitlines())
505 for l in d.splitlines())
506 except ValueError:
506 except ValueError:
507 self._abort(error.ResponseError(_("unexpected response:"), d))
507 self._abort(error.ResponseError(_("unexpected response:"), d))
508 return r
508 return r
509
509
510 def changegroup(self, nodes, source):
510 def changegroup(self, nodes, source):
511 n = wireprototypes.encodelist(nodes)
511 n = wireprototypes.encodelist(nodes)
512 f = self._callcompressable("changegroup", roots=n)
512 f = self._callcompressable("changegroup", roots=n)
513 return changegroupmod.cg1unpacker(f, 'UN')
513 return changegroupmod.cg1unpacker(f, 'UN')
514
514
515 def changegroupsubset(self, bases, heads, source):
515 def changegroupsubset(self, bases, heads, source):
516 self.requirecap('changegroupsubset', _('look up remote changes'))
516 self.requirecap('changegroupsubset', _('look up remote changes'))
517 bases = wireprototypes.encodelist(bases)
517 bases = wireprototypes.encodelist(bases)
518 heads = wireprototypes.encodelist(heads)
518 heads = wireprototypes.encodelist(heads)
519 f = self._callcompressable("changegroupsubset",
519 f = self._callcompressable("changegroupsubset",
520 bases=bases, heads=heads)
520 bases=bases, heads=heads)
521 return changegroupmod.cg1unpacker(f, 'UN')
521 return changegroupmod.cg1unpacker(f, 'UN')
522
522
523 # End of ipeerlegacycommands interface.
523 # End of ipeerlegacycommands interface.
524
524
525 def _submitbatch(self, req):
525 def _submitbatch(self, req):
526 """run batch request <req> on the server
526 """run batch request <req> on the server
527
527
528 Returns an iterator of the raw responses from the server.
528 Returns an iterator of the raw responses from the server.
529 """
529 """
530 ui = self.ui
530 ui = self.ui
531 if ui.debugflag and ui.configbool('devel', 'debug.peer-request'):
531 if ui.debugflag and ui.configbool('devel', 'debug.peer-request'):
532 ui.debug('devel-peer-request: batched-content\n')
532 ui.debug('devel-peer-request: batched-content\n')
533 for op, args in req:
533 for op, args in req:
534 msg = 'devel-peer-request: - %s (%d arguments)\n'
534 msg = 'devel-peer-request: - %s (%d arguments)\n'
535 ui.debug(msg % (op, len(args)))
535 ui.debug(msg % (op, len(args)))
536
536
537 unescapearg = wireprototypes.unescapebatcharg
537 unescapearg = wireprototypes.unescapebatcharg
538
538
539 rsp = self._callstream("batch", cmds=encodebatchcmds(req))
539 rsp = self._callstream("batch", cmds=encodebatchcmds(req))
540 chunk = rsp.read(1024)
540 chunk = rsp.read(1024)
541 work = [chunk]
541 work = [chunk]
542 while chunk:
542 while chunk:
543 while ';' not in chunk and chunk:
543 while ';' not in chunk and chunk:
544 chunk = rsp.read(1024)
544 chunk = rsp.read(1024)
545 work.append(chunk)
545 work.append(chunk)
546 merged = ''.join(work)
546 merged = ''.join(work)
547 while ';' in merged:
547 while ';' in merged:
548 one, merged = merged.split(';', 1)
548 one, merged = merged.split(';', 1)
549 yield unescapearg(one)
549 yield unescapearg(one)
550 chunk = rsp.read(1024)
550 chunk = rsp.read(1024)
551 work = [merged, chunk]
551 work = [merged, chunk]
552 yield unescapearg(''.join(work))
552 yield unescapearg(''.join(work))
553
553
554 def _submitone(self, op, args):
554 def _submitone(self, op, args):
555 return self._call(op, **pycompat.strkwargs(args))
555 return self._call(op, **pycompat.strkwargs(args))
556
556
557 def debugwireargs(self, one, two, three=None, four=None, five=None):
557 def debugwireargs(self, one, two, three=None, four=None, five=None):
558 # don't pass optional arguments left at their default value
558 # don't pass optional arguments left at their default value
559 opts = {}
559 opts = {}
560 if three is not None:
560 if three is not None:
561 opts[r'three'] = three
561 opts[r'three'] = three
562 if four is not None:
562 if four is not None:
563 opts[r'four'] = four
563 opts[r'four'] = four
564 return self._call('debugwireargs', one=one, two=two, **opts)
564 return self._call('debugwireargs', one=one, two=two, **opts)
565
565
566 def _call(self, cmd, **args):
566 def _call(self, cmd, **args):
567 """execute <cmd> on the server
567 """execute <cmd> on the server
568
568
569 The command is expected to return a simple string.
569 The command is expected to return a simple string.
570
570
571 returns the server reply as a string."""
571 returns the server reply as a string."""
572 raise NotImplementedError()
572 raise NotImplementedError()
573
573
574 def _callstream(self, cmd, **args):
574 def _callstream(self, cmd, **args):
575 """execute <cmd> on the server
575 """execute <cmd> on the server
576
576
577 The command is expected to return a stream. Note that if the
577 The command is expected to return a stream. Note that if the
578 command doesn't return a stream, _callstream behaves
578 command doesn't return a stream, _callstream behaves
579 differently for ssh and http peers.
579 differently for ssh and http peers.
580
580
581 returns the server reply as a file like object.
581 returns the server reply as a file like object.
582 """
582 """
583 raise NotImplementedError()
583 raise NotImplementedError()
584
584
585 def _callcompressable(self, cmd, **args):
585 def _callcompressable(self, cmd, **args):
586 """execute <cmd> on the server
586 """execute <cmd> on the server
587
587
588 The command is expected to return a stream.
588 The command is expected to return a stream.
589
589
590 The stream may have been compressed in some implementations. This
590 The stream may have been compressed in some implementations. This
591 function takes care of the decompression. This is the only difference
591 function takes care of the decompression. This is the only difference
592 with _callstream.
592 with _callstream.
593
593
594 returns the server reply as a file like object.
594 returns the server reply as a file like object.
595 """
595 """
596 raise NotImplementedError()
596 raise NotImplementedError()
597
597
598 def _callpush(self, cmd, fp, **args):
598 def _callpush(self, cmd, fp, **args):
599 """execute a <cmd> on server
599 """execute a <cmd> on server
600
600
601 The command is expected to be related to a push. Push has a special
601 The command is expected to be related to a push. Push has a special
602 return method.
602 return method.
603
603
604 returns the server reply as a (ret, output) tuple. ret is either
604 returns the server reply as a (ret, output) tuple. ret is either
605 empty (error) or a stringified int.
605 empty (error) or a stringified int.
606 """
606 """
607 raise NotImplementedError()
607 raise NotImplementedError()
608
608
609 def _calltwowaystream(self, cmd, fp, **args):
609 def _calltwowaystream(self, cmd, fp, **args):
610 """execute <cmd> on server
610 """execute <cmd> on server
611
611
612 The command will send a stream to the server and get a stream in reply.
612 The command will send a stream to the server and get a stream in reply.
613 """
613 """
614 raise NotImplementedError()
614 raise NotImplementedError()
615
615
616 def _abort(self, exception):
616 def _abort(self, exception):
617 """clearly abort the wire protocol connection and raise the exception
617 """clearly abort the wire protocol connection and raise the exception
618 """
618 """
619 raise NotImplementedError()
619 raise NotImplementedError()
General Comments 0
You need to be logged in to leave comments. Login now