##// END OF EJS Templates
push: document return values between various repo methods....
Greg Ward -
r11153:9936ed1d default
parent child Browse files
Show More
@@ -1,275 +1,281 b''
1 # httprepo.py - HTTP repository proxy classes for mercurial
1 # httprepo.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 node import bin, hex, nullid
9 from node import bin, hex, nullid
10 from i18n import _
10 from i18n import _
11 import repo, changegroup, statichttprepo, error, url, util
11 import repo, changegroup, statichttprepo, error, url, util
12 import os, urllib, urllib2, urlparse, zlib, httplib
12 import os, urllib, urllib2, urlparse, zlib, httplib
13 import errno, socket
13 import errno, socket
14 import encoding
14 import encoding
15
15
16 def zgenerator(f):
16 def zgenerator(f):
17 zd = zlib.decompressobj()
17 zd = zlib.decompressobj()
18 try:
18 try:
19 for chunk in util.filechunkiter(f):
19 for chunk in util.filechunkiter(f):
20 yield zd.decompress(chunk)
20 yield zd.decompress(chunk)
21 except httplib.HTTPException:
21 except httplib.HTTPException:
22 raise IOError(None, _('connection ended unexpectedly'))
22 raise IOError(None, _('connection ended unexpectedly'))
23 yield zd.flush()
23 yield zd.flush()
24
24
25 class httprepository(repo.repository):
25 class httprepository(repo.repository):
26 def __init__(self, ui, path):
26 def __init__(self, ui, path):
27 self.path = path
27 self.path = path
28 self.caps = None
28 self.caps = None
29 self.handler = None
29 self.handler = None
30 scheme, netloc, urlpath, query, frag = urlparse.urlsplit(path)
30 scheme, netloc, urlpath, query, frag = urlparse.urlsplit(path)
31 if query or frag:
31 if query or frag:
32 raise util.Abort(_('unsupported URL component: "%s"') %
32 raise util.Abort(_('unsupported URL component: "%s"') %
33 (query or frag))
33 (query or frag))
34
34
35 # urllib cannot handle URLs with embedded user or passwd
35 # urllib cannot handle URLs with embedded user or passwd
36 self._url, authinfo = url.getauthinfo(path)
36 self._url, authinfo = url.getauthinfo(path)
37
37
38 self.ui = ui
38 self.ui = ui
39 self.ui.debug('using %s\n' % self._url)
39 self.ui.debug('using %s\n' % self._url)
40
40
41 self.urlopener = url.opener(ui, authinfo)
41 self.urlopener = url.opener(ui, authinfo)
42
42
43 def __del__(self):
43 def __del__(self):
44 for h in self.urlopener.handlers:
44 for h in self.urlopener.handlers:
45 h.close()
45 h.close()
46 if hasattr(h, "close_all"):
46 if hasattr(h, "close_all"):
47 h.close_all()
47 h.close_all()
48
48
49 def url(self):
49 def url(self):
50 return self.path
50 return self.path
51
51
52 # look up capabilities only when needed
52 # look up capabilities only when needed
53
53
54 def get_caps(self):
54 def get_caps(self):
55 if self.caps is None:
55 if self.caps is None:
56 try:
56 try:
57 self.caps = set(self.do_read('capabilities').split())
57 self.caps = set(self.do_read('capabilities').split())
58 except error.RepoError:
58 except error.RepoError:
59 self.caps = set()
59 self.caps = set()
60 self.ui.debug('capabilities: %s\n' %
60 self.ui.debug('capabilities: %s\n' %
61 (' '.join(self.caps or ['none'])))
61 (' '.join(self.caps or ['none'])))
62 return self.caps
62 return self.caps
63
63
64 capabilities = property(get_caps)
64 capabilities = property(get_caps)
65
65
66 def lock(self):
66 def lock(self):
67 raise util.Abort(_('operation not supported over http'))
67 raise util.Abort(_('operation not supported over http'))
68
68
69 def do_cmd(self, cmd, **args):
69 def do_cmd(self, cmd, **args):
70 data = args.pop('data', None)
70 data = args.pop('data', None)
71 headers = args.pop('headers', {})
71 headers = args.pop('headers', {})
72 self.ui.debug("sending %s command\n" % cmd)
72 self.ui.debug("sending %s command\n" % cmd)
73 q = {"cmd": cmd}
73 q = {"cmd": cmd}
74 q.update(args)
74 q.update(args)
75 qs = '?%s' % urllib.urlencode(q)
75 qs = '?%s' % urllib.urlencode(q)
76 cu = "%s%s" % (self._url, qs)
76 cu = "%s%s" % (self._url, qs)
77 req = urllib2.Request(cu, data, headers)
77 req = urllib2.Request(cu, data, headers)
78 if data is not None:
78 if data is not None:
79 # len(data) is broken if data doesn't fit into Py_ssize_t
79 # len(data) is broken if data doesn't fit into Py_ssize_t
80 # add the header ourself to avoid OverflowError
80 # add the header ourself to avoid OverflowError
81 size = data.__len__()
81 size = data.__len__()
82 self.ui.debug("sending %s bytes\n" % size)
82 self.ui.debug("sending %s bytes\n" % size)
83 req.add_unredirected_header('Content-Length', '%d' % size)
83 req.add_unredirected_header('Content-Length', '%d' % size)
84 try:
84 try:
85 resp = self.urlopener.open(req)
85 resp = self.urlopener.open(req)
86 except urllib2.HTTPError, inst:
86 except urllib2.HTTPError, inst:
87 if inst.code == 401:
87 if inst.code == 401:
88 raise util.Abort(_('authorization failed'))
88 raise util.Abort(_('authorization failed'))
89 raise
89 raise
90 except httplib.HTTPException, inst:
90 except httplib.HTTPException, inst:
91 self.ui.debug('http error while sending %s command\n' % cmd)
91 self.ui.debug('http error while sending %s command\n' % cmd)
92 self.ui.traceback()
92 self.ui.traceback()
93 raise IOError(None, inst)
93 raise IOError(None, inst)
94 except IndexError:
94 except IndexError:
95 # this only happens with Python 2.3, later versions raise URLError
95 # this only happens with Python 2.3, later versions raise URLError
96 raise util.Abort(_('http error, possibly caused by proxy setting'))
96 raise util.Abort(_('http error, possibly caused by proxy setting'))
97 # record the url we got redirected to
97 # record the url we got redirected to
98 resp_url = resp.geturl()
98 resp_url = resp.geturl()
99 if resp_url.endswith(qs):
99 if resp_url.endswith(qs):
100 resp_url = resp_url[:-len(qs)]
100 resp_url = resp_url[:-len(qs)]
101 if self._url.rstrip('/') != resp_url.rstrip('/'):
101 if self._url.rstrip('/') != resp_url.rstrip('/'):
102 self.ui.status(_('real URL is %s\n') % resp_url)
102 self.ui.status(_('real URL is %s\n') % resp_url)
103 self._url = resp_url
103 self._url = resp_url
104 try:
104 try:
105 proto = resp.getheader('content-type')
105 proto = resp.getheader('content-type')
106 except AttributeError:
106 except AttributeError:
107 proto = resp.headers['content-type']
107 proto = resp.headers['content-type']
108
108
109 safeurl = url.hidepassword(self._url)
109 safeurl = url.hidepassword(self._url)
110 # accept old "text/plain" and "application/hg-changegroup" for now
110 # accept old "text/plain" and "application/hg-changegroup" for now
111 if not (proto.startswith('application/mercurial-') or
111 if not (proto.startswith('application/mercurial-') or
112 proto.startswith('text/plain') or
112 proto.startswith('text/plain') or
113 proto.startswith('application/hg-changegroup')):
113 proto.startswith('application/hg-changegroup')):
114 self.ui.debug("requested URL: '%s'\n" % url.hidepassword(cu))
114 self.ui.debug("requested URL: '%s'\n" % url.hidepassword(cu))
115 raise error.RepoError(
115 raise error.RepoError(
116 _("'%s' does not appear to be an hg repository:\n"
116 _("'%s' does not appear to be an hg repository:\n"
117 "---%%<--- (%s)\n%s\n---%%<---\n")
117 "---%%<--- (%s)\n%s\n---%%<---\n")
118 % (safeurl, proto, resp.read()))
118 % (safeurl, proto, resp.read()))
119
119
120 if proto.startswith('application/mercurial-'):
120 if proto.startswith('application/mercurial-'):
121 try:
121 try:
122 version = proto.split('-', 1)[1]
122 version = proto.split('-', 1)[1]
123 version_info = tuple([int(n) for n in version.split('.')])
123 version_info = tuple([int(n) for n in version.split('.')])
124 except ValueError:
124 except ValueError:
125 raise error.RepoError(_("'%s' sent a broken Content-Type "
125 raise error.RepoError(_("'%s' sent a broken Content-Type "
126 "header (%s)") % (safeurl, proto))
126 "header (%s)") % (safeurl, proto))
127 if version_info > (0, 1):
127 if version_info > (0, 1):
128 raise error.RepoError(_("'%s' uses newer protocol %s") %
128 raise error.RepoError(_("'%s' uses newer protocol %s") %
129 (safeurl, version))
129 (safeurl, version))
130
130
131 return resp
131 return resp
132
132
133 def do_read(self, cmd, **args):
133 def do_read(self, cmd, **args):
134 fp = self.do_cmd(cmd, **args)
134 fp = self.do_cmd(cmd, **args)
135 try:
135 try:
136 return fp.read()
136 return fp.read()
137 finally:
137 finally:
138 # if using keepalive, allow connection to be reused
138 # if using keepalive, allow connection to be reused
139 fp.close()
139 fp.close()
140
140
141 def lookup(self, key):
141 def lookup(self, key):
142 self.requirecap('lookup', _('look up remote revision'))
142 self.requirecap('lookup', _('look up remote revision'))
143 d = self.do_cmd("lookup", key = key).read()
143 d = self.do_cmd("lookup", key = key).read()
144 success, data = d[:-1].split(' ', 1)
144 success, data = d[:-1].split(' ', 1)
145 if int(success):
145 if int(success):
146 return bin(data)
146 return bin(data)
147 raise error.RepoError(data)
147 raise error.RepoError(data)
148
148
149 def heads(self):
149 def heads(self):
150 d = self.do_read("heads")
150 d = self.do_read("heads")
151 try:
151 try:
152 return map(bin, d[:-1].split(" "))
152 return map(bin, d[:-1].split(" "))
153 except:
153 except:
154 raise error.ResponseError(_("unexpected response:"), d)
154 raise error.ResponseError(_("unexpected response:"), d)
155
155
156 def branchmap(self):
156 def branchmap(self):
157 d = self.do_read("branchmap")
157 d = self.do_read("branchmap")
158 try:
158 try:
159 branchmap = {}
159 branchmap = {}
160 for branchpart in d.splitlines():
160 for branchpart in d.splitlines():
161 branchheads = branchpart.split(' ')
161 branchheads = branchpart.split(' ')
162 branchname = urllib.unquote(branchheads[0])
162 branchname = urllib.unquote(branchheads[0])
163 # Earlier servers (1.3.x) send branch names in (their) local
163 # Earlier servers (1.3.x) send branch names in (their) local
164 # charset. The best we can do is assume it's identical to our
164 # charset. The best we can do is assume it's identical to our
165 # own local charset, in case it's not utf-8.
165 # own local charset, in case it's not utf-8.
166 try:
166 try:
167 branchname.decode('utf-8')
167 branchname.decode('utf-8')
168 except UnicodeDecodeError:
168 except UnicodeDecodeError:
169 branchname = encoding.fromlocal(branchname)
169 branchname = encoding.fromlocal(branchname)
170 branchheads = [bin(x) for x in branchheads[1:]]
170 branchheads = [bin(x) for x in branchheads[1:]]
171 branchmap[branchname] = branchheads
171 branchmap[branchname] = branchheads
172 return branchmap
172 return branchmap
173 except:
173 except:
174 raise error.ResponseError(_("unexpected response:"), d)
174 raise error.ResponseError(_("unexpected response:"), d)
175
175
176 def branches(self, nodes):
176 def branches(self, nodes):
177 n = " ".join(map(hex, nodes))
177 n = " ".join(map(hex, nodes))
178 d = self.do_read("branches", nodes=n)
178 d = self.do_read("branches", nodes=n)
179 try:
179 try:
180 br = [tuple(map(bin, b.split(" "))) for b in d.splitlines()]
180 br = [tuple(map(bin, b.split(" "))) for b in d.splitlines()]
181 return br
181 return br
182 except:
182 except:
183 raise error.ResponseError(_("unexpected response:"), d)
183 raise error.ResponseError(_("unexpected response:"), d)
184
184
185 def between(self, pairs):
185 def between(self, pairs):
186 batch = 8 # avoid giant requests
186 batch = 8 # avoid giant requests
187 r = []
187 r = []
188 for i in xrange(0, len(pairs), batch):
188 for i in xrange(0, len(pairs), batch):
189 n = " ".join(["-".join(map(hex, p)) for p in pairs[i:i + batch]])
189 n = " ".join(["-".join(map(hex, p)) for p in pairs[i:i + batch]])
190 d = self.do_read("between", pairs=n)
190 d = self.do_read("between", pairs=n)
191 try:
191 try:
192 r += [l and map(bin, l.split(" ")) or []
192 r += [l and map(bin, l.split(" ")) or []
193 for l in d.splitlines()]
193 for l in d.splitlines()]
194 except:
194 except:
195 raise error.ResponseError(_("unexpected response:"), d)
195 raise error.ResponseError(_("unexpected response:"), d)
196 return r
196 return r
197
197
198 def changegroup(self, nodes, kind):
198 def changegroup(self, nodes, kind):
199 n = " ".join(map(hex, nodes))
199 n = " ".join(map(hex, nodes))
200 f = self.do_cmd("changegroup", roots=n)
200 f = self.do_cmd("changegroup", roots=n)
201 return util.chunkbuffer(zgenerator(f))
201 return util.chunkbuffer(zgenerator(f))
202
202
203 def changegroupsubset(self, bases, heads, source):
203 def changegroupsubset(self, bases, heads, source):
204 self.requirecap('changegroupsubset', _('look up remote changes'))
204 self.requirecap('changegroupsubset', _('look up remote changes'))
205 baselst = " ".join([hex(n) for n in bases])
205 baselst = " ".join([hex(n) for n in bases])
206 headlst = " ".join([hex(n) for n in heads])
206 headlst = " ".join([hex(n) for n in heads])
207 f = self.do_cmd("changegroupsubset", bases=baselst, heads=headlst)
207 f = self.do_cmd("changegroupsubset", bases=baselst, heads=headlst)
208 return util.chunkbuffer(zgenerator(f))
208 return util.chunkbuffer(zgenerator(f))
209
209
210 def unbundle(self, cg, heads, source):
210 def unbundle(self, cg, heads, source):
211 '''Send cg (a readable file-like object representing the
212 changegroup to push, typically a chunkbuffer object) to the
213 remote server as a bundle. Return an integer response code:
214 non-zero indicates a successful push (see
215 localrepository.addchangegroup()), and zero indicates either
216 error or nothing to push.'''
211 # have to stream bundle to a temp file because we do not have
217 # have to stream bundle to a temp file because we do not have
212 # http 1.1 chunked transfer.
218 # http 1.1 chunked transfer.
213
219
214 type = ""
220 type = ""
215 types = self.capable('unbundle')
221 types = self.capable('unbundle')
216 # servers older than d1b16a746db6 will send 'unbundle' as a
222 # servers older than d1b16a746db6 will send 'unbundle' as a
217 # boolean capability
223 # boolean capability
218 try:
224 try:
219 types = types.split(',')
225 types = types.split(',')
220 except AttributeError:
226 except AttributeError:
221 types = [""]
227 types = [""]
222 if types:
228 if types:
223 for x in types:
229 for x in types:
224 if x in changegroup.bundletypes:
230 if x in changegroup.bundletypes:
225 type = x
231 type = x
226 break
232 break
227
233
228 tempname = changegroup.writebundle(cg, None, type)
234 tempname = changegroup.writebundle(cg, None, type)
229 fp = url.httpsendfile(tempname, "rb")
235 fp = url.httpsendfile(tempname, "rb")
230 try:
236 try:
231 try:
237 try:
232 resp = self.do_read(
238 resp = self.do_read(
233 'unbundle', data=fp,
239 'unbundle', data=fp,
234 headers={'Content-Type': 'application/mercurial-0.1'},
240 headers={'Content-Type': 'application/mercurial-0.1'},
235 heads=' '.join(map(hex, heads)))
241 heads=' '.join(map(hex, heads)))
236 resp_code, output = resp.split('\n', 1)
242 resp_code, output = resp.split('\n', 1)
237 try:
243 try:
238 ret = int(resp_code)
244 ret = int(resp_code)
239 except ValueError, err:
245 except ValueError, err:
240 raise error.ResponseError(
246 raise error.ResponseError(
241 _('push failed (unexpected response):'), resp)
247 _('push failed (unexpected response):'), resp)
242 for l in output.splitlines(True):
248 for l in output.splitlines(True):
243 self.ui.status(_('remote: '), l)
249 self.ui.status(_('remote: '), l)
244 return ret
250 return ret
245 except socket.error, err:
251 except socket.error, err:
246 if err[0] in (errno.ECONNRESET, errno.EPIPE):
252 if err[0] in (errno.ECONNRESET, errno.EPIPE):
247 raise util.Abort(_('push failed: %s') % err[1])
253 raise util.Abort(_('push failed: %s') % err[1])
248 raise util.Abort(err[1])
254 raise util.Abort(err[1])
249 finally:
255 finally:
250 fp.close()
256 fp.close()
251 os.unlink(tempname)
257 os.unlink(tempname)
252
258
253 def stream_out(self):
259 def stream_out(self):
254 return self.do_cmd('stream_out')
260 return self.do_cmd('stream_out')
255
261
256 class httpsrepository(httprepository):
262 class httpsrepository(httprepository):
257 def __init__(self, ui, path):
263 def __init__(self, ui, path):
258 if not url.has_https:
264 if not url.has_https:
259 raise util.Abort(_('Python support for SSL and HTTPS '
265 raise util.Abort(_('Python support for SSL and HTTPS '
260 'is not installed'))
266 'is not installed'))
261 httprepository.__init__(self, ui, path)
267 httprepository.__init__(self, ui, path)
262
268
263 def instance(ui, path, create):
269 def instance(ui, path, create):
264 if create:
270 if create:
265 raise util.Abort(_('cannot create new http repository'))
271 raise util.Abort(_('cannot create new http repository'))
266 try:
272 try:
267 if path.startswith('https:'):
273 if path.startswith('https:'):
268 inst = httpsrepository(ui, path)
274 inst = httpsrepository(ui, path)
269 else:
275 else:
270 inst = httprepository(ui, path)
276 inst = httprepository(ui, path)
271 inst.between([(nullid, nullid)])
277 inst.between([(nullid, nullid)])
272 return inst
278 return inst
273 except error.RepoError:
279 except error.RepoError:
274 ui.note('(falling back to static-http)\n')
280 ui.note('(falling back to static-http)\n')
275 return statichttprepo.instance(ui, "static-" + path, create)
281 return statichttprepo.instance(ui, "static-" + path, create)
@@ -1,2263 +1,2291 b''
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 node import bin, hex, nullid, nullrev, short
8 from node import bin, hex, nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import repo, changegroup, subrepo
10 import repo, changegroup, subrepo
11 import changelog, dirstate, filelog, manifest, context
11 import changelog, dirstate, filelog, manifest, context
12 import lock, transaction, store, encoding
12 import lock, transaction, store, encoding
13 import util, extensions, hook, error
13 import util, extensions, hook, error
14 import match as matchmod
14 import match as matchmod
15 import merge as mergemod
15 import merge as mergemod
16 import tags as tagsmod
16 import tags as tagsmod
17 import url as urlmod
17 import url as urlmod
18 from lock import release
18 from lock import release
19 import weakref, stat, errno, os, time, inspect
19 import weakref, stat, errno, os, time, inspect
20 propertycache = util.propertycache
20 propertycache = util.propertycache
21
21
22 class localrepository(repo.repository):
22 class localrepository(repo.repository):
23 capabilities = set(('lookup', 'changegroupsubset', 'branchmap'))
23 capabilities = set(('lookup', 'changegroupsubset', 'branchmap'))
24 supported = set('revlogv1 store fncache shared'.split())
24 supported = set('revlogv1 store fncache shared'.split())
25
25
26 def __init__(self, baseui, path=None, create=0):
26 def __init__(self, baseui, path=None, create=0):
27 repo.repository.__init__(self)
27 repo.repository.__init__(self)
28 self.root = os.path.realpath(path)
28 self.root = os.path.realpath(path)
29 self.path = os.path.join(self.root, ".hg")
29 self.path = os.path.join(self.root, ".hg")
30 self.origroot = path
30 self.origroot = path
31 self.opener = util.opener(self.path)
31 self.opener = util.opener(self.path)
32 self.wopener = util.opener(self.root)
32 self.wopener = util.opener(self.root)
33 self.baseui = baseui
33 self.baseui = baseui
34 self.ui = baseui.copy()
34 self.ui = baseui.copy()
35
35
36 try:
36 try:
37 self.ui.readconfig(self.join("hgrc"), self.root)
37 self.ui.readconfig(self.join("hgrc"), self.root)
38 extensions.loadall(self.ui)
38 extensions.loadall(self.ui)
39 except IOError:
39 except IOError:
40 pass
40 pass
41
41
42 if not os.path.isdir(self.path):
42 if not os.path.isdir(self.path):
43 if create:
43 if create:
44 if not os.path.exists(path):
44 if not os.path.exists(path):
45 os.mkdir(path)
45 os.mkdir(path)
46 os.mkdir(self.path)
46 os.mkdir(self.path)
47 requirements = ["revlogv1"]
47 requirements = ["revlogv1"]
48 if self.ui.configbool('format', 'usestore', True):
48 if self.ui.configbool('format', 'usestore', True):
49 os.mkdir(os.path.join(self.path, "store"))
49 os.mkdir(os.path.join(self.path, "store"))
50 requirements.append("store")
50 requirements.append("store")
51 if self.ui.configbool('format', 'usefncache', True):
51 if self.ui.configbool('format', 'usefncache', True):
52 requirements.append("fncache")
52 requirements.append("fncache")
53 # create an invalid changelog
53 # create an invalid changelog
54 self.opener("00changelog.i", "a").write(
54 self.opener("00changelog.i", "a").write(
55 '\0\0\0\2' # represents revlogv2
55 '\0\0\0\2' # represents revlogv2
56 ' dummy changelog to prevent using the old repo layout'
56 ' dummy changelog to prevent using the old repo layout'
57 )
57 )
58 reqfile = self.opener("requires", "w")
58 reqfile = self.opener("requires", "w")
59 for r in requirements:
59 for r in requirements:
60 reqfile.write("%s\n" % r)
60 reqfile.write("%s\n" % r)
61 reqfile.close()
61 reqfile.close()
62 else:
62 else:
63 raise error.RepoError(_("repository %s not found") % path)
63 raise error.RepoError(_("repository %s not found") % path)
64 elif create:
64 elif create:
65 raise error.RepoError(_("repository %s already exists") % path)
65 raise error.RepoError(_("repository %s already exists") % path)
66 else:
66 else:
67 # find requirements
67 # find requirements
68 requirements = set()
68 requirements = set()
69 try:
69 try:
70 requirements = set(self.opener("requires").read().splitlines())
70 requirements = set(self.opener("requires").read().splitlines())
71 except IOError, inst:
71 except IOError, inst:
72 if inst.errno != errno.ENOENT:
72 if inst.errno != errno.ENOENT:
73 raise
73 raise
74 for r in requirements - self.supported:
74 for r in requirements - self.supported:
75 raise error.RepoError(_("requirement '%s' not supported") % r)
75 raise error.RepoError(_("requirement '%s' not supported") % r)
76
76
77 self.sharedpath = self.path
77 self.sharedpath = self.path
78 try:
78 try:
79 s = os.path.realpath(self.opener("sharedpath").read())
79 s = os.path.realpath(self.opener("sharedpath").read())
80 if not os.path.exists(s):
80 if not os.path.exists(s):
81 raise error.RepoError(
81 raise error.RepoError(
82 _('.hg/sharedpath points to nonexistent directory %s') % s)
82 _('.hg/sharedpath points to nonexistent directory %s') % s)
83 self.sharedpath = s
83 self.sharedpath = s
84 except IOError, inst:
84 except IOError, inst:
85 if inst.errno != errno.ENOENT:
85 if inst.errno != errno.ENOENT:
86 raise
86 raise
87
87
88 self.store = store.store(requirements, self.sharedpath, util.opener)
88 self.store = store.store(requirements, self.sharedpath, util.opener)
89 self.spath = self.store.path
89 self.spath = self.store.path
90 self.sopener = self.store.opener
90 self.sopener = self.store.opener
91 self.sjoin = self.store.join
91 self.sjoin = self.store.join
92 self.opener.createmode = self.store.createmode
92 self.opener.createmode = self.store.createmode
93 self.sopener.options = {}
93 self.sopener.options = {}
94
94
95 # These two define the set of tags for this repository. _tags
95 # These two define the set of tags for this repository. _tags
96 # maps tag name to node; _tagtypes maps tag name to 'global' or
96 # maps tag name to node; _tagtypes maps tag name to 'global' or
97 # 'local'. (Global tags are defined by .hgtags across all
97 # 'local'. (Global tags are defined by .hgtags across all
98 # heads, and local tags are defined in .hg/localtags.) They
98 # heads, and local tags are defined in .hg/localtags.) They
99 # constitute the in-memory cache of tags.
99 # constitute the in-memory cache of tags.
100 self._tags = None
100 self._tags = None
101 self._tagtypes = None
101 self._tagtypes = None
102
102
103 self._branchcache = None # in UTF-8
103 self._branchcache = None # in UTF-8
104 self._branchcachetip = None
104 self._branchcachetip = None
105 self.nodetagscache = None
105 self.nodetagscache = None
106 self.filterpats = {}
106 self.filterpats = {}
107 self._datafilters = {}
107 self._datafilters = {}
108 self._transref = self._lockref = self._wlockref = None
108 self._transref = self._lockref = self._wlockref = None
109
109
110 @propertycache
110 @propertycache
111 def changelog(self):
111 def changelog(self):
112 c = changelog.changelog(self.sopener)
112 c = changelog.changelog(self.sopener)
113 if 'HG_PENDING' in os.environ:
113 if 'HG_PENDING' in os.environ:
114 p = os.environ['HG_PENDING']
114 p = os.environ['HG_PENDING']
115 if p.startswith(self.root):
115 if p.startswith(self.root):
116 c.readpending('00changelog.i.a')
116 c.readpending('00changelog.i.a')
117 self.sopener.options['defversion'] = c.version
117 self.sopener.options['defversion'] = c.version
118 return c
118 return c
119
119
120 @propertycache
120 @propertycache
121 def manifest(self):
121 def manifest(self):
122 return manifest.manifest(self.sopener)
122 return manifest.manifest(self.sopener)
123
123
124 @propertycache
124 @propertycache
125 def dirstate(self):
125 def dirstate(self):
126 return dirstate.dirstate(self.opener, self.ui, self.root)
126 return dirstate.dirstate(self.opener, self.ui, self.root)
127
127
128 def __getitem__(self, changeid):
128 def __getitem__(self, changeid):
129 if changeid is None:
129 if changeid is None:
130 return context.workingctx(self)
130 return context.workingctx(self)
131 return context.changectx(self, changeid)
131 return context.changectx(self, changeid)
132
132
133 def __contains__(self, changeid):
133 def __contains__(self, changeid):
134 try:
134 try:
135 return bool(self.lookup(changeid))
135 return bool(self.lookup(changeid))
136 except error.RepoLookupError:
136 except error.RepoLookupError:
137 return False
137 return False
138
138
139 def __nonzero__(self):
139 def __nonzero__(self):
140 return True
140 return True
141
141
142 def __len__(self):
142 def __len__(self):
143 return len(self.changelog)
143 return len(self.changelog)
144
144
145 def __iter__(self):
145 def __iter__(self):
146 for i in xrange(len(self)):
146 for i in xrange(len(self)):
147 yield i
147 yield i
148
148
149 def url(self):
149 def url(self):
150 return 'file:' + self.root
150 return 'file:' + self.root
151
151
152 def hook(self, name, throw=False, **args):
152 def hook(self, name, throw=False, **args):
153 return hook.hook(self.ui, self, name, throw, **args)
153 return hook.hook(self.ui, self, name, throw, **args)
154
154
155 tag_disallowed = ':\r\n'
155 tag_disallowed = ':\r\n'
156
156
157 def _tag(self, names, node, message, local, user, date, extra={}):
157 def _tag(self, names, node, message, local, user, date, extra={}):
158 if isinstance(names, str):
158 if isinstance(names, str):
159 allchars = names
159 allchars = names
160 names = (names,)
160 names = (names,)
161 else:
161 else:
162 allchars = ''.join(names)
162 allchars = ''.join(names)
163 for c in self.tag_disallowed:
163 for c in self.tag_disallowed:
164 if c in allchars:
164 if c in allchars:
165 raise util.Abort(_('%r cannot be used in a tag name') % c)
165 raise util.Abort(_('%r cannot be used in a tag name') % c)
166
166
167 branches = self.branchmap()
167 branches = self.branchmap()
168 for name in names:
168 for name in names:
169 self.hook('pretag', throw=True, node=hex(node), tag=name,
169 self.hook('pretag', throw=True, node=hex(node), tag=name,
170 local=local)
170 local=local)
171 if name in branches:
171 if name in branches:
172 self.ui.warn(_("warning: tag %s conflicts with existing"
172 self.ui.warn(_("warning: tag %s conflicts with existing"
173 " branch name\n") % name)
173 " branch name\n") % name)
174
174
175 def writetags(fp, names, munge, prevtags):
175 def writetags(fp, names, munge, prevtags):
176 fp.seek(0, 2)
176 fp.seek(0, 2)
177 if prevtags and prevtags[-1] != '\n':
177 if prevtags and prevtags[-1] != '\n':
178 fp.write('\n')
178 fp.write('\n')
179 for name in names:
179 for name in names:
180 m = munge and munge(name) or name
180 m = munge and munge(name) or name
181 if self._tagtypes and name in self._tagtypes:
181 if self._tagtypes and name in self._tagtypes:
182 old = self._tags.get(name, nullid)
182 old = self._tags.get(name, nullid)
183 fp.write('%s %s\n' % (hex(old), m))
183 fp.write('%s %s\n' % (hex(old), m))
184 fp.write('%s %s\n' % (hex(node), m))
184 fp.write('%s %s\n' % (hex(node), m))
185 fp.close()
185 fp.close()
186
186
187 prevtags = ''
187 prevtags = ''
188 if local:
188 if local:
189 try:
189 try:
190 fp = self.opener('localtags', 'r+')
190 fp = self.opener('localtags', 'r+')
191 except IOError:
191 except IOError:
192 fp = self.opener('localtags', 'a')
192 fp = self.opener('localtags', 'a')
193 else:
193 else:
194 prevtags = fp.read()
194 prevtags = fp.read()
195
195
196 # local tags are stored in the current charset
196 # local tags are stored in the current charset
197 writetags(fp, names, None, prevtags)
197 writetags(fp, names, None, prevtags)
198 for name in names:
198 for name in names:
199 self.hook('tag', node=hex(node), tag=name, local=local)
199 self.hook('tag', node=hex(node), tag=name, local=local)
200 return
200 return
201
201
202 try:
202 try:
203 fp = self.wfile('.hgtags', 'rb+')
203 fp = self.wfile('.hgtags', 'rb+')
204 except IOError:
204 except IOError:
205 fp = self.wfile('.hgtags', 'ab')
205 fp = self.wfile('.hgtags', 'ab')
206 else:
206 else:
207 prevtags = fp.read()
207 prevtags = fp.read()
208
208
209 # committed tags are stored in UTF-8
209 # committed tags are stored in UTF-8
210 writetags(fp, names, encoding.fromlocal, prevtags)
210 writetags(fp, names, encoding.fromlocal, prevtags)
211
211
212 if '.hgtags' not in self.dirstate:
212 if '.hgtags' not in self.dirstate:
213 self.add(['.hgtags'])
213 self.add(['.hgtags'])
214
214
215 m = matchmod.exact(self.root, '', ['.hgtags'])
215 m = matchmod.exact(self.root, '', ['.hgtags'])
216 tagnode = self.commit(message, user, date, extra=extra, match=m)
216 tagnode = self.commit(message, user, date, extra=extra, match=m)
217
217
218 for name in names:
218 for name in names:
219 self.hook('tag', node=hex(node), tag=name, local=local)
219 self.hook('tag', node=hex(node), tag=name, local=local)
220
220
221 return tagnode
221 return tagnode
222
222
223 def tag(self, names, node, message, local, user, date):
223 def tag(self, names, node, message, local, user, date):
224 '''tag a revision with one or more symbolic names.
224 '''tag a revision with one or more symbolic names.
225
225
226 names is a list of strings or, when adding a single tag, names may be a
226 names is a list of strings or, when adding a single tag, names may be a
227 string.
227 string.
228
228
229 if local is True, the tags are stored in a per-repository file.
229 if local is True, the tags are stored in a per-repository file.
230 otherwise, they are stored in the .hgtags file, and a new
230 otherwise, they are stored in the .hgtags file, and a new
231 changeset is committed with the change.
231 changeset is committed with the change.
232
232
233 keyword arguments:
233 keyword arguments:
234
234
235 local: whether to store tags in non-version-controlled file
235 local: whether to store tags in non-version-controlled file
236 (default False)
236 (default False)
237
237
238 message: commit message to use if committing
238 message: commit message to use if committing
239
239
240 user: name of user to use if committing
240 user: name of user to use if committing
241
241
242 date: date tuple to use if committing'''
242 date: date tuple to use if committing'''
243
243
244 for x in self.status()[:5]:
244 for x in self.status()[:5]:
245 if '.hgtags' in x:
245 if '.hgtags' in x:
246 raise util.Abort(_('working copy of .hgtags is changed '
246 raise util.Abort(_('working copy of .hgtags is changed '
247 '(please commit .hgtags manually)'))
247 '(please commit .hgtags manually)'))
248
248
249 self.tags() # instantiate the cache
249 self.tags() # instantiate the cache
250 self._tag(names, node, message, local, user, date)
250 self._tag(names, node, message, local, user, date)
251
251
252 def tags(self):
252 def tags(self):
253 '''return a mapping of tag to node'''
253 '''return a mapping of tag to node'''
254 if self._tags is None:
254 if self._tags is None:
255 (self._tags, self._tagtypes) = self._findtags()
255 (self._tags, self._tagtypes) = self._findtags()
256
256
257 return self._tags
257 return self._tags
258
258
259 def _findtags(self):
259 def _findtags(self):
260 '''Do the hard work of finding tags. Return a pair of dicts
260 '''Do the hard work of finding tags. Return a pair of dicts
261 (tags, tagtypes) where tags maps tag name to node, and tagtypes
261 (tags, tagtypes) where tags maps tag name to node, and tagtypes
262 maps tag name to a string like \'global\' or \'local\'.
262 maps tag name to a string like \'global\' or \'local\'.
263 Subclasses or extensions are free to add their own tags, but
263 Subclasses or extensions are free to add their own tags, but
264 should be aware that the returned dicts will be retained for the
264 should be aware that the returned dicts will be retained for the
265 duration of the localrepo object.'''
265 duration of the localrepo object.'''
266
266
267 # XXX what tagtype should subclasses/extensions use? Currently
267 # XXX what tagtype should subclasses/extensions use? Currently
268 # mq and bookmarks add tags, but do not set the tagtype at all.
268 # mq and bookmarks add tags, but do not set the tagtype at all.
269 # Should each extension invent its own tag type? Should there
269 # Should each extension invent its own tag type? Should there
270 # be one tagtype for all such "virtual" tags? Or is the status
270 # be one tagtype for all such "virtual" tags? Or is the status
271 # quo fine?
271 # quo fine?
272
272
273 alltags = {} # map tag name to (node, hist)
273 alltags = {} # map tag name to (node, hist)
274 tagtypes = {}
274 tagtypes = {}
275
275
276 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
276 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
277 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
277 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
278
278
279 # Build the return dicts. Have to re-encode tag names because
279 # Build the return dicts. Have to re-encode tag names because
280 # the tags module always uses UTF-8 (in order not to lose info
280 # the tags module always uses UTF-8 (in order not to lose info
281 # writing to the cache), but the rest of Mercurial wants them in
281 # writing to the cache), but the rest of Mercurial wants them in
282 # local encoding.
282 # local encoding.
283 tags = {}
283 tags = {}
284 for (name, (node, hist)) in alltags.iteritems():
284 for (name, (node, hist)) in alltags.iteritems():
285 if node != nullid:
285 if node != nullid:
286 tags[encoding.tolocal(name)] = node
286 tags[encoding.tolocal(name)] = node
287 tags['tip'] = self.changelog.tip()
287 tags['tip'] = self.changelog.tip()
288 tagtypes = dict([(encoding.tolocal(name), value)
288 tagtypes = dict([(encoding.tolocal(name), value)
289 for (name, value) in tagtypes.iteritems()])
289 for (name, value) in tagtypes.iteritems()])
290 return (tags, tagtypes)
290 return (tags, tagtypes)
291
291
292 def tagtype(self, tagname):
292 def tagtype(self, tagname):
293 '''
293 '''
294 return the type of the given tag. result can be:
294 return the type of the given tag. result can be:
295
295
296 'local' : a local tag
296 'local' : a local tag
297 'global' : a global tag
297 'global' : a global tag
298 None : tag does not exist
298 None : tag does not exist
299 '''
299 '''
300
300
301 self.tags()
301 self.tags()
302
302
303 return self._tagtypes.get(tagname)
303 return self._tagtypes.get(tagname)
304
304
305 def tagslist(self):
305 def tagslist(self):
306 '''return a list of tags ordered by revision'''
306 '''return a list of tags ordered by revision'''
307 l = []
307 l = []
308 for t, n in self.tags().iteritems():
308 for t, n in self.tags().iteritems():
309 try:
309 try:
310 r = self.changelog.rev(n)
310 r = self.changelog.rev(n)
311 except:
311 except:
312 r = -2 # sort to the beginning of the list if unknown
312 r = -2 # sort to the beginning of the list if unknown
313 l.append((r, t, n))
313 l.append((r, t, n))
314 return [(t, n) for r, t, n in sorted(l)]
314 return [(t, n) for r, t, n in sorted(l)]
315
315
316 def nodetags(self, node):
316 def nodetags(self, node):
317 '''return the tags associated with a node'''
317 '''return the tags associated with a node'''
318 if not self.nodetagscache:
318 if not self.nodetagscache:
319 self.nodetagscache = {}
319 self.nodetagscache = {}
320 for t, n in self.tags().iteritems():
320 for t, n in self.tags().iteritems():
321 self.nodetagscache.setdefault(n, []).append(t)
321 self.nodetagscache.setdefault(n, []).append(t)
322 for tags in self.nodetagscache.itervalues():
322 for tags in self.nodetagscache.itervalues():
323 tags.sort()
323 tags.sort()
324 return self.nodetagscache.get(node, [])
324 return self.nodetagscache.get(node, [])
325
325
326 def _branchtags(self, partial, lrev):
326 def _branchtags(self, partial, lrev):
327 # TODO: rename this function?
327 # TODO: rename this function?
328 tiprev = len(self) - 1
328 tiprev = len(self) - 1
329 if lrev != tiprev:
329 if lrev != tiprev:
330 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
330 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
331 self._updatebranchcache(partial, ctxgen)
331 self._updatebranchcache(partial, ctxgen)
332 self._writebranchcache(partial, self.changelog.tip(), tiprev)
332 self._writebranchcache(partial, self.changelog.tip(), tiprev)
333
333
334 return partial
334 return partial
335
335
336 def branchmap(self):
336 def branchmap(self):
337 '''returns a dictionary {branch: [branchheads]}'''
337 '''returns a dictionary {branch: [branchheads]}'''
338 tip = self.changelog.tip()
338 tip = self.changelog.tip()
339 if self._branchcache is not None and self._branchcachetip == tip:
339 if self._branchcache is not None and self._branchcachetip == tip:
340 return self._branchcache
340 return self._branchcache
341
341
342 oldtip = self._branchcachetip
342 oldtip = self._branchcachetip
343 self._branchcachetip = tip
343 self._branchcachetip = tip
344 if oldtip is None or oldtip not in self.changelog.nodemap:
344 if oldtip is None or oldtip not in self.changelog.nodemap:
345 partial, last, lrev = self._readbranchcache()
345 partial, last, lrev = self._readbranchcache()
346 else:
346 else:
347 lrev = self.changelog.rev(oldtip)
347 lrev = self.changelog.rev(oldtip)
348 partial = self._branchcache
348 partial = self._branchcache
349
349
350 self._branchtags(partial, lrev)
350 self._branchtags(partial, lrev)
351 # this private cache holds all heads (not just tips)
351 # this private cache holds all heads (not just tips)
352 self._branchcache = partial
352 self._branchcache = partial
353
353
354 return self._branchcache
354 return self._branchcache
355
355
356 def branchtags(self):
356 def branchtags(self):
357 '''return a dict where branch names map to the tipmost head of
357 '''return a dict where branch names map to the tipmost head of
358 the branch, open heads come before closed'''
358 the branch, open heads come before closed'''
359 bt = {}
359 bt = {}
360 for bn, heads in self.branchmap().iteritems():
360 for bn, heads in self.branchmap().iteritems():
361 tip = heads[-1]
361 tip = heads[-1]
362 for h in reversed(heads):
362 for h in reversed(heads):
363 if 'close' not in self.changelog.read(h)[5]:
363 if 'close' not in self.changelog.read(h)[5]:
364 tip = h
364 tip = h
365 break
365 break
366 bt[bn] = tip
366 bt[bn] = tip
367 return bt
367 return bt
368
368
369
369
370 def _readbranchcache(self):
370 def _readbranchcache(self):
371 partial = {}
371 partial = {}
372 try:
372 try:
373 f = self.opener("branchheads.cache")
373 f = self.opener("branchheads.cache")
374 lines = f.read().split('\n')
374 lines = f.read().split('\n')
375 f.close()
375 f.close()
376 except (IOError, OSError):
376 except (IOError, OSError):
377 return {}, nullid, nullrev
377 return {}, nullid, nullrev
378
378
379 try:
379 try:
380 last, lrev = lines.pop(0).split(" ", 1)
380 last, lrev = lines.pop(0).split(" ", 1)
381 last, lrev = bin(last), int(lrev)
381 last, lrev = bin(last), int(lrev)
382 if lrev >= len(self) or self[lrev].node() != last:
382 if lrev >= len(self) or self[lrev].node() != last:
383 # invalidate the cache
383 # invalidate the cache
384 raise ValueError('invalidating branch cache (tip differs)')
384 raise ValueError('invalidating branch cache (tip differs)')
385 for l in lines:
385 for l in lines:
386 if not l:
386 if not l:
387 continue
387 continue
388 node, label = l.split(" ", 1)
388 node, label = l.split(" ", 1)
389 partial.setdefault(label.strip(), []).append(bin(node))
389 partial.setdefault(label.strip(), []).append(bin(node))
390 except KeyboardInterrupt:
390 except KeyboardInterrupt:
391 raise
391 raise
392 except Exception, inst:
392 except Exception, inst:
393 if self.ui.debugflag:
393 if self.ui.debugflag:
394 self.ui.warn(str(inst), '\n')
394 self.ui.warn(str(inst), '\n')
395 partial, last, lrev = {}, nullid, nullrev
395 partial, last, lrev = {}, nullid, nullrev
396 return partial, last, lrev
396 return partial, last, lrev
397
397
398 def _writebranchcache(self, branches, tip, tiprev):
398 def _writebranchcache(self, branches, tip, tiprev):
399 try:
399 try:
400 f = self.opener("branchheads.cache", "w", atomictemp=True)
400 f = self.opener("branchheads.cache", "w", atomictemp=True)
401 f.write("%s %s\n" % (hex(tip), tiprev))
401 f.write("%s %s\n" % (hex(tip), tiprev))
402 for label, nodes in branches.iteritems():
402 for label, nodes in branches.iteritems():
403 for node in nodes:
403 for node in nodes:
404 f.write("%s %s\n" % (hex(node), label))
404 f.write("%s %s\n" % (hex(node), label))
405 f.rename()
405 f.rename()
406 except (IOError, OSError):
406 except (IOError, OSError):
407 pass
407 pass
408
408
409 def _updatebranchcache(self, partial, ctxgen):
409 def _updatebranchcache(self, partial, ctxgen):
410 # collect new branch entries
410 # collect new branch entries
411 newbranches = {}
411 newbranches = {}
412 for c in ctxgen:
412 for c in ctxgen:
413 newbranches.setdefault(c.branch(), []).append(c.node())
413 newbranches.setdefault(c.branch(), []).append(c.node())
414 # if older branchheads are reachable from new ones, they aren't
414 # if older branchheads are reachable from new ones, they aren't
415 # really branchheads. Note checking parents is insufficient:
415 # really branchheads. Note checking parents is insufficient:
416 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
416 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
417 for branch, newnodes in newbranches.iteritems():
417 for branch, newnodes in newbranches.iteritems():
418 bheads = partial.setdefault(branch, [])
418 bheads = partial.setdefault(branch, [])
419 bheads.extend(newnodes)
419 bheads.extend(newnodes)
420 if len(bheads) <= 1:
420 if len(bheads) <= 1:
421 continue
421 continue
422 # starting from tip means fewer passes over reachable
422 # starting from tip means fewer passes over reachable
423 while newnodes:
423 while newnodes:
424 latest = newnodes.pop()
424 latest = newnodes.pop()
425 if latest not in bheads:
425 if latest not in bheads:
426 continue
426 continue
427 minbhrev = self[min([self[bh].rev() for bh in bheads])].node()
427 minbhrev = self[min([self[bh].rev() for bh in bheads])].node()
428 reachable = self.changelog.reachable(latest, minbhrev)
428 reachable = self.changelog.reachable(latest, minbhrev)
429 reachable.remove(latest)
429 reachable.remove(latest)
430 bheads = [b for b in bheads if b not in reachable]
430 bheads = [b for b in bheads if b not in reachable]
431 partial[branch] = bheads
431 partial[branch] = bheads
432
432
433 def lookup(self, key):
433 def lookup(self, key):
434 if isinstance(key, int):
434 if isinstance(key, int):
435 return self.changelog.node(key)
435 return self.changelog.node(key)
436 elif key == '.':
436 elif key == '.':
437 return self.dirstate.parents()[0]
437 return self.dirstate.parents()[0]
438 elif key == 'null':
438 elif key == 'null':
439 return nullid
439 return nullid
440 elif key == 'tip':
440 elif key == 'tip':
441 return self.changelog.tip()
441 return self.changelog.tip()
442 n = self.changelog._match(key)
442 n = self.changelog._match(key)
443 if n:
443 if n:
444 return n
444 return n
445 if key in self.tags():
445 if key in self.tags():
446 return self.tags()[key]
446 return self.tags()[key]
447 if key in self.branchtags():
447 if key in self.branchtags():
448 return self.branchtags()[key]
448 return self.branchtags()[key]
449 n = self.changelog._partialmatch(key)
449 n = self.changelog._partialmatch(key)
450 if n:
450 if n:
451 return n
451 return n
452
452
453 # can't find key, check if it might have come from damaged dirstate
453 # can't find key, check if it might have come from damaged dirstate
454 if key in self.dirstate.parents():
454 if key in self.dirstate.parents():
455 raise error.Abort(_("working directory has unknown parent '%s'!")
455 raise error.Abort(_("working directory has unknown parent '%s'!")
456 % short(key))
456 % short(key))
457 try:
457 try:
458 if len(key) == 20:
458 if len(key) == 20:
459 key = hex(key)
459 key = hex(key)
460 except:
460 except:
461 pass
461 pass
462 raise error.RepoLookupError(_("unknown revision '%s'") % key)
462 raise error.RepoLookupError(_("unknown revision '%s'") % key)
463
463
464 def lookupbranch(self, key, remote=None):
464 def lookupbranch(self, key, remote=None):
465 repo = remote or self
465 repo = remote or self
466 if key in repo.branchmap():
466 if key in repo.branchmap():
467 return key
467 return key
468
468
469 repo = (remote and remote.local()) and remote or self
469 repo = (remote and remote.local()) and remote or self
470 return repo[key].branch()
470 return repo[key].branch()
471
471
472 def local(self):
472 def local(self):
473 return True
473 return True
474
474
475 def join(self, f):
475 def join(self, f):
476 return os.path.join(self.path, f)
476 return os.path.join(self.path, f)
477
477
478 def wjoin(self, f):
478 def wjoin(self, f):
479 return os.path.join(self.root, f)
479 return os.path.join(self.root, f)
480
480
481 def rjoin(self, f):
481 def rjoin(self, f):
482 return os.path.join(self.root, util.pconvert(f))
482 return os.path.join(self.root, util.pconvert(f))
483
483
484 def file(self, f):
484 def file(self, f):
485 if f[0] == '/':
485 if f[0] == '/':
486 f = f[1:]
486 f = f[1:]
487 return filelog.filelog(self.sopener, f)
487 return filelog.filelog(self.sopener, f)
488
488
489 def changectx(self, changeid):
489 def changectx(self, changeid):
490 return self[changeid]
490 return self[changeid]
491
491
492 def parents(self, changeid=None):
492 def parents(self, changeid=None):
493 '''get list of changectxs for parents of changeid'''
493 '''get list of changectxs for parents of changeid'''
494 return self[changeid].parents()
494 return self[changeid].parents()
495
495
496 def filectx(self, path, changeid=None, fileid=None):
496 def filectx(self, path, changeid=None, fileid=None):
497 """changeid can be a changeset revision, node, or tag.
497 """changeid can be a changeset revision, node, or tag.
498 fileid can be a file revision or node."""
498 fileid can be a file revision or node."""
499 return context.filectx(self, path, changeid, fileid)
499 return context.filectx(self, path, changeid, fileid)
500
500
501 def getcwd(self):
501 def getcwd(self):
502 return self.dirstate.getcwd()
502 return self.dirstate.getcwd()
503
503
504 def pathto(self, f, cwd=None):
504 def pathto(self, f, cwd=None):
505 return self.dirstate.pathto(f, cwd)
505 return self.dirstate.pathto(f, cwd)
506
506
507 def wfile(self, f, mode='r'):
507 def wfile(self, f, mode='r'):
508 return self.wopener(f, mode)
508 return self.wopener(f, mode)
509
509
510 def _link(self, f):
510 def _link(self, f):
511 return os.path.islink(self.wjoin(f))
511 return os.path.islink(self.wjoin(f))
512
512
513 def _filter(self, filter, filename, data):
513 def _filter(self, filter, filename, data):
514 if filter not in self.filterpats:
514 if filter not in self.filterpats:
515 l = []
515 l = []
516 for pat, cmd in self.ui.configitems(filter):
516 for pat, cmd in self.ui.configitems(filter):
517 if cmd == '!':
517 if cmd == '!':
518 continue
518 continue
519 mf = matchmod.match(self.root, '', [pat])
519 mf = matchmod.match(self.root, '', [pat])
520 fn = None
520 fn = None
521 params = cmd
521 params = cmd
522 for name, filterfn in self._datafilters.iteritems():
522 for name, filterfn in self._datafilters.iteritems():
523 if cmd.startswith(name):
523 if cmd.startswith(name):
524 fn = filterfn
524 fn = filterfn
525 params = cmd[len(name):].lstrip()
525 params = cmd[len(name):].lstrip()
526 break
526 break
527 if not fn:
527 if not fn:
528 fn = lambda s, c, **kwargs: util.filter(s, c)
528 fn = lambda s, c, **kwargs: util.filter(s, c)
529 # Wrap old filters not supporting keyword arguments
529 # Wrap old filters not supporting keyword arguments
530 if not inspect.getargspec(fn)[2]:
530 if not inspect.getargspec(fn)[2]:
531 oldfn = fn
531 oldfn = fn
532 fn = lambda s, c, **kwargs: oldfn(s, c)
532 fn = lambda s, c, **kwargs: oldfn(s, c)
533 l.append((mf, fn, params))
533 l.append((mf, fn, params))
534 self.filterpats[filter] = l
534 self.filterpats[filter] = l
535
535
536 for mf, fn, cmd in self.filterpats[filter]:
536 for mf, fn, cmd in self.filterpats[filter]:
537 if mf(filename):
537 if mf(filename):
538 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
538 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
539 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
539 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
540 break
540 break
541
541
542 return data
542 return data
543
543
544 def adddatafilter(self, name, filter):
544 def adddatafilter(self, name, filter):
545 self._datafilters[name] = filter
545 self._datafilters[name] = filter
546
546
547 def wread(self, filename):
547 def wread(self, filename):
548 if self._link(filename):
548 if self._link(filename):
549 data = os.readlink(self.wjoin(filename))
549 data = os.readlink(self.wjoin(filename))
550 else:
550 else:
551 data = self.wopener(filename, 'r').read()
551 data = self.wopener(filename, 'r').read()
552 return self._filter("encode", filename, data)
552 return self._filter("encode", filename, data)
553
553
554 def wwrite(self, filename, data, flags):
554 def wwrite(self, filename, data, flags):
555 data = self._filter("decode", filename, data)
555 data = self._filter("decode", filename, data)
556 try:
556 try:
557 os.unlink(self.wjoin(filename))
557 os.unlink(self.wjoin(filename))
558 except OSError:
558 except OSError:
559 pass
559 pass
560 if 'l' in flags:
560 if 'l' in flags:
561 self.wopener.symlink(data, filename)
561 self.wopener.symlink(data, filename)
562 else:
562 else:
563 self.wopener(filename, 'w').write(data)
563 self.wopener(filename, 'w').write(data)
564 if 'x' in flags:
564 if 'x' in flags:
565 util.set_flags(self.wjoin(filename), False, True)
565 util.set_flags(self.wjoin(filename), False, True)
566
566
567 def wwritedata(self, filename, data):
567 def wwritedata(self, filename, data):
568 return self._filter("decode", filename, data)
568 return self._filter("decode", filename, data)
569
569
570 def transaction(self, desc):
570 def transaction(self, desc):
571 tr = self._transref and self._transref() or None
571 tr = self._transref and self._transref() or None
572 if tr and tr.running():
572 if tr and tr.running():
573 return tr.nest()
573 return tr.nest()
574
574
575 # abort here if the journal already exists
575 # abort here if the journal already exists
576 if os.path.exists(self.sjoin("journal")):
576 if os.path.exists(self.sjoin("journal")):
577 raise error.RepoError(
577 raise error.RepoError(
578 _("abandoned transaction found - run hg recover"))
578 _("abandoned transaction found - run hg recover"))
579
579
580 # save dirstate for rollback
580 # save dirstate for rollback
581 try:
581 try:
582 ds = self.opener("dirstate").read()
582 ds = self.opener("dirstate").read()
583 except IOError:
583 except IOError:
584 ds = ""
584 ds = ""
585 self.opener("journal.dirstate", "w").write(ds)
585 self.opener("journal.dirstate", "w").write(ds)
586 self.opener("journal.branch", "w").write(self.dirstate.branch())
586 self.opener("journal.branch", "w").write(self.dirstate.branch())
587 self.opener("journal.desc", "w").write("%d\n%s\n" % (len(self), desc))
587 self.opener("journal.desc", "w").write("%d\n%s\n" % (len(self), desc))
588
588
589 renames = [(self.sjoin("journal"), self.sjoin("undo")),
589 renames = [(self.sjoin("journal"), self.sjoin("undo")),
590 (self.join("journal.dirstate"), self.join("undo.dirstate")),
590 (self.join("journal.dirstate"), self.join("undo.dirstate")),
591 (self.join("journal.branch"), self.join("undo.branch")),
591 (self.join("journal.branch"), self.join("undo.branch")),
592 (self.join("journal.desc"), self.join("undo.desc"))]
592 (self.join("journal.desc"), self.join("undo.desc"))]
593 tr = transaction.transaction(self.ui.warn, self.sopener,
593 tr = transaction.transaction(self.ui.warn, self.sopener,
594 self.sjoin("journal"),
594 self.sjoin("journal"),
595 aftertrans(renames),
595 aftertrans(renames),
596 self.store.createmode)
596 self.store.createmode)
597 self._transref = weakref.ref(tr)
597 self._transref = weakref.ref(tr)
598 return tr
598 return tr
599
599
600 def recover(self):
600 def recover(self):
601 lock = self.lock()
601 lock = self.lock()
602 try:
602 try:
603 if os.path.exists(self.sjoin("journal")):
603 if os.path.exists(self.sjoin("journal")):
604 self.ui.status(_("rolling back interrupted transaction\n"))
604 self.ui.status(_("rolling back interrupted transaction\n"))
605 transaction.rollback(self.sopener, self.sjoin("journal"),
605 transaction.rollback(self.sopener, self.sjoin("journal"),
606 self.ui.warn)
606 self.ui.warn)
607 self.invalidate()
607 self.invalidate()
608 return True
608 return True
609 else:
609 else:
610 self.ui.warn(_("no interrupted transaction available\n"))
610 self.ui.warn(_("no interrupted transaction available\n"))
611 return False
611 return False
612 finally:
612 finally:
613 lock.release()
613 lock.release()
614
614
615 def rollback(self, dryrun=False):
615 def rollback(self, dryrun=False):
616 wlock = lock = None
616 wlock = lock = None
617 try:
617 try:
618 wlock = self.wlock()
618 wlock = self.wlock()
619 lock = self.lock()
619 lock = self.lock()
620 if os.path.exists(self.sjoin("undo")):
620 if os.path.exists(self.sjoin("undo")):
621 try:
621 try:
622 args = self.opener("undo.desc", "r").read().splitlines()
622 args = self.opener("undo.desc", "r").read().splitlines()
623 if len(args) >= 3 and self.ui.verbose:
623 if len(args) >= 3 and self.ui.verbose:
624 desc = _("rolling back to revision %s"
624 desc = _("rolling back to revision %s"
625 " (undo %s: %s)\n") % (
625 " (undo %s: %s)\n") % (
626 args[0], args[1], args[2])
626 args[0], args[1], args[2])
627 elif len(args) >= 2:
627 elif len(args) >= 2:
628 desc = _("rolling back to revision %s (undo %s)\n") % (
628 desc = _("rolling back to revision %s (undo %s)\n") % (
629 args[0], args[1])
629 args[0], args[1])
630 except IOError:
630 except IOError:
631 desc = _("rolling back unknown transaction\n")
631 desc = _("rolling back unknown transaction\n")
632 self.ui.status(desc)
632 self.ui.status(desc)
633 if dryrun:
633 if dryrun:
634 return
634 return
635 transaction.rollback(self.sopener, self.sjoin("undo"),
635 transaction.rollback(self.sopener, self.sjoin("undo"),
636 self.ui.warn)
636 self.ui.warn)
637 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
637 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
638 try:
638 try:
639 branch = self.opener("undo.branch").read()
639 branch = self.opener("undo.branch").read()
640 self.dirstate.setbranch(branch)
640 self.dirstate.setbranch(branch)
641 except IOError:
641 except IOError:
642 self.ui.warn(_("Named branch could not be reset, "
642 self.ui.warn(_("Named branch could not be reset, "
643 "current branch still is: %s\n")
643 "current branch still is: %s\n")
644 % encoding.tolocal(self.dirstate.branch()))
644 % encoding.tolocal(self.dirstate.branch()))
645 self.invalidate()
645 self.invalidate()
646 self.dirstate.invalidate()
646 self.dirstate.invalidate()
647 self.destroyed()
647 self.destroyed()
648 else:
648 else:
649 self.ui.warn(_("no rollback information available\n"))
649 self.ui.warn(_("no rollback information available\n"))
650 finally:
650 finally:
651 release(lock, wlock)
651 release(lock, wlock)
652
652
653 def invalidatecaches(self):
653 def invalidatecaches(self):
654 self._tags = None
654 self._tags = None
655 self._tagtypes = None
655 self._tagtypes = None
656 self.nodetagscache = None
656 self.nodetagscache = None
657 self._branchcache = None # in UTF-8
657 self._branchcache = None # in UTF-8
658 self._branchcachetip = None
658 self._branchcachetip = None
659
659
660 def invalidate(self):
660 def invalidate(self):
661 for a in "changelog manifest".split():
661 for a in "changelog manifest".split():
662 if a in self.__dict__:
662 if a in self.__dict__:
663 delattr(self, a)
663 delattr(self, a)
664 self.invalidatecaches()
664 self.invalidatecaches()
665
665
666 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
666 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
667 try:
667 try:
668 l = lock.lock(lockname, 0, releasefn, desc=desc)
668 l = lock.lock(lockname, 0, releasefn, desc=desc)
669 except error.LockHeld, inst:
669 except error.LockHeld, inst:
670 if not wait:
670 if not wait:
671 raise
671 raise
672 self.ui.warn(_("waiting for lock on %s held by %r\n") %
672 self.ui.warn(_("waiting for lock on %s held by %r\n") %
673 (desc, inst.locker))
673 (desc, inst.locker))
674 # default to 600 seconds timeout
674 # default to 600 seconds timeout
675 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
675 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
676 releasefn, desc=desc)
676 releasefn, desc=desc)
677 if acquirefn:
677 if acquirefn:
678 acquirefn()
678 acquirefn()
679 return l
679 return l
680
680
681 def lock(self, wait=True):
681 def lock(self, wait=True):
682 '''Lock the repository store (.hg/store) and return a weak reference
682 '''Lock the repository store (.hg/store) and return a weak reference
683 to the lock. Use this before modifying the store (e.g. committing or
683 to the lock. Use this before modifying the store (e.g. committing or
684 stripping). If you are opening a transaction, get a lock as well.)'''
684 stripping). If you are opening a transaction, get a lock as well.)'''
685 l = self._lockref and self._lockref()
685 l = self._lockref and self._lockref()
686 if l is not None and l.held:
686 if l is not None and l.held:
687 l.lock()
687 l.lock()
688 return l
688 return l
689
689
690 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
690 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
691 _('repository %s') % self.origroot)
691 _('repository %s') % self.origroot)
692 self._lockref = weakref.ref(l)
692 self._lockref = weakref.ref(l)
693 return l
693 return l
694
694
695 def wlock(self, wait=True):
695 def wlock(self, wait=True):
696 '''Lock the non-store parts of the repository (everything under
696 '''Lock the non-store parts of the repository (everything under
697 .hg except .hg/store) and return a weak reference to the lock.
697 .hg except .hg/store) and return a weak reference to the lock.
698 Use this before modifying files in .hg.'''
698 Use this before modifying files in .hg.'''
699 l = self._wlockref and self._wlockref()
699 l = self._wlockref and self._wlockref()
700 if l is not None and l.held:
700 if l is not None and l.held:
701 l.lock()
701 l.lock()
702 return l
702 return l
703
703
704 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
704 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
705 self.dirstate.invalidate, _('working directory of %s') %
705 self.dirstate.invalidate, _('working directory of %s') %
706 self.origroot)
706 self.origroot)
707 self._wlockref = weakref.ref(l)
707 self._wlockref = weakref.ref(l)
708 return l
708 return l
709
709
710 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
710 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
711 """
711 """
712 commit an individual file as part of a larger transaction
712 commit an individual file as part of a larger transaction
713 """
713 """
714
714
715 fname = fctx.path()
715 fname = fctx.path()
716 text = fctx.data()
716 text = fctx.data()
717 flog = self.file(fname)
717 flog = self.file(fname)
718 fparent1 = manifest1.get(fname, nullid)
718 fparent1 = manifest1.get(fname, nullid)
719 fparent2 = fparent2o = manifest2.get(fname, nullid)
719 fparent2 = fparent2o = manifest2.get(fname, nullid)
720
720
721 meta = {}
721 meta = {}
722 copy = fctx.renamed()
722 copy = fctx.renamed()
723 if copy and copy[0] != fname:
723 if copy and copy[0] != fname:
724 # Mark the new revision of this file as a copy of another
724 # Mark the new revision of this file as a copy of another
725 # file. This copy data will effectively act as a parent
725 # file. This copy data will effectively act as a parent
726 # of this new revision. If this is a merge, the first
726 # of this new revision. If this is a merge, the first
727 # parent will be the nullid (meaning "look up the copy data")
727 # parent will be the nullid (meaning "look up the copy data")
728 # and the second one will be the other parent. For example:
728 # and the second one will be the other parent. For example:
729 #
729 #
730 # 0 --- 1 --- 3 rev1 changes file foo
730 # 0 --- 1 --- 3 rev1 changes file foo
731 # \ / rev2 renames foo to bar and changes it
731 # \ / rev2 renames foo to bar and changes it
732 # \- 2 -/ rev3 should have bar with all changes and
732 # \- 2 -/ rev3 should have bar with all changes and
733 # should record that bar descends from
733 # should record that bar descends from
734 # bar in rev2 and foo in rev1
734 # bar in rev2 and foo in rev1
735 #
735 #
736 # this allows this merge to succeed:
736 # this allows this merge to succeed:
737 #
737 #
738 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
738 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
739 # \ / merging rev3 and rev4 should use bar@rev2
739 # \ / merging rev3 and rev4 should use bar@rev2
740 # \- 2 --- 4 as the merge base
740 # \- 2 --- 4 as the merge base
741 #
741 #
742
742
743 cfname = copy[0]
743 cfname = copy[0]
744 crev = manifest1.get(cfname)
744 crev = manifest1.get(cfname)
745 newfparent = fparent2
745 newfparent = fparent2
746
746
747 if manifest2: # branch merge
747 if manifest2: # branch merge
748 if fparent2 == nullid or crev is None: # copied on remote side
748 if fparent2 == nullid or crev is None: # copied on remote side
749 if cfname in manifest2:
749 if cfname in manifest2:
750 crev = manifest2[cfname]
750 crev = manifest2[cfname]
751 newfparent = fparent1
751 newfparent = fparent1
752
752
753 # find source in nearest ancestor if we've lost track
753 # find source in nearest ancestor if we've lost track
754 if not crev:
754 if not crev:
755 self.ui.debug(" %s: searching for copy revision for %s\n" %
755 self.ui.debug(" %s: searching for copy revision for %s\n" %
756 (fname, cfname))
756 (fname, cfname))
757 for ancestor in self['.'].ancestors():
757 for ancestor in self['.'].ancestors():
758 if cfname in ancestor:
758 if cfname in ancestor:
759 crev = ancestor[cfname].filenode()
759 crev = ancestor[cfname].filenode()
760 break
760 break
761
761
762 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
762 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
763 meta["copy"] = cfname
763 meta["copy"] = cfname
764 meta["copyrev"] = hex(crev)
764 meta["copyrev"] = hex(crev)
765 fparent1, fparent2 = nullid, newfparent
765 fparent1, fparent2 = nullid, newfparent
766 elif fparent2 != nullid:
766 elif fparent2 != nullid:
767 # is one parent an ancestor of the other?
767 # is one parent an ancestor of the other?
768 fparentancestor = flog.ancestor(fparent1, fparent2)
768 fparentancestor = flog.ancestor(fparent1, fparent2)
769 if fparentancestor == fparent1:
769 if fparentancestor == fparent1:
770 fparent1, fparent2 = fparent2, nullid
770 fparent1, fparent2 = fparent2, nullid
771 elif fparentancestor == fparent2:
771 elif fparentancestor == fparent2:
772 fparent2 = nullid
772 fparent2 = nullid
773
773
774 # is the file changed?
774 # is the file changed?
775 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
775 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
776 changelist.append(fname)
776 changelist.append(fname)
777 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
777 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
778
778
779 # are just the flags changed during merge?
779 # are just the flags changed during merge?
780 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
780 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
781 changelist.append(fname)
781 changelist.append(fname)
782
782
783 return fparent1
783 return fparent1
784
784
785 def commit(self, text="", user=None, date=None, match=None, force=False,
785 def commit(self, text="", user=None, date=None, match=None, force=False,
786 editor=False, extra={}):
786 editor=False, extra={}):
787 """Add a new revision to current repository.
787 """Add a new revision to current repository.
788
788
789 Revision information is gathered from the working directory,
789 Revision information is gathered from the working directory,
790 match can be used to filter the committed files. If editor is
790 match can be used to filter the committed files. If editor is
791 supplied, it is called to get a commit message.
791 supplied, it is called to get a commit message.
792 """
792 """
793
793
794 def fail(f, msg):
794 def fail(f, msg):
795 raise util.Abort('%s: %s' % (f, msg))
795 raise util.Abort('%s: %s' % (f, msg))
796
796
797 if not match:
797 if not match:
798 match = matchmod.always(self.root, '')
798 match = matchmod.always(self.root, '')
799
799
800 if not force:
800 if not force:
801 vdirs = []
801 vdirs = []
802 match.dir = vdirs.append
802 match.dir = vdirs.append
803 match.bad = fail
803 match.bad = fail
804
804
805 wlock = self.wlock()
805 wlock = self.wlock()
806 try:
806 try:
807 wctx = self[None]
807 wctx = self[None]
808 merge = len(wctx.parents()) > 1
808 merge = len(wctx.parents()) > 1
809
809
810 if (not force and merge and match and
810 if (not force and merge and match and
811 (match.files() or match.anypats())):
811 (match.files() or match.anypats())):
812 raise util.Abort(_('cannot partially commit a merge '
812 raise util.Abort(_('cannot partially commit a merge '
813 '(do not specify files or patterns)'))
813 '(do not specify files or patterns)'))
814
814
815 changes = self.status(match=match, clean=force)
815 changes = self.status(match=match, clean=force)
816 if force:
816 if force:
817 changes[0].extend(changes[6]) # mq may commit unchanged files
817 changes[0].extend(changes[6]) # mq may commit unchanged files
818
818
819 # check subrepos
819 # check subrepos
820 subs = []
820 subs = []
821 removedsubs = set()
821 removedsubs = set()
822 for p in wctx.parents():
822 for p in wctx.parents():
823 removedsubs.update(s for s in p.substate if match(s))
823 removedsubs.update(s for s in p.substate if match(s))
824 for s in wctx.substate:
824 for s in wctx.substate:
825 removedsubs.discard(s)
825 removedsubs.discard(s)
826 if match(s) and wctx.sub(s).dirty():
826 if match(s) and wctx.sub(s).dirty():
827 subs.append(s)
827 subs.append(s)
828 if (subs or removedsubs) and '.hgsubstate' not in changes[0]:
828 if (subs or removedsubs) and '.hgsubstate' not in changes[0]:
829 changes[0].insert(0, '.hgsubstate')
829 changes[0].insert(0, '.hgsubstate')
830
830
831 # make sure all explicit patterns are matched
831 # make sure all explicit patterns are matched
832 if not force and match.files():
832 if not force and match.files():
833 matched = set(changes[0] + changes[1] + changes[2])
833 matched = set(changes[0] + changes[1] + changes[2])
834
834
835 for f in match.files():
835 for f in match.files():
836 if f == '.' or f in matched or f in wctx.substate:
836 if f == '.' or f in matched or f in wctx.substate:
837 continue
837 continue
838 if f in changes[3]: # missing
838 if f in changes[3]: # missing
839 fail(f, _('file not found!'))
839 fail(f, _('file not found!'))
840 if f in vdirs: # visited directory
840 if f in vdirs: # visited directory
841 d = f + '/'
841 d = f + '/'
842 for mf in matched:
842 for mf in matched:
843 if mf.startswith(d):
843 if mf.startswith(d):
844 break
844 break
845 else:
845 else:
846 fail(f, _("no match under directory!"))
846 fail(f, _("no match under directory!"))
847 elif f not in self.dirstate:
847 elif f not in self.dirstate:
848 fail(f, _("file not tracked!"))
848 fail(f, _("file not tracked!"))
849
849
850 if (not force and not extra.get("close") and not merge
850 if (not force and not extra.get("close") and not merge
851 and not (changes[0] or changes[1] or changes[2])
851 and not (changes[0] or changes[1] or changes[2])
852 and wctx.branch() == wctx.p1().branch()):
852 and wctx.branch() == wctx.p1().branch()):
853 return None
853 return None
854
854
855 ms = mergemod.mergestate(self)
855 ms = mergemod.mergestate(self)
856 for f in changes[0]:
856 for f in changes[0]:
857 if f in ms and ms[f] == 'u':
857 if f in ms and ms[f] == 'u':
858 raise util.Abort(_("unresolved merge conflicts "
858 raise util.Abort(_("unresolved merge conflicts "
859 "(see hg resolve)"))
859 "(see hg resolve)"))
860
860
861 cctx = context.workingctx(self, text, user, date, extra, changes)
861 cctx = context.workingctx(self, text, user, date, extra, changes)
862 if editor:
862 if editor:
863 cctx._text = editor(self, cctx, subs)
863 cctx._text = editor(self, cctx, subs)
864 edited = (text != cctx._text)
864 edited = (text != cctx._text)
865
865
866 # commit subs
866 # commit subs
867 if subs or removedsubs:
867 if subs or removedsubs:
868 state = wctx.substate.copy()
868 state = wctx.substate.copy()
869 for s in subs:
869 for s in subs:
870 sub = wctx.sub(s)
870 sub = wctx.sub(s)
871 self.ui.status(_('committing subrepository %s\n') %
871 self.ui.status(_('committing subrepository %s\n') %
872 subrepo.relpath(sub))
872 subrepo.relpath(sub))
873 sr = sub.commit(cctx._text, user, date)
873 sr = sub.commit(cctx._text, user, date)
874 state[s] = (state[s][0], sr)
874 state[s] = (state[s][0], sr)
875 subrepo.writestate(self, state)
875 subrepo.writestate(self, state)
876
876
877 # Save commit message in case this transaction gets rolled back
877 # Save commit message in case this transaction gets rolled back
878 # (e.g. by a pretxncommit hook). Leave the content alone on
878 # (e.g. by a pretxncommit hook). Leave the content alone on
879 # the assumption that the user will use the same editor again.
879 # the assumption that the user will use the same editor again.
880 msgfile = self.opener('last-message.txt', 'wb')
880 msgfile = self.opener('last-message.txt', 'wb')
881 msgfile.write(cctx._text)
881 msgfile.write(cctx._text)
882 msgfile.close()
882 msgfile.close()
883
883
884 p1, p2 = self.dirstate.parents()
884 p1, p2 = self.dirstate.parents()
885 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
885 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
886 try:
886 try:
887 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
887 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
888 ret = self.commitctx(cctx, True)
888 ret = self.commitctx(cctx, True)
889 except:
889 except:
890 if edited:
890 if edited:
891 msgfn = self.pathto(msgfile.name[len(self.root)+1:])
891 msgfn = self.pathto(msgfile.name[len(self.root)+1:])
892 self.ui.write(
892 self.ui.write(
893 _('note: commit message saved in %s\n') % msgfn)
893 _('note: commit message saved in %s\n') % msgfn)
894 raise
894 raise
895
895
896 # update dirstate and mergestate
896 # update dirstate and mergestate
897 for f in changes[0] + changes[1]:
897 for f in changes[0] + changes[1]:
898 self.dirstate.normal(f)
898 self.dirstate.normal(f)
899 for f in changes[2]:
899 for f in changes[2]:
900 self.dirstate.forget(f)
900 self.dirstate.forget(f)
901 self.dirstate.setparents(ret)
901 self.dirstate.setparents(ret)
902 ms.reset()
902 ms.reset()
903 finally:
903 finally:
904 wlock.release()
904 wlock.release()
905
905
906 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
906 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
907 return ret
907 return ret
908
908
909 def commitctx(self, ctx, error=False):
909 def commitctx(self, ctx, error=False):
910 """Add a new revision to current repository.
910 """Add a new revision to current repository.
911 Revision information is passed via the context argument.
911 Revision information is passed via the context argument.
912 """
912 """
913
913
914 tr = lock = None
914 tr = lock = None
915 removed = ctx.removed()
915 removed = ctx.removed()
916 p1, p2 = ctx.p1(), ctx.p2()
916 p1, p2 = ctx.p1(), ctx.p2()
917 m1 = p1.manifest().copy()
917 m1 = p1.manifest().copy()
918 m2 = p2.manifest()
918 m2 = p2.manifest()
919 user = ctx.user()
919 user = ctx.user()
920
920
921 lock = self.lock()
921 lock = self.lock()
922 try:
922 try:
923 tr = self.transaction("commit")
923 tr = self.transaction("commit")
924 trp = weakref.proxy(tr)
924 trp = weakref.proxy(tr)
925
925
926 # check in files
926 # check in files
927 new = {}
927 new = {}
928 changed = []
928 changed = []
929 linkrev = len(self)
929 linkrev = len(self)
930 for f in sorted(ctx.modified() + ctx.added()):
930 for f in sorted(ctx.modified() + ctx.added()):
931 self.ui.note(f + "\n")
931 self.ui.note(f + "\n")
932 try:
932 try:
933 fctx = ctx[f]
933 fctx = ctx[f]
934 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
934 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
935 changed)
935 changed)
936 m1.set(f, fctx.flags())
936 m1.set(f, fctx.flags())
937 except OSError, inst:
937 except OSError, inst:
938 self.ui.warn(_("trouble committing %s!\n") % f)
938 self.ui.warn(_("trouble committing %s!\n") % f)
939 raise
939 raise
940 except IOError, inst:
940 except IOError, inst:
941 errcode = getattr(inst, 'errno', errno.ENOENT)
941 errcode = getattr(inst, 'errno', errno.ENOENT)
942 if error or errcode and errcode != errno.ENOENT:
942 if error or errcode and errcode != errno.ENOENT:
943 self.ui.warn(_("trouble committing %s!\n") % f)
943 self.ui.warn(_("trouble committing %s!\n") % f)
944 raise
944 raise
945 else:
945 else:
946 removed.append(f)
946 removed.append(f)
947
947
948 # update manifest
948 # update manifest
949 m1.update(new)
949 m1.update(new)
950 removed = [f for f in sorted(removed) if f in m1 or f in m2]
950 removed = [f for f in sorted(removed) if f in m1 or f in m2]
951 drop = [f for f in removed if f in m1]
951 drop = [f for f in removed if f in m1]
952 for f in drop:
952 for f in drop:
953 del m1[f]
953 del m1[f]
954 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
954 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
955 p2.manifestnode(), (new, drop))
955 p2.manifestnode(), (new, drop))
956
956
957 # update changelog
957 # update changelog
958 self.changelog.delayupdate()
958 self.changelog.delayupdate()
959 n = self.changelog.add(mn, changed + removed, ctx.description(),
959 n = self.changelog.add(mn, changed + removed, ctx.description(),
960 trp, p1.node(), p2.node(),
960 trp, p1.node(), p2.node(),
961 user, ctx.date(), ctx.extra().copy())
961 user, ctx.date(), ctx.extra().copy())
962 p = lambda: self.changelog.writepending() and self.root or ""
962 p = lambda: self.changelog.writepending() and self.root or ""
963 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
963 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
964 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
964 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
965 parent2=xp2, pending=p)
965 parent2=xp2, pending=p)
966 self.changelog.finalize(trp)
966 self.changelog.finalize(trp)
967 tr.close()
967 tr.close()
968
968
969 if self._branchcache:
969 if self._branchcache:
970 self.branchtags()
970 self.branchtags()
971 return n
971 return n
972 finally:
972 finally:
973 del tr
973 del tr
974 lock.release()
974 lock.release()
975
975
976 def destroyed(self):
976 def destroyed(self):
977 '''Inform the repository that nodes have been destroyed.
977 '''Inform the repository that nodes have been destroyed.
978 Intended for use by strip and rollback, so there's a common
978 Intended for use by strip and rollback, so there's a common
979 place for anything that has to be done after destroying history.'''
979 place for anything that has to be done after destroying history.'''
980 # XXX it might be nice if we could take the list of destroyed
980 # XXX it might be nice if we could take the list of destroyed
981 # nodes, but I don't see an easy way for rollback() to do that
981 # nodes, but I don't see an easy way for rollback() to do that
982
982
983 # Ensure the persistent tag cache is updated. Doing it now
983 # Ensure the persistent tag cache is updated. Doing it now
984 # means that the tag cache only has to worry about destroyed
984 # means that the tag cache only has to worry about destroyed
985 # heads immediately after a strip/rollback. That in turn
985 # heads immediately after a strip/rollback. That in turn
986 # guarantees that "cachetip == currenttip" (comparing both rev
986 # guarantees that "cachetip == currenttip" (comparing both rev
987 # and node) always means no nodes have been added or destroyed.
987 # and node) always means no nodes have been added or destroyed.
988
988
989 # XXX this is suboptimal when qrefresh'ing: we strip the current
989 # XXX this is suboptimal when qrefresh'ing: we strip the current
990 # head, refresh the tag cache, then immediately add a new head.
990 # head, refresh the tag cache, then immediately add a new head.
991 # But I think doing it this way is necessary for the "instant
991 # But I think doing it this way is necessary for the "instant
992 # tag cache retrieval" case to work.
992 # tag cache retrieval" case to work.
993 self.invalidatecaches()
993 self.invalidatecaches()
994
994
995 def walk(self, match, node=None):
995 def walk(self, match, node=None):
996 '''
996 '''
997 walk recursively through the directory tree or a given
997 walk recursively through the directory tree or a given
998 changeset, finding all files matched by the match
998 changeset, finding all files matched by the match
999 function
999 function
1000 '''
1000 '''
1001 return self[node].walk(match)
1001 return self[node].walk(match)
1002
1002
1003 def status(self, node1='.', node2=None, match=None,
1003 def status(self, node1='.', node2=None, match=None,
1004 ignored=False, clean=False, unknown=False):
1004 ignored=False, clean=False, unknown=False):
1005 """return status of files between two nodes or node and working directory
1005 """return status of files between two nodes or node and working directory
1006
1006
1007 If node1 is None, use the first dirstate parent instead.
1007 If node1 is None, use the first dirstate parent instead.
1008 If node2 is None, compare node1 with working directory.
1008 If node2 is None, compare node1 with working directory.
1009 """
1009 """
1010
1010
1011 def mfmatches(ctx):
1011 def mfmatches(ctx):
1012 mf = ctx.manifest().copy()
1012 mf = ctx.manifest().copy()
1013 for fn in mf.keys():
1013 for fn in mf.keys():
1014 if not match(fn):
1014 if not match(fn):
1015 del mf[fn]
1015 del mf[fn]
1016 return mf
1016 return mf
1017
1017
1018 if isinstance(node1, context.changectx):
1018 if isinstance(node1, context.changectx):
1019 ctx1 = node1
1019 ctx1 = node1
1020 else:
1020 else:
1021 ctx1 = self[node1]
1021 ctx1 = self[node1]
1022 if isinstance(node2, context.changectx):
1022 if isinstance(node2, context.changectx):
1023 ctx2 = node2
1023 ctx2 = node2
1024 else:
1024 else:
1025 ctx2 = self[node2]
1025 ctx2 = self[node2]
1026
1026
1027 working = ctx2.rev() is None
1027 working = ctx2.rev() is None
1028 parentworking = working and ctx1 == self['.']
1028 parentworking = working and ctx1 == self['.']
1029 match = match or matchmod.always(self.root, self.getcwd())
1029 match = match or matchmod.always(self.root, self.getcwd())
1030 listignored, listclean, listunknown = ignored, clean, unknown
1030 listignored, listclean, listunknown = ignored, clean, unknown
1031
1031
1032 # load earliest manifest first for caching reasons
1032 # load earliest manifest first for caching reasons
1033 if not working and ctx2.rev() < ctx1.rev():
1033 if not working and ctx2.rev() < ctx1.rev():
1034 ctx2.manifest()
1034 ctx2.manifest()
1035
1035
1036 if not parentworking:
1036 if not parentworking:
1037 def bad(f, msg):
1037 def bad(f, msg):
1038 if f not in ctx1:
1038 if f not in ctx1:
1039 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1039 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1040 match.bad = bad
1040 match.bad = bad
1041
1041
1042 if working: # we need to scan the working dir
1042 if working: # we need to scan the working dir
1043 subrepos = ctx1.substate.keys()
1043 subrepos = ctx1.substate.keys()
1044 s = self.dirstate.status(match, subrepos, listignored,
1044 s = self.dirstate.status(match, subrepos, listignored,
1045 listclean, listunknown)
1045 listclean, listunknown)
1046 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1046 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1047
1047
1048 # check for any possibly clean files
1048 # check for any possibly clean files
1049 if parentworking and cmp:
1049 if parentworking and cmp:
1050 fixup = []
1050 fixup = []
1051 # do a full compare of any files that might have changed
1051 # do a full compare of any files that might have changed
1052 for f in sorted(cmp):
1052 for f in sorted(cmp):
1053 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1053 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1054 or ctx1[f].cmp(ctx2[f].data())):
1054 or ctx1[f].cmp(ctx2[f].data())):
1055 modified.append(f)
1055 modified.append(f)
1056 else:
1056 else:
1057 fixup.append(f)
1057 fixup.append(f)
1058
1058
1059 if listclean:
1059 if listclean:
1060 clean += fixup
1060 clean += fixup
1061
1061
1062 # update dirstate for files that are actually clean
1062 # update dirstate for files that are actually clean
1063 if fixup:
1063 if fixup:
1064 try:
1064 try:
1065 # updating the dirstate is optional
1065 # updating the dirstate is optional
1066 # so we don't wait on the lock
1066 # so we don't wait on the lock
1067 wlock = self.wlock(False)
1067 wlock = self.wlock(False)
1068 try:
1068 try:
1069 for f in fixup:
1069 for f in fixup:
1070 self.dirstate.normal(f)
1070 self.dirstate.normal(f)
1071 finally:
1071 finally:
1072 wlock.release()
1072 wlock.release()
1073 except error.LockError:
1073 except error.LockError:
1074 pass
1074 pass
1075
1075
1076 if not parentworking:
1076 if not parentworking:
1077 mf1 = mfmatches(ctx1)
1077 mf1 = mfmatches(ctx1)
1078 if working:
1078 if working:
1079 # we are comparing working dir against non-parent
1079 # we are comparing working dir against non-parent
1080 # generate a pseudo-manifest for the working dir
1080 # generate a pseudo-manifest for the working dir
1081 mf2 = mfmatches(self['.'])
1081 mf2 = mfmatches(self['.'])
1082 for f in cmp + modified + added:
1082 for f in cmp + modified + added:
1083 mf2[f] = None
1083 mf2[f] = None
1084 mf2.set(f, ctx2.flags(f))
1084 mf2.set(f, ctx2.flags(f))
1085 for f in removed:
1085 for f in removed:
1086 if f in mf2:
1086 if f in mf2:
1087 del mf2[f]
1087 del mf2[f]
1088 else:
1088 else:
1089 # we are comparing two revisions
1089 # we are comparing two revisions
1090 deleted, unknown, ignored = [], [], []
1090 deleted, unknown, ignored = [], [], []
1091 mf2 = mfmatches(ctx2)
1091 mf2 = mfmatches(ctx2)
1092
1092
1093 modified, added, clean = [], [], []
1093 modified, added, clean = [], [], []
1094 for fn in mf2:
1094 for fn in mf2:
1095 if fn in mf1:
1095 if fn in mf1:
1096 if (mf1.flags(fn) != mf2.flags(fn) or
1096 if (mf1.flags(fn) != mf2.flags(fn) or
1097 (mf1[fn] != mf2[fn] and
1097 (mf1[fn] != mf2[fn] and
1098 (mf2[fn] or ctx1[fn].cmp(ctx2[fn].data())))):
1098 (mf2[fn] or ctx1[fn].cmp(ctx2[fn].data())))):
1099 modified.append(fn)
1099 modified.append(fn)
1100 elif listclean:
1100 elif listclean:
1101 clean.append(fn)
1101 clean.append(fn)
1102 del mf1[fn]
1102 del mf1[fn]
1103 else:
1103 else:
1104 added.append(fn)
1104 added.append(fn)
1105 removed = mf1.keys()
1105 removed = mf1.keys()
1106
1106
1107 r = modified, added, removed, deleted, unknown, ignored, clean
1107 r = modified, added, removed, deleted, unknown, ignored, clean
1108 [l.sort() for l in r]
1108 [l.sort() for l in r]
1109 return r
1109 return r
1110
1110
1111 def add(self, list):
1111 def add(self, list):
1112 wlock = self.wlock()
1112 wlock = self.wlock()
1113 try:
1113 try:
1114 rejected = []
1114 rejected = []
1115 for f in list:
1115 for f in list:
1116 p = self.wjoin(f)
1116 p = self.wjoin(f)
1117 try:
1117 try:
1118 st = os.lstat(p)
1118 st = os.lstat(p)
1119 except:
1119 except:
1120 self.ui.warn(_("%s does not exist!\n") % f)
1120 self.ui.warn(_("%s does not exist!\n") % f)
1121 rejected.append(f)
1121 rejected.append(f)
1122 continue
1122 continue
1123 if st.st_size > 10000000:
1123 if st.st_size > 10000000:
1124 self.ui.warn(_("%s: up to %d MB of RAM may be required "
1124 self.ui.warn(_("%s: up to %d MB of RAM may be required "
1125 "to manage this file\n"
1125 "to manage this file\n"
1126 "(use 'hg revert %s' to cancel the "
1126 "(use 'hg revert %s' to cancel the "
1127 "pending addition)\n")
1127 "pending addition)\n")
1128 % (f, 3 * st.st_size // 1000000, f))
1128 % (f, 3 * st.st_size // 1000000, f))
1129 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1129 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1130 self.ui.warn(_("%s not added: only files and symlinks "
1130 self.ui.warn(_("%s not added: only files and symlinks "
1131 "supported currently\n") % f)
1131 "supported currently\n") % f)
1132 rejected.append(p)
1132 rejected.append(p)
1133 elif self.dirstate[f] in 'amn':
1133 elif self.dirstate[f] in 'amn':
1134 self.ui.warn(_("%s already tracked!\n") % f)
1134 self.ui.warn(_("%s already tracked!\n") % f)
1135 elif self.dirstate[f] == 'r':
1135 elif self.dirstate[f] == 'r':
1136 self.dirstate.normallookup(f)
1136 self.dirstate.normallookup(f)
1137 else:
1137 else:
1138 self.dirstate.add(f)
1138 self.dirstate.add(f)
1139 return rejected
1139 return rejected
1140 finally:
1140 finally:
1141 wlock.release()
1141 wlock.release()
1142
1142
1143 def forget(self, list):
1143 def forget(self, list):
1144 wlock = self.wlock()
1144 wlock = self.wlock()
1145 try:
1145 try:
1146 for f in list:
1146 for f in list:
1147 if self.dirstate[f] != 'a':
1147 if self.dirstate[f] != 'a':
1148 self.ui.warn(_("%s not added!\n") % f)
1148 self.ui.warn(_("%s not added!\n") % f)
1149 else:
1149 else:
1150 self.dirstate.forget(f)
1150 self.dirstate.forget(f)
1151 finally:
1151 finally:
1152 wlock.release()
1152 wlock.release()
1153
1153
1154 def remove(self, list, unlink=False):
1154 def remove(self, list, unlink=False):
1155 if unlink:
1155 if unlink:
1156 for f in list:
1156 for f in list:
1157 try:
1157 try:
1158 util.unlink(self.wjoin(f))
1158 util.unlink(self.wjoin(f))
1159 except OSError, inst:
1159 except OSError, inst:
1160 if inst.errno != errno.ENOENT:
1160 if inst.errno != errno.ENOENT:
1161 raise
1161 raise
1162 wlock = self.wlock()
1162 wlock = self.wlock()
1163 try:
1163 try:
1164 for f in list:
1164 for f in list:
1165 if unlink and os.path.exists(self.wjoin(f)):
1165 if unlink and os.path.exists(self.wjoin(f)):
1166 self.ui.warn(_("%s still exists!\n") % f)
1166 self.ui.warn(_("%s still exists!\n") % f)
1167 elif self.dirstate[f] == 'a':
1167 elif self.dirstate[f] == 'a':
1168 self.dirstate.forget(f)
1168 self.dirstate.forget(f)
1169 elif f not in self.dirstate:
1169 elif f not in self.dirstate:
1170 self.ui.warn(_("%s not tracked!\n") % f)
1170 self.ui.warn(_("%s not tracked!\n") % f)
1171 else:
1171 else:
1172 self.dirstate.remove(f)
1172 self.dirstate.remove(f)
1173 finally:
1173 finally:
1174 wlock.release()
1174 wlock.release()
1175
1175
1176 def undelete(self, list):
1176 def undelete(self, list):
1177 manifests = [self.manifest.read(self.changelog.read(p)[0])
1177 manifests = [self.manifest.read(self.changelog.read(p)[0])
1178 for p in self.dirstate.parents() if p != nullid]
1178 for p in self.dirstate.parents() if p != nullid]
1179 wlock = self.wlock()
1179 wlock = self.wlock()
1180 try:
1180 try:
1181 for f in list:
1181 for f in list:
1182 if self.dirstate[f] != 'r':
1182 if self.dirstate[f] != 'r':
1183 self.ui.warn(_("%s not removed!\n") % f)
1183 self.ui.warn(_("%s not removed!\n") % f)
1184 else:
1184 else:
1185 m = f in manifests[0] and manifests[0] or manifests[1]
1185 m = f in manifests[0] and manifests[0] or manifests[1]
1186 t = self.file(f).read(m[f])
1186 t = self.file(f).read(m[f])
1187 self.wwrite(f, t, m.flags(f))
1187 self.wwrite(f, t, m.flags(f))
1188 self.dirstate.normal(f)
1188 self.dirstate.normal(f)
1189 finally:
1189 finally:
1190 wlock.release()
1190 wlock.release()
1191
1191
1192 def copy(self, source, dest):
1192 def copy(self, source, dest):
1193 p = self.wjoin(dest)
1193 p = self.wjoin(dest)
1194 if not (os.path.exists(p) or os.path.islink(p)):
1194 if not (os.path.exists(p) or os.path.islink(p)):
1195 self.ui.warn(_("%s does not exist!\n") % dest)
1195 self.ui.warn(_("%s does not exist!\n") % dest)
1196 elif not (os.path.isfile(p) or os.path.islink(p)):
1196 elif not (os.path.isfile(p) or os.path.islink(p)):
1197 self.ui.warn(_("copy failed: %s is not a file or a "
1197 self.ui.warn(_("copy failed: %s is not a file or a "
1198 "symbolic link\n") % dest)
1198 "symbolic link\n") % dest)
1199 else:
1199 else:
1200 wlock = self.wlock()
1200 wlock = self.wlock()
1201 try:
1201 try:
1202 if self.dirstate[dest] in '?r':
1202 if self.dirstate[dest] in '?r':
1203 self.dirstate.add(dest)
1203 self.dirstate.add(dest)
1204 self.dirstate.copy(source, dest)
1204 self.dirstate.copy(source, dest)
1205 finally:
1205 finally:
1206 wlock.release()
1206 wlock.release()
1207
1207
1208 def heads(self, start=None):
1208 def heads(self, start=None):
1209 heads = self.changelog.heads(start)
1209 heads = self.changelog.heads(start)
1210 # sort the output in rev descending order
1210 # sort the output in rev descending order
1211 heads = [(-self.changelog.rev(h), h) for h in heads]
1211 heads = [(-self.changelog.rev(h), h) for h in heads]
1212 return [n for (r, n) in sorted(heads)]
1212 return [n for (r, n) in sorted(heads)]
1213
1213
1214 def branchheads(self, branch=None, start=None, closed=False):
1214 def branchheads(self, branch=None, start=None, closed=False):
1215 '''return a (possibly filtered) list of heads for the given branch
1215 '''return a (possibly filtered) list of heads for the given branch
1216
1216
1217 Heads are returned in topological order, from newest to oldest.
1217 Heads are returned in topological order, from newest to oldest.
1218 If branch is None, use the dirstate branch.
1218 If branch is None, use the dirstate branch.
1219 If start is not None, return only heads reachable from start.
1219 If start is not None, return only heads reachable from start.
1220 If closed is True, return heads that are marked as closed as well.
1220 If closed is True, return heads that are marked as closed as well.
1221 '''
1221 '''
1222 if branch is None:
1222 if branch is None:
1223 branch = self[None].branch()
1223 branch = self[None].branch()
1224 branches = self.branchmap()
1224 branches = self.branchmap()
1225 if branch not in branches:
1225 if branch not in branches:
1226 return []
1226 return []
1227 # the cache returns heads ordered lowest to highest
1227 # the cache returns heads ordered lowest to highest
1228 bheads = list(reversed(branches[branch]))
1228 bheads = list(reversed(branches[branch]))
1229 if start is not None:
1229 if start is not None:
1230 # filter out the heads that cannot be reached from startrev
1230 # filter out the heads that cannot be reached from startrev
1231 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1231 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1232 bheads = [h for h in bheads if h in fbheads]
1232 bheads = [h for h in bheads if h in fbheads]
1233 if not closed:
1233 if not closed:
1234 bheads = [h for h in bheads if
1234 bheads = [h for h in bheads if
1235 ('close' not in self.changelog.read(h)[5])]
1235 ('close' not in self.changelog.read(h)[5])]
1236 return bheads
1236 return bheads
1237
1237
1238 def branches(self, nodes):
1238 def branches(self, nodes):
1239 if not nodes:
1239 if not nodes:
1240 nodes = [self.changelog.tip()]
1240 nodes = [self.changelog.tip()]
1241 b = []
1241 b = []
1242 for n in nodes:
1242 for n in nodes:
1243 t = n
1243 t = n
1244 while 1:
1244 while 1:
1245 p = self.changelog.parents(n)
1245 p = self.changelog.parents(n)
1246 if p[1] != nullid or p[0] == nullid:
1246 if p[1] != nullid or p[0] == nullid:
1247 b.append((t, n, p[0], p[1]))
1247 b.append((t, n, p[0], p[1]))
1248 break
1248 break
1249 n = p[0]
1249 n = p[0]
1250 return b
1250 return b
1251
1251
1252 def between(self, pairs):
1252 def between(self, pairs):
1253 r = []
1253 r = []
1254
1254
1255 for top, bottom in pairs:
1255 for top, bottom in pairs:
1256 n, l, i = top, [], 0
1256 n, l, i = top, [], 0
1257 f = 1
1257 f = 1
1258
1258
1259 while n != bottom and n != nullid:
1259 while n != bottom and n != nullid:
1260 p = self.changelog.parents(n)[0]
1260 p = self.changelog.parents(n)[0]
1261 if i == f:
1261 if i == f:
1262 l.append(n)
1262 l.append(n)
1263 f = f * 2
1263 f = f * 2
1264 n = p
1264 n = p
1265 i += 1
1265 i += 1
1266
1266
1267 r.append(l)
1267 r.append(l)
1268
1268
1269 return r
1269 return r
1270
1270
1271 def findincoming(self, remote, base=None, heads=None, force=False):
1271 def findincoming(self, remote, base=None, heads=None, force=False):
1272 """Return list of roots of the subsets of missing nodes from remote
1272 """Return list of roots of the subsets of missing nodes from remote
1273
1273
1274 If base dict is specified, assume that these nodes and their parents
1274 If base dict is specified, assume that these nodes and their parents
1275 exist on the remote side and that no child of a node of base exists
1275 exist on the remote side and that no child of a node of base exists
1276 in both remote and self.
1276 in both remote and self.
1277 Furthermore base will be updated to include the nodes that exists
1277 Furthermore base will be updated to include the nodes that exists
1278 in self and remote but no children exists in self and remote.
1278 in self and remote but no children exists in self and remote.
1279 If a list of heads is specified, return only nodes which are heads
1279 If a list of heads is specified, return only nodes which are heads
1280 or ancestors of these heads.
1280 or ancestors of these heads.
1281
1281
1282 All the ancestors of base are in self and in remote.
1282 All the ancestors of base are in self and in remote.
1283 All the descendants of the list returned are missing in self.
1283 All the descendants of the list returned are missing in self.
1284 (and so we know that the rest of the nodes are missing in remote, see
1284 (and so we know that the rest of the nodes are missing in remote, see
1285 outgoing)
1285 outgoing)
1286 """
1286 """
1287 return self.findcommonincoming(remote, base, heads, force)[1]
1287 return self.findcommonincoming(remote, base, heads, force)[1]
1288
1288
1289 def findcommonincoming(self, remote, base=None, heads=None, force=False):
1289 def findcommonincoming(self, remote, base=None, heads=None, force=False):
1290 """Return a tuple (common, missing roots, heads) used to identify
1290 """Return a tuple (common, missing roots, heads) used to identify
1291 missing nodes from remote.
1291 missing nodes from remote.
1292
1292
1293 If base dict is specified, assume that these nodes and their parents
1293 If base dict is specified, assume that these nodes and their parents
1294 exist on the remote side and that no child of a node of base exists
1294 exist on the remote side and that no child of a node of base exists
1295 in both remote and self.
1295 in both remote and self.
1296 Furthermore base will be updated to include the nodes that exists
1296 Furthermore base will be updated to include the nodes that exists
1297 in self and remote but no children exists in self and remote.
1297 in self and remote but no children exists in self and remote.
1298 If a list of heads is specified, return only nodes which are heads
1298 If a list of heads is specified, return only nodes which are heads
1299 or ancestors of these heads.
1299 or ancestors of these heads.
1300
1300
1301 All the ancestors of base are in self and in remote.
1301 All the ancestors of base are in self and in remote.
1302 """
1302 """
1303 m = self.changelog.nodemap
1303 m = self.changelog.nodemap
1304 search = []
1304 search = []
1305 fetch = set()
1305 fetch = set()
1306 seen = set()
1306 seen = set()
1307 seenbranch = set()
1307 seenbranch = set()
1308 if base is None:
1308 if base is None:
1309 base = {}
1309 base = {}
1310
1310
1311 if not heads:
1311 if not heads:
1312 heads = remote.heads()
1312 heads = remote.heads()
1313
1313
1314 if self.changelog.tip() == nullid:
1314 if self.changelog.tip() == nullid:
1315 base[nullid] = 1
1315 base[nullid] = 1
1316 if heads != [nullid]:
1316 if heads != [nullid]:
1317 return [nullid], [nullid], list(heads)
1317 return [nullid], [nullid], list(heads)
1318 return [nullid], [], []
1318 return [nullid], [], []
1319
1319
1320 # assume we're closer to the tip than the root
1320 # assume we're closer to the tip than the root
1321 # and start by examining the heads
1321 # and start by examining the heads
1322 self.ui.status(_("searching for changes\n"))
1322 self.ui.status(_("searching for changes\n"))
1323
1323
1324 unknown = []
1324 unknown = []
1325 for h in heads:
1325 for h in heads:
1326 if h not in m:
1326 if h not in m:
1327 unknown.append(h)
1327 unknown.append(h)
1328 else:
1328 else:
1329 base[h] = 1
1329 base[h] = 1
1330
1330
1331 heads = unknown
1331 heads = unknown
1332 if not unknown:
1332 if not unknown:
1333 return base.keys(), [], []
1333 return base.keys(), [], []
1334
1334
1335 req = set(unknown)
1335 req = set(unknown)
1336 reqcnt = 0
1336 reqcnt = 0
1337
1337
1338 # search through remote branches
1338 # search through remote branches
1339 # a 'branch' here is a linear segment of history, with four parts:
1339 # a 'branch' here is a linear segment of history, with four parts:
1340 # head, root, first parent, second parent
1340 # head, root, first parent, second parent
1341 # (a branch always has two parents (or none) by definition)
1341 # (a branch always has two parents (or none) by definition)
1342 unknown = remote.branches(unknown)
1342 unknown = remote.branches(unknown)
1343 while unknown:
1343 while unknown:
1344 r = []
1344 r = []
1345 while unknown:
1345 while unknown:
1346 n = unknown.pop(0)
1346 n = unknown.pop(0)
1347 if n[0] in seen:
1347 if n[0] in seen:
1348 continue
1348 continue
1349
1349
1350 self.ui.debug("examining %s:%s\n"
1350 self.ui.debug("examining %s:%s\n"
1351 % (short(n[0]), short(n[1])))
1351 % (short(n[0]), short(n[1])))
1352 if n[0] == nullid: # found the end of the branch
1352 if n[0] == nullid: # found the end of the branch
1353 pass
1353 pass
1354 elif n in seenbranch:
1354 elif n in seenbranch:
1355 self.ui.debug("branch already found\n")
1355 self.ui.debug("branch already found\n")
1356 continue
1356 continue
1357 elif n[1] and n[1] in m: # do we know the base?
1357 elif n[1] and n[1] in m: # do we know the base?
1358 self.ui.debug("found incomplete branch %s:%s\n"
1358 self.ui.debug("found incomplete branch %s:%s\n"
1359 % (short(n[0]), short(n[1])))
1359 % (short(n[0]), short(n[1])))
1360 search.append(n[0:2]) # schedule branch range for scanning
1360 search.append(n[0:2]) # schedule branch range for scanning
1361 seenbranch.add(n)
1361 seenbranch.add(n)
1362 else:
1362 else:
1363 if n[1] not in seen and n[1] not in fetch:
1363 if n[1] not in seen and n[1] not in fetch:
1364 if n[2] in m and n[3] in m:
1364 if n[2] in m and n[3] in m:
1365 self.ui.debug("found new changeset %s\n" %
1365 self.ui.debug("found new changeset %s\n" %
1366 short(n[1]))
1366 short(n[1]))
1367 fetch.add(n[1]) # earliest unknown
1367 fetch.add(n[1]) # earliest unknown
1368 for p in n[2:4]:
1368 for p in n[2:4]:
1369 if p in m:
1369 if p in m:
1370 base[p] = 1 # latest known
1370 base[p] = 1 # latest known
1371
1371
1372 for p in n[2:4]:
1372 for p in n[2:4]:
1373 if p not in req and p not in m:
1373 if p not in req and p not in m:
1374 r.append(p)
1374 r.append(p)
1375 req.add(p)
1375 req.add(p)
1376 seen.add(n[0])
1376 seen.add(n[0])
1377
1377
1378 if r:
1378 if r:
1379 reqcnt += 1
1379 reqcnt += 1
1380 self.ui.progress(_('searching'), reqcnt, unit=_('queries'))
1380 self.ui.progress(_('searching'), reqcnt, unit=_('queries'))
1381 self.ui.debug("request %d: %s\n" %
1381 self.ui.debug("request %d: %s\n" %
1382 (reqcnt, " ".join(map(short, r))))
1382 (reqcnt, " ".join(map(short, r))))
1383 for p in xrange(0, len(r), 10):
1383 for p in xrange(0, len(r), 10):
1384 for b in remote.branches(r[p:p + 10]):
1384 for b in remote.branches(r[p:p + 10]):
1385 self.ui.debug("received %s:%s\n" %
1385 self.ui.debug("received %s:%s\n" %
1386 (short(b[0]), short(b[1])))
1386 (short(b[0]), short(b[1])))
1387 unknown.append(b)
1387 unknown.append(b)
1388
1388
1389 # do binary search on the branches we found
1389 # do binary search on the branches we found
1390 while search:
1390 while search:
1391 newsearch = []
1391 newsearch = []
1392 reqcnt += 1
1392 reqcnt += 1
1393 self.ui.progress(_('searching'), reqcnt, unit=_('queries'))
1393 self.ui.progress(_('searching'), reqcnt, unit=_('queries'))
1394 for n, l in zip(search, remote.between(search)):
1394 for n, l in zip(search, remote.between(search)):
1395 l.append(n[1])
1395 l.append(n[1])
1396 p = n[0]
1396 p = n[0]
1397 f = 1
1397 f = 1
1398 for i in l:
1398 for i in l:
1399 self.ui.debug("narrowing %d:%d %s\n" % (f, len(l), short(i)))
1399 self.ui.debug("narrowing %d:%d %s\n" % (f, len(l), short(i)))
1400 if i in m:
1400 if i in m:
1401 if f <= 2:
1401 if f <= 2:
1402 self.ui.debug("found new branch changeset %s\n" %
1402 self.ui.debug("found new branch changeset %s\n" %
1403 short(p))
1403 short(p))
1404 fetch.add(p)
1404 fetch.add(p)
1405 base[i] = 1
1405 base[i] = 1
1406 else:
1406 else:
1407 self.ui.debug("narrowed branch search to %s:%s\n"
1407 self.ui.debug("narrowed branch search to %s:%s\n"
1408 % (short(p), short(i)))
1408 % (short(p), short(i)))
1409 newsearch.append((p, i))
1409 newsearch.append((p, i))
1410 break
1410 break
1411 p, f = i, f * 2
1411 p, f = i, f * 2
1412 search = newsearch
1412 search = newsearch
1413
1413
1414 # sanity check our fetch list
1414 # sanity check our fetch list
1415 for f in fetch:
1415 for f in fetch:
1416 if f in m:
1416 if f in m:
1417 raise error.RepoError(_("already have changeset ")
1417 raise error.RepoError(_("already have changeset ")
1418 + short(f[:4]))
1418 + short(f[:4]))
1419
1419
1420 if base.keys() == [nullid]:
1420 if base.keys() == [nullid]:
1421 if force:
1421 if force:
1422 self.ui.warn(_("warning: repository is unrelated\n"))
1422 self.ui.warn(_("warning: repository is unrelated\n"))
1423 else:
1423 else:
1424 raise util.Abort(_("repository is unrelated"))
1424 raise util.Abort(_("repository is unrelated"))
1425
1425
1426 self.ui.debug("found new changesets starting at " +
1426 self.ui.debug("found new changesets starting at " +
1427 " ".join([short(f) for f in fetch]) + "\n")
1427 " ".join([short(f) for f in fetch]) + "\n")
1428
1428
1429 self.ui.progress(_('searching'), None)
1429 self.ui.progress(_('searching'), None)
1430 self.ui.debug("%d total queries\n" % reqcnt)
1430 self.ui.debug("%d total queries\n" % reqcnt)
1431
1431
1432 return base.keys(), list(fetch), heads
1432 return base.keys(), list(fetch), heads
1433
1433
1434 def findoutgoing(self, remote, base=None, heads=None, force=False):
1434 def findoutgoing(self, remote, base=None, heads=None, force=False):
1435 """Return list of nodes that are roots of subsets not in remote
1435 """Return list of nodes that are roots of subsets not in remote
1436
1436
1437 If base dict is specified, assume that these nodes and their parents
1437 If base dict is specified, assume that these nodes and their parents
1438 exist on the remote side.
1438 exist on the remote side.
1439 If a list of heads is specified, return only nodes which are heads
1439 If a list of heads is specified, return only nodes which are heads
1440 or ancestors of these heads, and return a second element which
1440 or ancestors of these heads, and return a second element which
1441 contains all remote heads which get new children.
1441 contains all remote heads which get new children.
1442 """
1442 """
1443 if base is None:
1443 if base is None:
1444 base = {}
1444 base = {}
1445 self.findincoming(remote, base, heads, force=force)
1445 self.findincoming(remote, base, heads, force=force)
1446
1446
1447 self.ui.debug("common changesets up to "
1447 self.ui.debug("common changesets up to "
1448 + " ".join(map(short, base.keys())) + "\n")
1448 + " ".join(map(short, base.keys())) + "\n")
1449
1449
1450 remain = set(self.changelog.nodemap)
1450 remain = set(self.changelog.nodemap)
1451
1451
1452 # prune everything remote has from the tree
1452 # prune everything remote has from the tree
1453 remain.remove(nullid)
1453 remain.remove(nullid)
1454 remove = base.keys()
1454 remove = base.keys()
1455 while remove:
1455 while remove:
1456 n = remove.pop(0)
1456 n = remove.pop(0)
1457 if n in remain:
1457 if n in remain:
1458 remain.remove(n)
1458 remain.remove(n)
1459 for p in self.changelog.parents(n):
1459 for p in self.changelog.parents(n):
1460 remove.append(p)
1460 remove.append(p)
1461
1461
1462 # find every node whose parents have been pruned
1462 # find every node whose parents have been pruned
1463 subset = []
1463 subset = []
1464 # find every remote head that will get new children
1464 # find every remote head that will get new children
1465 updated_heads = set()
1465 updated_heads = set()
1466 for n in remain:
1466 for n in remain:
1467 p1, p2 = self.changelog.parents(n)
1467 p1, p2 = self.changelog.parents(n)
1468 if p1 not in remain and p2 not in remain:
1468 if p1 not in remain and p2 not in remain:
1469 subset.append(n)
1469 subset.append(n)
1470 if heads:
1470 if heads:
1471 if p1 in heads:
1471 if p1 in heads:
1472 updated_heads.add(p1)
1472 updated_heads.add(p1)
1473 if p2 in heads:
1473 if p2 in heads:
1474 updated_heads.add(p2)
1474 updated_heads.add(p2)
1475
1475
1476 # this is the set of all roots we have to push
1476 # this is the set of all roots we have to push
1477 if heads:
1477 if heads:
1478 return subset, list(updated_heads)
1478 return subset, list(updated_heads)
1479 else:
1479 else:
1480 return subset
1480 return subset
1481
1481
1482 def pull(self, remote, heads=None, force=False):
1482 def pull(self, remote, heads=None, force=False):
1483 lock = self.lock()
1483 lock = self.lock()
1484 try:
1484 try:
1485 common, fetch, rheads = self.findcommonincoming(remote, heads=heads,
1485 common, fetch, rheads = self.findcommonincoming(remote, heads=heads,
1486 force=force)
1486 force=force)
1487 if not fetch:
1487 if not fetch:
1488 self.ui.status(_("no changes found\n"))
1488 self.ui.status(_("no changes found\n"))
1489 return 0
1489 return 0
1490
1490
1491 if fetch == [nullid]:
1491 if fetch == [nullid]:
1492 self.ui.status(_("requesting all changes\n"))
1492 self.ui.status(_("requesting all changes\n"))
1493 elif heads is None and remote.capable('changegroupsubset'):
1493 elif heads is None and remote.capable('changegroupsubset'):
1494 # issue1320, avoid a race if remote changed after discovery
1494 # issue1320, avoid a race if remote changed after discovery
1495 heads = rheads
1495 heads = rheads
1496
1496
1497 if heads is None:
1497 if heads is None:
1498 cg = remote.changegroup(fetch, 'pull')
1498 cg = remote.changegroup(fetch, 'pull')
1499 else:
1499 else:
1500 if not remote.capable('changegroupsubset'):
1500 if not remote.capable('changegroupsubset'):
1501 raise util.Abort(_("Partial pull cannot be done because "
1501 raise util.Abort(_("Partial pull cannot be done because "
1502 "other repository doesn't support "
1502 "other repository doesn't support "
1503 "changegroupsubset."))
1503 "changegroupsubset."))
1504 cg = remote.changegroupsubset(fetch, heads, 'pull')
1504 cg = remote.changegroupsubset(fetch, heads, 'pull')
1505 return self.addchangegroup(cg, 'pull', remote.url())
1505 return self.addchangegroup(cg, 'pull', remote.url())
1506 finally:
1506 finally:
1507 lock.release()
1507 lock.release()
1508
1508
1509 def push(self, remote, force=False, revs=None):
1509 def push(self, remote, force=False, revs=None):
1510 '''Push outgoing changesets (limited by revs) from the current
1511 repository to remote. Return an integer:
1512 - 0 means HTTP error *or* nothing to push
1513 - 1 means we pushed and remote head count is unchanged *or*
1514 we have outgoing changesets but refused to push
1515 - other values as described by addchangegroup()
1516 '''
1510 # there are two ways to push to remote repo:
1517 # there are two ways to push to remote repo:
1511 #
1518 #
1512 # addchangegroup assumes local user can lock remote
1519 # addchangegroup assumes local user can lock remote
1513 # repo (local filesystem, old ssh servers).
1520 # repo (local filesystem, old ssh servers).
1514 #
1521 #
1515 # unbundle assumes local user cannot lock remote repo (new ssh
1522 # unbundle assumes local user cannot lock remote repo (new ssh
1516 # servers, http servers).
1523 # servers, http servers).
1517
1524
1518 if remote.capable('unbundle'):
1525 if remote.capable('unbundle'):
1519 return self.push_unbundle(remote, force, revs)
1526 return self.push_unbundle(remote, force, revs)
1520 return self.push_addchangegroup(remote, force, revs)
1527 return self.push_addchangegroup(remote, force, revs)
1521
1528
1522 def prepush(self, remote, force, revs):
1529 def prepush(self, remote, force, revs):
1523 '''Analyze the local and remote repositories and determine which
1530 '''Analyze the local and remote repositories and determine which
1524 changesets need to be pushed to the remote. Return a tuple
1531 changesets need to be pushed to the remote. Return value depends
1525 (changegroup, remoteheads). changegroup is a readable file-like
1532 on circumstances:
1526 object whose read() returns successive changegroup chunks ready to
1533
1527 be sent over the wire. remoteheads is the list of remote heads.
1534 If we are not going to push anything, return a tuple (None,
1528 '''
1535 outgoing) where outgoing is 0 if there are no outgoing
1536 changesets and 1 if there are, but we refuse to push them
1537 (e.g. would create new remote heads).
1538
1539 Otherwise, return a tuple (changegroup, remoteheads), where
1540 changegroup is a readable file-like object whose read() returns
1541 successive changegroup chunks ready to be sent over the wire and
1542 remoteheads is the list of remote heads.'''
1529 common = {}
1543 common = {}
1530 remote_heads = remote.heads()
1544 remote_heads = remote.heads()
1531 inc = self.findincoming(remote, common, remote_heads, force=force)
1545 inc = self.findincoming(remote, common, remote_heads, force=force)
1532
1546
1533 cl = self.changelog
1547 cl = self.changelog
1534 update, updated_heads = self.findoutgoing(remote, common, remote_heads)
1548 update, updated_heads = self.findoutgoing(remote, common, remote_heads)
1535 outg, bases, heads = cl.nodesbetween(update, revs)
1549 outg, bases, heads = cl.nodesbetween(update, revs)
1536
1550
1537 if not bases:
1551 if not bases:
1538 self.ui.status(_("no changes found\n"))
1552 self.ui.status(_("no changes found\n"))
1539 return None, 1
1553 return None, 1
1540
1554
1541 if not force and remote_heads != [nullid]:
1555 if not force and remote_heads != [nullid]:
1542
1556
1543 def fail_multiple_heads(unsynced, branch=None):
1557 def fail_multiple_heads(unsynced, branch=None):
1544 if branch:
1558 if branch:
1545 msg = _("abort: push creates new remote heads"
1559 msg = _("abort: push creates new remote heads"
1546 " on branch '%s'!\n") % branch
1560 " on branch '%s'!\n") % branch
1547 else:
1561 else:
1548 msg = _("abort: push creates new remote heads!\n")
1562 msg = _("abort: push creates new remote heads!\n")
1549 self.ui.warn(msg)
1563 self.ui.warn(msg)
1550 if unsynced:
1564 if unsynced:
1551 self.ui.status(_("(you should pull and merge or"
1565 self.ui.status(_("(you should pull and merge or"
1552 " use push -f to force)\n"))
1566 " use push -f to force)\n"))
1553 else:
1567 else:
1554 self.ui.status(_("(did you forget to merge?"
1568 self.ui.status(_("(did you forget to merge?"
1555 " use push -f to force)\n"))
1569 " use push -f to force)\n"))
1556 return None, 0
1570 return None, 0
1557
1571
1558 if remote.capable('branchmap'):
1572 if remote.capable('branchmap'):
1559 # Check for each named branch if we're creating new remote heads.
1573 # Check for each named branch if we're creating new remote heads.
1560 # To be a remote head after push, node must be either:
1574 # To be a remote head after push, node must be either:
1561 # - unknown locally
1575 # - unknown locally
1562 # - a local outgoing head descended from update
1576 # - a local outgoing head descended from update
1563 # - a remote head that's known locally and not
1577 # - a remote head that's known locally and not
1564 # ancestral to an outgoing head
1578 # ancestral to an outgoing head
1565 #
1579 #
1566 # New named branches cannot be created without --force.
1580 # New named branches cannot be created without --force.
1567
1581
1568 # 1. Create set of branches involved in the push.
1582 # 1. Create set of branches involved in the push.
1569 branches = set(self[n].branch() for n in outg)
1583 branches = set(self[n].branch() for n in outg)
1570
1584
1571 # 2. Check for new branches on the remote.
1585 # 2. Check for new branches on the remote.
1572 remotemap = remote.branchmap()
1586 remotemap = remote.branchmap()
1573 newbranches = branches - set(remotemap)
1587 newbranches = branches - set(remotemap)
1574 if newbranches: # new branch requires --force
1588 if newbranches: # new branch requires --force
1575 branchnames = ', '.join("%s" % b for b in newbranches)
1589 branchnames = ', '.join("%s" % b for b in newbranches)
1576 self.ui.warn(_("abort: push creates "
1590 self.ui.warn(_("abort: push creates "
1577 "new remote branches: %s!\n")
1591 "new remote branches: %s!\n")
1578 % branchnames)
1592 % branchnames)
1579 self.ui.status(_("(use 'hg push -f' to force)\n"))
1593 self.ui.status(_("(use 'hg push -f' to force)\n"))
1580 return None, 0
1594 return None, 0
1581
1595
1582 # 3. Construct the initial oldmap and newmap dicts.
1596 # 3. Construct the initial oldmap and newmap dicts.
1583 # They contain information about the remote heads before and
1597 # They contain information about the remote heads before and
1584 # after the push, respectively.
1598 # after the push, respectively.
1585 # Heads not found locally are not included in either dict,
1599 # Heads not found locally are not included in either dict,
1586 # since they won't be affected by the push.
1600 # since they won't be affected by the push.
1587 # unsynced contains all branches with incoming changesets.
1601 # unsynced contains all branches with incoming changesets.
1588 oldmap = {}
1602 oldmap = {}
1589 newmap = {}
1603 newmap = {}
1590 unsynced = set()
1604 unsynced = set()
1591 for branch in branches:
1605 for branch in branches:
1592 remoteheads = remotemap[branch]
1606 remoteheads = remotemap[branch]
1593 prunedheads = [h for h in remoteheads if h in cl.nodemap]
1607 prunedheads = [h for h in remoteheads if h in cl.nodemap]
1594 oldmap[branch] = prunedheads
1608 oldmap[branch] = prunedheads
1595 newmap[branch] = list(prunedheads)
1609 newmap[branch] = list(prunedheads)
1596 if len(remoteheads) > len(prunedheads):
1610 if len(remoteheads) > len(prunedheads):
1597 unsynced.add(branch)
1611 unsynced.add(branch)
1598
1612
1599 # 4. Update newmap with outgoing changes.
1613 # 4. Update newmap with outgoing changes.
1600 # This will possibly add new heads and remove existing ones.
1614 # This will possibly add new heads and remove existing ones.
1601 ctxgen = (self[n] for n in outg)
1615 ctxgen = (self[n] for n in outg)
1602 self._updatebranchcache(newmap, ctxgen)
1616 self._updatebranchcache(newmap, ctxgen)
1603
1617
1604 # 5. Check for new heads.
1618 # 5. Check for new heads.
1605 # If there are more heads after the push than before, a suitable
1619 # If there are more heads after the push than before, a suitable
1606 # warning, depending on unsynced status, is displayed.
1620 # warning, depending on unsynced status, is displayed.
1607 for branch in branches:
1621 for branch in branches:
1608 if len(newmap[branch]) > len(oldmap[branch]):
1622 if len(newmap[branch]) > len(oldmap[branch]):
1609 return fail_multiple_heads(branch in unsynced, branch)
1623 return fail_multiple_heads(branch in unsynced, branch)
1610
1624
1611 # 6. Check for unsynced changes on involved branches.
1625 # 6. Check for unsynced changes on involved branches.
1612 if unsynced:
1626 if unsynced:
1613 self.ui.warn(_("note: unsynced remote changes!\n"))
1627 self.ui.warn(_("note: unsynced remote changes!\n"))
1614
1628
1615 else:
1629 else:
1616 # Old servers: Check for new topological heads.
1630 # Old servers: Check for new topological heads.
1617 # Code based on _updatebranchcache.
1631 # Code based on _updatebranchcache.
1618 newheads = set(h for h in remote_heads if h in cl.nodemap)
1632 newheads = set(h for h in remote_heads if h in cl.nodemap)
1619 oldheadcnt = len(newheads)
1633 oldheadcnt = len(newheads)
1620 newheads.update(outg)
1634 newheads.update(outg)
1621 if len(newheads) > 1:
1635 if len(newheads) > 1:
1622 for latest in reversed(outg):
1636 for latest in reversed(outg):
1623 if latest not in newheads:
1637 if latest not in newheads:
1624 continue
1638 continue
1625 minhrev = min(cl.rev(h) for h in newheads)
1639 minhrev = min(cl.rev(h) for h in newheads)
1626 reachable = cl.reachable(latest, cl.node(minhrev))
1640 reachable = cl.reachable(latest, cl.node(minhrev))
1627 reachable.remove(latest)
1641 reachable.remove(latest)
1628 newheads.difference_update(reachable)
1642 newheads.difference_update(reachable)
1629 if len(newheads) > oldheadcnt:
1643 if len(newheads) > oldheadcnt:
1630 return fail_multiple_heads(inc)
1644 return fail_multiple_heads(inc)
1631 if inc:
1645 if inc:
1632 self.ui.warn(_("note: unsynced remote changes!\n"))
1646 self.ui.warn(_("note: unsynced remote changes!\n"))
1633
1647
1634 if revs is None:
1648 if revs is None:
1635 # use the fast path, no race possible on push
1649 # use the fast path, no race possible on push
1636 nodes = self.changelog.findmissing(common.keys())
1650 nodes = self.changelog.findmissing(common.keys())
1637 cg = self._changegroup(nodes, 'push')
1651 cg = self._changegroup(nodes, 'push')
1638 else:
1652 else:
1639 cg = self.changegroupsubset(update, revs, 'push')
1653 cg = self.changegroupsubset(update, revs, 'push')
1640 return cg, remote_heads
1654 return cg, remote_heads
1641
1655
1642 def push_addchangegroup(self, remote, force, revs):
1656 def push_addchangegroup(self, remote, force, revs):
1657 '''Push a changegroup by locking the remote and sending the
1658 addchangegroup command to it. Used for local and old SSH repos.
1659 Return an integer: see push().
1660 '''
1643 lock = remote.lock()
1661 lock = remote.lock()
1644 try:
1662 try:
1645 ret = self.prepush(remote, force, revs)
1663 ret = self.prepush(remote, force, revs)
1646 if ret[0] is not None:
1664 if ret[0] is not None:
1647 cg, remote_heads = ret
1665 cg, remote_heads = ret
1666 # here, we return an integer indicating remote head count change
1648 return remote.addchangegroup(cg, 'push', self.url())
1667 return remote.addchangegroup(cg, 'push', self.url())
1668 # and here we return 0 for "nothing to push" or 1 for
1669 # "something to push but I refuse"
1649 return ret[1]
1670 return ret[1]
1650 finally:
1671 finally:
1651 lock.release()
1672 lock.release()
1652
1673
1653 def push_unbundle(self, remote, force, revs):
1674 def push_unbundle(self, remote, force, revs):
1675 '''Push a changegroup by unbundling it on the remote. Used for new
1676 SSH and HTTP repos. Return an integer: see push().'''
1654 # local repo finds heads on server, finds out what revs it
1677 # local repo finds heads on server, finds out what revs it
1655 # must push. once revs transferred, if server finds it has
1678 # must push. once revs transferred, if server finds it has
1656 # different heads (someone else won commit/push race), server
1679 # different heads (someone else won commit/push race), server
1657 # aborts.
1680 # aborts.
1658
1681
1659 ret = self.prepush(remote, force, revs)
1682 ret = self.prepush(remote, force, revs)
1660 if ret[0] is not None:
1683 if ret[0] is not None:
1661 cg, remote_heads = ret
1684 cg, remote_heads = ret
1662 if force:
1685 if force:
1663 remote_heads = ['force']
1686 remote_heads = ['force']
1687 # ssh: return remote's addchangegroup()
1688 # http: return remote's addchangegroup() or 0 for error
1664 return remote.unbundle(cg, remote_heads, 'push')
1689 return remote.unbundle(cg, remote_heads, 'push')
1690 # as in push_addchangegroup()
1665 return ret[1]
1691 return ret[1]
1666
1692
1667 def changegroupinfo(self, nodes, source):
1693 def changegroupinfo(self, nodes, source):
1668 if self.ui.verbose or source == 'bundle':
1694 if self.ui.verbose or source == 'bundle':
1669 self.ui.status(_("%d changesets found\n") % len(nodes))
1695 self.ui.status(_("%d changesets found\n") % len(nodes))
1670 if self.ui.debugflag:
1696 if self.ui.debugflag:
1671 self.ui.debug("list of changesets:\n")
1697 self.ui.debug("list of changesets:\n")
1672 for node in nodes:
1698 for node in nodes:
1673 self.ui.debug("%s\n" % hex(node))
1699 self.ui.debug("%s\n" % hex(node))
1674
1700
1675 def changegroupsubset(self, bases, heads, source, extranodes=None):
1701 def changegroupsubset(self, bases, heads, source, extranodes=None):
1676 """Compute a changegroup consisting of all the nodes that are
1702 """Compute a changegroup consisting of all the nodes that are
1677 descendents of any of the bases and ancestors of any of the heads.
1703 descendents of any of the bases and ancestors of any of the heads.
1678 Return a chunkbuffer object whose read() method will return
1704 Return a chunkbuffer object whose read() method will return
1679 successive changegroup chunks.
1705 successive changegroup chunks.
1680
1706
1681 It is fairly complex as determining which filenodes and which
1707 It is fairly complex as determining which filenodes and which
1682 manifest nodes need to be included for the changeset to be complete
1708 manifest nodes need to be included for the changeset to be complete
1683 is non-trivial.
1709 is non-trivial.
1684
1710
1685 Another wrinkle is doing the reverse, figuring out which changeset in
1711 Another wrinkle is doing the reverse, figuring out which changeset in
1686 the changegroup a particular filenode or manifestnode belongs to.
1712 the changegroup a particular filenode or manifestnode belongs to.
1687
1713
1688 The caller can specify some nodes that must be included in the
1714 The caller can specify some nodes that must be included in the
1689 changegroup using the extranodes argument. It should be a dict
1715 changegroup using the extranodes argument. It should be a dict
1690 where the keys are the filenames (or 1 for the manifest), and the
1716 where the keys are the filenames (or 1 for the manifest), and the
1691 values are lists of (node, linknode) tuples, where node is a wanted
1717 values are lists of (node, linknode) tuples, where node is a wanted
1692 node and linknode is the changelog node that should be transmitted as
1718 node and linknode is the changelog node that should be transmitted as
1693 the linkrev.
1719 the linkrev.
1694 """
1720 """
1695
1721
1696 # Set up some initial variables
1722 # Set up some initial variables
1697 # Make it easy to refer to self.changelog
1723 # Make it easy to refer to self.changelog
1698 cl = self.changelog
1724 cl = self.changelog
1699 # msng is short for missing - compute the list of changesets in this
1725 # msng is short for missing - compute the list of changesets in this
1700 # changegroup.
1726 # changegroup.
1701 if not bases:
1727 if not bases:
1702 bases = [nullid]
1728 bases = [nullid]
1703 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1729 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1704
1730
1705 if extranodes is None:
1731 if extranodes is None:
1706 # can we go through the fast path ?
1732 # can we go through the fast path ?
1707 heads.sort()
1733 heads.sort()
1708 allheads = self.heads()
1734 allheads = self.heads()
1709 allheads.sort()
1735 allheads.sort()
1710 if heads == allheads:
1736 if heads == allheads:
1711 return self._changegroup(msng_cl_lst, source)
1737 return self._changegroup(msng_cl_lst, source)
1712
1738
1713 # slow path
1739 # slow path
1714 self.hook('preoutgoing', throw=True, source=source)
1740 self.hook('preoutgoing', throw=True, source=source)
1715
1741
1716 self.changegroupinfo(msng_cl_lst, source)
1742 self.changegroupinfo(msng_cl_lst, source)
1717 # Some bases may turn out to be superfluous, and some heads may be
1743 # Some bases may turn out to be superfluous, and some heads may be
1718 # too. nodesbetween will return the minimal set of bases and heads
1744 # too. nodesbetween will return the minimal set of bases and heads
1719 # necessary to re-create the changegroup.
1745 # necessary to re-create the changegroup.
1720
1746
1721 # Known heads are the list of heads that it is assumed the recipient
1747 # Known heads are the list of heads that it is assumed the recipient
1722 # of this changegroup will know about.
1748 # of this changegroup will know about.
1723 knownheads = set()
1749 knownheads = set()
1724 # We assume that all parents of bases are known heads.
1750 # We assume that all parents of bases are known heads.
1725 for n in bases:
1751 for n in bases:
1726 knownheads.update(cl.parents(n))
1752 knownheads.update(cl.parents(n))
1727 knownheads.discard(nullid)
1753 knownheads.discard(nullid)
1728 knownheads = list(knownheads)
1754 knownheads = list(knownheads)
1729 if knownheads:
1755 if knownheads:
1730 # Now that we know what heads are known, we can compute which
1756 # Now that we know what heads are known, we can compute which
1731 # changesets are known. The recipient must know about all
1757 # changesets are known. The recipient must know about all
1732 # changesets required to reach the known heads from the null
1758 # changesets required to reach the known heads from the null
1733 # changeset.
1759 # changeset.
1734 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1760 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1735 junk = None
1761 junk = None
1736 # Transform the list into a set.
1762 # Transform the list into a set.
1737 has_cl_set = set(has_cl_set)
1763 has_cl_set = set(has_cl_set)
1738 else:
1764 else:
1739 # If there were no known heads, the recipient cannot be assumed to
1765 # If there were no known heads, the recipient cannot be assumed to
1740 # know about any changesets.
1766 # know about any changesets.
1741 has_cl_set = set()
1767 has_cl_set = set()
1742
1768
1743 # Make it easy to refer to self.manifest
1769 # Make it easy to refer to self.manifest
1744 mnfst = self.manifest
1770 mnfst = self.manifest
1745 # We don't know which manifests are missing yet
1771 # We don't know which manifests are missing yet
1746 msng_mnfst_set = {}
1772 msng_mnfst_set = {}
1747 # Nor do we know which filenodes are missing.
1773 # Nor do we know which filenodes are missing.
1748 msng_filenode_set = {}
1774 msng_filenode_set = {}
1749
1775
1750 junk = mnfst.index[len(mnfst) - 1] # Get around a bug in lazyindex
1776 junk = mnfst.index[len(mnfst) - 1] # Get around a bug in lazyindex
1751 junk = None
1777 junk = None
1752
1778
1753 # A changeset always belongs to itself, so the changenode lookup
1779 # A changeset always belongs to itself, so the changenode lookup
1754 # function for a changenode is identity.
1780 # function for a changenode is identity.
1755 def identity(x):
1781 def identity(x):
1756 return x
1782 return x
1757
1783
1758 # If we determine that a particular file or manifest node must be a
1784 # If we determine that a particular file or manifest node must be a
1759 # node that the recipient of the changegroup will already have, we can
1785 # node that the recipient of the changegroup will already have, we can
1760 # also assume the recipient will have all the parents. This function
1786 # also assume the recipient will have all the parents. This function
1761 # prunes them from the set of missing nodes.
1787 # prunes them from the set of missing nodes.
1762 def prune_parents(revlog, hasset, msngset):
1788 def prune_parents(revlog, hasset, msngset):
1763 for r in revlog.ancestors(*[revlog.rev(n) for n in hasset]):
1789 for r in revlog.ancestors(*[revlog.rev(n) for n in hasset]):
1764 msngset.pop(revlog.node(r), None)
1790 msngset.pop(revlog.node(r), None)
1765
1791
1766 # Use the information collected in collect_manifests_and_files to say
1792 # Use the information collected in collect_manifests_and_files to say
1767 # which changenode any manifestnode belongs to.
1793 # which changenode any manifestnode belongs to.
1768 def lookup_manifest_link(mnfstnode):
1794 def lookup_manifest_link(mnfstnode):
1769 return msng_mnfst_set[mnfstnode]
1795 return msng_mnfst_set[mnfstnode]
1770
1796
1771 # A function generating function that sets up the initial environment
1797 # A function generating function that sets up the initial environment
1772 # the inner function.
1798 # the inner function.
1773 def filenode_collector(changedfiles):
1799 def filenode_collector(changedfiles):
1774 # This gathers information from each manifestnode included in the
1800 # This gathers information from each manifestnode included in the
1775 # changegroup about which filenodes the manifest node references
1801 # changegroup about which filenodes the manifest node references
1776 # so we can include those in the changegroup too.
1802 # so we can include those in the changegroup too.
1777 #
1803 #
1778 # It also remembers which changenode each filenode belongs to. It
1804 # It also remembers which changenode each filenode belongs to. It
1779 # does this by assuming the a filenode belongs to the changenode
1805 # does this by assuming the a filenode belongs to the changenode
1780 # the first manifest that references it belongs to.
1806 # the first manifest that references it belongs to.
1781 def collect_msng_filenodes(mnfstnode):
1807 def collect_msng_filenodes(mnfstnode):
1782 r = mnfst.rev(mnfstnode)
1808 r = mnfst.rev(mnfstnode)
1783 if r - 1 in mnfst.parentrevs(r):
1809 if r - 1 in mnfst.parentrevs(r):
1784 # If the previous rev is one of the parents,
1810 # If the previous rev is one of the parents,
1785 # we only need to see a diff.
1811 # we only need to see a diff.
1786 deltamf = mnfst.readdelta(mnfstnode)
1812 deltamf = mnfst.readdelta(mnfstnode)
1787 # For each line in the delta
1813 # For each line in the delta
1788 for f, fnode in deltamf.iteritems():
1814 for f, fnode in deltamf.iteritems():
1789 f = changedfiles.get(f, None)
1815 f = changedfiles.get(f, None)
1790 # And if the file is in the list of files we care
1816 # And if the file is in the list of files we care
1791 # about.
1817 # about.
1792 if f is not None:
1818 if f is not None:
1793 # Get the changenode this manifest belongs to
1819 # Get the changenode this manifest belongs to
1794 clnode = msng_mnfst_set[mnfstnode]
1820 clnode = msng_mnfst_set[mnfstnode]
1795 # Create the set of filenodes for the file if
1821 # Create the set of filenodes for the file if
1796 # there isn't one already.
1822 # there isn't one already.
1797 ndset = msng_filenode_set.setdefault(f, {})
1823 ndset = msng_filenode_set.setdefault(f, {})
1798 # And set the filenode's changelog node to the
1824 # And set the filenode's changelog node to the
1799 # manifest's if it hasn't been set already.
1825 # manifest's if it hasn't been set already.
1800 ndset.setdefault(fnode, clnode)
1826 ndset.setdefault(fnode, clnode)
1801 else:
1827 else:
1802 # Otherwise we need a full manifest.
1828 # Otherwise we need a full manifest.
1803 m = mnfst.read(mnfstnode)
1829 m = mnfst.read(mnfstnode)
1804 # For every file in we care about.
1830 # For every file in we care about.
1805 for f in changedfiles:
1831 for f in changedfiles:
1806 fnode = m.get(f, None)
1832 fnode = m.get(f, None)
1807 # If it's in the manifest
1833 # If it's in the manifest
1808 if fnode is not None:
1834 if fnode is not None:
1809 # See comments above.
1835 # See comments above.
1810 clnode = msng_mnfst_set[mnfstnode]
1836 clnode = msng_mnfst_set[mnfstnode]
1811 ndset = msng_filenode_set.setdefault(f, {})
1837 ndset = msng_filenode_set.setdefault(f, {})
1812 ndset.setdefault(fnode, clnode)
1838 ndset.setdefault(fnode, clnode)
1813 return collect_msng_filenodes
1839 return collect_msng_filenodes
1814
1840
1815 # We have a list of filenodes we think we need for a file, lets remove
1841 # We have a list of filenodes we think we need for a file, lets remove
1816 # all those we know the recipient must have.
1842 # all those we know the recipient must have.
1817 def prune_filenodes(f, filerevlog):
1843 def prune_filenodes(f, filerevlog):
1818 msngset = msng_filenode_set[f]
1844 msngset = msng_filenode_set[f]
1819 hasset = set()
1845 hasset = set()
1820 # If a 'missing' filenode thinks it belongs to a changenode we
1846 # If a 'missing' filenode thinks it belongs to a changenode we
1821 # assume the recipient must have, then the recipient must have
1847 # assume the recipient must have, then the recipient must have
1822 # that filenode.
1848 # that filenode.
1823 for n in msngset:
1849 for n in msngset:
1824 clnode = cl.node(filerevlog.linkrev(filerevlog.rev(n)))
1850 clnode = cl.node(filerevlog.linkrev(filerevlog.rev(n)))
1825 if clnode in has_cl_set:
1851 if clnode in has_cl_set:
1826 hasset.add(n)
1852 hasset.add(n)
1827 prune_parents(filerevlog, hasset, msngset)
1853 prune_parents(filerevlog, hasset, msngset)
1828
1854
1829 # A function generator function that sets up the a context for the
1855 # A function generator function that sets up the a context for the
1830 # inner function.
1856 # inner function.
1831 def lookup_filenode_link_func(fname):
1857 def lookup_filenode_link_func(fname):
1832 msngset = msng_filenode_set[fname]
1858 msngset = msng_filenode_set[fname]
1833 # Lookup the changenode the filenode belongs to.
1859 # Lookup the changenode the filenode belongs to.
1834 def lookup_filenode_link(fnode):
1860 def lookup_filenode_link(fnode):
1835 return msngset[fnode]
1861 return msngset[fnode]
1836 return lookup_filenode_link
1862 return lookup_filenode_link
1837
1863
1838 # Add the nodes that were explicitly requested.
1864 # Add the nodes that were explicitly requested.
1839 def add_extra_nodes(name, nodes):
1865 def add_extra_nodes(name, nodes):
1840 if not extranodes or name not in extranodes:
1866 if not extranodes or name not in extranodes:
1841 return
1867 return
1842
1868
1843 for node, linknode in extranodes[name]:
1869 for node, linknode in extranodes[name]:
1844 if node not in nodes:
1870 if node not in nodes:
1845 nodes[node] = linknode
1871 nodes[node] = linknode
1846
1872
1847 # Now that we have all theses utility functions to help out and
1873 # Now that we have all theses utility functions to help out and
1848 # logically divide up the task, generate the group.
1874 # logically divide up the task, generate the group.
1849 def gengroup():
1875 def gengroup():
1850 # The set of changed files starts empty.
1876 # The set of changed files starts empty.
1851 changedfiles = {}
1877 changedfiles = {}
1852 collect = changegroup.collector(cl, msng_mnfst_set, changedfiles)
1878 collect = changegroup.collector(cl, msng_mnfst_set, changedfiles)
1853
1879
1854 # Create a changenode group generator that will call our functions
1880 # Create a changenode group generator that will call our functions
1855 # back to lookup the owning changenode and collect information.
1881 # back to lookup the owning changenode and collect information.
1856 group = cl.group(msng_cl_lst, identity, collect)
1882 group = cl.group(msng_cl_lst, identity, collect)
1857 cnt = 0
1883 cnt = 0
1858 for chnk in group:
1884 for chnk in group:
1859 yield chnk
1885 yield chnk
1860 self.ui.progress(_('bundling changes'), cnt, unit=_('chunks'))
1886 self.ui.progress(_('bundling changes'), cnt, unit=_('chunks'))
1861 cnt += 1
1887 cnt += 1
1862 self.ui.progress(_('bundling changes'), None)
1888 self.ui.progress(_('bundling changes'), None)
1863
1889
1864
1890
1865 # Figure out which manifest nodes (of the ones we think might be
1891 # Figure out which manifest nodes (of the ones we think might be
1866 # part of the changegroup) the recipient must know about and
1892 # part of the changegroup) the recipient must know about and
1867 # remove them from the changegroup.
1893 # remove them from the changegroup.
1868 has_mnfst_set = set()
1894 has_mnfst_set = set()
1869 for n in msng_mnfst_set:
1895 for n in msng_mnfst_set:
1870 # If a 'missing' manifest thinks it belongs to a changenode
1896 # If a 'missing' manifest thinks it belongs to a changenode
1871 # the recipient is assumed to have, obviously the recipient
1897 # the recipient is assumed to have, obviously the recipient
1872 # must have that manifest.
1898 # must have that manifest.
1873 linknode = cl.node(mnfst.linkrev(mnfst.rev(n)))
1899 linknode = cl.node(mnfst.linkrev(mnfst.rev(n)))
1874 if linknode in has_cl_set:
1900 if linknode in has_cl_set:
1875 has_mnfst_set.add(n)
1901 has_mnfst_set.add(n)
1876 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1902 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1877 add_extra_nodes(1, msng_mnfst_set)
1903 add_extra_nodes(1, msng_mnfst_set)
1878 msng_mnfst_lst = msng_mnfst_set.keys()
1904 msng_mnfst_lst = msng_mnfst_set.keys()
1879 # Sort the manifestnodes by revision number.
1905 # Sort the manifestnodes by revision number.
1880 msng_mnfst_lst.sort(key=mnfst.rev)
1906 msng_mnfst_lst.sort(key=mnfst.rev)
1881 # Create a generator for the manifestnodes that calls our lookup
1907 # Create a generator for the manifestnodes that calls our lookup
1882 # and data collection functions back.
1908 # and data collection functions back.
1883 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1909 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1884 filenode_collector(changedfiles))
1910 filenode_collector(changedfiles))
1885 cnt = 0
1911 cnt = 0
1886 for chnk in group:
1912 for chnk in group:
1887 yield chnk
1913 yield chnk
1888 self.ui.progress(_('bundling manifests'), cnt, unit=_('chunks'))
1914 self.ui.progress(_('bundling manifests'), cnt, unit=_('chunks'))
1889 cnt += 1
1915 cnt += 1
1890 self.ui.progress(_('bundling manifests'), None)
1916 self.ui.progress(_('bundling manifests'), None)
1891
1917
1892 # These are no longer needed, dereference and toss the memory for
1918 # These are no longer needed, dereference and toss the memory for
1893 # them.
1919 # them.
1894 msng_mnfst_lst = None
1920 msng_mnfst_lst = None
1895 msng_mnfst_set.clear()
1921 msng_mnfst_set.clear()
1896
1922
1897 if extranodes:
1923 if extranodes:
1898 for fname in extranodes:
1924 for fname in extranodes:
1899 if isinstance(fname, int):
1925 if isinstance(fname, int):
1900 continue
1926 continue
1901 msng_filenode_set.setdefault(fname, {})
1927 msng_filenode_set.setdefault(fname, {})
1902 changedfiles[fname] = 1
1928 changedfiles[fname] = 1
1903 # Go through all our files in order sorted by name.
1929 # Go through all our files in order sorted by name.
1904 cnt = 0
1930 cnt = 0
1905 for fname in sorted(changedfiles):
1931 for fname in sorted(changedfiles):
1906 filerevlog = self.file(fname)
1932 filerevlog = self.file(fname)
1907 if not len(filerevlog):
1933 if not len(filerevlog):
1908 raise util.Abort(_("empty or missing revlog for %s") % fname)
1934 raise util.Abort(_("empty or missing revlog for %s") % fname)
1909 # Toss out the filenodes that the recipient isn't really
1935 # Toss out the filenodes that the recipient isn't really
1910 # missing.
1936 # missing.
1911 if fname in msng_filenode_set:
1937 if fname in msng_filenode_set:
1912 prune_filenodes(fname, filerevlog)
1938 prune_filenodes(fname, filerevlog)
1913 add_extra_nodes(fname, msng_filenode_set[fname])
1939 add_extra_nodes(fname, msng_filenode_set[fname])
1914 msng_filenode_lst = msng_filenode_set[fname].keys()
1940 msng_filenode_lst = msng_filenode_set[fname].keys()
1915 else:
1941 else:
1916 msng_filenode_lst = []
1942 msng_filenode_lst = []
1917 # If any filenodes are left, generate the group for them,
1943 # If any filenodes are left, generate the group for them,
1918 # otherwise don't bother.
1944 # otherwise don't bother.
1919 if len(msng_filenode_lst) > 0:
1945 if len(msng_filenode_lst) > 0:
1920 yield changegroup.chunkheader(len(fname))
1946 yield changegroup.chunkheader(len(fname))
1921 yield fname
1947 yield fname
1922 # Sort the filenodes by their revision #
1948 # Sort the filenodes by their revision #
1923 msng_filenode_lst.sort(key=filerevlog.rev)
1949 msng_filenode_lst.sort(key=filerevlog.rev)
1924 # Create a group generator and only pass in a changenode
1950 # Create a group generator and only pass in a changenode
1925 # lookup function as we need to collect no information
1951 # lookup function as we need to collect no information
1926 # from filenodes.
1952 # from filenodes.
1927 group = filerevlog.group(msng_filenode_lst,
1953 group = filerevlog.group(msng_filenode_lst,
1928 lookup_filenode_link_func(fname))
1954 lookup_filenode_link_func(fname))
1929 for chnk in group:
1955 for chnk in group:
1930 self.ui.progress(
1956 self.ui.progress(
1931 _('bundling files'), cnt, item=fname, unit=_('chunks'))
1957 _('bundling files'), cnt, item=fname, unit=_('chunks'))
1932 cnt += 1
1958 cnt += 1
1933 yield chnk
1959 yield chnk
1934 if fname in msng_filenode_set:
1960 if fname in msng_filenode_set:
1935 # Don't need this anymore, toss it to free memory.
1961 # Don't need this anymore, toss it to free memory.
1936 del msng_filenode_set[fname]
1962 del msng_filenode_set[fname]
1937 # Signal that no more groups are left.
1963 # Signal that no more groups are left.
1938 yield changegroup.closechunk()
1964 yield changegroup.closechunk()
1939 self.ui.progress(_('bundling files'), None)
1965 self.ui.progress(_('bundling files'), None)
1940
1966
1941 if msng_cl_lst:
1967 if msng_cl_lst:
1942 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1968 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1943
1969
1944 return util.chunkbuffer(gengroup())
1970 return util.chunkbuffer(gengroup())
1945
1971
1946 def changegroup(self, basenodes, source):
1972 def changegroup(self, basenodes, source):
1947 # to avoid a race we use changegroupsubset() (issue1320)
1973 # to avoid a race we use changegroupsubset() (issue1320)
1948 return self.changegroupsubset(basenodes, self.heads(), source)
1974 return self.changegroupsubset(basenodes, self.heads(), source)
1949
1975
1950 def _changegroup(self, nodes, source):
1976 def _changegroup(self, nodes, source):
1951 """Compute the changegroup of all nodes that we have that a recipient
1977 """Compute the changegroup of all nodes that we have that a recipient
1952 doesn't. Return a chunkbuffer object whose read() method will return
1978 doesn't. Return a chunkbuffer object whose read() method will return
1953 successive changegroup chunks.
1979 successive changegroup chunks.
1954
1980
1955 This is much easier than the previous function as we can assume that
1981 This is much easier than the previous function as we can assume that
1956 the recipient has any changenode we aren't sending them.
1982 the recipient has any changenode we aren't sending them.
1957
1983
1958 nodes is the set of nodes to send"""
1984 nodes is the set of nodes to send"""
1959
1985
1960 self.hook('preoutgoing', throw=True, source=source)
1986 self.hook('preoutgoing', throw=True, source=source)
1961
1987
1962 cl = self.changelog
1988 cl = self.changelog
1963 revset = set([cl.rev(n) for n in nodes])
1989 revset = set([cl.rev(n) for n in nodes])
1964 self.changegroupinfo(nodes, source)
1990 self.changegroupinfo(nodes, source)
1965
1991
1966 def identity(x):
1992 def identity(x):
1967 return x
1993 return x
1968
1994
1969 def gennodelst(log):
1995 def gennodelst(log):
1970 for r in log:
1996 for r in log:
1971 if log.linkrev(r) in revset:
1997 if log.linkrev(r) in revset:
1972 yield log.node(r)
1998 yield log.node(r)
1973
1999
1974 def lookuprevlink_func(revlog):
2000 def lookuprevlink_func(revlog):
1975 def lookuprevlink(n):
2001 def lookuprevlink(n):
1976 return cl.node(revlog.linkrev(revlog.rev(n)))
2002 return cl.node(revlog.linkrev(revlog.rev(n)))
1977 return lookuprevlink
2003 return lookuprevlink
1978
2004
1979 def gengroup():
2005 def gengroup():
1980 '''yield a sequence of changegroup chunks (strings)'''
2006 '''yield a sequence of changegroup chunks (strings)'''
1981 # construct a list of all changed files
2007 # construct a list of all changed files
1982 changedfiles = {}
2008 changedfiles = {}
1983 mmfs = {}
2009 mmfs = {}
1984 collect = changegroup.collector(cl, mmfs, changedfiles)
2010 collect = changegroup.collector(cl, mmfs, changedfiles)
1985
2011
1986 cnt = 0
2012 cnt = 0
1987 for chnk in cl.group(nodes, identity, collect):
2013 for chnk in cl.group(nodes, identity, collect):
1988 self.ui.progress(_('bundling changes'), cnt, unit=_('chunks'))
2014 self.ui.progress(_('bundling changes'), cnt, unit=_('chunks'))
1989 cnt += 1
2015 cnt += 1
1990 yield chnk
2016 yield chnk
1991 self.ui.progress(_('bundling changes'), None)
2017 self.ui.progress(_('bundling changes'), None)
1992
2018
1993 mnfst = self.manifest
2019 mnfst = self.manifest
1994 nodeiter = gennodelst(mnfst)
2020 nodeiter = gennodelst(mnfst)
1995 cnt = 0
2021 cnt = 0
1996 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
2022 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1997 self.ui.progress(_('bundling manifests'), cnt, unit=_('chunks'))
2023 self.ui.progress(_('bundling manifests'), cnt, unit=_('chunks'))
1998 cnt += 1
2024 cnt += 1
1999 yield chnk
2025 yield chnk
2000 self.ui.progress(_('bundling manifests'), None)
2026 self.ui.progress(_('bundling manifests'), None)
2001
2027
2002 cnt = 0
2028 cnt = 0
2003 for fname in sorted(changedfiles):
2029 for fname in sorted(changedfiles):
2004 filerevlog = self.file(fname)
2030 filerevlog = self.file(fname)
2005 if not len(filerevlog):
2031 if not len(filerevlog):
2006 raise util.Abort(_("empty or missing revlog for %s") % fname)
2032 raise util.Abort(_("empty or missing revlog for %s") % fname)
2007 nodeiter = gennodelst(filerevlog)
2033 nodeiter = gennodelst(filerevlog)
2008 nodeiter = list(nodeiter)
2034 nodeiter = list(nodeiter)
2009 if nodeiter:
2035 if nodeiter:
2010 yield changegroup.chunkheader(len(fname))
2036 yield changegroup.chunkheader(len(fname))
2011 yield fname
2037 yield fname
2012 lookup = lookuprevlink_func(filerevlog)
2038 lookup = lookuprevlink_func(filerevlog)
2013 for chnk in filerevlog.group(nodeiter, lookup):
2039 for chnk in filerevlog.group(nodeiter, lookup):
2014 self.ui.progress(
2040 self.ui.progress(
2015 _('bundling files'), cnt, item=fname, unit=_('chunks'))
2041 _('bundling files'), cnt, item=fname, unit=_('chunks'))
2016 cnt += 1
2042 cnt += 1
2017 yield chnk
2043 yield chnk
2018 self.ui.progress(_('bundling files'), None)
2044 self.ui.progress(_('bundling files'), None)
2019
2045
2020 yield changegroup.closechunk()
2046 yield changegroup.closechunk()
2021
2047
2022 if nodes:
2048 if nodes:
2023 self.hook('outgoing', node=hex(nodes[0]), source=source)
2049 self.hook('outgoing', node=hex(nodes[0]), source=source)
2024
2050
2025 return util.chunkbuffer(gengroup())
2051 return util.chunkbuffer(gengroup())
2026
2052
2027 def addchangegroup(self, source, srctype, url, emptyok=False):
2053 def addchangegroup(self, source, srctype, url, emptyok=False):
2028 """add changegroup to repo.
2054 """Add the changegroup returned by source.read() to this repo.
2055 srctype is a string like 'push', 'pull', or 'unbundle'. url is
2056 the URL of the repo where this changegroup is coming from.
2029
2057
2030 return values:
2058 Return an integer summarizing the change to this repo:
2031 - nothing changed or no source: 0
2059 - nothing changed or no source: 0
2032 - more heads than before: 1+added heads (2..n)
2060 - more heads than before: 1+added heads (2..n)
2033 - less heads than before: -1-removed heads (-2..-n)
2061 - fewer heads than before: -1-removed heads (-2..-n)
2034 - number of heads stays the same: 1
2062 - number of heads stays the same: 1
2035 """
2063 """
2036 def csmap(x):
2064 def csmap(x):
2037 self.ui.debug("add changeset %s\n" % short(x))
2065 self.ui.debug("add changeset %s\n" % short(x))
2038 return len(cl)
2066 return len(cl)
2039
2067
2040 def revmap(x):
2068 def revmap(x):
2041 return cl.rev(x)
2069 return cl.rev(x)
2042
2070
2043 if not source:
2071 if not source:
2044 return 0
2072 return 0
2045
2073
2046 self.hook('prechangegroup', throw=True, source=srctype, url=url)
2074 self.hook('prechangegroup', throw=True, source=srctype, url=url)
2047
2075
2048 changesets = files = revisions = 0
2076 changesets = files = revisions = 0
2049 efiles = set()
2077 efiles = set()
2050
2078
2051 # write changelog data to temp files so concurrent readers will not see
2079 # write changelog data to temp files so concurrent readers will not see
2052 # inconsistent view
2080 # inconsistent view
2053 cl = self.changelog
2081 cl = self.changelog
2054 cl.delayupdate()
2082 cl.delayupdate()
2055 oldheads = len(cl.heads())
2083 oldheads = len(cl.heads())
2056
2084
2057 tr = self.transaction("\n".join([srctype, urlmod.hidepassword(url)]))
2085 tr = self.transaction("\n".join([srctype, urlmod.hidepassword(url)]))
2058 try:
2086 try:
2059 trp = weakref.proxy(tr)
2087 trp = weakref.proxy(tr)
2060 # pull off the changeset group
2088 # pull off the changeset group
2061 self.ui.status(_("adding changesets\n"))
2089 self.ui.status(_("adding changesets\n"))
2062 clstart = len(cl)
2090 clstart = len(cl)
2063 class prog(object):
2091 class prog(object):
2064 step = _('changesets')
2092 step = _('changesets')
2065 count = 1
2093 count = 1
2066 ui = self.ui
2094 ui = self.ui
2067 total = None
2095 total = None
2068 def __call__(self):
2096 def __call__(self):
2069 self.ui.progress(self.step, self.count, unit=_('chunks'),
2097 self.ui.progress(self.step, self.count, unit=_('chunks'),
2070 total=self.total)
2098 total=self.total)
2071 self.count += 1
2099 self.count += 1
2072 pr = prog()
2100 pr = prog()
2073 chunkiter = changegroup.chunkiter(source, progress=pr)
2101 chunkiter = changegroup.chunkiter(source, progress=pr)
2074 if cl.addgroup(chunkiter, csmap, trp) is None and not emptyok:
2102 if cl.addgroup(chunkiter, csmap, trp) is None and not emptyok:
2075 raise util.Abort(_("received changelog group is empty"))
2103 raise util.Abort(_("received changelog group is empty"))
2076 clend = len(cl)
2104 clend = len(cl)
2077 changesets = clend - clstart
2105 changesets = clend - clstart
2078 for c in xrange(clstart, clend):
2106 for c in xrange(clstart, clend):
2079 efiles.update(self[c].files())
2107 efiles.update(self[c].files())
2080 efiles = len(efiles)
2108 efiles = len(efiles)
2081 self.ui.progress(_('changesets'), None)
2109 self.ui.progress(_('changesets'), None)
2082
2110
2083 # pull off the manifest group
2111 # pull off the manifest group
2084 self.ui.status(_("adding manifests\n"))
2112 self.ui.status(_("adding manifests\n"))
2085 pr.step = _('manifests')
2113 pr.step = _('manifests')
2086 pr.count = 1
2114 pr.count = 1
2087 pr.total = changesets # manifests <= changesets
2115 pr.total = changesets # manifests <= changesets
2088 chunkiter = changegroup.chunkiter(source, progress=pr)
2116 chunkiter = changegroup.chunkiter(source, progress=pr)
2089 # no need to check for empty manifest group here:
2117 # no need to check for empty manifest group here:
2090 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2118 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2091 # no new manifest will be created and the manifest group will
2119 # no new manifest will be created and the manifest group will
2092 # be empty during the pull
2120 # be empty during the pull
2093 self.manifest.addgroup(chunkiter, revmap, trp)
2121 self.manifest.addgroup(chunkiter, revmap, trp)
2094 self.ui.progress(_('manifests'), None)
2122 self.ui.progress(_('manifests'), None)
2095
2123
2096 needfiles = {}
2124 needfiles = {}
2097 if self.ui.configbool('server', 'validate', default=False):
2125 if self.ui.configbool('server', 'validate', default=False):
2098 # validate incoming csets have their manifests
2126 # validate incoming csets have their manifests
2099 for cset in xrange(clstart, clend):
2127 for cset in xrange(clstart, clend):
2100 mfest = self.changelog.read(self.changelog.node(cset))[0]
2128 mfest = self.changelog.read(self.changelog.node(cset))[0]
2101 mfest = self.manifest.readdelta(mfest)
2129 mfest = self.manifest.readdelta(mfest)
2102 # store file nodes we must see
2130 # store file nodes we must see
2103 for f, n in mfest.iteritems():
2131 for f, n in mfest.iteritems():
2104 needfiles.setdefault(f, set()).add(n)
2132 needfiles.setdefault(f, set()).add(n)
2105
2133
2106 # process the files
2134 # process the files
2107 self.ui.status(_("adding file changes\n"))
2135 self.ui.status(_("adding file changes\n"))
2108 pr.step = 'files'
2136 pr.step = 'files'
2109 pr.count = 1
2137 pr.count = 1
2110 pr.total = efiles
2138 pr.total = efiles
2111 while 1:
2139 while 1:
2112 f = changegroup.getchunk(source)
2140 f = changegroup.getchunk(source)
2113 if not f:
2141 if not f:
2114 break
2142 break
2115 self.ui.debug("adding %s revisions\n" % f)
2143 self.ui.debug("adding %s revisions\n" % f)
2116 pr()
2144 pr()
2117 fl = self.file(f)
2145 fl = self.file(f)
2118 o = len(fl)
2146 o = len(fl)
2119 chunkiter = changegroup.chunkiter(source)
2147 chunkiter = changegroup.chunkiter(source)
2120 if fl.addgroup(chunkiter, revmap, trp) is None:
2148 if fl.addgroup(chunkiter, revmap, trp) is None:
2121 raise util.Abort(_("received file revlog group is empty"))
2149 raise util.Abort(_("received file revlog group is empty"))
2122 revisions += len(fl) - o
2150 revisions += len(fl) - o
2123 files += 1
2151 files += 1
2124 if f in needfiles:
2152 if f in needfiles:
2125 needs = needfiles[f]
2153 needs = needfiles[f]
2126 for new in xrange(o, len(fl)):
2154 for new in xrange(o, len(fl)):
2127 n = fl.node(new)
2155 n = fl.node(new)
2128 if n in needs:
2156 if n in needs:
2129 needs.remove(n)
2157 needs.remove(n)
2130 if not needs:
2158 if not needs:
2131 del needfiles[f]
2159 del needfiles[f]
2132 self.ui.progress(_('files'), None)
2160 self.ui.progress(_('files'), None)
2133
2161
2134 for f, needs in needfiles.iteritems():
2162 for f, needs in needfiles.iteritems():
2135 fl = self.file(f)
2163 fl = self.file(f)
2136 for n in needs:
2164 for n in needs:
2137 try:
2165 try:
2138 fl.rev(n)
2166 fl.rev(n)
2139 except error.LookupError:
2167 except error.LookupError:
2140 raise util.Abort(
2168 raise util.Abort(
2141 _('missing file data for %s:%s - run hg verify') %
2169 _('missing file data for %s:%s - run hg verify') %
2142 (f, hex(n)))
2170 (f, hex(n)))
2143
2171
2144 newheads = len(cl.heads())
2172 newheads = len(cl.heads())
2145 heads = ""
2173 heads = ""
2146 if oldheads and newheads != oldheads:
2174 if oldheads and newheads != oldheads:
2147 heads = _(" (%+d heads)") % (newheads - oldheads)
2175 heads = _(" (%+d heads)") % (newheads - oldheads)
2148
2176
2149 self.ui.status(_("added %d changesets"
2177 self.ui.status(_("added %d changesets"
2150 " with %d changes to %d files%s\n")
2178 " with %d changes to %d files%s\n")
2151 % (changesets, revisions, files, heads))
2179 % (changesets, revisions, files, heads))
2152
2180
2153 if changesets > 0:
2181 if changesets > 0:
2154 p = lambda: cl.writepending() and self.root or ""
2182 p = lambda: cl.writepending() and self.root or ""
2155 self.hook('pretxnchangegroup', throw=True,
2183 self.hook('pretxnchangegroup', throw=True,
2156 node=hex(cl.node(clstart)), source=srctype,
2184 node=hex(cl.node(clstart)), source=srctype,
2157 url=url, pending=p)
2185 url=url, pending=p)
2158
2186
2159 # make changelog see real files again
2187 # make changelog see real files again
2160 cl.finalize(trp)
2188 cl.finalize(trp)
2161
2189
2162 tr.close()
2190 tr.close()
2163 finally:
2191 finally:
2164 del tr
2192 del tr
2165
2193
2166 if changesets > 0:
2194 if changesets > 0:
2167 # forcefully update the on-disk branch cache
2195 # forcefully update the on-disk branch cache
2168 self.ui.debug("updating the branch cache\n")
2196 self.ui.debug("updating the branch cache\n")
2169 self.branchtags()
2197 self.branchtags()
2170 self.hook("changegroup", node=hex(cl.node(clstart)),
2198 self.hook("changegroup", node=hex(cl.node(clstart)),
2171 source=srctype, url=url)
2199 source=srctype, url=url)
2172
2200
2173 for i in xrange(clstart, clend):
2201 for i in xrange(clstart, clend):
2174 self.hook("incoming", node=hex(cl.node(i)),
2202 self.hook("incoming", node=hex(cl.node(i)),
2175 source=srctype, url=url)
2203 source=srctype, url=url)
2176
2204
2177 # never return 0 here:
2205 # never return 0 here:
2178 if newheads < oldheads:
2206 if newheads < oldheads:
2179 return newheads - oldheads - 1
2207 return newheads - oldheads - 1
2180 else:
2208 else:
2181 return newheads - oldheads + 1
2209 return newheads - oldheads + 1
2182
2210
2183
2211
2184 def stream_in(self, remote):
2212 def stream_in(self, remote):
2185 fp = remote.stream_out()
2213 fp = remote.stream_out()
2186 l = fp.readline()
2214 l = fp.readline()
2187 try:
2215 try:
2188 resp = int(l)
2216 resp = int(l)
2189 except ValueError:
2217 except ValueError:
2190 raise error.ResponseError(
2218 raise error.ResponseError(
2191 _('Unexpected response from remote server:'), l)
2219 _('Unexpected response from remote server:'), l)
2192 if resp == 1:
2220 if resp == 1:
2193 raise util.Abort(_('operation forbidden by server'))
2221 raise util.Abort(_('operation forbidden by server'))
2194 elif resp == 2:
2222 elif resp == 2:
2195 raise util.Abort(_('locking the remote repository failed'))
2223 raise util.Abort(_('locking the remote repository failed'))
2196 elif resp != 0:
2224 elif resp != 0:
2197 raise util.Abort(_('the server sent an unknown error code'))
2225 raise util.Abort(_('the server sent an unknown error code'))
2198 self.ui.status(_('streaming all changes\n'))
2226 self.ui.status(_('streaming all changes\n'))
2199 l = fp.readline()
2227 l = fp.readline()
2200 try:
2228 try:
2201 total_files, total_bytes = map(int, l.split(' ', 1))
2229 total_files, total_bytes = map(int, l.split(' ', 1))
2202 except (ValueError, TypeError):
2230 except (ValueError, TypeError):
2203 raise error.ResponseError(
2231 raise error.ResponseError(
2204 _('Unexpected response from remote server:'), l)
2232 _('Unexpected response from remote server:'), l)
2205 self.ui.status(_('%d files to transfer, %s of data\n') %
2233 self.ui.status(_('%d files to transfer, %s of data\n') %
2206 (total_files, util.bytecount(total_bytes)))
2234 (total_files, util.bytecount(total_bytes)))
2207 start = time.time()
2235 start = time.time()
2208 for i in xrange(total_files):
2236 for i in xrange(total_files):
2209 # XXX doesn't support '\n' or '\r' in filenames
2237 # XXX doesn't support '\n' or '\r' in filenames
2210 l = fp.readline()
2238 l = fp.readline()
2211 try:
2239 try:
2212 name, size = l.split('\0', 1)
2240 name, size = l.split('\0', 1)
2213 size = int(size)
2241 size = int(size)
2214 except (ValueError, TypeError):
2242 except (ValueError, TypeError):
2215 raise error.ResponseError(
2243 raise error.ResponseError(
2216 _('Unexpected response from remote server:'), l)
2244 _('Unexpected response from remote server:'), l)
2217 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2245 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2218 # for backwards compat, name was partially encoded
2246 # for backwards compat, name was partially encoded
2219 ofp = self.sopener(store.decodedir(name), 'w')
2247 ofp = self.sopener(store.decodedir(name), 'w')
2220 for chunk in util.filechunkiter(fp, limit=size):
2248 for chunk in util.filechunkiter(fp, limit=size):
2221 ofp.write(chunk)
2249 ofp.write(chunk)
2222 ofp.close()
2250 ofp.close()
2223 elapsed = time.time() - start
2251 elapsed = time.time() - start
2224 if elapsed <= 0:
2252 if elapsed <= 0:
2225 elapsed = 0.001
2253 elapsed = 0.001
2226 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2254 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2227 (util.bytecount(total_bytes), elapsed,
2255 (util.bytecount(total_bytes), elapsed,
2228 util.bytecount(total_bytes / elapsed)))
2256 util.bytecount(total_bytes / elapsed)))
2229 self.invalidate()
2257 self.invalidate()
2230 return len(self.heads()) + 1
2258 return len(self.heads()) + 1
2231
2259
2232 def clone(self, remote, heads=[], stream=False):
2260 def clone(self, remote, heads=[], stream=False):
2233 '''clone remote repository.
2261 '''clone remote repository.
2234
2262
2235 keyword arguments:
2263 keyword arguments:
2236 heads: list of revs to clone (forces use of pull)
2264 heads: list of revs to clone (forces use of pull)
2237 stream: use streaming clone if possible'''
2265 stream: use streaming clone if possible'''
2238
2266
2239 # now, all clients that can request uncompressed clones can
2267 # now, all clients that can request uncompressed clones can
2240 # read repo formats supported by all servers that can serve
2268 # read repo formats supported by all servers that can serve
2241 # them.
2269 # them.
2242
2270
2243 # if revlog format changes, client will have to check version
2271 # if revlog format changes, client will have to check version
2244 # and format flags on "stream" capability, and use
2272 # and format flags on "stream" capability, and use
2245 # uncompressed only if compatible.
2273 # uncompressed only if compatible.
2246
2274
2247 if stream and not heads and remote.capable('stream'):
2275 if stream and not heads and remote.capable('stream'):
2248 return self.stream_in(remote)
2276 return self.stream_in(remote)
2249 return self.pull(remote, heads)
2277 return self.pull(remote, heads)
2250
2278
2251 # used to avoid circular references so destructors work
2279 # used to avoid circular references so destructors work
2252 def aftertrans(files):
2280 def aftertrans(files):
2253 renamefiles = [tuple(t) for t in files]
2281 renamefiles = [tuple(t) for t in files]
2254 def a():
2282 def a():
2255 for src, dest in renamefiles:
2283 for src, dest in renamefiles:
2256 util.rename(src, dest)
2284 util.rename(src, dest)
2257 return a
2285 return a
2258
2286
2259 def instance(ui, path, create):
2287 def instance(ui, path, create):
2260 return localrepository(ui, util.drop_scheme('file', path), create)
2288 return localrepository(ui, util.drop_scheme('file', path), create)
2261
2289
2262 def islocal(path):
2290 def islocal(path):
2263 return True
2291 return True
@@ -1,269 +1,276 b''
1 # sshrepo.py - ssh repository proxy class for mercurial
1 # sshrepo.py - ssh repository proxy class for mercurial
2 #
2 #
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005, 2006 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 node import bin, hex
8 from node import bin, hex
9 from i18n import _
9 from i18n import _
10 import repo, util, error, encoding
10 import repo, util, error, encoding
11 import re, urllib
11 import re, urllib
12
12
13 class remotelock(object):
13 class remotelock(object):
14 def __init__(self, repo):
14 def __init__(self, repo):
15 self.repo = repo
15 self.repo = repo
16 def release(self):
16 def release(self):
17 self.repo.unlock()
17 self.repo.unlock()
18 self.repo = None
18 self.repo = None
19 def __del__(self):
19 def __del__(self):
20 if self.repo:
20 if self.repo:
21 self.release()
21 self.release()
22
22
23 class sshrepository(repo.repository):
23 class sshrepository(repo.repository):
24 def __init__(self, ui, path, create=0):
24 def __init__(self, ui, path, create=0):
25 self._url = path
25 self._url = path
26 self.ui = ui
26 self.ui = ui
27
27
28 m = re.match(r'^ssh://(([^@]+)@)?([^:/]+)(:(\d+))?(/(.*))?$', path)
28 m = re.match(r'^ssh://(([^@]+)@)?([^:/]+)(:(\d+))?(/(.*))?$', path)
29 if not m:
29 if not m:
30 self.abort(error.RepoError(_("couldn't parse location %s") % path))
30 self.abort(error.RepoError(_("couldn't parse location %s") % path))
31
31
32 self.user = m.group(2)
32 self.user = m.group(2)
33 self.host = m.group(3)
33 self.host = m.group(3)
34 self.port = m.group(5)
34 self.port = m.group(5)
35 self.path = m.group(7) or "."
35 self.path = m.group(7) or "."
36
36
37 sshcmd = self.ui.config("ui", "ssh", "ssh")
37 sshcmd = self.ui.config("ui", "ssh", "ssh")
38 remotecmd = self.ui.config("ui", "remotecmd", "hg")
38 remotecmd = self.ui.config("ui", "remotecmd", "hg")
39
39
40 args = util.sshargs(sshcmd, self.host, self.user, self.port)
40 args = util.sshargs(sshcmd, self.host, self.user, self.port)
41
41
42 if create:
42 if create:
43 cmd = '%s %s "%s init %s"'
43 cmd = '%s %s "%s init %s"'
44 cmd = cmd % (sshcmd, args, remotecmd, self.path)
44 cmd = cmd % (sshcmd, args, remotecmd, self.path)
45
45
46 ui.note(_('running %s\n') % cmd)
46 ui.note(_('running %s\n') % cmd)
47 res = util.system(cmd)
47 res = util.system(cmd)
48 if res != 0:
48 if res != 0:
49 self.abort(error.RepoError(_("could not create remote repo")))
49 self.abort(error.RepoError(_("could not create remote repo")))
50
50
51 self.validate_repo(ui, sshcmd, args, remotecmd)
51 self.validate_repo(ui, sshcmd, args, remotecmd)
52
52
53 def url(self):
53 def url(self):
54 return self._url
54 return self._url
55
55
56 def validate_repo(self, ui, sshcmd, args, remotecmd):
56 def validate_repo(self, ui, sshcmd, args, remotecmd):
57 # cleanup up previous run
57 # cleanup up previous run
58 self.cleanup()
58 self.cleanup()
59
59
60 cmd = '%s %s "%s -R %s serve --stdio"'
60 cmd = '%s %s "%s -R %s serve --stdio"'
61 cmd = cmd % (sshcmd, args, remotecmd, self.path)
61 cmd = cmd % (sshcmd, args, remotecmd, self.path)
62
62
63 cmd = util.quotecommand(cmd)
63 cmd = util.quotecommand(cmd)
64 ui.note(_('running %s\n') % cmd)
64 ui.note(_('running %s\n') % cmd)
65 self.pipeo, self.pipei, self.pipee = util.popen3(cmd)
65 self.pipeo, self.pipei, self.pipee = util.popen3(cmd)
66
66
67 # skip any noise generated by remote shell
67 # skip any noise generated by remote shell
68 self.do_cmd("hello")
68 self.do_cmd("hello")
69 r = self.do_cmd("between", pairs=("%s-%s" % ("0"*40, "0"*40)))
69 r = self.do_cmd("between", pairs=("%s-%s" % ("0"*40, "0"*40)))
70 lines = ["", "dummy"]
70 lines = ["", "dummy"]
71 max_noise = 500
71 max_noise = 500
72 while lines[-1] and max_noise:
72 while lines[-1] and max_noise:
73 l = r.readline()
73 l = r.readline()
74 self.readerr()
74 self.readerr()
75 if lines[-1] == "1\n" and l == "\n":
75 if lines[-1] == "1\n" and l == "\n":
76 break
76 break
77 if l:
77 if l:
78 ui.debug("remote: ", l)
78 ui.debug("remote: ", l)
79 lines.append(l)
79 lines.append(l)
80 max_noise -= 1
80 max_noise -= 1
81 else:
81 else:
82 self.abort(error.RepoError(_("no suitable response from remote hg")))
82 self.abort(error.RepoError(_("no suitable response from remote hg")))
83
83
84 self.capabilities = set()
84 self.capabilities = set()
85 for l in reversed(lines):
85 for l in reversed(lines):
86 if l.startswith("capabilities:"):
86 if l.startswith("capabilities:"):
87 self.capabilities.update(l[:-1].split(":")[1].split())
87 self.capabilities.update(l[:-1].split(":")[1].split())
88 break
88 break
89
89
90 def readerr(self):
90 def readerr(self):
91 while 1:
91 while 1:
92 size = util.fstat(self.pipee).st_size
92 size = util.fstat(self.pipee).st_size
93 if size == 0:
93 if size == 0:
94 break
94 break
95 l = self.pipee.readline()
95 l = self.pipee.readline()
96 if not l:
96 if not l:
97 break
97 break
98 self.ui.status(_("remote: "), l)
98 self.ui.status(_("remote: "), l)
99
99
100 def abort(self, exception):
100 def abort(self, exception):
101 self.cleanup()
101 self.cleanup()
102 raise exception
102 raise exception
103
103
104 def cleanup(self):
104 def cleanup(self):
105 try:
105 try:
106 self.pipeo.close()
106 self.pipeo.close()
107 self.pipei.close()
107 self.pipei.close()
108 # read the error descriptor until EOF
108 # read the error descriptor until EOF
109 for l in self.pipee:
109 for l in self.pipee:
110 self.ui.status(_("remote: "), l)
110 self.ui.status(_("remote: "), l)
111 self.pipee.close()
111 self.pipee.close()
112 except:
112 except:
113 pass
113 pass
114
114
115 __del__ = cleanup
115 __del__ = cleanup
116
116
117 def do_cmd(self, cmd, **args):
117 def do_cmd(self, cmd, **args):
118 self.ui.debug("sending %s command\n" % cmd)
118 self.ui.debug("sending %s command\n" % cmd)
119 self.pipeo.write("%s\n" % cmd)
119 self.pipeo.write("%s\n" % cmd)
120 for k, v in args.iteritems():
120 for k, v in args.iteritems():
121 self.pipeo.write("%s %d\n" % (k, len(v)))
121 self.pipeo.write("%s %d\n" % (k, len(v)))
122 self.pipeo.write(v)
122 self.pipeo.write(v)
123 self.pipeo.flush()
123 self.pipeo.flush()
124
124
125 return self.pipei
125 return self.pipei
126
126
127 def call(self, cmd, **args):
127 def call(self, cmd, **args):
128 self.do_cmd(cmd, **args)
128 self.do_cmd(cmd, **args)
129 return self._recv()
129 return self._recv()
130
130
131 def _recv(self):
131 def _recv(self):
132 l = self.pipei.readline()
132 l = self.pipei.readline()
133 self.readerr()
133 self.readerr()
134 try:
134 try:
135 l = int(l)
135 l = int(l)
136 except:
136 except:
137 self.abort(error.ResponseError(_("unexpected response:"), l))
137 self.abort(error.ResponseError(_("unexpected response:"), l))
138 return self.pipei.read(l)
138 return self.pipei.read(l)
139
139
140 def _send(self, data, flush=False):
140 def _send(self, data, flush=False):
141 self.pipeo.write("%d\n" % len(data))
141 self.pipeo.write("%d\n" % len(data))
142 if data:
142 if data:
143 self.pipeo.write(data)
143 self.pipeo.write(data)
144 if flush:
144 if flush:
145 self.pipeo.flush()
145 self.pipeo.flush()
146 self.readerr()
146 self.readerr()
147
147
148 def lock(self):
148 def lock(self):
149 self.call("lock")
149 self.call("lock")
150 return remotelock(self)
150 return remotelock(self)
151
151
152 def unlock(self):
152 def unlock(self):
153 self.call("unlock")
153 self.call("unlock")
154
154
155 def lookup(self, key):
155 def lookup(self, key):
156 self.requirecap('lookup', _('look up remote revision'))
156 self.requirecap('lookup', _('look up remote revision'))
157 d = self.call("lookup", key=key)
157 d = self.call("lookup", key=key)
158 success, data = d[:-1].split(" ", 1)
158 success, data = d[:-1].split(" ", 1)
159 if int(success):
159 if int(success):
160 return bin(data)
160 return bin(data)
161 else:
161 else:
162 self.abort(error.RepoError(data))
162 self.abort(error.RepoError(data))
163
163
164 def heads(self):
164 def heads(self):
165 d = self.call("heads")
165 d = self.call("heads")
166 try:
166 try:
167 return map(bin, d[:-1].split(" "))
167 return map(bin, d[:-1].split(" "))
168 except:
168 except:
169 self.abort(error.ResponseError(_("unexpected response:"), d))
169 self.abort(error.ResponseError(_("unexpected response:"), d))
170
170
171 def branchmap(self):
171 def branchmap(self):
172 d = self.call("branchmap")
172 d = self.call("branchmap")
173 try:
173 try:
174 branchmap = {}
174 branchmap = {}
175 for branchpart in d.splitlines():
175 for branchpart in d.splitlines():
176 branchheads = branchpart.split(' ')
176 branchheads = branchpart.split(' ')
177 branchname = urllib.unquote(branchheads[0])
177 branchname = urllib.unquote(branchheads[0])
178 # Earlier servers (1.3.x) send branch names in (their) local
178 # Earlier servers (1.3.x) send branch names in (their) local
179 # charset. The best we can do is assume it's identical to our
179 # charset. The best we can do is assume it's identical to our
180 # own local charset, in case it's not utf-8.
180 # own local charset, in case it's not utf-8.
181 try:
181 try:
182 branchname.decode('utf-8')
182 branchname.decode('utf-8')
183 except UnicodeDecodeError:
183 except UnicodeDecodeError:
184 branchname = encoding.fromlocal(branchname)
184 branchname = encoding.fromlocal(branchname)
185 branchheads = [bin(x) for x in branchheads[1:]]
185 branchheads = [bin(x) for x in branchheads[1:]]
186 branchmap[branchname] = branchheads
186 branchmap[branchname] = branchheads
187 return branchmap
187 return branchmap
188 except:
188 except:
189 raise error.ResponseError(_("unexpected response:"), d)
189 raise error.ResponseError(_("unexpected response:"), d)
190
190
191 def branches(self, nodes):
191 def branches(self, nodes):
192 n = " ".join(map(hex, nodes))
192 n = " ".join(map(hex, nodes))
193 d = self.call("branches", nodes=n)
193 d = self.call("branches", nodes=n)
194 try:
194 try:
195 br = [tuple(map(bin, b.split(" "))) for b in d.splitlines()]
195 br = [tuple(map(bin, b.split(" "))) for b in d.splitlines()]
196 return br
196 return br
197 except:
197 except:
198 self.abort(error.ResponseError(_("unexpected response:"), d))
198 self.abort(error.ResponseError(_("unexpected response:"), d))
199
199
200 def between(self, pairs):
200 def between(self, pairs):
201 n = " ".join(["-".join(map(hex, p)) for p in pairs])
201 n = " ".join(["-".join(map(hex, p)) for p in pairs])
202 d = self.call("between", pairs=n)
202 d = self.call("between", pairs=n)
203 try:
203 try:
204 p = [l and map(bin, l.split(" ")) or [] for l in d.splitlines()]
204 p = [l and map(bin, l.split(" ")) or [] for l in d.splitlines()]
205 return p
205 return p
206 except:
206 except:
207 self.abort(error.ResponseError(_("unexpected response:"), d))
207 self.abort(error.ResponseError(_("unexpected response:"), d))
208
208
209 def changegroup(self, nodes, kind):
209 def changegroup(self, nodes, kind):
210 n = " ".join(map(hex, nodes))
210 n = " ".join(map(hex, nodes))
211 return self.do_cmd("changegroup", roots=n)
211 return self.do_cmd("changegroup", roots=n)
212
212
213 def changegroupsubset(self, bases, heads, kind):
213 def changegroupsubset(self, bases, heads, kind):
214 self.requirecap('changegroupsubset', _('look up remote changes'))
214 self.requirecap('changegroupsubset', _('look up remote changes'))
215 bases = " ".join(map(hex, bases))
215 bases = " ".join(map(hex, bases))
216 heads = " ".join(map(hex, heads))
216 heads = " ".join(map(hex, heads))
217 return self.do_cmd("changegroupsubset", bases=bases, heads=heads)
217 return self.do_cmd("changegroupsubset", bases=bases, heads=heads)
218
218
219 def unbundle(self, cg, heads, source):
219 def unbundle(self, cg, heads, source):
220 '''Send cg (a readable file-like object representing the
221 changegroup to push, typically a chunkbuffer object) to the
222 remote server as a bundle. Return an integer indicating the
223 result of the push (see localrepository.addchangegroup()).'''
220 d = self.call("unbundle", heads=' '.join(map(hex, heads)))
224 d = self.call("unbundle", heads=' '.join(map(hex, heads)))
221 if d:
225 if d:
222 # remote may send "unsynced changes"
226 # remote may send "unsynced changes"
223 self.abort(error.RepoError(_("push refused: %s") % d))
227 self.abort(error.RepoError(_("push refused: %s") % d))
224
228
225 while 1:
229 while 1:
226 d = cg.read(4096)
230 d = cg.read(4096)
227 if not d:
231 if not d:
228 break
232 break
229 self._send(d)
233 self._send(d)
230
234
231 self._send("", flush=True)
235 self._send("", flush=True)
232
236
233 r = self._recv()
237 r = self._recv()
234 if r:
238 if r:
235 # remote may send "unsynced changes"
239 # remote may send "unsynced changes"
236 self.abort(error.RepoError(_("push failed: %s") % r))
240 self.abort(error.RepoError(_("push failed: %s") % r))
237
241
238 r = self._recv()
242 r = self._recv()
239 try:
243 try:
240 return int(r)
244 return int(r)
241 except:
245 except:
242 self.abort(error.ResponseError(_("unexpected response:"), r))
246 self.abort(error.ResponseError(_("unexpected response:"), r))
243
247
244 def addchangegroup(self, cg, source, url):
248 def addchangegroup(self, cg, source, url):
249 '''Send a changegroup to the remote server. Return an integer
250 similar to unbundle(). DEPRECATED, since it requires locking the
251 remote.'''
245 d = self.call("addchangegroup")
252 d = self.call("addchangegroup")
246 if d:
253 if d:
247 self.abort(error.RepoError(_("push refused: %s") % d))
254 self.abort(error.RepoError(_("push refused: %s") % d))
248 while 1:
255 while 1:
249 d = cg.read(4096)
256 d = cg.read(4096)
250 if not d:
257 if not d:
251 break
258 break
252 self.pipeo.write(d)
259 self.pipeo.write(d)
253 self.readerr()
260 self.readerr()
254
261
255 self.pipeo.flush()
262 self.pipeo.flush()
256
263
257 self.readerr()
264 self.readerr()
258 r = self._recv()
265 r = self._recv()
259 if not r:
266 if not r:
260 return 1
267 return 1
261 try:
268 try:
262 return int(r)
269 return int(r)
263 except:
270 except:
264 self.abort(error.ResponseError(_("unexpected response:"), r))
271 self.abort(error.ResponseError(_("unexpected response:"), r))
265
272
266 def stream_out(self):
273 def stream_out(self):
267 return self.do_cmd('stream_out')
274 return self.do_cmd('stream_out')
268
275
269 instance = sshrepository
276 instance = sshrepository
General Comments 0
You need to be logged in to leave comments. Login now